11541Srgrimes//===-- Target.cpp ----------------------------------------------*- C++ -*-===//
211150Swollman//
31541Srgrimes//                     The LLVM Compiler Infrastructure
41541Srgrimes//
51541Srgrimes// This file is distributed under the University of Illinois Open Source
61541Srgrimes// License. See LICENSE.TXT for details.
71541Srgrimes//
81541Srgrimes//===----------------------------------------------------------------------===//
91541Srgrimes
101541Srgrimes#include "lldb/lldb-python.h"
111541Srgrimes
121541Srgrimes#include "lldb/Target/Target.h"
131541Srgrimes
141541Srgrimes// C Includes
151541Srgrimes// C++ Includes
161541Srgrimes// Other libraries and framework includes
171541Srgrimes// Project includes
181541Srgrimes#include "lldb/Breakpoint/BreakpointResolver.h"
191541Srgrimes#include "lldb/Breakpoint/BreakpointResolverAddress.h"
201541Srgrimes#include "lldb/Breakpoint/BreakpointResolverFileLine.h"
211541Srgrimes#include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
221541Srgrimes#include "lldb/Breakpoint/BreakpointResolverName.h"
231541Srgrimes#include "lldb/Breakpoint/Watchpoint.h"
241541Srgrimes#include "lldb/Core/Debugger.h"
251541Srgrimes#include "lldb/Core/Event.h"
261541Srgrimes#include "lldb/Core/Log.h"
271541Srgrimes#include "lldb/Core/Module.h"
281541Srgrimes#include "lldb/Core/ModuleSpec.h"
291541Srgrimes#include "lldb/Core/Section.h"
301541Srgrimes#include "lldb/Core/SourceManager.h"
311541Srgrimes#include "lldb/Core/State.h"
321541Srgrimes#include "lldb/Core/StreamFile.h"
3311150Swollman#include "lldb/Core/StreamString.h"
3429514Sjoerg#include "lldb/Core/Timer.h"
351541Srgrimes#include "lldb/Core/ValueObject.h"
361541Srgrimes#include "lldb/Expression/ClangASTSource.h"
3729514Sjoerg#include "lldb/Expression/ClangUserExpression.h"
3829514Sjoerg#include "lldb/Host/Host.h"
391541Srgrimes#include "lldb/Interpreter/CommandInterpreter.h"
401541Srgrimes#include "lldb/Interpreter/CommandReturnObject.h"
4114546Sdg#include "lldb/Interpreter/OptionGroupWatchpoint.h"
421541Srgrimes#include "lldb/Interpreter/OptionValues.h"
4312172Sphk#include "lldb/Interpreter/Property.h"
4412172Sphk#include "lldb/lldb-private-log.h"
451541Srgrimes#include "lldb/Symbol/ObjectFile.h"
461541Srgrimes#include "lldb/Target/Process.h"
4725201Swollman#include "lldb/Target/SectionLoadList.h"
481541Srgrimes#include "lldb/Target/StackFrame.h"
491541Srgrimes#include "lldb/Target/SystemRuntime.h"
501541Srgrimes#include "lldb/Target/Thread.h"
511541Srgrimes#include "lldb/Target/ThreadSpec.h"
5215038Sphk
531541Srgrimesusing namespace lldb;
5411150Swollmanusing namespace lldb_private;
5511150Swollman
561541SrgrimesConstString &
571541SrgrimesTarget::GetStaticBroadcasterClass ()
581541Srgrimes{
591541Srgrimes    static ConstString class_name ("lldb.target");
601541Srgrimes    return class_name;
611541Srgrimes}
621541Srgrimes
631541Srgrimes//----------------------------------------------------------------------
641541Srgrimes// Target constructor
651541Srgrimes//----------------------------------------------------------------------
661541SrgrimesTarget::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
671541Srgrimes    TargetProperties (this),
681541Srgrimes    Broadcaster (&debugger, Target::GetStaticBroadcasterClass().AsCString()),
691541Srgrimes    ExecutionContextScope (),
702788Sdg    m_debugger (debugger),
711541Srgrimes    m_platform_sp (platform_sp),
7212820Sphk    m_mutex (Mutex::eMutexTypeRecursive),
732788Sdg    m_arch (target_arch),
741541Srgrimes    m_images (this),
7512296Sphk    m_section_load_history (),
766348Swollman    m_breakpoint_list (false),
776348Swollman    m_internal_breakpoint_list (true),
7812296Sphk    m_watchpoint_list (),
796348Swollman    m_process_sp (),
8012172Sphk    m_search_filter_sp (),
8112172Sphk    m_image_search_paths (ImageSearchPathsChanged, this),
8212296Sphk    m_scratch_ast_context_ap (),
8315154Spst    m_scratch_ast_source_ap (),
8415038Sphk    m_ast_importer_ap (),
8515038Sphk    m_persistent_variables (),
8615038Sphk    m_source_manager_ap(),
876348Swollman    m_stop_hooks (),
887684Sdg    m_stop_hook_next_id (0),
897684Sdg    m_valid (true),
901541Srgrimes    m_suppress_stop_hooks (false)
9112296Sphk{
9212296Sphk    SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
9312296Sphk    SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
9412296Sphk    SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
9512296Sphk    SetEventName (eBroadcastBitWatchpointChanged, "watchpoint-changed");
9612296Sphk    SetEventName (eBroadcastBitSymbolsLoaded, "symbols-loaded");
9712296Sphk
981541Srgrimes    CheckInWithManager();
991541Srgrimes
1001541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
1011541Srgrimes    if (log)
1021541Srgrimes        log->Printf ("%p Target::Target()", this);
1031541Srgrimes    if (m_arch.IsValid())
1041541Srgrimes    {
1051541Srgrimes        LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::Target created with architecture %s (%s)", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
1061541Srgrimes    }
1071541Srgrimes}
1081541Srgrimes
1091541Srgrimes//----------------------------------------------------------------------
1108429Sdg// Destructor
1111541Srgrimes//----------------------------------------------------------------------
1121541SrgrimesTarget::~Target()
1131541Srgrimes{
1141541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
1157738Sdg    if (log)
1167738Sdg        log->Printf ("%p Target::~Target()", this);
1177738Sdg    DeleteCurrentProcess ();
1187738Sdg}
1191541Srgrimes
1201541Srgrimesvoid
1211541SrgrimesTarget::Dump (Stream *s, lldb::DescriptionLevel description_level)
1221541Srgrimes{
1231541Srgrimes//    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1241541Srgrimes    if (description_level != lldb::eDescriptionLevelBrief)
1251541Srgrimes    {
1261541Srgrimes        s->Indent();
1271541Srgrimes        s->PutCString("Target\n");
1281541Srgrimes        s->IndentMore();
1291541Srgrimes            m_images.Dump(s);
1308429Sdg            m_breakpoint_list.Dump(s);
1318429Sdg            m_internal_breakpoint_list.Dump(s);
1328429Sdg        s->IndentLess();
1338429Sdg    }
1348429Sdg    else
1358429Sdg    {
1368429Sdg        Module *exe_module = GetExecutableModulePointer();
1378429Sdg        if (exe_module)
1388429Sdg            s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
1398429Sdg        else
1408429Sdg            s->PutCString ("No executable module.");
1418429Sdg    }
1428429Sdg}
1438429Sdg
1448429Sdgvoid
1458429SdgTarget::CleanupProcess ()
1468429Sdg{
1478429Sdg    // Do any cleanup of the target we need to do between process instances.
1481541Srgrimes    // NB It is better to do this before destroying the process in case the
1491541Srgrimes    // clean up needs some help from the process.
15012296Sphk    m_breakpoint_list.ClearAllBreakpointSites();
1511541Srgrimes    m_internal_breakpoint_list.ClearAllBreakpointSites();
1521541Srgrimes    // Disable watchpoints just on the debugger side.
1531541Srgrimes    Mutex::Locker locker;
1541541Srgrimes    this->GetWatchpointList().GetListMutex(locker);
1551541Srgrimes    DisableAllWatchpoints(false);
1561541Srgrimes    ClearAllWatchpointHitCounts();
1571541Srgrimes}
1581541Srgrimes
1591541Srgrimesvoid
1601541SrgrimesTarget::DeleteCurrentProcess ()
1611541Srgrimes{
1621541Srgrimes    if (m_process_sp.get())
1631541Srgrimes    {
1641541Srgrimes        m_section_load_history.Clear();
1651541Srgrimes        if (m_process_sp->IsAlive())
1661541Srgrimes            m_process_sp->Destroy();
1671541Srgrimes
1681541Srgrimes        m_process_sp->Finalize();
1691541Srgrimes
1701541Srgrimes        CleanupProcess ();
1711541Srgrimes
1721541Srgrimes        m_process_sp.reset();
1731541Srgrimes    }
1741541Srgrimes}
1751541Srgrimes
1761541Srgrimesconst lldb::ProcessSP &
1771541SrgrimesTarget::CreateProcess (Listener &listener, const char *plugin_name, const FileSpec *crash_file)
1781541Srgrimes{
1791541Srgrimes    DeleteCurrentProcess ();
1801541Srgrimes    m_process_sp = Process::FindPlugin(*this, plugin_name, listener, crash_file);
1811541Srgrimes    return m_process_sp;
1821541Srgrimes}
1831541Srgrimes
1841541Srgrimesconst lldb::ProcessSP &
1851541SrgrimesTarget::GetProcessSP () const
1861541Srgrimes{
1871541Srgrimes    return m_process_sp;
1881541Srgrimes}
1891541Srgrimes
1906283Swollmanvoid
1916283SwollmanTarget::Destroy()
1926283Swollman{
1936283Swollman    Mutex::Locker locker (m_mutex);
1946283Swollman    m_valid = false;
1956283Swollman    DeleteCurrentProcess ();
1966283Swollman    m_platform_sp.reset();
1971541Srgrimes    m_arch.Clear();
1981541Srgrimes    ClearModules(true);
1991541Srgrimes    m_section_load_history.Clear();
2001541Srgrimes    const bool notify = false;
2011541Srgrimes    m_breakpoint_list.RemoveAll(notify);
2021541Srgrimes    m_internal_breakpoint_list.RemoveAll(notify);
2031541Srgrimes    m_last_created_breakpoint.reset();
2041541Srgrimes    m_last_created_watchpoint.reset();
2051541Srgrimes    m_search_filter_sp.reset();
2061541Srgrimes    m_image_search_paths.Clear(notify);
2071541Srgrimes    m_persistent_variables.Clear();
2081541Srgrimes    m_stop_hooks.clear();
2091541Srgrimes    m_stop_hook_next_id = 0;
2101541Srgrimes    m_suppress_stop_hooks = false;
2111541Srgrimes}
2121541Srgrimes
2131541Srgrimes
2141541SrgrimesBreakpointList &
2151541SrgrimesTarget::GetBreakpointList(bool internal)
2161541Srgrimes{
2171541Srgrimes    if (internal)
2181541Srgrimes        return m_internal_breakpoint_list;
2191541Srgrimes    else
2201541Srgrimes        return m_breakpoint_list;
2211541Srgrimes}
2221541Srgrimes
2231541Srgrimesconst BreakpointList &
2241541SrgrimesTarget::GetBreakpointList(bool internal) const
2251541Srgrimes{
2261541Srgrimes    if (internal)
2271541Srgrimes        return m_internal_breakpoint_list;
2281541Srgrimes    else
2291541Srgrimes        return m_breakpoint_list;
2301541Srgrimes}
2311541Srgrimes
2321541SrgrimesBreakpointSP
2331541SrgrimesTarget::GetBreakpointByID (break_id_t break_id)
2341541Srgrimes{
2351541Srgrimes    BreakpointSP bp_sp;
2361541Srgrimes
2371541Srgrimes    if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
2386283Swollman        bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
2391541Srgrimes    else
2401541Srgrimes        bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
2411541Srgrimes
2421541Srgrimes    return bp_sp;
2431541Srgrimes}
2441541Srgrimes
2451541SrgrimesBreakpointSP
2461541SrgrimesTarget::CreateSourceRegexBreakpoint (const FileSpecList *containingModules,
2471541Srgrimes                                     const FileSpecList *source_file_spec_list,
2481541Srgrimes                                     RegularExpression &source_regex,
2491541Srgrimes                                     bool internal,
2501541Srgrimes                                     bool hardware)
2511541Srgrimes{
2521541Srgrimes    SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, source_file_spec_list));
2531541Srgrimes    BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex (NULL, source_regex));
2541541Srgrimes    return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
2551541Srgrimes}
2561541Srgrimes
2571541Srgrimes
2581541SrgrimesBreakpointSP
2591541SrgrimesTarget::CreateBreakpoint (const FileSpecList *containingModules,
2601541Srgrimes                          const FileSpec &file,
2611541Srgrimes                          uint32_t line_no,
2621541Srgrimes                          LazyBool check_inlines,
2631541Srgrimes                          LazyBool skip_prologue,
2641541Srgrimes                          bool internal,
2651541Srgrimes                          bool hardware)
2661541Srgrimes{
2671541Srgrimes    if (check_inlines == eLazyBoolCalculate)
2681541Srgrimes    {
26911150Swollman        const InlineStrategy inline_strategy = GetInlineStrategy();
2701549Srgrimes        switch (inline_strategy)
2711541Srgrimes        {
2721541Srgrimes            case eInlineBreakpointsNever:
2731541Srgrimes                check_inlines = eLazyBoolNo;
2741549Srgrimes                break;
2751541Srgrimes
2761541Srgrimes            case eInlineBreakpointsHeaders:
2771541Srgrimes                if (file.IsSourceImplementationFile())
2781541Srgrimes                    check_inlines = eLazyBoolNo;
2796283Swollman                else
2806283Swollman                    check_inlines = eLazyBoolYes;
2816283Swollman                break;
2826283Swollman
2832788Sdg            case eInlineBreakpointsAlways:
2842788Sdg                check_inlines = eLazyBoolYes;
2852788Sdg                break;
2861541Srgrimes        }
2876283Swollman    }
2886283Swollman    SearchFilterSP filter_sp;
2891541Srgrimes    if (check_inlines == eLazyBoolNo)
2901541Srgrimes    {
2911541Srgrimes        // Not checking for inlines, we are looking only for matching compile units
2921541Srgrimes        FileSpecList compile_unit_list;
2931541Srgrimes        compile_unit_list.Append (file);
2941541Srgrimes        filter_sp = GetSearchFilterForModuleAndCUList (containingModules, &compile_unit_list);
2951541Srgrimes    }
2961541Srgrimes    else
2971541Srgrimes    {
2981541Srgrimes        filter_sp = GetSearchFilterForModuleList (containingModules);
2991541Srgrimes    }
3001541Srgrimes    if (skip_prologue == eLazyBoolCalculate)
3011541Srgrimes        skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
3021541Srgrimes
3031541Srgrimes    BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL,
3041541Srgrimes                                                                     file,
3051541Srgrimes                                                                     line_no,
3061541Srgrimes                                                                     check_inlines,
3071541Srgrimes                                                                     skip_prologue));
3081541Srgrimes    return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
3091541Srgrimes}
3101541Srgrimes
3111541Srgrimes
3121541SrgrimesBreakpointSP
3131541SrgrimesTarget::CreateBreakpoint (lldb::addr_t addr, bool internal, bool hardware)
3143311Sphk{
3153311Sphk    Address so_addr;
3161541Srgrimes    // Attempt to resolve our load address if possible, though it is ok if
3171541Srgrimes    // it doesn't resolve to section/offset.
3181541Srgrimes
3191541Srgrimes    // Try and resolve as a load address if possible
3201541Srgrimes    GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
3211541Srgrimes    if (!so_addr.IsValid())
3221541Srgrimes    {
3231541Srgrimes        // The address didn't resolve, so just set this as an absolute address
3241541Srgrimes        so_addr.SetOffset (addr);
3251541Srgrimes    }
3261541Srgrimes    BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal, hardware));
3271541Srgrimes    return bp_sp;
3281541Srgrimes}
3291541Srgrimes
3301541SrgrimesBreakpointSP
3311541SrgrimesTarget::CreateBreakpoint (Address &addr, bool internal, bool hardware)
3321541Srgrimes{
3331541Srgrimes    SearchFilterSP filter_sp(new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
3341541Srgrimes    BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
3351541Srgrimes    return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, false);
3361541Srgrimes}
3371541Srgrimes
3381541SrgrimesBreakpointSP
3391541SrgrimesTarget::CreateBreakpoint (const FileSpecList *containingModules,
3401541Srgrimes                          const FileSpecList *containingSourceFiles,
34111150Swollman                          const char *func_name,
3421541Srgrimes                          uint32_t func_name_type_mask,
3431541Srgrimes                          LazyBool skip_prologue,
3441541Srgrimes                          bool internal,
3451541Srgrimes                          bool hardware)
3461541Srgrimes{
3471541Srgrimes    BreakpointSP bp_sp;
3481541Srgrimes    if (func_name)
3491541Srgrimes    {
3501541Srgrimes        SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
3511541Srgrimes
3521541Srgrimes        if (skip_prologue == eLazyBoolCalculate)
3531541Srgrimes            skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
3547634Solah
3557634Solah        BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
3567634Solah                                                                      func_name,
3577634Solah                                                                      func_name_type_mask,
3587634Solah                                                                      Breakpoint::Exact,
3597634Solah                                                                      skip_prologue));
3601541Srgrimes        bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
3611541Srgrimes    }
3621541Srgrimes    return bp_sp;
3638235Sdg}
36418795Sdg
3651541Srgrimeslldb::BreakpointSP
3661541SrgrimesTarget::CreateBreakpoint (const FileSpecList *containingModules,
3671541Srgrimes                          const FileSpecList *containingSourceFiles,
3681541Srgrimes                          const std::vector<std::string> &func_names,
3691541Srgrimes                          uint32_t func_name_type_mask,
3701541Srgrimes                          LazyBool skip_prologue,
3711541Srgrimes                          bool internal,
37215038Sphk                          bool hardware)
37315414Sache{
37415525Sfenner    BreakpointSP bp_sp;
37515414Sache    size_t num_names = func_names.size();
37615414Sache    if (num_names > 0)
37715038Sphk    {
37815038Sphk        SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
37915414Sache
38015038Sphk        if (skip_prologue == eLazyBoolCalculate)
38115414Sache            skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
3821541Srgrimes
38315038Sphk        BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
3841541Srgrimes                                                                      func_names,
3851541Srgrimes                                                                      func_name_type_mask,
3861541Srgrimes                                                                      skip_prologue));
3871541Srgrimes        bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
3881541Srgrimes    }
3898876Srgrimes    return bp_sp;
3901541Srgrimes}
3911541Srgrimes
3921541SrgrimesBreakpointSP
3931541SrgrimesTarget::CreateBreakpoint (const FileSpecList *containingModules,
3941541Srgrimes                          const FileSpecList *containingSourceFiles,
3951541Srgrimes                          const char *func_names[],
3961541Srgrimes                          size_t num_names,
3971541Srgrimes                          uint32_t func_name_type_mask,
3982788Sdg                          LazyBool skip_prologue,
3991541Srgrimes                          bool internal,
4001541Srgrimes                          bool hardware)
4011541Srgrimes{
4021541Srgrimes    BreakpointSP bp_sp;
4032788Sdg    if (num_names > 0)
4041541Srgrimes    {
4056283Swollman        SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
40618431Spst
40718787Spst        if (skip_prologue == eLazyBoolCalculate)
40818787Spst            skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
40918787Spst
41018787Spst        BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
41118787Spst                                                                      func_names,
41218787Spst                                                                      num_names,
41318787Spst                                                                      func_name_type_mask,
41418787Spst                                                                      skip_prologue));
41518787Spst        bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
41618787Spst    }
41718787Spst    return bp_sp;
41818431Spst}
41918787Spst
42018437SpstSearchFilterSP
42118787SpstTarget::GetSearchFilterForModule (const FileSpec *containingModule)
42218874Spst{
42318874Spst    SearchFilterSP filter_sp;
42418874Spst    if (containingModule != NULL)
42518874Spst    {
42618874Spst        // TODO: We should look into sharing module based search filters
42718874Spst        // across many breakpoints like we do for the simple target based one
42814268Sguido        filter_sp.reset (new SearchFilterByModule (shared_from_this(), *containingModule));
42918431Spst    }
4301541Srgrimes    else
4311541Srgrimes    {
4321541Srgrimes        if (m_search_filter_sp.get() == NULL)
4331541Srgrimes            m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
4341541Srgrimes        filter_sp = m_search_filter_sp;
4351541Srgrimes    }
4361541Srgrimes    return filter_sp;
4371541Srgrimes}
4381541Srgrimes
4391541SrgrimesSearchFilterSP
4401541SrgrimesTarget::GetSearchFilterForModuleList (const FileSpecList *containingModules)
4411541Srgrimes{
4421541Srgrimes    SearchFilterSP filter_sp;
4431541Srgrimes    if (containingModules && containingModules->GetSize() != 0)
4441541Srgrimes    {
4457684Sdg        // TODO: We should look into sharing module based search filters
4461541Srgrimes        // across many breakpoints like we do for the simple target based one
4471541Srgrimes        filter_sp.reset (new SearchFilterByModuleList (shared_from_this(), *containingModules));
4481541Srgrimes    }
4491541Srgrimes    else
4501541Srgrimes    {
4516283Swollman        if (m_search_filter_sp.get() == NULL)
4521541Srgrimes            m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
4536283Swollman        filter_sp = m_search_filter_sp;
4541541Srgrimes    }
4551541Srgrimes    return filter_sp;
4561541Srgrimes}
4571541Srgrimes
4581541SrgrimesSearchFilterSP
4591541SrgrimesTarget::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules,
4601541Srgrimes                                           const FileSpecList *containingSourceFiles)
4611541Srgrimes{
4621541Srgrimes    if (containingSourceFiles == NULL || containingSourceFiles->GetSize() == 0)
4631541Srgrimes        return GetSearchFilterForModuleList(containingModules);
4641541Srgrimes
46518278Spst    SearchFilterSP filter_sp;
46618278Spst    if (containingModules == NULL)
4671541Srgrimes    {
4681541Srgrimes        // We could make a special "CU List only SearchFilter".  Better yet was if these could be composable,
4691541Srgrimes        // but that will take a little reworking.
4701541Srgrimes
4711541Srgrimes        filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), FileSpecList(), *containingSourceFiles));
47214181Sdg    }
47314181Sdg    else
4741541Srgrimes    {
4758876Srgrimes        filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), *containingModules, *containingSourceFiles));
4761541Srgrimes    }
4771541Srgrimes    return filter_sp;
4781541Srgrimes}
4791541Srgrimes
4801541SrgrimesBreakpointSP
4811541SrgrimesTarget::CreateFuncRegexBreakpoint (const FileSpecList *containingModules,
4821541Srgrimes                                   const FileSpecList *containingSourceFiles,
4831541Srgrimes                                   RegularExpression &func_regex,
4841541Srgrimes                                   LazyBool skip_prologue,
4851541Srgrimes                                   bool internal,
4861541Srgrimes                                   bool hardware)
4871541Srgrimes{
4886283Swollman    SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
4896283Swollman    BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
4906283Swollman                                                                 func_regex,
4911541Srgrimes                                                                 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
4921541Srgrimes
4931541Srgrimes    return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
4946283Swollman}
4956283Swollman
4966283Swollmanlldb::BreakpointSP
4976283SwollmanTarget::CreateExceptionBreakpoint (enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal)
4986283Swollman{
4996283Swollman    return LanguageRuntime::CreateExceptionBreakpoint (*this, language, catch_bp, throw_bp, internal);
5006283Swollman}
5016283Swollman
5026283SwollmanBreakpointSP
5036283SwollmanTarget::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal, bool request_hardware, bool resolve_indirect_symbols)
5041541Srgrimes{
5051541Srgrimes    BreakpointSP bp_sp;
5061541Srgrimes    if (filter_sp && resolver_sp)
5071541Srgrimes    {
5088876Srgrimes        bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp, request_hardware, resolve_indirect_symbols));
5091541Srgrimes        resolver_sp->SetBreakpoint (bp_sp.get());
5106283Swollman
5116283Swollman        if (internal)
5126283Swollman            m_internal_breakpoint_list.Add (bp_sp, false);
5131541Srgrimes        else
5146283Swollman            m_breakpoint_list.Add (bp_sp, true);
5156283Swollman
5161541Srgrimes        Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
5176283Swollman        if (log)
5181541Srgrimes        {
5191541Srgrimes            StreamString s;
5201541Srgrimes            bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5211541Srgrimes            log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
5221541Srgrimes        }
52314753Swollman
52414753Swollman        bp_sp->ResolveBreakpoint();
5251541Srgrimes    }
5261541Srgrimes
5271541Srgrimes    if (!internal && bp_sp)
5281541Srgrimes    {
5296283Swollman        m_last_created_breakpoint = bp_sp;
5306283Swollman    }
5316283Swollman
5321541Srgrimes    return bp_sp;
5331541Srgrimes}
5341541Srgrimes
5351541Srgrimesbool
5361541SrgrimesTarget::ProcessIsValid()
5371541Srgrimes{
5381541Srgrimes    return (m_process_sp && m_process_sp->IsAlive());
5391541Srgrimes}
5401541Srgrimes
5411541Srgrimesstatic bool
5421541SrgrimesCheckIfWatchpointsExhausted(Target *target, Error &error)
5431541Srgrimes{
5441541Srgrimes    uint32_t num_supported_hardware_watchpoints;
5451541Srgrimes    Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints);
5461541Srgrimes    if (rc.Success())
5471541Srgrimes    {
5481541Srgrimes        uint32_t num_current_watchpoints = target->GetWatchpointList().GetSize();
5491541Srgrimes        if (num_current_watchpoints >= num_supported_hardware_watchpoints)
5501541Srgrimes            error.SetErrorStringWithFormat("number of supported hardware watchpoints (%u) has been reached",
5511541Srgrimes                                           num_supported_hardware_watchpoints);
5521541Srgrimes    }
5531541Srgrimes    return false;
5541541Srgrimes}
5551541Srgrimes
5561541Srgrimes// See also Watchpoint::SetWatchpointType(uint32_t type) and
5571541Srgrimes// the OptionGroupWatchpoint::WatchType enum type.
5581541SrgrimesWatchpointSP
5591541SrgrimesTarget::CreateWatchpoint(lldb::addr_t addr, size_t size, const ClangASTType *type, uint32_t kind, Error &error)
5601541Srgrimes{
5611541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
5621541Srgrimes    if (log)
5631541Srgrimes        log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64 " type = %u)\n",
5641541Srgrimes                    __FUNCTION__, addr, (uint64_t)size, kind);
5651541Srgrimes
5661541Srgrimes    WatchpointSP wp_sp;
5671541Srgrimes    if (!ProcessIsValid())
5681541Srgrimes    {
5691541Srgrimes        error.SetErrorString("process is not alive");
5701541Srgrimes        return wp_sp;
5711541Srgrimes    }
5721541Srgrimes
5731541Srgrimes    if (addr == LLDB_INVALID_ADDRESS || size == 0)
5741541Srgrimes    {
5757634Solah        if (size == 0)
5761541Srgrimes            error.SetErrorString("cannot set a watchpoint with watch_size of 0");
5771541Srgrimes        else
5781541Srgrimes            error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
5798429Sdg        return wp_sp;
5807417Sdg    }
5817417Sdg
5827417Sdg    if (!LLDB_WATCH_TYPE_IS_VALID(kind))
5837417Sdg    {
5847417Sdg        error.SetErrorStringWithFormat ("invalid watchpoint type: %d", kind);
5857737Sdg    }
5867417Sdg
5877417Sdg    // Currently we only support one watchpoint per address, with total number
5887417Sdg    // of watchpoints limited by the hardware which the inferior is running on.
5897417Sdg
5907417Sdg    // Grab the list mutex while doing operations.
5918429Sdg    const bool notify = false;   // Don't notify about all the state changes we do on creating the watchpoint.
5928429Sdg    Mutex::Locker locker;
5938429Sdg    this->GetWatchpointList().GetListMutex(locker);
5941541Srgrimes    WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
5951541Srgrimes    if (matched_sp)
5961541Srgrimes    {
5971541Srgrimes        size_t old_size = matched_sp->GetByteSize();
5981541Srgrimes        uint32_t old_type =
5991541Srgrimes            (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
6001541Srgrimes            (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
6011541Srgrimes        // Return the existing watchpoint if both size and type match.
6021541Srgrimes        if (size == old_size && kind == old_type)
6031541Srgrimes        {
6041541Srgrimes            wp_sp = matched_sp;
6051541Srgrimes            wp_sp->SetEnabled(false, notify);
6061541Srgrimes        }
6071541Srgrimes        else
6081541Srgrimes        {
60927135Sjdp            // Nil the matched watchpoint; we will be creating a new one.
6101541Srgrimes            m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
6111541Srgrimes            m_watchpoint_list.Remove(matched_sp->GetID(), true);
6121541Srgrimes        }
6131541Srgrimes    }
6141541Srgrimes
6151541Srgrimes    if (!wp_sp)
6161541Srgrimes    {
6171541Srgrimes        wp_sp.reset(new Watchpoint(*this, addr, size, type));
6181541Srgrimes        wp_sp->SetWatchpointType(kind, notify);
6191541Srgrimes        m_watchpoint_list.Add (wp_sp, true);
6201541Srgrimes    }
6211541Srgrimes
6221541Srgrimes    error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
6231541Srgrimes    if (log)
6241541Srgrimes        log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
6251541Srgrimes                    __FUNCTION__,
6261541Srgrimes                    error.Success() ? "succeeded" : "failed",
6271541Srgrimes                    wp_sp->GetID());
6281541Srgrimes
6291541Srgrimes    if (error.Fail())
6301541Srgrimes    {
6311541Srgrimes        // Enabling the watchpoint on the device side failed.
6321541Srgrimes        // Remove the said watchpoint from the list maintained by the target instance.
6331541Srgrimes        m_watchpoint_list.Remove (wp_sp->GetID(), true);
6341541Srgrimes        // See if we could provide more helpful error message.
6351541Srgrimes        if (!CheckIfWatchpointsExhausted(this, error))
6361541Srgrimes        {
6371541Srgrimes            if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
6381541Srgrimes                error.SetErrorStringWithFormat("watch size of %zu is not supported", size);
6391541Srgrimes        }
6401541Srgrimes        wp_sp.reset();
6411541Srgrimes    }
6421541Srgrimes    else
6431565Sdg        m_last_created_watchpoint = wp_sp;
6441541Srgrimes    return wp_sp;
64528270Swollman}
64628270Swollman
64728270Swollmanvoid
6481541SrgrimesTarget::RemoveAllBreakpoints (bool internal_also)
6491541Srgrimes{
6501541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
6511541Srgrimes    if (log)
6521541Srgrimes        log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
6531541Srgrimes
6541541Srgrimes    m_breakpoint_list.RemoveAll (true);
6551541Srgrimes    if (internal_also)
6561541Srgrimes        m_internal_breakpoint_list.RemoveAll (false);
65728270Swollman
6581541Srgrimes    m_last_created_breakpoint.reset();
65928270Swollman}
6601541Srgrimes
6611541Srgrimesvoid
66228270SwollmanTarget::DisableAllBreakpoints (bool internal_also)
6631541Srgrimes{
6641541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
6651541Srgrimes    if (log)
6661541Srgrimes        log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
6671541Srgrimes
6681541Srgrimes    m_breakpoint_list.SetEnabledAll (false);
6696283Swollman    if (internal_also)
6706283Swollman        m_internal_breakpoint_list.SetEnabledAll (false);
6716283Swollman}
6726283Swollman
67314181Sdgvoid
6741541SrgrimesTarget::EnableAllBreakpoints (bool internal_also)
6751541Srgrimes{
6761541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
6771541Srgrimes    if (log)
67811150Swollman        log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
6791541Srgrimes
6801541Srgrimes    m_breakpoint_list.SetEnabledAll (true);
6811541Srgrimes    if (internal_also)
6826283Swollman        m_internal_breakpoint_list.SetEnabledAll (true);
6836283Swollman}
6846283Swollman
6856283Swollmanbool
6866283SwollmanTarget::RemoveBreakpointByID (break_id_t break_id)
6876283Swollman{
6886283Swollman    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
6896283Swollman    if (log)
6906283Swollman        log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
6916283Swollman
6928876Srgrimes    if (DisableBreakpointByID (break_id))
6936283Swollman    {
6946283Swollman        if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
6956283Swollman            m_internal_breakpoint_list.Remove(break_id, false);
6966283Swollman        else
6976283Swollman        {
6986283Swollman            if (m_last_created_breakpoint)
6996283Swollman            {
7006283Swollman                if (m_last_created_breakpoint->GetID() == break_id)
7016283Swollman                    m_last_created_breakpoint.reset();
7026283Swollman            }
7036283Swollman            m_breakpoint_list.Remove(break_id, true);
7046283Swollman        }
7056283Swollman        return true;
7066283Swollman    }
7076283Swollman    return false;
7086283Swollman}
7096283Swollman
7106283Swollmanbool
7116283SwollmanTarget::DisableBreakpointByID (break_id_t break_id)
7126283Swollman{
7136283Swollman    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
7146283Swollman    if (log)
7156283Swollman        log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
7166283Swollman
7176283Swollman    BreakpointSP bp_sp;
7186283Swollman
7196283Swollman    if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
72013779Solah        bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
72113779Solah    else
72213779Solah        bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
72313779Solah    if (bp_sp)
72413779Solah    {
72513779Solah        bp_sp->SetEnabled (false);
72613779Solah        return true;
7276283Swollman    }
7286283Swollman    return false;
72918280Spst}
7306283Swollman
7316283Swollmanbool
7326283SwollmanTarget::EnableBreakpointByID (break_id_t break_id)
7336283Swollman{
7346283Swollman    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
7356283Swollman    if (log)
7366283Swollman        log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
7376283Swollman                     __FUNCTION__,
7386283Swollman                     break_id,
7396283Swollman                     LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
7406283Swollman
7416283Swollman    BreakpointSP bp_sp;
7426283Swollman
7436283Swollman    if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
7446283Swollman        bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
7456283Swollman    else
7461541Srgrimes        bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
7471541Srgrimes
74818280Spst    if (bp_sp)
7491541Srgrimes    {
7501541Srgrimes        bp_sp->SetEnabled (true);
7511541Srgrimes        return true;
7521541Srgrimes    }
7531541Srgrimes    return false;
7541541Srgrimes}
75518787Spst
75618787Spst// The flag 'end_to_end', default to true, signifies that the operation is
7571541Srgrimes// performed end to end, for both the debugger and the debuggee.
7581541Srgrimes
7591541Srgrimes// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
7601541Srgrimes// to end operations.
7611541Srgrimesbool
7621541SrgrimesTarget::RemoveAllWatchpoints (bool end_to_end)
7631541Srgrimes{
7641541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
7651541Srgrimes    if (log)
7661541Srgrimes        log->Printf ("Target::%s\n", __FUNCTION__);
7671541Srgrimes
76818787Spst    if (!end_to_end) {
7691541Srgrimes        m_watchpoint_list.RemoveAll(true);
7706283Swollman        return true;
7716283Swollman    }
7726283Swollman
7736283Swollman    // Otherwise, it's an end to end operation.
7746283Swollman
7751541Srgrimes    if (!ProcessIsValid())
7761541Srgrimes        return false;
7776283Swollman
7786283Swollman    size_t num_watchpoints = m_watchpoint_list.GetSize();
7796283Swollman    for (size_t i = 0; i < num_watchpoints; ++i)
7806283Swollman    {
7816283Swollman        WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
7826283Swollman        if (!wp_sp)
7836283Swollman            return false;
7846283Swollman
7856283Swollman        Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
7866283Swollman        if (rc.Fail())
7876283Swollman            return false;
7886283Swollman    }
7896283Swollman    m_watchpoint_list.RemoveAll (true);
7906283Swollman    m_last_created_watchpoint.reset();
7911541Srgrimes    return true; // Success!
7921541Srgrimes}
7931541Srgrimes
7941541Srgrimes// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
7951541Srgrimes// end operations.
79618787Spstbool
79718787SpstTarget::DisableAllWatchpoints (bool end_to_end)
7981541Srgrimes{
7991541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
8006283Swollman    if (log)
8016283Swollman        log->Printf ("Target::%s\n", __FUNCTION__);
8026283Swollman
8031541Srgrimes    if (!end_to_end) {
8041541Srgrimes        m_watchpoint_list.SetEnabledAll(false);
80512047Solah        return true;
8066283Swollman    }
8076283Swollman
8086283Swollman    // Otherwise, it's an end to end operation.
8096283Swollman
8106283Swollman    if (!ProcessIsValid())
8116283Swollman        return false;
8126283Swollman
8136283Swollman    size_t num_watchpoints = m_watchpoint_list.GetSize();
8146283Swollman    for (size_t i = 0; i < num_watchpoints; ++i)
8156283Swollman    {
8166283Swollman        WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
8176283Swollman        if (!wp_sp)
8186283Swollman            return false;
8196283Swollman
82012047Solah        Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
82112047Solah        if (rc.Fail())
82212047Solah            return false;
82312047Solah    }
82412047Solah    return true; // Success!
82512047Solah}
82612047Solah
82712047Solah// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
8286283Swollman// end operations.
8296283Swollmanbool
8306283SwollmanTarget::EnableAllWatchpoints (bool end_to_end)
8318876Srgrimes{
8326283Swollman    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
8336283Swollman    if (log)
8346283Swollman        log->Printf ("Target::%s\n", __FUNCTION__);
8356283Swollman
8366283Swollman    if (!end_to_end) {
8376283Swollman        m_watchpoint_list.SetEnabledAll(true);
8386283Swollman        return true;
8396283Swollman    }
8406283Swollman
8416283Swollman    // Otherwise, it's an end to end operation.
8426283Swollman
8436283Swollman    if (!ProcessIsValid())
8446283Swollman        return false;
8456283Swollman
8466283Swollman    size_t num_watchpoints = m_watchpoint_list.GetSize();
8476283Swollman    for (size_t i = 0; i < num_watchpoints; ++i)
8486283Swollman    {
8496283Swollman        WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
8506283Swollman        if (!wp_sp)
8516283Swollman            return false;
85218278Spst
8536283Swollman        Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
85418278Spst        if (rc.Fail())
85518278Spst            return false;
8566283Swollman    }
8576283Swollman    return true; // Success!
8586283Swollman}
8596283Swollman
8608876Srgrimes// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
8616283Swollmanbool
8626283SwollmanTarget::ClearAllWatchpointHitCounts ()
8636283Swollman{
8646283Swollman    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
8656283Swollman    if (log)
8666283Swollman        log->Printf ("Target::%s\n", __FUNCTION__);
8678876Srgrimes
8686283Swollman    size_t num_watchpoints = m_watchpoint_list.GetSize();
8696283Swollman    for (size_t i = 0; i < num_watchpoints; ++i)
8706283Swollman    {
8716283Swollman        WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
8728876Srgrimes        if (!wp_sp)
8736283Swollman            return false;
8746283Swollman
8756283Swollman        wp_sp->ResetHitCount();
8766283Swollman    }
8776283Swollman    return true; // Success!
8786283Swollman}
8796283Swollman
88018278Spst// Assumption: Caller holds the list mutex lock for m_watchpoint_list
8816283Swollman// during these operations.
88218278Spstbool
88318278SpstTarget::IgnoreAllWatchpoints (uint32_t ignore_count)
8846283Swollman{
8856283Swollman    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
8866283Swollman    if (log)
8876283Swollman        log->Printf ("Target::%s\n", __FUNCTION__);
8886283Swollman
8896283Swollman    if (!ProcessIsValid())
8906283Swollman        return false;
8916283Swollman
8928876Srgrimes    size_t num_watchpoints = m_watchpoint_list.GetSize();
8931541Srgrimes    for (size_t i = 0; i < num_watchpoints; ++i)
8941541Srgrimes    {
8951541Srgrimes        WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
8961541Srgrimes        if (!wp_sp)
8971541Srgrimes            return false;
8981541Srgrimes
8991541Srgrimes        wp_sp->SetIgnoreCount(ignore_count);
9001541Srgrimes    }
9011541Srgrimes    return true; // Success!
9021541Srgrimes}
9031541Srgrimes
9041541Srgrimes// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
9051541Srgrimesbool
9061541SrgrimesTarget::DisableWatchpointByID (lldb::watch_id_t watch_id)
9071541Srgrimes{
9081541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
9091541Srgrimes    if (log)
9101541Srgrimes        log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
9116283Swollman
9126283Swollman    if (!ProcessIsValid())
9136283Swollman        return false;
9146283Swollman
9156283Swollman    WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
9166283Swollman    if (wp_sp)
9178876Srgrimes    {
9186283Swollman        Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
9196283Swollman        if (rc.Success())
9201541Srgrimes            return true;
9216283Swollman
9226283Swollman        // Else, fallthrough.
9236283Swollman    }
9246283Swollman    return false;
9256283Swollman}
9266283Swollman
9276283Swollman// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
9286283Swollmanbool
9296283SwollmanTarget::EnableWatchpointByID (lldb::watch_id_t watch_id)
9306283Swollman{
9316283Swollman    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
9326283Swollman    if (log)
9338876Srgrimes        log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
9348876Srgrimes
9356283Swollman    if (!ProcessIsValid())
9366283Swollman        return false;
9376283Swollman
9386283Swollman    WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
9396283Swollman    if (wp_sp)
9406283Swollman    {
9416283Swollman        Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
9426283Swollman        if (rc.Success())
9436283Swollman            return true;
9446283Swollman
9456283Swollman        // Else, fallthrough.
9466283Swollman    }
9476283Swollman    return false;
9486283Swollman}
9496283Swollman
9506283Swollman// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
9511541Srgrimesbool
9521541SrgrimesTarget::RemoveWatchpointByID (lldb::watch_id_t watch_id)
9531541Srgrimes{
9541541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
9551541Srgrimes    if (log)
9566283Swollman        log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
9578876Srgrimes
9581541Srgrimes    WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
9591541Srgrimes    if (watch_to_remove_sp == m_last_created_watchpoint)
9606283Swollman        m_last_created_watchpoint.reset();
9611541Srgrimes
9621541Srgrimes    if (DisableWatchpointByID (watch_id))
9631541Srgrimes    {
9646283Swollman        m_watchpoint_list.Remove(watch_id, true);
9656283Swollman        return true;
9661541Srgrimes    }
9671541Srgrimes    return false;
9681541Srgrimes}
9691541Srgrimes
9701541Srgrimes// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
9711541Srgrimesbool
9721541SrgrimesTarget::IgnoreWatchpointByID (lldb::watch_id_t watch_id, uint32_t ignore_count)
9731541Srgrimes{
9741541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
9751541Srgrimes    if (log)
9761541Srgrimes        log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
9771541Srgrimes
9781541Srgrimes    if (!ProcessIsValid())
9791541Srgrimes        return false;
9801541Srgrimes
9811541Srgrimes    WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
9821541Srgrimes    if (wp_sp)
9831541Srgrimes    {
9841541Srgrimes        wp_sp->SetIgnoreCount(ignore_count);
9851541Srgrimes        return true;
9861541Srgrimes    }
9871541Srgrimes    return false;
9881541Srgrimes}
9896283Swollman
9906283SwollmanModuleSP
9916283SwollmanTarget::GetExecutableModule ()
9926283Swollman{
9936283Swollman    return m_images.GetModuleAtIndex(0);
9946283Swollman}
9956283Swollman
9966283SwollmanModule*
9976283SwollmanTarget::GetExecutableModulePointer ()
9986283Swollman{
9996283Swollman    return m_images.GetModulePointerAtIndex(0);
10001541Srgrimes}
10011541Srgrimes
10021541Srgrimesstatic void
10031541SrgrimesLoadScriptingResourceForModule (const ModuleSP &module_sp, Target *target)
10041541Srgrimes{
10058876Srgrimes    Error error;
10061541Srgrimes    StreamString feedback_stream;
10071541Srgrimes    if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error, &feedback_stream))
10081541Srgrimes    {
10091541Srgrimes        if (error.AsCString())
10101541Srgrimes            target->GetDebugger().GetErrorFile()->Printf("unable to load scripting data for module %s - error reported was %s\n",
10116480Swollman                                                           module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
10126480Swollman                                                           error.AsCString());
10136480Swollman        if (feedback_stream.GetSize())
10146480Swollman            target->GetDebugger().GetErrorFile()->Printf("%s\n",
10156480Swollman                                                           feedback_stream.GetData());
10161541Srgrimes    }
10176480Swollman}
10186480Swollman
10196480Swollmanvoid
10201541SrgrimesTarget::ClearModules(bool delete_locations)
10216480Swollman{
10226480Swollman    ModulesDidUnload (m_images, delete_locations);
10236480Swollman    m_section_load_history.Clear();
10246480Swollman    m_images.Clear();
10256480Swollman    m_scratch_ast_context_ap.reset();
10266480Swollman    m_scratch_ast_source_ap.reset();
10276480Swollman    m_ast_importer_ap.reset();
10286480Swollman}
10296480Swollman
10306480Swollmanvoid
10311541SrgrimesTarget::DidExec ()
10321541Srgrimes{
10331541Srgrimes    // When a process exec's we need to know about it so we can do some cleanup.
10341541Srgrimes    m_breakpoint_list.RemoveInvalidLocations(m_arch);
10351541Srgrimes    m_internal_breakpoint_list.RemoveInvalidLocations(m_arch);
10361541Srgrimes}
10371541Srgrimes
10381541Srgrimesvoid
10391541SrgrimesTarget::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
10401541Srgrimes{
10411541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
10421541Srgrimes    ClearModules(false);
10431541Srgrimes
10441541Srgrimes    if (executable_sp.get())
10451541Srgrimes    {
10461541Srgrimes        Timer scoped_timer (__PRETTY_FUNCTION__,
10471541Srgrimes                            "Target::SetExecutableModule (executable = '%s')",
10481541Srgrimes                            executable_sp->GetFileSpec().GetPath().c_str());
10491541Srgrimes
10501541Srgrimes        m_images.Append(executable_sp); // The first image is our exectuable file
10511541Srgrimes
10521541Srgrimes        // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
10531541Srgrimes        if (!m_arch.IsValid())
10541541Srgrimes        {
10551541Srgrimes            m_arch = executable_sp->GetArchitecture();
10561541Srgrimes            if (log)
10571541Srgrimes              log->Printf ("Target::SetExecutableModule setting architecture to %s (%s) based on executable file", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
10581541Srgrimes        }
10591541Srgrimes
10601541Srgrimes        FileSpecList dependent_files;
10611541Srgrimes        ObjectFile *executable_objfile = executable_sp->GetObjectFile();
10621541Srgrimes
10631541Srgrimes        if (executable_objfile && get_dependent_files)
10641541Srgrimes        {
10651541Srgrimes            executable_objfile->GetDependentModules(dependent_files);
10661541Srgrimes            for (uint32_t i=0; i<dependent_files.GetSize(); i++)
10671541Srgrimes            {
10681541Srgrimes                FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
10691541Srgrimes                FileSpec platform_dependent_file_spec;
10701541Srgrimes                if (m_platform_sp)
10711541Srgrimes                    m_platform_sp->GetFileWithUUID (dependent_file_spec, NULL, platform_dependent_file_spec);
10721541Srgrimes                else
10731541Srgrimes                    platform_dependent_file_spec = dependent_file_spec;
10741541Srgrimes
10751541Srgrimes                ModuleSpec module_spec (platform_dependent_file_spec, m_arch);
10761541Srgrimes                ModuleSP image_module_sp(GetSharedModule (module_spec));
10771541Srgrimes                if (image_module_sp.get())
10781541Srgrimes                {
10791541Srgrimes                    ObjectFile *objfile = image_module_sp->GetObjectFile();
10801541Srgrimes                    if (objfile)
10811541Srgrimes                        objfile->GetDependentModules(dependent_files);
10821541Srgrimes                }
10831541Srgrimes            }
10841541Srgrimes        }
10851541Srgrimes    }
10861541Srgrimes}
10871541Srgrimes
10881541Srgrimes
10891541Srgrimesbool
10901541SrgrimesTarget::SetArchitecture (const ArchSpec &arch_spec)
10911541Srgrimes{
10921541Srgrimes    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
10931541Srgrimes    if (m_arch.IsCompatibleMatch(arch_spec) || !m_arch.IsValid())
10941541Srgrimes    {
10951541Srgrimes        // If we haven't got a valid arch spec, or the architectures are
10961541Srgrimes        // compatible, so just update the architecture. Architectures can be
10971541Srgrimes        // equal, yet the triple OS and vendor might change, so we need to do
10981541Srgrimes        // the assignment here just in case.
10991541Srgrimes        m_arch = arch_spec;
11001541Srgrimes        if (log)
11016283Swollman            log->Printf ("Target::SetArchitecture setting architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
11026283Swollman        return true;
11031541Srgrimes    }
11048876Srgrimes    else
11056283Swollman    {
11061541Srgrimes        // If we have an executable file, try to reset the executable to the desired architecture
11076283Swollman        if (log)
11081541Srgrimes          log->Printf ("Target::SetArchitecture changing architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
11091541Srgrimes        m_arch = arch_spec;
11101541Srgrimes        ModuleSP executable_sp = GetExecutableModule ();
11111541Srgrimes
11121541Srgrimes        ClearModules(true);
11131541Srgrimes        // Need to do something about unsetting breakpoints.
11141541Srgrimes
11151541Srgrimes        if (executable_sp)
11161541Srgrimes        {
11171541Srgrimes            if (log)
11181541Srgrimes              log->Printf("Target::SetArchitecture Trying to select executable file architecture %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
11191541Srgrimes            ModuleSpec module_spec (executable_sp->GetFileSpec(), arch_spec);
11201541Srgrimes            Error error = ModuleList::GetSharedModule (module_spec,
11211541Srgrimes                                                       executable_sp,
11221541Srgrimes                                                       &GetExecutableSearchPaths(),
11231541Srgrimes                                                       NULL,
11241541Srgrimes                                                       NULL);
11251541Srgrimes
11261541Srgrimes            if (!error.Fail() && executable_sp)
11271541Srgrimes            {
11281541Srgrimes                SetExecutableModule (executable_sp, true);
11291541Srgrimes                return true;
11301541Srgrimes            }
11311541Srgrimes        }
11321541Srgrimes    }
11331541Srgrimes    return false;
11341541Srgrimes}
11351541Srgrimes
11361541Srgrimesvoid
11371541SrgrimesTarget::WillClearList (const ModuleList& module_list)
11381541Srgrimes{
11391541Srgrimes}
11401541Srgrimes
11411541Srgrimesvoid
11421541SrgrimesTarget::ModuleAdded (const ModuleList& module_list, const ModuleSP &module_sp)
11431541Srgrimes{
11441541Srgrimes    // A module is being added to this target for the first time
11451541Srgrimes    ModuleList my_module_list;
11461541Srgrimes    my_module_list.Append(module_sp);
11471541Srgrimes    LoadScriptingResourceForModule(module_sp, this);
11481541Srgrimes    ModulesDidLoad (my_module_list);
11491541Srgrimes}
11501541Srgrimes
11511541Srgrimesvoid
11521541SrgrimesTarget::ModuleRemoved (const ModuleList& module_list, const ModuleSP &module_sp)
11531541Srgrimes{
11546283Swollman    // A module is being added to this target for the first time
11556283Swollman    ModuleList my_module_list;
11566283Swollman    my_module_list.Append(module_sp);
11576283Swollman    ModulesDidUnload (my_module_list, false);
11586283Swollman}
11596283Swollman
11606283Swollmanvoid
11616283SwollmanTarget::ModuleUpdated (const ModuleList& module_list, const ModuleSP &old_module_sp, const ModuleSP &new_module_sp)
11626283Swollman{
11636283Swollman    // A module is replacing an already added module
11646283Swollman    m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
11658876Srgrimes}
11661541Srgrimes
11671541Srgrimesvoid
11681541SrgrimesTarget::ModulesDidLoad (ModuleList &module_list)
11691541Srgrimes{
11701541Srgrimes    if (module_list.GetSize())
11711541Srgrimes    {
11721541Srgrimes        m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
11731541Srgrimes        if (m_process_sp)
11741541Srgrimes        {
11751541Srgrimes            SystemRuntime *sys_runtime = m_process_sp->GetSystemRuntime();
11761541Srgrimes            if (sys_runtime)
11771541Srgrimes            {
11781541Srgrimes                sys_runtime->ModulesDidLoad (module_list);
11791541Srgrimes            }
11806283Swollman        }
11811541Srgrimes        // TODO: make event data that packages up the module_list
11821541Srgrimes        BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
11831541Srgrimes    }
11841541Srgrimes}
11851541Srgrimes
11861541Srgrimesvoid
11871541SrgrimesTarget::SymbolsDidLoad (ModuleList &module_list)
11881541Srgrimes{
11896283Swollman    if (module_list.GetSize())
11906283Swollman    {
11916283Swollman        if (m_process_sp)
11926283Swollman        {
11936283Swollman            LanguageRuntime* runtime = m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
11946283Swollman            if (runtime)
11956283Swollman            {
11966283Swollman                ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime*)runtime;
11976283Swollman                objc_runtime->SymbolsDidLoad(module_list);
11986283Swollman            }
11998876Srgrimes        }
12006283Swollman
12016283Swollman        m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
12026283Swollman        BroadcastEvent(eBroadcastBitSymbolsLoaded, NULL);
12036283Swollman    }
12046283Swollman}
12056283Swollman
120618278Spstvoid
12076283SwollmanTarget::ModulesDidUnload (ModuleList &module_list, bool delete_locations)
120818278Spst{
120918278Spst    if (module_list.GetSize())
12108876Srgrimes    {
12116283Swollman        m_breakpoint_list.UpdateBreakpoints (module_list, false, delete_locations);
12126283Swollman        // TODO: make event data that packages up the module_list
12136283Swollman        BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
12146283Swollman    }
12156283Swollman}
12166283Swollman
12171541Srgrimesbool
12181541SrgrimesTarget::ModuleIsExcludedForNonModuleSpecificSearches (const FileSpec &module_file_spec)
12191541Srgrimes{
12201541Srgrimes    if (GetBreakpointsConsultPlatformAvoidList())
12211541Srgrimes    {
12221541Srgrimes        ModuleList matchingModules;
12231541Srgrimes        ModuleSpec module_spec (module_file_spec);
12241541Srgrimes        size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
12251541Srgrimes
12261541Srgrimes        // If there is more than one module for this file spec, only return true if ALL the modules are on the
12271541Srgrimes        // black list.
12281541Srgrimes        if (num_modules > 0)
12291541Srgrimes        {
12301541Srgrimes            for (size_t i  = 0; i < num_modules; i++)
12311541Srgrimes            {
12321541Srgrimes                if (!ModuleIsExcludedForNonModuleSpecificSearches (matchingModules.GetModuleAtIndex(i)))
12331541Srgrimes                    return false;
12341541Srgrimes            }
12351541Srgrimes            return true;
12361541Srgrimes        }
12371541Srgrimes    }
12381541Srgrimes    return false;
12391541Srgrimes}
12401541Srgrimes
12411541Srgrimesbool
12421541SrgrimesTarget::ModuleIsExcludedForNonModuleSpecificSearches (const lldb::ModuleSP &module_sp)
12431541Srgrimes{
12441541Srgrimes    if (GetBreakpointsConsultPlatformAvoidList())
12451541Srgrimes    {
12461541Srgrimes        if (m_platform_sp)
12471541Srgrimes            return m_platform_sp->ModuleIsExcludedForNonModuleSpecificSearches (*this, module_sp);
12481541Srgrimes    }
12491541Srgrimes    return false;
12501541Srgrimes}
12511541Srgrimes
12521541Srgrimessize_t
12531541SrgrimesTarget::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
12541541Srgrimes{
12551541Srgrimes    SectionSP section_sp (addr.GetSection());
12561541Srgrimes    if (section_sp)
12571541Srgrimes    {
12588876Srgrimes        // If the contents of this section are encrypted, the on-disk file is unusuable.  Read only from live memory.
12591541Srgrimes        if (section_sp->IsEncrypted())
12601541Srgrimes        {
12611541Srgrimes            error.SetErrorString("section is encrypted");
12621541Srgrimes            return 0;
12631541Srgrimes        }
12641541Srgrimes        ModuleSP module_sp (section_sp->GetModule());
12651541Srgrimes        if (module_sp)
12661541Srgrimes        {
12671541Srgrimes            ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
12681541Srgrimes            if (objfile)
12691541Srgrimes            {
12701541Srgrimes                size_t bytes_read = objfile->ReadSectionData (section_sp.get(),
12711541Srgrimes                                                              addr.GetOffset(),
12721541Srgrimes                                                              dst,
12731541Srgrimes                                                              dst_len);
12741541Srgrimes                if (bytes_read > 0)
12751541Srgrimes                    return bytes_read;
12761541Srgrimes                else
12771541Srgrimes                    error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString());
12781541Srgrimes            }
12791541Srgrimes            else
12801541Srgrimes                error.SetErrorString("address isn't from a object file");
12811541Srgrimes        }
12821541Srgrimes        else
12831541Srgrimes            error.SetErrorString("address isn't in a module");
12841541Srgrimes    }
12851541Srgrimes    else
12861541Srgrimes        error.SetErrorString("address doesn't contain a section that points to a section in a object file");
12871541Srgrimes
12881541Srgrimes    return 0;
12891541Srgrimes}
12901541Srgrimes
12911541Srgrimessize_t
12921541SrgrimesTarget::ReadMemory (const Address& addr,
12931541Srgrimes                    bool prefer_file_cache,
12941541Srgrimes                    void *dst,
12951541Srgrimes                    size_t dst_len,
12961541Srgrimes                    Error &error,
12971541Srgrimes                    lldb::addr_t *load_addr_ptr)
129814753Swollman{
12991541Srgrimes    error.Clear();
13001541Srgrimes
13011541Srgrimes    // if we end up reading this from process memory, we will fill this
13021541Srgrimes    // with the actual load address
13031541Srgrimes    if (load_addr_ptr)
13041541Srgrimes        *load_addr_ptr = LLDB_INVALID_ADDRESS;
13051541Srgrimes
13066283Swollman    size_t bytes_read = 0;
13078876Srgrimes
13086283Swollman    addr_t load_addr = LLDB_INVALID_ADDRESS;
13096283Swollman    addr_t file_addr = LLDB_INVALID_ADDRESS;
13106283Swollman    Address resolved_addr;
13118876Srgrimes    if (!addr.IsSectionOffset())
131213779Solah    {
131313779Solah        SectionLoadList &section_load_list = GetSectionLoadList();
131413779Solah        if (section_load_list.IsEmpty())
131513779Solah        {
131613779Solah            // No sections are loaded, so we must assume we are not running
13176283Swollman            // yet and anything we are given is a file address.
13186283Swollman            file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
13196283Swollman            m_images.ResolveFileAddress (file_addr, resolved_addr);
132013779Solah        }
132113779Solah        else
132213779Solah        {
132313779Solah            // We have at least one section loaded. This can be becuase
132413779Solah            // we have manually loaded some sections with "target modules load ..."
132513779Solah            // or because we have have a live process that has sections loaded
13266283Swollman            // through the dynamic loader
13276283Swollman            load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
13286283Swollman            section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
13291541Srgrimes        }
13301541Srgrimes    }
13311541Srgrimes    if (!resolved_addr.IsValid())
13321541Srgrimes        resolved_addr = addr;
13331541Srgrimes
13341541Srgrimes
13351541Srgrimes    if (prefer_file_cache)
13361541Srgrimes    {
13371541Srgrimes        bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
13381541Srgrimes        if (bytes_read > 0)
13391541Srgrimes            return bytes_read;
13401541Srgrimes    }
13411541Srgrimes
13426283Swollman    if (ProcessIsValid())
13436283Swollman    {
13441541Srgrimes        if (load_addr == LLDB_INVALID_ADDRESS)
13451541Srgrimes            load_addr = resolved_addr.GetLoadAddress (this);
13461541Srgrimes
13471541Srgrimes        if (load_addr == LLDB_INVALID_ADDRESS)
13481541Srgrimes        {
13491541Srgrimes            ModuleSP addr_module_sp (resolved_addr.GetModule());
13501541Srgrimes            if (addr_module_sp && addr_module_sp->GetFileSpec())
13511541Srgrimes                error.SetErrorStringWithFormat("%s[0x%" PRIx64 "] can't be resolved, %s in not currently loaded",
13521541Srgrimes                                               addr_module_sp->GetFileSpec().GetFilename().AsCString(),
13531541Srgrimes                                               resolved_addr.GetFileAddress(),
13541541Srgrimes                                               addr_module_sp->GetFileSpec().GetFilename().AsCString());
13551541Srgrimes            else
13561541Srgrimes                error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
13571541Srgrimes        }
13586283Swollman        else
13591541Srgrimes        {
13606283Swollman            bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
13616283Swollman            if (bytes_read != dst_len)
13626283Swollman            {
13636283Swollman                if (error.Success())
13646283Swollman                {
13656283Swollman                    if (bytes_read == 0)
13666283Swollman                        error.SetErrorStringWithFormat("read memory from 0x%" PRIx64 " failed", load_addr);
13671541Srgrimes                    else
13681541Srgrimes                        error.SetErrorStringWithFormat("only %" PRIu64 " of %" PRIu64 " bytes were read from memory at 0x%" PRIx64, (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
13691541Srgrimes                }
13701541Srgrimes            }
13713561Swollman            if (bytes_read)
13721541Srgrimes            {
13731541Srgrimes                if (load_addr_ptr)
13741541Srgrimes                    *load_addr_ptr = load_addr;
13751541Srgrimes                return bytes_read;
13761541Srgrimes            }
13771541Srgrimes            // If the address is not section offset we have an address that
13783561Swollman            // doesn't resolve to any address in any currently loaded shared
13791541Srgrimes            // libaries and we failed to read memory so there isn't anything
13801541Srgrimes            // more we can do. If it is section offset, we might be able to
13811541Srgrimes            // read cached memory from the object file.
13821541Srgrimes            if (!resolved_addr.IsSectionOffset())
13831541Srgrimes                return 0;
13841541Srgrimes        }
13851541Srgrimes    }
13861541Srgrimes
13871541Srgrimes    if (!prefer_file_cache && resolved_addr.IsSectionOffset())
13881541Srgrimes    {
13891541Srgrimes        // If we didn't already try and read from the object file cache, then
13901541Srgrimes        // try it after failing to read from the process.
13911541Srgrimes        return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
13921541Srgrimes    }
13931541Srgrimes    return 0;
13941541Srgrimes}
13951541Srgrimes
13961541Srgrimessize_t
13971541SrgrimesTarget::ReadCStringFromMemory (const Address& addr, std::string &out_str, Error &error)
13981541Srgrimes{
13991541Srgrimes    char buf[256];
14001541Srgrimes    out_str.clear();
14011541Srgrimes    addr_t curr_addr = addr.GetLoadAddress(this);
14021541Srgrimes    Address address(addr);
14031541Srgrimes    while (1)
14041541Srgrimes    {
14051541Srgrimes        size_t length = ReadCStringFromMemory (address, buf, sizeof(buf), error);
14061541Srgrimes        if (length == 0)
14071541Srgrimes            break;
14081541Srgrimes        out_str.append(buf, length);
14091541Srgrimes        // If we got "length - 1" bytes, we didn't get the whole C string, we
14101541Srgrimes        // need to read some more characters
14111541Srgrimes        if (length == sizeof(buf) - 1)
14121541Srgrimes            curr_addr += length;
14131541Srgrimes        else
14141541Srgrimes            break;
14151541Srgrimes        address = Address(curr_addr);
14161541Srgrimes    }
14171541Srgrimes    return out_str.size();
14181541Srgrimes}
14191541Srgrimes
14201541Srgrimes
14211541Srgrimessize_t
14221541SrgrimesTarget::ReadCStringFromMemory (const Address& addr, char *dst, size_t dst_max_len, Error &result_error)
14231541Srgrimes{
14241541Srgrimes    size_t total_cstr_len = 0;
14251541Srgrimes    if (dst && dst_max_len)
14261541Srgrimes    {
14271541Srgrimes        result_error.Clear();
14281541Srgrimes        // NULL out everything just to be safe
14291541Srgrimes        memset (dst, 0, dst_max_len);
14306283Swollman        Error error;
14316283Swollman        addr_t curr_addr = addr.GetLoadAddress(this);
14326283Swollman        Address address(addr);
14336283Swollman        const size_t cache_line_size = 512;
14346283Swollman        size_t bytes_left = dst_max_len - 1;
14356283Swollman        char *curr_dst = dst;
14366283Swollman
14371541Srgrimes        while (bytes_left > 0)
14381541Srgrimes        {
14391541Srgrimes            addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
14401541Srgrimes            addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
14411541Srgrimes            size_t bytes_read = ReadMemory (address, false, curr_dst, bytes_to_read, error);
14421541Srgrimes
14431541Srgrimes            if (bytes_read == 0)
14441541Srgrimes            {
14451541Srgrimes                result_error = error;
14461541Srgrimes                dst[total_cstr_len] = '\0';
14471541Srgrimes                break;
14481541Srgrimes            }
14491541Srgrimes            const size_t len = strlen(curr_dst);
14501541Srgrimes
14511541Srgrimes            total_cstr_len += len;
14521541Srgrimes
14531541Srgrimes            if (len < bytes_to_read)
14541541Srgrimes                break;
14551541Srgrimes
14561541Srgrimes            curr_dst += bytes_read;
14571541Srgrimes            curr_addr += bytes_read;
14581541Srgrimes            bytes_left -= bytes_read;
14591541Srgrimes            address = Address(curr_addr);
14601541Srgrimes        }
14611541Srgrimes    }
14621541Srgrimes    else
14631541Srgrimes    {
14641541Srgrimes        if (dst == NULL)
14651541Srgrimes            result_error.SetErrorString("invalid arguments");
14661541Srgrimes        else
14671541Srgrimes            result_error.Clear();
14681541Srgrimes    }
14691541Srgrimes    return total_cstr_len;
14701541Srgrimes}
14718876Srgrimes
14723311Sphksize_t
14733311SphkTarget::ReadScalarIntegerFromMemory (const Address& addr,
14741541Srgrimes                                     bool prefer_file_cache,
14751541Srgrimes                                     uint32_t byte_size,
14761541Srgrimes                                     bool is_signed,
14771541Srgrimes                                     Scalar &scalar,
14781541Srgrimes                                     Error &error)
14791541Srgrimes{
14801541Srgrimes    uint64_t uval;
14811541Srgrimes
14821541Srgrimes    if (byte_size <= sizeof(uval))
14831541Srgrimes    {
14841541Srgrimes        size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
14851541Srgrimes        if (bytes_read == byte_size)
14861541Srgrimes        {
14871541Srgrimes            DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
14881541Srgrimes            lldb::offset_t offset = 0;
14891541Srgrimes            if (byte_size <= 4)
14901541Srgrimes                scalar = data.GetMaxU32 (&offset, byte_size);
14911541Srgrimes            else
14921541Srgrimes                scalar = data.GetMaxU64 (&offset, byte_size);
14931541Srgrimes
14941541Srgrimes            if (is_signed)
14951541Srgrimes                scalar.SignExtend(byte_size * 8);
14961541Srgrimes            return bytes_read;
14971541Srgrimes        }
14981541Srgrimes    }
14991541Srgrimes    else
15001541Srgrimes    {
15011541Srgrimes        error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
15021541Srgrimes    }
15031541Srgrimes    return 0;
15041541Srgrimes}
15051541Srgrimes
15068876Srgrimesuint64_t
15071541SrgrimesTarget::ReadUnsignedIntegerFromMemory (const Address& addr,
15081541Srgrimes                                       bool prefer_file_cache,
15091541Srgrimes                                       size_t integer_byte_size,
15101541Srgrimes                                       uint64_t fail_value,
15111541Srgrimes                                       Error &error)
15121541Srgrimes{
15138876Srgrimes    Scalar scalar;
15141541Srgrimes    if (ReadScalarIntegerFromMemory (addr,
15151541Srgrimes                                     prefer_file_cache,
15161541Srgrimes                                     integer_byte_size,
15171541Srgrimes                                     false,
15181541Srgrimes                                     scalar,
15191541Srgrimes                                     error))
15201541Srgrimes        return scalar.ULongLong(fail_value);
15211541Srgrimes    return fail_value;
15221541Srgrimes}
15231541Srgrimes
15241541Srgrimesbool
15251541SrgrimesTarget::ReadPointerFromMemory (const Address& addr,
15261541Srgrimes                               bool prefer_file_cache,
15271541Srgrimes                               Error &error,
15281541Srgrimes                               Address &pointer_addr)
15291541Srgrimes{
15301541Srgrimes    Scalar scalar;
15311549Srgrimes    if (ReadScalarIntegerFromMemory (addr,
15321541Srgrimes                                     prefer_file_cache,
15331541Srgrimes                                     m_arch.GetAddressByteSize(),
15341541Srgrimes                                     false,
15351541Srgrimes                                     scalar,
15361541Srgrimes                                     error))
15371541Srgrimes    {
15381541Srgrimes        addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
15391541Srgrimes        if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
15401541Srgrimes        {
15411541Srgrimes            SectionLoadList &section_load_list = GetSectionLoadList();
15421541Srgrimes            if (section_load_list.IsEmpty())
15431541Srgrimes            {
15441541Srgrimes                // No sections are loaded, so we must assume we are not running
15451541Srgrimes                // yet and anything we are given is a file address.
15461541Srgrimes                m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
15471541Srgrimes            }
15481541Srgrimes            else
15491541Srgrimes            {
15501541Srgrimes                // We have at least one section loaded. This can be becuase
15511541Srgrimes                // we have manually loaded some sections with "target modules load ..."
15521541Srgrimes                // or because we have have a live process that has sections loaded
15531541Srgrimes                // through the dynamic loader
15541541Srgrimes                section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
15551541Srgrimes            }
15561541Srgrimes            // We weren't able to resolve the pointer value, so just return
15571541Srgrimes            // an address with no section
15581541Srgrimes            if (!pointer_addr.IsValid())
15591541Srgrimes                pointer_addr.SetOffset (pointer_vm_addr);
15601541Srgrimes            return true;
15611541Srgrimes
15621541Srgrimes        }
15631541Srgrimes    }
15641541Srgrimes    return false;
15651541Srgrimes}
15661541Srgrimes
15671541SrgrimesModuleSP
15681541SrgrimesTarget::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr)
15691541Srgrimes{
15701541Srgrimes    ModuleSP module_sp;
15711541Srgrimes
15721541Srgrimes    Error error;
15731541Srgrimes
15741541Srgrimes    // First see if we already have this module in our module list.  If we do, then we're done, we don't need
15751541Srgrimes    // to consult the shared modules list.  But only do this if we are passed a UUID.
15766283Swollman
15776283Swollman    if (module_spec.GetUUID().IsValid())
15789818Solah        module_sp = m_images.FindFirstModule(module_spec);
15796283Swollman
15806283Swollman    if (!module_sp)
15818876Srgrimes    {
15826283Swollman        ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
15836283Swollman        bool did_create_module = false;
15846283Swollman
15858876Srgrimes        // If there are image search path entries, try to use them first to acquire a suitable image.
15866283Swollman        if (m_image_search_paths.GetSize())
15871541Srgrimes        {
15881541Srgrimes            ModuleSpec transformed_spec (module_spec);
15891541Srgrimes            if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory()))
15901541Srgrimes            {
15911541Srgrimes                transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename();
15921541Srgrimes                error = ModuleList::GetSharedModule (transformed_spec,
15931541Srgrimes                                                     module_sp,
15941541Srgrimes                                                     &GetExecutableSearchPaths(),
15951541Srgrimes                                                     &old_module_sp,
15961541Srgrimes                                                     &did_create_module);
15971541Srgrimes            }
15981541Srgrimes        }
15991541Srgrimes
16001541Srgrimes        if (!module_sp)
16011541Srgrimes        {
16021541Srgrimes            // If we have a UUID, we can check our global shared module list in case
16031541Srgrimes            // we already have it. If we don't have a valid UUID, then we can't since
16041541Srgrimes            // the path in "module_spec" will be a platform path, and we will need to
16051541Srgrimes            // let the platform find that file. For example, we could be asking for
16061541Srgrimes            // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
16071541Srgrimes            // the local copy of "/usr/lib/dyld" since our platform could be a remote
16081541Srgrimes            // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
16091541Srgrimes            // cache.
16108876Srgrimes            if (module_spec.GetUUID().IsValid())
16111541Srgrimes            {
16121541Srgrimes                // We have a UUID, it is OK to check the global module list...
16131541Srgrimes                error = ModuleList::GetSharedModule (module_spec,
16141541Srgrimes                                                     module_sp,
16151541Srgrimes                                                     &GetExecutableSearchPaths(),
16166283Swollman                                                     &old_module_sp,
16176283Swollman                                                     &did_create_module);
16186283Swollman            }
16196283Swollman
16206283Swollman            if (!module_sp)
16216283Swollman            {
16226283Swollman                // The platform is responsible for finding and caching an appropriate
16236283Swollman                // module in the shared module cache.
16246283Swollman                if (m_platform_sp)
16256283Swollman                {
16261541Srgrimes                    FileSpec platform_file_spec;
16271541Srgrimes                    error = m_platform_sp->GetSharedModule (module_spec,
16281541Srgrimes                                                            module_sp,
16291541Srgrimes                                                            &GetExecutableSearchPaths(),
16301541Srgrimes                                                            &old_module_sp,
16311541Srgrimes                                                            &did_create_module);
16321541Srgrimes                }
16331541Srgrimes                else
16341541Srgrimes                {
16351541Srgrimes                    error.SetErrorString("no platform is currently set");
16361541Srgrimes                }
16372788Sdg            }
16381541Srgrimes        }
16391541Srgrimes
16402788Sdg        // We found a module that wasn't in our target list.  Let's make sure that there wasn't an equivalent
16411541Srgrimes        // module in the list already, and if there was, let's remove it.
16421541Srgrimes        if (module_sp)
16431541Srgrimes        {
16441541Srgrimes            ObjectFile *objfile = module_sp->GetObjectFile();
16451541Srgrimes            if (objfile)
16461541Srgrimes            {
16471541Srgrimes                switch (objfile->GetType())
16481541Srgrimes                {
16491541Srgrimes                    case ObjectFile::eTypeCoreFile:      /// A core file that has a checkpoint of a program's execution state
16501541Srgrimes                    case ObjectFile::eTypeExecutable:    /// A normal executable
16511541Srgrimes                    case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker executable
16521541Srgrimes                    case ObjectFile::eTypeObjectFile:    /// An intermediate object file
16531541Srgrimes                    case ObjectFile::eTypeSharedLibrary: /// A shared library that can be used during execution
16541541Srgrimes                        break;
16551541Srgrimes                    case ObjectFile::eTypeDebugInfo:     /// An object file that contains only debug information
16566283Swollman                        if (error_ptr)
16576283Swollman                            error_ptr->SetErrorString("debug info files aren't valid target modules, please specify an executable");
16586283Swollman                        return ModuleSP();
16596283Swollman                    case ObjectFile::eTypeStubLibrary:   /// A library that can be linked against but not used for execution
16601541Srgrimes                        if (error_ptr)
16611541Srgrimes                            error_ptr->SetErrorString("stub libraries aren't valid target modules, please specify an executable");
16621541Srgrimes                        return ModuleSP();
16631541Srgrimes                    default:
16641541Srgrimes                        if (error_ptr)
16651541Srgrimes                            error_ptr->SetErrorString("unsupported file type, please specify an executable");
16661541Srgrimes                        return ModuleSP();
16671541Srgrimes                }
16681541Srgrimes                // GetSharedModule is not guaranteed to find the old shared module, for instance
16691541Srgrimes                // in the common case where you pass in the UUID, it is only going to find the one
16701541Srgrimes                // module matching the UUID.  In fact, it has no good way to know what the "old module"
16711541Srgrimes                // relevant to this target is, since there might be many copies of a module with this file spec
16721565Sdg                // in various running debug sessions, but only one of them will belong to this target.
16731541Srgrimes                // So let's remove the UUID from the module list, and look in the target's module list.
16746283Swollman                // Only do this if there is SOMETHING else in the module spec...
16756283Swollman                if (!old_module_sp)
16766283Swollman                {
16776283Swollman                    if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty())
16781541Srgrimes                    {
16791541Srgrimes                        ModuleSpec module_spec_copy(module_spec.GetFileSpec());
16801541Srgrimes                        module_spec_copy.GetUUID().Clear();
16811541Srgrimes
16821541Srgrimes                        ModuleList found_modules;
16831541Srgrimes                        size_t num_found = m_images.FindModules (module_spec_copy, found_modules);
16841541Srgrimes                        if (num_found == 1)
16851541Srgrimes                        {
16861541Srgrimes                            old_module_sp = found_modules.GetModuleAtIndex(0);
16871541Srgrimes                        }
16881541Srgrimes                    }
16891541Srgrimes                }
16901541Srgrimes
16911541Srgrimes                if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
16921541Srgrimes                {
16931541Srgrimes                    m_images.ReplaceModule(old_module_sp, module_sp);
16941541Srgrimes                    Module *old_module_ptr = old_module_sp.get();
16952788Sdg                    old_module_sp.reset();
16966283Swollman                    ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr);
16976283Swollman                }
16982788Sdg                else
16991541Srgrimes                    m_images.Append(module_sp);
17001541Srgrimes            }
17011541Srgrimes        }
17021541Srgrimes    }
17031541Srgrimes    if (error_ptr)
17041541Srgrimes        *error_ptr = error;
17051541Srgrimes    return module_sp;
17061541Srgrimes}
170712296Sphk
17086283Swollman
17091541SrgrimesTargetSP
17101541SrgrimesTarget::CalculateTarget ()
17111541Srgrimes{
17121541Srgrimes    return shared_from_this();
17136283Swollman}
17141541Srgrimes
17156283SwollmanProcessSP
17161541SrgrimesTarget::CalculateProcess ()
17171541Srgrimes{
17181541Srgrimes    return ProcessSP();
17191541Srgrimes}
17201541Srgrimes
17211541SrgrimesThreadSP
17221541SrgrimesTarget::CalculateThread ()
17231541Srgrimes{
17241541Srgrimes    return ThreadSP();
17251541Srgrimes}
17261541Srgrimes
17271541SrgrimesStackFrameSP
17281541SrgrimesTarget::CalculateStackFrame ()
17291541Srgrimes{
17301541Srgrimes    return StackFrameSP();
17311541Srgrimes}
17321541Srgrimes
17331541Srgrimesvoid
17341541SrgrimesTarget::CalculateExecutionContext (ExecutionContext &exe_ctx)
17351541Srgrimes{
17361541Srgrimes    exe_ctx.Clear();
17371541Srgrimes    exe_ctx.SetTargetPtr(this);
17381541Srgrimes}
17391541Srgrimes
17401541SrgrimesPathMappingList &
17411541SrgrimesTarget::GetImageSearchPathList ()
17421541Srgrimes{
17431541Srgrimes    return m_image_search_paths;
17441541Srgrimes}
17451541Srgrimes
17461541Srgrimesvoid
17471541SrgrimesTarget::ImageSearchPathsChanged
17481541Srgrimes(
17491541Srgrimes    const PathMappingList &path_list,
17501541Srgrimes    void *baton
17511541Srgrimes)
17521541Srgrimes{
17531541Srgrimes    Target *target = (Target *)baton;
17541541Srgrimes    ModuleSP exe_module_sp (target->GetExecutableModule());
17556283Swollman    if (exe_module_sp)
17566283Swollman        target->SetExecutableModule (exe_module_sp, true);
17576283Swollman}
17586283Swollman
17596283SwollmanClangASTContext *
17606283SwollmanTarget::GetScratchClangASTContext(bool create_on_demand)
17616283Swollman{
17621541Srgrimes    // Now see if we know the target triple, and if so, create our scratch AST context:
17638876Srgrimes    if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid() && create_on_demand)
17641541Srgrimes    {
17651541Srgrimes        m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
17661541Srgrimes        m_scratch_ast_source_ap.reset (new ClangASTSource(shared_from_this()));
17671541Srgrimes        m_scratch_ast_source_ap->InstallASTContext(m_scratch_ast_context_ap->getASTContext());
17681541Srgrimes        llvm::OwningPtr<clang::ExternalASTSource> proxy_ast_source(m_scratch_ast_source_ap->CreateProxy());
17696283Swollman        m_scratch_ast_context_ap->SetExternalSource(proxy_ast_source);
17701541Srgrimes    }
17711541Srgrimes    return m_scratch_ast_context_ap.get();
17721541Srgrimes}
17736283Swollman
17746283SwollmanClangASTImporter *
17756283SwollmanTarget::GetClangASTImporter()
17768377Solah{
17776283Swollman    ClangASTImporter *ast_importer = m_ast_importer_ap.get();
17786283Swollman
17796283Swollman    if (!ast_importer)
17808876Srgrimes    {
17816283Swollman        ast_importer = new ClangASTImporter();
17826283Swollman        m_ast_importer_ap.reset(ast_importer);
17836283Swollman    }
17846283Swollman
17856283Swollman    return ast_importer;
17866283Swollman}
17876283Swollman
17886283Swollmanvoid
17896283SwollmanTarget::SettingsInitialize ()
17906283Swollman{
17916283Swollman    Process::SettingsInitialize ();
17926283Swollman}
17936283Swollman
17946283Swollmanvoid
17956283SwollmanTarget::SettingsTerminate ()
17968876Srgrimes{
17976283Swollman    Process::SettingsTerminate ();
17986283Swollman}
17996283Swollman
18006283SwollmanFileSpecList
18016283SwollmanTarget::GetDefaultExecutableSearchPaths ()
18026283Swollman{
18036283Swollman    TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
18046283Swollman    if (properties_sp)
18056283Swollman        return properties_sp->GetExecutableSearchPaths();
18066283Swollman    return FileSpecList();
18076283Swollman}
18086283Swollman
18096283SwollmanFileSpecList
18106283SwollmanTarget::GetDefaultDebugFileSearchPaths ()
18116283Swollman{
18121541Srgrimes    TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
18131541Srgrimes    if (properties_sp)
18146283Swollman        return properties_sp->GetDebugFileSearchPaths();
18156283Swollman    return FileSpecList();
18161541Srgrimes}
18171541Srgrimes
18181541SrgrimesArchSpec
18191541SrgrimesTarget::GetDefaultArchitecture ()
18201541Srgrimes{
18211541Srgrimes    TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
18221541Srgrimes    if (properties_sp)
18231541Srgrimes        return properties_sp->GetDefaultArchitecture();
182412296Sphk    return ArchSpec();
18251541Srgrimes}
18261541Srgrimes
18271541Srgrimesvoid
18281541SrgrimesTarget::SetDefaultArchitecture (const ArchSpec &arch)
18291541Srgrimes{
18301541Srgrimes    TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
18318876Srgrimes    if (properties_sp)
18321541Srgrimes    {
18331541Srgrimes        LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's default architecture to  %s (%s)", arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
18341541Srgrimes        return properties_sp->SetDefaultArchitecture(arch);
18351541Srgrimes    }
18361541Srgrimes}
18371541Srgrimes
18381541SrgrimesTarget *
18391541SrgrimesTarget::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
18401541Srgrimes{
18411541Srgrimes    // The target can either exist in the "process" of ExecutionContext, or in
18421541Srgrimes    // the "target_sp" member of SymbolContext. This accessor helper function
18431541Srgrimes    // will get the target from one of these locations.
18441541Srgrimes
18451541Srgrimes    Target *target = NULL;
18461541Srgrimes    if (sc_ptr != NULL)
18471541Srgrimes        target = sc_ptr->target_sp.get();
18481541Srgrimes    if (target == NULL && exe_ctx_ptr)
18491541Srgrimes        target = exe_ctx_ptr->GetTargetPtr();
18501541Srgrimes    return target;
18511541Srgrimes}
18521541Srgrimes
18531541SrgrimesExecutionResults
18541541SrgrimesTarget::EvaluateExpression
185512296Sphk(
18561541Srgrimes    const char *expr_cstr,
18571541Srgrimes    StackFrame *frame,
18581541Srgrimes    lldb::ValueObjectSP &result_valobj_sp,
18591541Srgrimes    const EvaluateExpressionOptions& options
186014753Swollman)
186114753Swollman{
186214753Swollman    result_valobj_sp.reset();
186314753Swollman
186414753Swollman    ExecutionResults execution_results = eExecutionSetupError;
186514753Swollman
186614753Swollman    if (expr_cstr == NULL || expr_cstr[0] == '\0')
186714753Swollman        return execution_results;
186814753Swollman
186914753Swollman    // We shouldn't run stop hooks in expressions.
187014753Swollman    // Be sure to reset this if you return anywhere within this function.
187114753Swollman    bool old_suppress_value = m_suppress_stop_hooks;
187214753Swollman    m_suppress_stop_hooks = true;
187314753Swollman
187414753Swollman    ExecutionContext exe_ctx;
187514753Swollman
187614753Swollman    if (frame)
187714753Swollman    {
187814753Swollman        frame->CalculateExecutionContext(exe_ctx);
187914753Swollman    }
188014753Swollman    else if (m_process_sp)
188114753Swollman    {
188214753Swollman        m_process_sp->CalculateExecutionContext(exe_ctx);
188314753Swollman    }
188414753Swollman    else
188514753Swollman    {
188614753Swollman        CalculateExecutionContext(exe_ctx);
188714753Swollman    }
188814753Swollman
188914753Swollman    // Make sure we aren't just trying to see the value of a persistent
189014753Swollman    // variable (something like "$0")
189114753Swollman    lldb::ClangExpressionVariableSP persistent_var_sp;
189214753Swollman    // Only check for persistent variables the expression starts with a '$'
189314753Swollman    if (expr_cstr[0] == '$')
189414753Swollman        persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
189514753Swollman
189614753Swollman    if (persistent_var_sp)
189714753Swollman    {
189814753Swollman        result_valobj_sp = persistent_var_sp->GetValueObject ();
189914753Swollman        execution_results = eExecutionCompleted;
190014753Swollman    }
190114753Swollman    else
19021541Srgrimes    {
19031541Srgrimes        const char *prefix = GetExpressionPrefixContentsAsCString();
19041541Srgrimes        Error error;
19051541Srgrimes        execution_results = ClangUserExpression::Evaluate (exe_ctx,
19061541Srgrimes                                                           options,
19071541Srgrimes                                                           expr_cstr,
19081541Srgrimes                                                           prefix,
19091541Srgrimes                                                           result_valobj_sp,
19101541Srgrimes                                                           error);
19111541Srgrimes    }
19121541Srgrimes
19131541Srgrimes    m_suppress_stop_hooks = old_suppress_value;
19141541Srgrimes
19151541Srgrimes    return execution_results;
19161541Srgrimes}
191714819Swollman
19188876Srgrimeslldb::addr_t
19191541SrgrimesTarget::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
19201541Srgrimes{
19211541Srgrimes    addr_t code_addr = load_addr;
19221541Srgrimes    switch (m_arch.GetMachine())
19231541Srgrimes    {
19241541Srgrimes    case llvm::Triple::arm:
19251541Srgrimes    case llvm::Triple::thumb:
19261541Srgrimes        switch (addr_class)
19271541Srgrimes        {
19281541Srgrimes        case eAddressClassData:
19291541Srgrimes        case eAddressClassDebug:
19301541Srgrimes            return LLDB_INVALID_ADDRESS;
19311541Srgrimes
19321541Srgrimes        case eAddressClassUnknown:
19331541Srgrimes        case eAddressClassInvalid:
19341541Srgrimes        case eAddressClassCode:
19351541Srgrimes        case eAddressClassCodeAlternateISA:
19361541Srgrimes        case eAddressClassRuntime:
19371541Srgrimes            // Check if bit zero it no set?
19381541Srgrimes            if ((code_addr & 1ull) == 0)
19391541Srgrimes            {
19401541Srgrimes                // Bit zero isn't set, check if the address is a multiple of 2?
19411541Srgrimes                if (code_addr & 2ull)
19421541Srgrimes                {
19436283Swollman                    // The address is a multiple of 2 so it must be thumb, set bit zero
19446283Swollman                    code_addr |= 1ull;
19456283Swollman                }
19466283Swollman                else if (addr_class == eAddressClassCodeAlternateISA)
19476283Swollman                {
19486283Swollman                    // We checked the address and the address claims to be the alternate ISA
19496283Swollman                    // which means thumb, so set bit zero.
19506283Swollman                    code_addr |= 1ull;
19516283Swollman                }
19526283Swollman            }
19536283Swollman            break;
19546283Swollman        }
19556283Swollman        break;
19561541Srgrimes
19576283Swollman    default:
19581541Srgrimes        break;
19596283Swollman    }
19606283Swollman    return code_addr;
19611541Srgrimes}
19621541Srgrimes
19631541Srgrimeslldb::addr_t
19641541SrgrimesTarget::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
19651541Srgrimes{
19661541Srgrimes    addr_t opcode_addr = load_addr;
19671541Srgrimes    switch (m_arch.GetMachine())
19686283Swollman    {
19696283Swollman    case llvm::Triple::arm:
19701541Srgrimes    case llvm::Triple::thumb:
19711541Srgrimes        switch (addr_class)
19726283Swollman        {
19736283Swollman        case eAddressClassData:
19746283Swollman        case eAddressClassDebug:
19751541Srgrimes            return LLDB_INVALID_ADDRESS;
19761541Srgrimes
19771541Srgrimes        case eAddressClassInvalid:
19781541Srgrimes        case eAddressClassUnknown:
19796283Swollman        case eAddressClassCode:
19806283Swollman        case eAddressClassCodeAlternateISA:
19816283Swollman        case eAddressClassRuntime:
19826283Swollman            opcode_addr &= ~(1ull);
19836283Swollman            break;
19846283Swollman        }
19856283Swollman        break;
19866283Swollman
19876283Swollman    default:
19886283Swollman        break;
19896283Swollman    }
19906283Swollman    return opcode_addr;
19916283Swollman}
19926283Swollman
19936283SwollmanSourceManager &
19946283SwollmanTarget::GetSourceManager ()
19956283Swollman{
19966283Swollman    if (m_source_manager_ap.get() == NULL)
19976283Swollman        m_source_manager_ap.reset (new SourceManager(shared_from_this()));
19986283Swollman    return *m_source_manager_ap;
19996283Swollman}
20006283Swollman
20016283Swollman
20021541SrgrimesTarget::StopHookSP
20031541SrgrimesTarget::CreateStopHook ()
20041541Srgrimes{
20051541Srgrimes    lldb::user_id_t new_uid = ++m_stop_hook_next_id;
20061541Srgrimes    Target::StopHookSP stop_hook_sp (new StopHook(shared_from_this(), new_uid));
20071541Srgrimes    m_stop_hooks[new_uid] = stop_hook_sp;
20081541Srgrimes    return stop_hook_sp;
20096283Swollman}
20101541Srgrimes
20111541Srgrimesbool
20121541SrgrimesTarget::RemoveStopHookByID (lldb::user_id_t user_id)
20131541Srgrimes{
20141541Srgrimes    size_t num_removed;
20159470Swollman    num_removed = m_stop_hooks.erase (user_id);
20169470Swollman    if (num_removed == 0)
20171541Srgrimes        return false;
20181541Srgrimes    else
20199470Swollman        return true;
20209470Swollman}
20211541Srgrimes
20221541Srgrimesvoid
20231541SrgrimesTarget::RemoveAllStopHooks ()
20249470Swollman{
20251541Srgrimes    m_stop_hooks.clear();
20261541Srgrimes}
20271541Srgrimes
20281541SrgrimesTarget::StopHookSP
20291541SrgrimesTarget::GetStopHookByID (lldb::user_id_t user_id)
20301541Srgrimes{
20311541Srgrimes    StopHookSP found_hook;
20321541Srgrimes
20331541Srgrimes    StopHookCollection::iterator specified_hook_iter;
20341541Srgrimes    specified_hook_iter = m_stop_hooks.find (user_id);
20351541Srgrimes    if (specified_hook_iter != m_stop_hooks.end())
20361541Srgrimes        found_hook = (*specified_hook_iter).second;
20376283Swollman    return found_hook;
20386283Swollman}
20396283Swollman
20406283Swollmanbool
20416283SwollmanTarget::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
20426283Swollman{
20436283Swollman    StopHookCollection::iterator specified_hook_iter;
20446283Swollman    specified_hook_iter = m_stop_hooks.find (user_id);
20456283Swollman    if (specified_hook_iter == m_stop_hooks.end())
20466283Swollman        return false;
20476283Swollman
20486283Swollman    (*specified_hook_iter).second->SetIsActive (active_state);
20496283Swollman    return true;
20506283Swollman}
20516283Swollman
20526283Swollmanvoid
20536283SwollmanTarget::SetAllStopHooksActiveState (bool active_state)
20546283Swollman{
20556283Swollman    StopHookCollection::iterator pos, end = m_stop_hooks.end();
20566283Swollman    for (pos = m_stop_hooks.begin(); pos != end; pos++)
20576283Swollman    {
20586283Swollman        (*pos).second->SetIsActive (active_state);
20596283Swollman    }
20606283Swollman}
20616283Swollman
20626283Swollmanvoid
20636283SwollmanTarget::RunStopHooks ()
20641541Srgrimes{
20651541Srgrimes    if (m_suppress_stop_hooks)
20661541Srgrimes        return;
20671541Srgrimes
20681541Srgrimes    if (!m_process_sp)
20691541Srgrimes        return;
20701541Srgrimes
20711541Srgrimes    // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
20726283Swollman    // since in that case we do not want to run the stop-hooks
20736283Swollman    if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
20746283Swollman        return;
20756283Swollman
20761541Srgrimes    if (m_stop_hooks.empty())
20771541Srgrimes        return;
20786283Swollman
20791541Srgrimes    StopHookCollection::iterator pos, end = m_stop_hooks.end();
20806283Swollman
20816283Swollman    // If there aren't any active stop hooks, don't bother either:
20826283Swollman    bool any_active_hooks = false;
20836283Swollman    for (pos = m_stop_hooks.begin(); pos != end; pos++)
20846283Swollman    {
20856283Swollman        if ((*pos).second->IsActive())
20866283Swollman        {
20876283Swollman            any_active_hooks = true;
20886283Swollman            break;
20896283Swollman        }
20901541Srgrimes    }
20911541Srgrimes    if (!any_active_hooks)
20926283Swollman        return;
20931541Srgrimes
20946283Swollman    CommandReturnObject result;
20956283Swollman
20966283Swollman    std::vector<ExecutionContext> exc_ctx_with_reasons;
20976283Swollman    std::vector<SymbolContext> sym_ctx_with_reasons;
20986283Swollman
20996283Swollman    ThreadList &cur_threadlist = m_process_sp->GetThreadList();
21001541Srgrimes    size_t num_threads = cur_threadlist.GetSize();
21016283Swollman    for (size_t i = 0; i < num_threads; i++)
21026283Swollman    {
21036283Swollman        lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
21046283Swollman        if (cur_thread_sp->ThreadStoppedForAReason())
21056283Swollman        {
21061541Srgrimes            lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
21071541Srgrimes            exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
21081541Srgrimes            sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
21091541Srgrimes        }
21101541Srgrimes    }
21111541Srgrimes
21121541Srgrimes    // If no threads stopped for a reason, don't run the stop-hooks.
21131541Srgrimes    size_t num_exe_ctx = exc_ctx_with_reasons.size();
21141541Srgrimes    if (num_exe_ctx == 0)
21159470Swollman        return;
21161541Srgrimes
21171541Srgrimes    result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
21186283Swollman    result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
21196283Swollman
21206283Swollman    bool keep_going = true;
21216283Swollman    bool hooks_ran = false;
21226283Swollman    bool print_hook_header;
21236283Swollman    bool print_thread_header;
21246283Swollman
21256283Swollman    if (num_exe_ctx == 1)
21266283Swollman        print_thread_header = false;
21276283Swollman    else
21286283Swollman        print_thread_header = true;
21296283Swollman
21306283Swollman    if (m_stop_hooks.size() == 1)
21316283Swollman        print_hook_header = false;
21326283Swollman    else
21336283Swollman        print_hook_header = true;
21341541Srgrimes
2135    for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
2136    {
2137        // result.Clear();
2138        StopHookSP cur_hook_sp = (*pos).second;
2139        if (!cur_hook_sp->IsActive())
2140            continue;
2141
2142        bool any_thread_matched = false;
2143        for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
2144        {
2145            if ((cur_hook_sp->GetSpecifier () == NULL
2146                  || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
2147                && (cur_hook_sp->GetThreadSpecifier() == NULL
2148                    || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
2149            {
2150                if (!hooks_ran)
2151                {
2152                    hooks_ran = true;
2153                }
2154                if (print_hook_header && !any_thread_matched)
2155                {
2156                    const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
2157                                       cur_hook_sp->GetCommands().GetStringAtIndex(0) :
2158                                       NULL);
2159                    if (cmd)
2160                        result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(), cmd);
2161                    else
2162                        result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2163                    any_thread_matched = true;
2164                }
2165
2166                if (print_thread_header)
2167                    result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2168
2169                bool stop_on_continue = true;
2170                bool stop_on_error = true;
2171                bool echo_commands = false;
2172                bool print_results = true;
2173                GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2174                                                                      &exc_ctx_with_reasons[i],
2175                                                                      stop_on_continue,
2176                                                                      stop_on_error,
2177                                                                      echo_commands,
2178                                                                      print_results,
2179                                                                      eLazyBoolNo,
2180                                                                      result);
2181
2182                // If the command started the target going again, we should bag out of
2183                // running the stop hooks.
2184                if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2185                    (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2186                {
2187                    result.AppendMessageWithFormat ("Aborting stop hooks, hook %" PRIu64 " set the program running.", cur_hook_sp->GetID());
2188                    keep_going = false;
2189                }
2190            }
2191        }
2192    }
2193
2194    result.GetImmediateOutputStream()->Flush();
2195    result.GetImmediateErrorStream()->Flush();
2196}
2197
2198const TargetPropertiesSP &
2199Target::GetGlobalProperties()
2200{
2201    static TargetPropertiesSP g_settings_sp;
2202    if (!g_settings_sp)
2203    {
2204        g_settings_sp.reset (new TargetProperties (NULL));
2205    }
2206    return g_settings_sp;
2207}
2208
2209Error
2210Target::Install (ProcessLaunchInfo *launch_info)
2211{
2212    Error error;
2213    PlatformSP platform_sp (GetPlatform());
2214    if (platform_sp)
2215    {
2216        if (platform_sp->IsRemote())
2217        {
2218            if (platform_sp->IsConnected())
2219            {
2220                // Install all files that have an install path, and always install the
2221                // main executable when connected to a remote platform
2222                const ModuleList& modules = GetImages();
2223                const size_t num_images = modules.GetSize();
2224                for (size_t idx = 0; idx < num_images; ++idx)
2225                {
2226                    const bool is_main_executable = idx == 0;
2227                    ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2228                    if (module_sp)
2229                    {
2230                        FileSpec local_file (module_sp->GetFileSpec());
2231                        if (local_file)
2232                        {
2233                            FileSpec remote_file (module_sp->GetRemoteInstallFileSpec());
2234                            if (!remote_file)
2235                            {
2236                                if (is_main_executable) // TODO: add setting for always installing main executable???
2237                                {
2238                                    // Always install the main executable
2239                                    remote_file.GetDirectory() = platform_sp->GetWorkingDirectory();
2240                                    remote_file.GetFilename() = module_sp->GetFileSpec().GetFilename();
2241                                }
2242                            }
2243                            if (remote_file)
2244                            {
2245                                error = platform_sp->Install(local_file, remote_file);
2246                                if (error.Success())
2247                                {
2248                                    module_sp->SetPlatformFileSpec(remote_file);
2249                                    if (is_main_executable)
2250                                    {
2251                                        if (launch_info)
2252                                            launch_info->SetExecutableFile(remote_file, false);
2253                                    }
2254                                }
2255                                else
2256                                    break;
2257                            }
2258                        }
2259                    }
2260                }
2261            }
2262        }
2263    }
2264    return error;
2265}
2266
2267bool
2268Target::ResolveLoadAddress (addr_t load_addr, Address &so_addr, uint32_t stop_id)
2269{
2270    return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2271}
2272
2273bool
2274Target::SetSectionLoadAddress (const SectionSP &section_sp, addr_t new_section_load_addr, bool warn_multiple)
2275{
2276    const addr_t old_section_load_addr = m_section_load_history.GetSectionLoadAddress (SectionLoadHistory::eStopIDNow, section_sp);
2277    if (old_section_load_addr != new_section_load_addr)
2278    {
2279        uint32_t stop_id = 0;
2280        ProcessSP process_sp(GetProcessSP());
2281        if (process_sp)
2282            stop_id = process_sp->GetStopID();
2283        else
2284            stop_id = m_section_load_history.GetLastStopID();
2285        if (m_section_load_history.SetSectionLoadAddress (stop_id, section_sp, new_section_load_addr, warn_multiple))
2286            return true; // Return true if the section load address was changed...
2287    }
2288    return false; // Return false to indicate nothing changed
2289
2290}
2291
2292bool
2293Target::SetSectionUnloaded (const lldb::SectionSP &section_sp)
2294{
2295    uint32_t stop_id = 0;
2296    ProcessSP process_sp(GetProcessSP());
2297    if (process_sp)
2298        stop_id = process_sp->GetStopID();
2299    else
2300        stop_id = m_section_load_history.GetLastStopID();
2301    return m_section_load_history.SetSectionUnloaded (stop_id, section_sp);
2302}
2303
2304bool
2305Target::SetSectionUnloaded (const lldb::SectionSP &section_sp, addr_t load_addr)
2306{
2307    uint32_t stop_id = 0;
2308    ProcessSP process_sp(GetProcessSP());
2309    if (process_sp)
2310        stop_id = process_sp->GetStopID();
2311    else
2312        stop_id = m_section_load_history.GetLastStopID();
2313    return m_section_load_history.SetSectionUnloaded (stop_id, section_sp, load_addr);
2314}
2315
2316void
2317Target::ClearAllLoadedSections ()
2318{
2319    m_section_load_history.Clear();
2320}
2321
2322
2323Error
2324Target::Launch (Listener &listener, ProcessLaunchInfo &launch_info)
2325{
2326    Error error;
2327
2328    StateType state = eStateInvalid;
2329
2330    // Scope to temporarily get the process state in case someone has manually
2331    // remotely connected already to a process and we can skip the platform
2332    // launching.
2333    {
2334        ProcessSP process_sp (GetProcessSP());
2335
2336        if (process_sp)
2337            state = process_sp->GetState();
2338    }
2339
2340    launch_info.GetFlags().Set (eLaunchFlagDebug);
2341
2342    // Get the value of synchronous execution here.  If you wait till after you have started to
2343    // run, then you could have hit a breakpoint, whose command might switch the value, and
2344    // then you'll pick up that incorrect value.
2345    Debugger &debugger = GetDebugger();
2346    const bool synchronous_execution = debugger.GetCommandInterpreter().GetSynchronous ();
2347
2348    PlatformSP platform_sp (GetPlatform());
2349
2350    // Finalize the file actions, and if none were given, default to opening
2351    // up a pseudo terminal
2352    const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2353    launch_info.FinalizeFileActions (this, default_to_use_pty);
2354
2355    if (state == eStateConnected)
2356    {
2357        if (launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY))
2358        {
2359            error.SetErrorString("can't launch in tty when launching through a remote connection");
2360            return error;
2361        }
2362    }
2363
2364    if (!launch_info.GetArchitecture().IsValid())
2365        launch_info.GetArchitecture() = GetArchitecture();
2366
2367    if (state != eStateConnected && platform_sp && platform_sp->CanDebugProcess ())
2368    {
2369        m_process_sp = GetPlatform()->DebugProcess (launch_info,
2370                                                    debugger,
2371                                                    this,
2372                                                    listener,
2373                                                    error);
2374    }
2375    else
2376    {
2377        if (state == eStateConnected)
2378        {
2379            assert(m_process_sp);
2380        }
2381        else
2382        {
2383            const char *plugin_name = launch_info.GetProcessPluginName();
2384            CreateProcess (listener, plugin_name, NULL);
2385        }
2386
2387        if (m_process_sp)
2388            error = m_process_sp->Launch (launch_info);
2389    }
2390
2391    if (!m_process_sp)
2392    {
2393        if (error.Success())
2394            error.SetErrorString("failed to launch or debug process");
2395        return error;
2396    }
2397
2398    if (error.Success())
2399    {
2400        if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry) == false)
2401        {
2402            ListenerSP hijack_listener_sp (launch_info.GetHijackListener());
2403
2404            StateType state = m_process_sp->WaitForProcessToStop (NULL, NULL, false, hijack_listener_sp.get());
2405
2406            if (state == eStateStopped)
2407            {
2408                if (!synchronous_execution)
2409                    m_process_sp->RestoreProcessEvents ();
2410
2411                error = m_process_sp->PrivateResume();
2412
2413                if (error.Success())
2414                {
2415                    if (synchronous_execution)
2416                    {
2417                        state = m_process_sp->WaitForProcessToStop (NULL, NULL, true, hijack_listener_sp.get());
2418                        const bool must_be_alive = false; // eStateExited is ok, so this must be false
2419                        if (!StateIsStoppedState(state, must_be_alive))
2420                        {
2421                            error.SetErrorStringWithFormat("process isn't stopped: %s", StateAsCString(state));
2422                        }
2423                    }
2424                }
2425                else
2426                {
2427                    Error error2;
2428                    error2.SetErrorStringWithFormat("process resume at entry point failed: %s", error.AsCString());
2429                    error = error2;
2430                }
2431            }
2432            else
2433            {
2434                error.SetErrorStringWithFormat ("initial process state wasn't stopped: %s", StateAsCString(state));
2435            }
2436        }
2437        m_process_sp->RestoreProcessEvents ();
2438    }
2439    else
2440    {
2441        Error error2;
2442        error2.SetErrorStringWithFormat ("process launch failed: %s", error.AsCString());
2443        error = error2;
2444    }
2445    return error;
2446}
2447//--------------------------------------------------------------
2448// Target::StopHook
2449//--------------------------------------------------------------
2450Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2451        UserID (uid),
2452        m_target_sp (target_sp),
2453        m_commands (),
2454        m_specifier_sp (),
2455        m_thread_spec_ap(),
2456        m_active (true)
2457{
2458}
2459
2460Target::StopHook::StopHook (const StopHook &rhs) :
2461        UserID (rhs.GetID()),
2462        m_target_sp (rhs.m_target_sp),
2463        m_commands (rhs.m_commands),
2464        m_specifier_sp (rhs.m_specifier_sp),
2465        m_thread_spec_ap (),
2466        m_active (rhs.m_active)
2467{
2468    if (rhs.m_thread_spec_ap.get() != NULL)
2469        m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2470}
2471
2472
2473Target::StopHook::~StopHook ()
2474{
2475}
2476
2477void
2478Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2479{
2480    m_thread_spec_ap.reset (specifier);
2481}
2482
2483
2484void
2485Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2486{
2487    int indent_level = s->GetIndentLevel();
2488
2489    s->SetIndentLevel(indent_level + 2);
2490
2491    s->Printf ("Hook: %" PRIu64 "\n", GetID());
2492    if (m_active)
2493        s->Indent ("State: enabled\n");
2494    else
2495        s->Indent ("State: disabled\n");
2496
2497    if (m_specifier_sp)
2498    {
2499        s->Indent();
2500        s->PutCString ("Specifier:\n");
2501        s->SetIndentLevel (indent_level + 4);
2502        m_specifier_sp->GetDescription (s, level);
2503        s->SetIndentLevel (indent_level + 2);
2504    }
2505
2506    if (m_thread_spec_ap.get() != NULL)
2507    {
2508        StreamString tmp;
2509        s->Indent("Thread:\n");
2510        m_thread_spec_ap->GetDescription (&tmp, level);
2511        s->SetIndentLevel (indent_level + 4);
2512        s->Indent (tmp.GetData());
2513        s->PutCString ("\n");
2514        s->SetIndentLevel (indent_level + 2);
2515    }
2516
2517    s->Indent ("Commands: \n");
2518    s->SetIndentLevel (indent_level + 4);
2519    uint32_t num_commands = m_commands.GetSize();
2520    for (uint32_t i = 0; i < num_commands; i++)
2521    {
2522        s->Indent(m_commands.GetStringAtIndex(i));
2523        s->PutCString ("\n");
2524    }
2525    s->SetIndentLevel (indent_level);
2526}
2527
2528//--------------------------------------------------------------
2529// class TargetProperties
2530//--------------------------------------------------------------
2531
2532OptionEnumValueElement
2533lldb_private::g_dynamic_value_types[] =
2534{
2535    { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2536    { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2537    { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2538    { 0, NULL, NULL }
2539};
2540
2541static OptionEnumValueElement
2542g_inline_breakpoint_enums[] =
2543{
2544    { eInlineBreakpointsNever,   "never",     "Never look for inline breakpoint locations (fastest). This setting should only be used if you know that no inlining occurs in your programs."},
2545    { eInlineBreakpointsHeaders, "headers",   "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
2546    { eInlineBreakpointsAlways,  "always",    "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
2547    { 0, NULL, NULL }
2548};
2549
2550typedef enum x86DisassemblyFlavor
2551{
2552    eX86DisFlavorDefault,
2553    eX86DisFlavorIntel,
2554    eX86DisFlavorATT
2555} x86DisassemblyFlavor;
2556
2557static OptionEnumValueElement
2558g_x86_dis_flavor_value_types[] =
2559{
2560    { eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
2561    { eX86DisFlavorIntel,   "intel",   "Intel disassembler flavor."},
2562    { eX86DisFlavorATT,     "att",     "AT&T disassembler flavor."},
2563    { 0, NULL, NULL }
2564};
2565
2566static OptionEnumValueElement
2567g_hex_immediate_style_values[] =
2568{
2569    { Disassembler::eHexStyleC,        "c",      "C-style (0xffff)."},
2570    { Disassembler::eHexStyleAsm,      "asm",    "Asm-style (0ffffh)."},
2571    { 0, NULL, NULL }
2572};
2573
2574static OptionEnumValueElement
2575g_load_script_from_sym_file_values[] =
2576{
2577    { eLoadScriptFromSymFileTrue,    "true",    "Load debug scripts inside symbol files"},
2578    { eLoadScriptFromSymFileFalse,   "false",   "Do not load debug scripts inside symbol files."},
2579    { eLoadScriptFromSymFileWarn,    "warn",    "Warn about debug scripts inside symbol files but do not load them."},
2580    { 0, NULL, NULL }
2581};
2582
2583
2584static OptionEnumValueElement
2585g_memory_module_load_level_values[] =
2586{
2587    { eMemoryModuleLoadLevelMinimal,  "minimal" , "Load minimal information when loading modules from memory. Currently this setting loads sections only."},
2588    { eMemoryModuleLoadLevelPartial,  "partial" , "Load partial information when loading modules from memory. Currently this setting loads sections and function bounds."},
2589    { eMemoryModuleLoadLevelComplete, "complete", "Load complete information when loading modules from memory. Currently this setting loads sections and all symbols."},
2590    { 0, NULL, NULL }
2591};
2592
2593static PropertyDefinition
2594g_properties[] =
2595{
2596    { "default-arch"                       , OptionValue::eTypeArch      , true , 0                         , NULL, NULL, "Default architecture to choose, when there's a choice." },
2597    { "expr-prefix"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2598    { "prefer-dynamic-value"               , OptionValue::eTypeEnum      , false, eNoDynamicValues          , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2599    { "enable-synthetic-value"             , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Should synthetic values be used by default whenever available." },
2600    { "skip-prologue"                      , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2601    { "source-map"                         , OptionValue::eTypePathMap   , false, 0                         , NULL, NULL, "Source path remappings used to track the change of location between a source file when built, and "
2602      "where it exists on the current system.  It consists of an array of duples, the first element of each duple is "
2603      "some part (starting at the root) of the path to the file when it was built, "
2604      "and the second is where the remainder of the original build hierarchy is rooted on the local system.  "
2605      "Each element of the array is checked in order and the first one that results in a match wins." },
2606    { "exec-search-paths"                  , OptionValue::eTypeFileSpecList, false, 0                       , NULL, NULL, "Executable search paths to use when locating executable files whose paths don't match the local file system." },
2607    { "debug-file-search-paths"            , OptionValue::eTypeFileSpecList, false, 0                       , NULL, NULL, "List of directories to be searched when locating debug symbol files." },
2608    { "max-children-count"                 , OptionValue::eTypeSInt64    , false, 256                       , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2609    { "max-string-summary-length"          , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2610    { "max-memory-read-size"               , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of bytes that 'memory read' will fetch before --force must be specified." },
2611    { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2612    { "arg0"                               , OptionValue::eTypeString    , false, 0                         , NULL, NULL, "The first argument passed to the program in the argument array which can be different from the executable itself." },
2613    { "run-args"                           , OptionValue::eTypeArgs      , false, 0                         , NULL, NULL, "A list containing all the arguments to be passed to the executable when it is run. Note that this does NOT include the argv[0] which is in target.arg0." },
2614    { "env-vars"                           , OptionValue::eTypeDictionary, false, OptionValue::eTypeString  , NULL, NULL, "A list of all the environment variables to be passed to the executable's environment, and their values." },
2615    { "inherit-env"                        , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2616    { "input-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2617    { "output-path"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2618    { "error-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2619    { "disable-aslr"                       , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2620    { "disable-stdio"                      , OptionValue::eTypeBoolean   , false, false                     , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2621    { "inline-breakpoint-strategy"         , OptionValue::eTypeEnum      , false, eInlineBreakpointsHeaders , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
2622        "Breakpoint locations can end up being inlined by the compiler, so that a compile unit 'a.c' might contain an inlined function from another source file. "
2623        "Usually this is limitted to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
2624        "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
2625        "Always checking for inlined breakpoint locations can be expensive (memory and time), so we try to minimize the "
2626        "times we look for inlined locations. This setting allows you to control exactly which strategy is used when settings "
2627        "file and line breakpoints." },
2628    // FIXME: This is the wrong way to do per-architecture settings, but we don't have a general per architecture settings system in place yet.
2629    { "x86-disassembly-flavor"             , OptionValue::eTypeEnum      , false, eX86DisFlavorDefault,       NULL, g_x86_dis_flavor_value_types, "The default disassembly flavor to use for x86 or x86-64 targets." },
2630    { "use-hex-immediates"                 , OptionValue::eTypeBoolean   , false, true,                       NULL, NULL, "Show immediates in disassembly as hexadecimal." },
2631    { "hex-immediate-style"                , OptionValue::eTypeEnum   ,    false, Disassembler::eHexStyleC,   NULL, g_hex_immediate_style_values, "Which style to use for printing hexadecimal disassembly values." },
2632    { "use-fast-stepping"                  , OptionValue::eTypeBoolean   , false, true,                       NULL, NULL, "Use a fast stepping algorithm based on running from branch to branch rather than instruction single-stepping." },
2633    { "load-script-from-symbol-file"       , OptionValue::eTypeEnum   ,    false, eLoadScriptFromSymFileWarn, NULL, g_load_script_from_sym_file_values, "Allow LLDB to load scripting resources embedded in symbol files when available." },
2634    { "memory-module-load-level"           , OptionValue::eTypeEnum   ,    false, eMemoryModuleLoadLevelComplete, NULL, g_memory_module_load_level_values,
2635        "Loading modules from memory can be slow as reading the symbol tables and other data can take a long time depending on your connection to the debug target. "
2636        "This setting helps users control how much information gets loaded when loading modules from memory."
2637        "'complete' is the default value for this setting which will load all sections and symbols by reading them from memory (slowest, most accurate). "
2638        "'partial' will load sections and attempt to find function bounds without downloading the symbol table (faster, still accurate, missing symbol names). "
2639        "'minimal' is the fastest setting and will load section data with no symbols, but should rarely be used as stack frames in these memory regions will be inaccurate and not provide any context (fastest). " },
2640    { "display-expression-in-crashlogs"    , OptionValue::eTypeBoolean   , false, false,                      NULL, NULL, "Expressions that crash will show up in crash logs if the host system supports executable specific crash log strings and this setting is set to true." },
2641    { "trap-handler-names"                 , OptionValue::eTypeArray     , true,  OptionValue::eTypeString,   NULL, NULL, "A list of trap handler function names, e.g. a common Unix user process one is _sigtramp." },
2642    { NULL                                 , OptionValue::eTypeInvalid   , false, 0                         , NULL, NULL, NULL }
2643};
2644enum
2645{
2646    ePropertyDefaultArch,
2647    ePropertyExprPrefix,
2648    ePropertyPreferDynamic,
2649    ePropertyEnableSynthetic,
2650    ePropertySkipPrologue,
2651    ePropertySourceMap,
2652    ePropertyExecutableSearchPaths,
2653    ePropertyDebugFileSearchPaths,
2654    ePropertyMaxChildrenCount,
2655    ePropertyMaxSummaryLength,
2656    ePropertyMaxMemReadSize,
2657    ePropertyBreakpointUseAvoidList,
2658    ePropertyArg0,
2659    ePropertyRunArgs,
2660    ePropertyEnvVars,
2661    ePropertyInheritEnv,
2662    ePropertyInputPath,
2663    ePropertyOutputPath,
2664    ePropertyErrorPath,
2665    ePropertyDisableASLR,
2666    ePropertyDisableSTDIO,
2667    ePropertyInlineStrategy,
2668    ePropertyDisassemblyFlavor,
2669    ePropertyUseHexImmediates,
2670    ePropertyHexImmediateStyle,
2671    ePropertyUseFastStepping,
2672    ePropertyLoadScriptFromSymbolFile,
2673    ePropertyMemoryModuleLoadLevel,
2674    ePropertyDisplayExpressionsInCrashlogs,
2675    ePropertyTrapHandlerNames
2676};
2677
2678
2679class TargetOptionValueProperties : public OptionValueProperties
2680{
2681public:
2682    TargetOptionValueProperties (const ConstString &name) :
2683        OptionValueProperties (name),
2684        m_target (NULL),
2685        m_got_host_env (false)
2686    {
2687    }
2688
2689    // This constructor is used when creating TargetOptionValueProperties when it
2690    // is part of a new lldb_private::Target instance. It will copy all current
2691    // global property values as needed
2692    TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
2693        OptionValueProperties(*target_properties_sp->GetValueProperties()),
2694        m_target (target),
2695        m_got_host_env (false)
2696    {
2697    }
2698
2699    virtual const Property *
2700    GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
2701    {
2702        // When gettings the value for a key from the target options, we will always
2703        // try and grab the setting from the current target if there is one. Else we just
2704        // use the one from this instance.
2705        if (idx == ePropertyEnvVars)
2706            GetHostEnvironmentIfNeeded ();
2707
2708        if (exe_ctx)
2709        {
2710            Target *target = exe_ctx->GetTargetPtr();
2711            if (target)
2712            {
2713                TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
2714                if (this != target_properties)
2715                    return target_properties->ProtectedGetPropertyAtIndex (idx);
2716            }
2717        }
2718        return ProtectedGetPropertyAtIndex (idx);
2719    }
2720
2721    lldb::TargetSP
2722    GetTargetSP ()
2723    {
2724        return m_target->shared_from_this();
2725    }
2726
2727protected:
2728
2729    void
2730    GetHostEnvironmentIfNeeded () const
2731    {
2732        if (!m_got_host_env)
2733        {
2734            if (m_target)
2735            {
2736                m_got_host_env = true;
2737                const uint32_t idx = ePropertyInheritEnv;
2738                if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
2739                {
2740                    PlatformSP platform_sp (m_target->GetPlatform());
2741                    if (platform_sp)
2742                    {
2743                        StringList env;
2744                        if (platform_sp->GetEnvironment(env))
2745                        {
2746                            OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
2747                            if (env_dict)
2748                            {
2749                                const bool can_replace = false;
2750                                const size_t envc = env.GetSize();
2751                                for (size_t idx=0; idx<envc; idx++)
2752                                {
2753                                    const char *env_entry = env.GetStringAtIndex (idx);
2754                                    if (env_entry)
2755                                    {
2756                                        const char *equal_pos = ::strchr(env_entry, '=');
2757                                        ConstString key;
2758                                        // It is ok to have environment variables with no values
2759                                        const char *value = NULL;
2760                                        if (equal_pos)
2761                                        {
2762                                            key.SetCStringWithLength(env_entry, equal_pos - env_entry);
2763                                            if (equal_pos[1])
2764                                                value = equal_pos + 1;
2765                                        }
2766                                        else
2767                                        {
2768                                            key.SetCString(env_entry);
2769                                        }
2770                                        // Don't allow existing keys to be replaced with ones we get from the platform environment
2771                                        env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
2772                                    }
2773                                }
2774                            }
2775                        }
2776                    }
2777                }
2778            }
2779        }
2780    }
2781    Target *m_target;
2782    mutable bool m_got_host_env;
2783};
2784
2785//----------------------------------------------------------------------
2786// TargetProperties
2787//----------------------------------------------------------------------
2788TargetProperties::TargetProperties (Target *target) :
2789    Properties ()
2790{
2791    if (target)
2792    {
2793        m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
2794    }
2795    else
2796    {
2797        m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
2798        m_collection_sp->Initialize(g_properties);
2799        m_collection_sp->AppendProperty(ConstString("process"),
2800                                        ConstString("Settings specify to processes."),
2801                                        true,
2802                                        Process::GetGlobalProperties()->GetValueProperties());
2803    }
2804}
2805
2806TargetProperties::~TargetProperties ()
2807{
2808}
2809ArchSpec
2810TargetProperties::GetDefaultArchitecture () const
2811{
2812    OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2813    if (value)
2814        return value->GetCurrentValue();
2815    return ArchSpec();
2816}
2817
2818void
2819TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
2820{
2821    OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2822    if (value)
2823        return value->SetCurrentValue(arch, true);
2824}
2825
2826lldb::DynamicValueType
2827TargetProperties::GetPreferDynamicValue() const
2828{
2829    const uint32_t idx = ePropertyPreferDynamic;
2830    return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2831}
2832
2833bool
2834TargetProperties::GetDisableASLR () const
2835{
2836    const uint32_t idx = ePropertyDisableASLR;
2837    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2838}
2839
2840void
2841TargetProperties::SetDisableASLR (bool b)
2842{
2843    const uint32_t idx = ePropertyDisableASLR;
2844    m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2845}
2846
2847bool
2848TargetProperties::GetDisableSTDIO () const
2849{
2850    const uint32_t idx = ePropertyDisableSTDIO;
2851    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2852}
2853
2854void
2855TargetProperties::SetDisableSTDIO (bool b)
2856{
2857    const uint32_t idx = ePropertyDisableSTDIO;
2858    m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2859}
2860
2861const char *
2862TargetProperties::GetDisassemblyFlavor () const
2863{
2864    const uint32_t idx = ePropertyDisassemblyFlavor;
2865    const char *return_value;
2866
2867    x86DisassemblyFlavor flavor_value = (x86DisassemblyFlavor) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2868    return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
2869    return return_value;
2870}
2871
2872InlineStrategy
2873TargetProperties::GetInlineStrategy () const
2874{
2875    const uint32_t idx = ePropertyInlineStrategy;
2876    return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2877}
2878
2879const char *
2880TargetProperties::GetArg0 () const
2881{
2882    const uint32_t idx = ePropertyArg0;
2883    return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, NULL);
2884}
2885
2886void
2887TargetProperties::SetArg0 (const char *arg)
2888{
2889    const uint32_t idx = ePropertyArg0;
2890    m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, arg);
2891}
2892
2893bool
2894TargetProperties::GetRunArguments (Args &args) const
2895{
2896    const uint32_t idx = ePropertyRunArgs;
2897    return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
2898}
2899
2900void
2901TargetProperties::SetRunArguments (const Args &args)
2902{
2903    const uint32_t idx = ePropertyRunArgs;
2904    m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
2905}
2906
2907size_t
2908TargetProperties::GetEnvironmentAsArgs (Args &env) const
2909{
2910    const uint32_t idx = ePropertyEnvVars;
2911    return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
2912}
2913
2914bool
2915TargetProperties::GetSkipPrologue() const
2916{
2917    const uint32_t idx = ePropertySkipPrologue;
2918    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2919}
2920
2921PathMappingList &
2922TargetProperties::GetSourcePathMap () const
2923{
2924    const uint32_t idx = ePropertySourceMap;
2925    OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
2926    assert(option_value);
2927    return option_value->GetCurrentValue();
2928}
2929
2930FileSpecList &
2931TargetProperties::GetExecutableSearchPaths ()
2932{
2933    const uint32_t idx = ePropertyExecutableSearchPaths;
2934    OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2935    assert(option_value);
2936    return option_value->GetCurrentValue();
2937}
2938
2939FileSpecList &
2940TargetProperties::GetDebugFileSearchPaths ()
2941{
2942    const uint32_t idx = ePropertyDebugFileSearchPaths;
2943    OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2944    assert(option_value);
2945    return option_value->GetCurrentValue();
2946}
2947
2948bool
2949TargetProperties::GetEnableSyntheticValue () const
2950{
2951    const uint32_t idx = ePropertyEnableSynthetic;
2952    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2953}
2954
2955uint32_t
2956TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
2957{
2958    const uint32_t idx = ePropertyMaxChildrenCount;
2959    return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2960}
2961
2962uint32_t
2963TargetProperties::GetMaximumSizeOfStringSummary() const
2964{
2965    const uint32_t idx = ePropertyMaxSummaryLength;
2966    return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2967}
2968
2969uint32_t
2970TargetProperties::GetMaximumMemReadSize () const
2971{
2972    const uint32_t idx = ePropertyMaxMemReadSize;
2973    return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2974}
2975
2976FileSpec
2977TargetProperties::GetStandardInputPath () const
2978{
2979    const uint32_t idx = ePropertyInputPath;
2980    return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2981}
2982
2983void
2984TargetProperties::SetStandardInputPath (const char *p)
2985{
2986    const uint32_t idx = ePropertyInputPath;
2987    m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2988}
2989
2990FileSpec
2991TargetProperties::GetStandardOutputPath () const
2992{
2993    const uint32_t idx = ePropertyOutputPath;
2994    return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2995}
2996
2997void
2998TargetProperties::SetStandardOutputPath (const char *p)
2999{
3000    const uint32_t idx = ePropertyOutputPath;
3001    m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3002}
3003
3004FileSpec
3005TargetProperties::GetStandardErrorPath () const
3006{
3007    const uint32_t idx = ePropertyErrorPath;
3008    return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
3009}
3010
3011const char *
3012TargetProperties::GetExpressionPrefixContentsAsCString ()
3013{
3014    const uint32_t idx = ePropertyExprPrefix;
3015    OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
3016    if (file)
3017    {
3018        const bool null_terminate = true;
3019        DataBufferSP data_sp(file->GetFileContents(null_terminate));
3020        if (data_sp)
3021            return (const char *) data_sp->GetBytes();
3022    }
3023    return NULL;
3024}
3025
3026void
3027TargetProperties::SetStandardErrorPath (const char *p)
3028{
3029    const uint32_t idx = ePropertyErrorPath;
3030    m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3031}
3032
3033bool
3034TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
3035{
3036    const uint32_t idx = ePropertyBreakpointUseAvoidList;
3037    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3038}
3039
3040bool
3041TargetProperties::GetUseHexImmediates () const
3042{
3043    const uint32_t idx = ePropertyUseHexImmediates;
3044    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3045}
3046
3047bool
3048TargetProperties::GetUseFastStepping () const
3049{
3050    const uint32_t idx = ePropertyUseFastStepping;
3051    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3052}
3053
3054bool
3055TargetProperties::GetDisplayExpressionsInCrashlogs () const
3056{
3057    const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3058    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3059}
3060
3061LoadScriptFromSymFile
3062TargetProperties::GetLoadScriptFromSymbolFile () const
3063{
3064    const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3065    return (LoadScriptFromSymFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3066}
3067
3068Disassembler::HexImmediateStyle
3069TargetProperties::GetHexImmediateStyle () const
3070{
3071    const uint32_t idx = ePropertyHexImmediateStyle;
3072    return (Disassembler::HexImmediateStyle)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3073}
3074
3075MemoryModuleLoadLevel
3076TargetProperties::GetMemoryModuleLoadLevel() const
3077{
3078    const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3079    return (MemoryModuleLoadLevel)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3080}
3081
3082bool
3083TargetProperties::GetUserSpecifiedTrapHandlerNames (Args &args) const
3084{
3085    const uint32_t idx = ePropertyTrapHandlerNames;
3086    return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
3087}
3088
3089void
3090TargetProperties::SetUserSpecifiedTrapHandlerNames (const Args &args)
3091{
3092    const uint32_t idx = ePropertyTrapHandlerNames;
3093    m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
3094}
3095
3096//----------------------------------------------------------------------
3097// Target::TargetEventData
3098//----------------------------------------------------------------------
3099const ConstString &
3100Target::TargetEventData::GetFlavorString ()
3101{
3102    static ConstString g_flavor ("Target::TargetEventData");
3103    return g_flavor;
3104}
3105
3106const ConstString &
3107Target::TargetEventData::GetFlavor () const
3108{
3109    return TargetEventData::GetFlavorString ();
3110}
3111
3112Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) :
3113    EventData(),
3114    m_target_sp (new_target_sp)
3115{
3116}
3117
3118Target::TargetEventData::~TargetEventData()
3119{
3120
3121}
3122
3123void
3124Target::TargetEventData::Dump (Stream *s) const
3125{
3126
3127}
3128
3129const TargetSP
3130Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp)
3131{
3132    TargetSP target_sp;
3133
3134    const TargetEventData *data = GetEventDataFromEvent (event_sp.get());
3135    if (data)
3136        target_sp = data->m_target_sp;
3137
3138    return target_sp;
3139}
3140
3141const Target::TargetEventData *
3142Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
3143{
3144    if (event_ptr)
3145    {
3146        const EventData *event_data = event_ptr->GetData();
3147        if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
3148            return static_cast <const TargetEventData *> (event_ptr->GetData());
3149    }
3150    return NULL;
3151}
3152
3153