Target.cpp revision 5b2fc57efda331443d9b81e5d2eba7d0b7091a9e
12b06aaa2a6bcd363c25fb0c43f6bb906906594bdBehdad Esfahbod//===-- Target.cpp ----------------------------------------------*- C++ -*-===//
28413c108d21e8cf0e9059bbfffde8d13f2616340Behdad Esfahbod//
37842e56b97ce677b83bdab09cda48bc2d89ac75aJust//                     The LLVM Compiler Infrastructure
47842e56b97ce677b83bdab09cda48bc2d89ac75aJust//
57842e56b97ce677b83bdab09cda48bc2d89ac75aJust// This file is distributed under the University of Illinois Open Source
6fd5a93240e40e265ab3f956300790e2eea0afa54Just// License. See LICENSE.TXT for details.
77842e56b97ce677b83bdab09cda48bc2d89ac75aJust//
87842e56b97ce677b83bdab09cda48bc2d89ac75aJust//===----------------------------------------------------------------------===//
97842e56b97ce677b83bdab09cda48bc2d89ac75aJust
107842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Target/Target.h"
117842e56b97ce677b83bdab09cda48bc2d89ac75aJust
127842e56b97ce677b83bdab09cda48bc2d89ac75aJust// C Includes
137842e56b97ce677b83bdab09cda48bc2d89ac75aJust// C++ Includes
147842e56b97ce677b83bdab09cda48bc2d89ac75aJust// Other libraries and framework includes
157842e56b97ce677b83bdab09cda48bc2d89ac75aJust// Project includes
167842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Breakpoint/BreakpointResolver.h"
177842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Breakpoint/BreakpointResolverAddress.h"
187842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Breakpoint/BreakpointResolverFileLine.h"
197842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Breakpoint/BreakpointResolverName.h"
207842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Core/Debugger.h"
217842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Core/Event.h"
227842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Core/Log.h"
237842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Core/StreamAsynchronousIO.h"
247842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Core/StreamString.h"
257842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Core/Timer.h"
267842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Core/ValueObject.h"
277842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Expression/ClangUserExpression.h"
287842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Host/Host.h"
297842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Interpreter/CommandInterpreter.h"
307842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Interpreter/CommandReturnObject.h"
317842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/lldb-private-log.h"
327842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Symbol/ObjectFile.h"
337842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Target/Process.h"
347842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Target/StackFrame.h"
357842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Target/Thread.h"
367842e56b97ce677b83bdab09cda48bc2d89ac75aJust#include "lldb/Target/ThreadSpec.h"
37ac1b4359467ca3deab03186a15eae1d55eb35567Behdad Esfahbod
387842e56b97ce677b83bdab09cda48bc2d89ac75aJustusing namespace lldb;
397842e56b97ce677b83bdab09cda48bc2d89ac75aJustusing namespace lldb_private;
407842e56b97ce677b83bdab09cda48bc2d89ac75aJust
417842e56b97ce677b83bdab09cda48bc2d89ac75aJust//----------------------------------------------------------------------
427842e56b97ce677b83bdab09cda48bc2d89ac75aJust// Target constructor
437842e56b97ce677b83bdab09cda48bc2d89ac75aJust//----------------------------------------------------------------------
447842e56b97ce677b83bdab09cda48bc2d89ac75aJustTarget::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
457842e56b97ce677b83bdab09cda48bc2d89ac75aJust    Broadcaster ("lldb.target"),
467842e56b97ce677b83bdab09cda48bc2d89ac75aJust    ExecutionContextScope (),
477842e56b97ce677b83bdab09cda48bc2d89ac75aJust    TargetInstanceSettings (*GetSettingsController()),
487842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_debugger (debugger),
49ac1b4359467ca3deab03186a15eae1d55eb35567Behdad Esfahbod    m_platform_sp (platform_sp),
507842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_mutex (Mutex::eMutexTypeRecursive),
517842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_arch (target_arch),
527842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_images (),
537842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_section_load_list (),
547842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_breakpoint_list (false),
557842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_internal_breakpoint_list (true),
567842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_watchpoint_location_list (),
577842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_process_sp (),
587842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_search_filter_sp (),
59dc7e6f3e5563a853477ebe26166b002c158dbe8bBehdad Esfahbod    m_image_search_paths (ImageSearchPathsChanged, this),
607842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_scratch_ast_context_ap (NULL),
617842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_persistent_variables (),
627842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_source_manager(*this),
637842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_stop_hooks (),
647842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_stop_hook_next_id (0),
657842e56b97ce677b83bdab09cda48bc2d89ac75aJust    m_suppress_stop_hooks (false)
667842e56b97ce677b83bdab09cda48bc2d89ac75aJust{
677842e56b97ce677b83bdab09cda48bc2d89ac75aJust    SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
681872557451256004f27133686eeddbbbdf163c69jvr    SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
691872557451256004f27133686eeddbbbdf163c69jvr    SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
707842e56b97ce677b83bdab09cda48bc2d89ac75aJust
717842e56b97ce677b83bdab09cda48bc2d89ac75aJust    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
727842e56b97ce677b83bdab09cda48bc2d89ac75aJust    if (log)
737842e56b97ce677b83bdab09cda48bc2d89ac75aJust        log->Printf ("%p Target::Target()", this);
747842e56b97ce677b83bdab09cda48bc2d89ac75aJust}
753a9fd301808f5a8991ca9ac44028d1ecb22d307fBehdad Esfahbod
76180ace6a5ff1399ec53bc696e8bef7cce6eef39aBehdad Esfahbod//----------------------------------------------------------------------
777842e56b97ce677b83bdab09cda48bc2d89ac75aJust// Destructor
78ca4c45681ef2ea9290c6845f8bf61dff281fc5c4jvr//----------------------------------------------------------------------
797842e56b97ce677b83bdab09cda48bc2d89ac75aJustTarget::~Target()
807842e56b97ce677b83bdab09cda48bc2d89ac75aJust{
817842e56b97ce677b83bdab09cda48bc2d89ac75aJust    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
82e5ca79699d00fdf7ac6eaceaed372aea8d6bc1fdBehdad Esfahbod    if (log)
837842e56b97ce677b83bdab09cda48bc2d89ac75aJust        log->Printf ("%p Target::~Target()", this);
847842e56b97ce677b83bdab09cda48bc2d89ac75aJust    DeleteCurrentProcess ();
857842e56b97ce677b83bdab09cda48bc2d89ac75aJust}
867842e56b97ce677b83bdab09cda48bc2d89ac75aJust
877842e56b97ce677b83bdab09cda48bc2d89ac75aJustvoid
887842e56b97ce677b83bdab09cda48bc2d89ac75aJustTarget::Dump (Stream *s, lldb::DescriptionLevel description_level)
897842e56b97ce677b83bdab09cda48bc2d89ac75aJust{
907842e56b97ce677b83bdab09cda48bc2d89ac75aJust//    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
917842e56b97ce677b83bdab09cda48bc2d89ac75aJust    if (description_level != lldb::eDescriptionLevelBrief)
921872557451256004f27133686eeddbbbdf163c69jvr    {
931872557451256004f27133686eeddbbbdf163c69jvr        s->Indent();
941872557451256004f27133686eeddbbbdf163c69jvr        s->PutCString("Target\n");
95e5ca79699d00fdf7ac6eaceaed372aea8d6bc1fdBehdad Esfahbod        s->IndentMore();
967842e56b97ce677b83bdab09cda48bc2d89ac75aJust            m_images.Dump(s);
977842e56b97ce677b83bdab09cda48bc2d89ac75aJust            m_breakpoint_list.Dump(s);
987842e56b97ce677b83bdab09cda48bc2d89ac75aJust            m_internal_breakpoint_list.Dump(s);
997842e56b97ce677b83bdab09cda48bc2d89ac75aJust        s->IndentLess();
100    }
101    else
102    {
103        Module *exe_module = GetExecutableModulePointer();
104        if (exe_module)
105            s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
106        else
107            s->PutCString ("No executable module.");
108    }
109}
110
111void
112Target::DeleteCurrentProcess ()
113{
114    if (m_process_sp.get())
115    {
116        m_section_load_list.Clear();
117        if (m_process_sp->IsAlive())
118            m_process_sp->Destroy();
119
120        m_process_sp->Finalize();
121
122        // Do any cleanup of the target we need to do between process instances.
123        // NB It is better to do this before destroying the process in case the
124        // clean up needs some help from the process.
125        m_breakpoint_list.ClearAllBreakpointSites();
126        m_internal_breakpoint_list.ClearAllBreakpointSites();
127        m_process_sp.reset();
128    }
129}
130
131const lldb::ProcessSP &
132Target::CreateProcess (Listener &listener, const char *plugin_name)
133{
134    DeleteCurrentProcess ();
135    m_process_sp.reset(Process::FindPlugin(*this, plugin_name, listener));
136    return m_process_sp;
137}
138
139const lldb::ProcessSP &
140Target::GetProcessSP () const
141{
142    return m_process_sp;
143}
144
145lldb::TargetSP
146Target::GetSP()
147{
148    return m_debugger.GetTargetList().GetTargetSP(this);
149}
150
151void
152Target::Destroy()
153{
154    Mutex::Locker locker (m_mutex);
155    DeleteCurrentProcess ();
156    m_platform_sp.reset();
157    m_arch.Clear();
158    m_images.Clear();
159    m_section_load_list.Clear();
160    const bool notify = false;
161    m_breakpoint_list.RemoveAll(notify);
162    m_internal_breakpoint_list.RemoveAll(notify);
163    m_last_created_breakpoint.reset();
164    m_search_filter_sp.reset();
165    m_image_search_paths.Clear(notify);
166    m_scratch_ast_context_ap.reset();
167    m_persistent_variables.Clear();
168    m_stop_hooks.clear();
169    m_stop_hook_next_id = 0;
170    m_suppress_stop_hooks = false;
171}
172
173
174BreakpointList &
175Target::GetBreakpointList(bool internal)
176{
177    if (internal)
178        return m_internal_breakpoint_list;
179    else
180        return m_breakpoint_list;
181}
182
183const BreakpointList &
184Target::GetBreakpointList(bool internal) const
185{
186    if (internal)
187        return m_internal_breakpoint_list;
188    else
189        return m_breakpoint_list;
190}
191
192BreakpointSP
193Target::GetBreakpointByID (break_id_t break_id)
194{
195    BreakpointSP bp_sp;
196
197    if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
198        bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
199    else
200        bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
201
202    return bp_sp;
203}
204
205BreakpointSP
206Target::CreateBreakpoint (const FileSpec *containingModule, const FileSpec &file, uint32_t line_no, bool check_inlines, bool internal)
207{
208    SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
209    BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL, file, line_no, check_inlines));
210    return CreateBreakpoint (filter_sp, resolver_sp, internal);
211}
212
213
214BreakpointSP
215Target::CreateBreakpoint (lldb::addr_t addr, bool internal)
216{
217    Address so_addr;
218    // Attempt to resolve our load address if possible, though it is ok if
219    // it doesn't resolve to section/offset.
220
221    // Try and resolve as a load address if possible
222    m_section_load_list.ResolveLoadAddress(addr, so_addr);
223    if (!so_addr.IsValid())
224    {
225        // The address didn't resolve, so just set this as an absolute address
226        so_addr.SetOffset (addr);
227    }
228    BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal));
229    return bp_sp;
230}
231
232BreakpointSP
233Target::CreateBreakpoint (Address &addr, bool internal)
234{
235    TargetSP target_sp = this->GetSP();
236    SearchFilterSP filter_sp(new SearchFilter (target_sp));
237    BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
238    return CreateBreakpoint (filter_sp, resolver_sp, internal);
239}
240
241BreakpointSP
242Target::CreateBreakpoint (const FileSpec *containingModule,
243                          const char *func_name,
244                          uint32_t func_name_type_mask,
245                          bool internal,
246                          LazyBool skip_prologue)
247{
248    BreakpointSP bp_sp;
249    if (func_name)
250    {
251        SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
252
253        BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
254                                                                      func_name,
255                                                                      func_name_type_mask,
256                                                                      Breakpoint::Exact,
257                                                                      skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
258        bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
259    }
260    return bp_sp;
261}
262
263
264SearchFilterSP
265Target::GetSearchFilterForModule (const FileSpec *containingModule)
266{
267    SearchFilterSP filter_sp;
268    lldb::TargetSP target_sp = this->GetSP();
269    if (containingModule != NULL)
270    {
271        // TODO: We should look into sharing module based search filters
272        // across many breakpoints like we do for the simple target based one
273        filter_sp.reset (new SearchFilterByModule (target_sp, *containingModule));
274    }
275    else
276    {
277        if (m_search_filter_sp.get() == NULL)
278            m_search_filter_sp.reset (new SearchFilter (target_sp));
279        filter_sp = m_search_filter_sp;
280    }
281    return filter_sp;
282}
283
284BreakpointSP
285Target::CreateBreakpoint (const FileSpec *containingModule,
286                          RegularExpression &func_regex,
287                          bool internal,
288                          LazyBool skip_prologue)
289{
290    SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
291    BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
292                                                                 func_regex,
293                                                                 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
294
295    return CreateBreakpoint (filter_sp, resolver_sp, internal);
296}
297
298BreakpointSP
299Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal)
300{
301    BreakpointSP bp_sp;
302    if (filter_sp && resolver_sp)
303    {
304        bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp));
305        resolver_sp->SetBreakpoint (bp_sp.get());
306
307        if (internal)
308            m_internal_breakpoint_list.Add (bp_sp, false);
309        else
310            m_breakpoint_list.Add (bp_sp, true);
311
312        LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
313        if (log)
314        {
315            StreamString s;
316            bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
317            log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
318        }
319
320        bp_sp->ResolveBreakpoint();
321    }
322
323    if (!internal && bp_sp)
324    {
325        m_last_created_breakpoint = bp_sp;
326    }
327
328    return bp_sp;
329}
330
331// See also WatchpointLocation::SetWatchpointType(uint32_t type) and
332// the OptionGroupWatchpoint::WatchType enum type.
333WatchpointLocationSP
334Target::CreateWatchpointLocation(lldb::addr_t addr, size_t size, uint32_t type)
335{
336    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
337    if (log)
338        log->Printf("Target::%s (addr = 0x%8.8llx size = %zu type = %u)\n",
339                    __FUNCTION__, addr, size, type);
340
341    WatchpointLocationSP wp_loc_sp;
342    bool process_is_valid = m_process_sp && m_process_sp->IsAlive();
343    if (!process_is_valid)
344        return wp_loc_sp;
345    if (addr == LLDB_INVALID_ADDRESS)
346        return wp_loc_sp;
347    if (size == 0)
348        return wp_loc_sp;
349
350    // Currently we only support one watchpoint location per address, with total
351    // number of watchpoint locations limited by the hardware which the inferior
352    // is running on.
353    WatchpointLocationSP matched_sp = m_watchpoint_location_list.FindByAddress(addr);
354    if (matched_sp)
355    {
356        size_t old_size = matched_sp->GetByteSize();
357        uint32_t old_type =
358            (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
359            (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
360        // Return an empty watchpoint location if the same one exists already.
361        if (size == old_size && type == old_type)
362            return wp_loc_sp;
363
364        // Nil the matched watchpoint location; we will be creating a new one.
365        m_process_sp->DisableWatchpoint(matched_sp.get());
366        m_watchpoint_location_list.Remove(matched_sp->GetID());
367    }
368
369    WatchpointLocation *new_loc = new WatchpointLocation(addr, size);
370    if (!new_loc)
371        printf("WatchpointLocation ctor failed, out of memory?\n");
372
373    new_loc->SetWatchpointType(type);
374    wp_loc_sp.reset(new_loc);
375    m_watchpoint_location_list.Add(wp_loc_sp);
376    Error rc = m_process_sp->EnableWatchpoint(wp_loc_sp.get());
377    if (rc.Success())
378        wp_loc_sp->SetEnabled(true);
379
380    if (log)
381            log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
382                        __FUNCTION__,
383                        rc.Success() ? "succeeded" : "failed",
384                        wp_loc_sp->GetID());
385
386    return wp_loc_sp;
387}
388
389void
390Target::RemoveAllBreakpoints (bool internal_also)
391{
392    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
393    if (log)
394        log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
395
396    m_breakpoint_list.RemoveAll (true);
397    if (internal_also)
398        m_internal_breakpoint_list.RemoveAll (false);
399
400    m_last_created_breakpoint.reset();
401}
402
403void
404Target::DisableAllBreakpoints (bool internal_also)
405{
406    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
407    if (log)
408        log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
409
410    m_breakpoint_list.SetEnabledAll (false);
411    if (internal_also)
412        m_internal_breakpoint_list.SetEnabledAll (false);
413}
414
415void
416Target::EnableAllBreakpoints (bool internal_also)
417{
418    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
419    if (log)
420        log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
421
422    m_breakpoint_list.SetEnabledAll (true);
423    if (internal_also)
424        m_internal_breakpoint_list.SetEnabledAll (true);
425}
426
427bool
428Target::RemoveBreakpointByID (break_id_t break_id)
429{
430    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
431    if (log)
432        log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
433
434    if (DisableBreakpointByID (break_id))
435    {
436        if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
437            m_internal_breakpoint_list.Remove(break_id, false);
438        else
439        {
440            if (m_last_created_breakpoint)
441            {
442                if (m_last_created_breakpoint->GetID() == break_id)
443                    m_last_created_breakpoint.reset();
444            }
445            m_breakpoint_list.Remove(break_id, true);
446        }
447        return true;
448    }
449    return false;
450}
451
452bool
453Target::DisableBreakpointByID (break_id_t break_id)
454{
455    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
456    if (log)
457        log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
458
459    BreakpointSP bp_sp;
460
461    if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
462        bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
463    else
464        bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
465    if (bp_sp)
466    {
467        bp_sp->SetEnabled (false);
468        return true;
469    }
470    return false;
471}
472
473bool
474Target::EnableBreakpointByID (break_id_t break_id)
475{
476    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
477    if (log)
478        log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
479                     __FUNCTION__,
480                     break_id,
481                     LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
482
483    BreakpointSP bp_sp;
484
485    if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
486        bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
487    else
488        bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
489
490    if (bp_sp)
491    {
492        bp_sp->SetEnabled (true);
493        return true;
494    }
495    return false;
496}
497
498ModuleSP
499Target::GetExecutableModule ()
500{
501    return m_images.GetModuleAtIndex(0);
502}
503
504Module*
505Target::GetExecutableModulePointer ()
506{
507    return m_images.GetModulePointerAtIndex(0);
508}
509
510void
511Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
512{
513    m_images.Clear();
514    m_scratch_ast_context_ap.reset();
515
516    if (executable_sp.get())
517    {
518        Timer scoped_timer (__PRETTY_FUNCTION__,
519                            "Target::SetExecutableModule (executable = '%s/%s')",
520                            executable_sp->GetFileSpec().GetDirectory().AsCString(),
521                            executable_sp->GetFileSpec().GetFilename().AsCString());
522
523        m_images.Append(executable_sp); // The first image is our exectuable file
524
525        // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
526        if (!m_arch.IsValid())
527            m_arch = executable_sp->GetArchitecture();
528
529        FileSpecList dependent_files;
530        ObjectFile *executable_objfile = executable_sp->GetObjectFile();
531        // Let's find the file & line for main and set the default source file from there.
532        if (!m_source_manager.DefaultFileAndLineSet())
533        {
534            SymbolContextList sc_list;
535            uint32_t num_matches;
536            ConstString main_name("main");
537            bool symbols_okay = false;  // Force it to be a debug symbol.
538            bool append = false;
539            num_matches = executable_sp->FindFunctions (main_name, eFunctionNameTypeBase, symbols_okay, append, sc_list);
540            for (uint32_t idx = 0; idx < num_matches; idx++)
541            {
542                SymbolContext sc;
543                sc_list.GetContextAtIndex(idx, sc);
544                if (sc.line_entry.file)
545                {
546                    m_source_manager.SetDefaultFileAndLine(sc.line_entry.file, sc.line_entry.line);
547                    break;
548                }
549            }
550        }
551
552        if (executable_objfile)
553        {
554            executable_objfile->GetDependentModules(dependent_files);
555            for (uint32_t i=0; i<dependent_files.GetSize(); i++)
556            {
557                FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
558                FileSpec platform_dependent_file_spec;
559                if (m_platform_sp)
560                    m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec);
561                else
562                    platform_dependent_file_spec = dependent_file_spec;
563
564                ModuleSP image_module_sp(GetSharedModule (platform_dependent_file_spec,
565                                                          m_arch));
566                if (image_module_sp.get())
567                {
568                    ObjectFile *objfile = image_module_sp->GetObjectFile();
569                    if (objfile)
570                        objfile->GetDependentModules(dependent_files);
571                }
572            }
573        }
574
575    }
576
577    UpdateInstanceName();
578}
579
580
581bool
582Target::SetArchitecture (const ArchSpec &arch_spec)
583{
584    if (m_arch == arch_spec)
585    {
586        // If we're setting the architecture to our current architecture, we
587        // don't need to do anything.
588        return true;
589    }
590    else if (!m_arch.IsValid())
591    {
592        // If we haven't got a valid arch spec, then we just need to set it.
593        m_arch = arch_spec;
594        return true;
595    }
596    else
597    {
598        // If we have an executable file, try to reset the executable to the desired architecture
599        m_arch = arch_spec;
600        ModuleSP executable_sp = GetExecutableModule ();
601        m_images.Clear();
602        m_scratch_ast_context_ap.reset();
603        // Need to do something about unsetting breakpoints.
604
605        if (executable_sp)
606        {
607            FileSpec exec_file_spec = executable_sp->GetFileSpec();
608            Error error = ModuleList::GetSharedModule(exec_file_spec,
609                                                      arch_spec,
610                                                      NULL,
611                                                      NULL,
612                                                      0,
613                                                      executable_sp,
614                                                      NULL,
615                                                      NULL);
616
617            if (!error.Fail() && executable_sp)
618            {
619                SetExecutableModule (executable_sp, true);
620                return true;
621            }
622            else
623            {
624                return false;
625            }
626        }
627        else
628        {
629            return false;
630        }
631    }
632}
633
634void
635Target::ModuleAdded (ModuleSP &module_sp)
636{
637    // A module is being added to this target for the first time
638    ModuleList module_list;
639    module_list.Append(module_sp);
640    ModulesDidLoad (module_list);
641}
642
643void
644Target::ModuleUpdated (ModuleSP &old_module_sp, ModuleSP &new_module_sp)
645{
646    // A module is replacing an already added module
647    ModuleList module_list;
648    module_list.Append (old_module_sp);
649    ModulesDidUnload (module_list);
650    module_list.Clear ();
651    module_list.Append (new_module_sp);
652    ModulesDidLoad (module_list);
653}
654
655void
656Target::ModulesDidLoad (ModuleList &module_list)
657{
658    m_breakpoint_list.UpdateBreakpoints (module_list, true);
659    // TODO: make event data that packages up the module_list
660    BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
661}
662
663void
664Target::ModulesDidUnload (ModuleList &module_list)
665{
666    m_breakpoint_list.UpdateBreakpoints (module_list, false);
667
668    // Remove the images from the target image list
669    m_images.Remove(module_list);
670
671    // TODO: make event data that packages up the module_list
672    BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
673}
674
675size_t
676Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
677{
678    const Section *section = addr.GetSection();
679    if (section && section->GetModule())
680    {
681        ObjectFile *objfile = section->GetModule()->GetObjectFile();
682        if (objfile)
683        {
684            size_t bytes_read = section->ReadSectionDataFromObjectFile (objfile,
685                                                                        addr.GetOffset(),
686                                                                        dst,
687                                                                        dst_len);
688            if (bytes_read > 0)
689                return bytes_read;
690            else
691                error.SetErrorStringWithFormat("error reading data from section %s", section->GetName().GetCString());
692        }
693        else
694        {
695            error.SetErrorString("address isn't from a object file");
696        }
697    }
698    else
699    {
700        error.SetErrorString("address doesn't contain a section that points to a section in a object file");
701    }
702    return 0;
703}
704
705size_t
706Target::ReadMemory (const Address& addr,
707                    bool prefer_file_cache,
708                    void *dst,
709                    size_t dst_len,
710                    Error &error,
711                    lldb::addr_t *load_addr_ptr)
712{
713    error.Clear();
714
715    // if we end up reading this from process memory, we will fill this
716    // with the actual load address
717    if (load_addr_ptr)
718        *load_addr_ptr = LLDB_INVALID_ADDRESS;
719
720    bool process_is_valid = m_process_sp && m_process_sp->IsAlive();
721
722    size_t bytes_read = 0;
723
724    addr_t load_addr = LLDB_INVALID_ADDRESS;
725    addr_t file_addr = LLDB_INVALID_ADDRESS;
726    Address resolved_addr;
727    if (!addr.IsSectionOffset())
728    {
729        if (m_section_load_list.IsEmpty())
730        {
731            // No sections are loaded, so we must assume we are not running
732            // yet and anything we are given is a file address.
733            file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
734            m_images.ResolveFileAddress (file_addr, resolved_addr);
735        }
736        else
737        {
738            // We have at least one section loaded. This can be becuase
739            // we have manually loaded some sections with "target modules load ..."
740            // or because we have have a live process that has sections loaded
741            // through the dynamic loader
742            load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
743            m_section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
744        }
745    }
746    if (!resolved_addr.IsValid())
747        resolved_addr = addr;
748
749
750    if (prefer_file_cache)
751    {
752        bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
753        if (bytes_read > 0)
754            return bytes_read;
755    }
756
757    if (process_is_valid)
758    {
759        if (load_addr == LLDB_INVALID_ADDRESS)
760            load_addr = resolved_addr.GetLoadAddress (this);
761
762        if (load_addr == LLDB_INVALID_ADDRESS)
763        {
764            if (resolved_addr.GetModule() && resolved_addr.GetModule()->GetFileSpec())
765                error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded.\n",
766                                               resolved_addr.GetModule()->GetFileSpec().GetFilename().AsCString(),
767                                               resolved_addr.GetFileAddress());
768            else
769                error.SetErrorStringWithFormat("0x%llx can't be resolved.\n", resolved_addr.GetFileAddress());
770        }
771        else
772        {
773            bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
774            if (bytes_read != dst_len)
775            {
776                if (error.Success())
777                {
778                    if (bytes_read == 0)
779                        error.SetErrorStringWithFormat("Read memory from 0x%llx failed.\n", load_addr);
780                    else
781                        error.SetErrorStringWithFormat("Only %zu of %zu bytes were read from memory at 0x%llx.\n", bytes_read, dst_len, load_addr);
782                }
783            }
784            if (bytes_read)
785            {
786                if (load_addr_ptr)
787                    *load_addr_ptr = load_addr;
788                return bytes_read;
789            }
790            // If the address is not section offset we have an address that
791            // doesn't resolve to any address in any currently loaded shared
792            // libaries and we failed to read memory so there isn't anything
793            // more we can do. If it is section offset, we might be able to
794            // read cached memory from the object file.
795            if (!resolved_addr.IsSectionOffset())
796                return 0;
797        }
798    }
799
800    if (!prefer_file_cache && resolved_addr.IsSectionOffset())
801    {
802        // If we didn't already try and read from the object file cache, then
803        // try it after failing to read from the process.
804        return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
805    }
806    return 0;
807}
808
809size_t
810Target::ReadScalarIntegerFromMemory (const Address& addr,
811                                     bool prefer_file_cache,
812                                     uint32_t byte_size,
813                                     bool is_signed,
814                                     Scalar &scalar,
815                                     Error &error)
816{
817    uint64_t uval;
818
819    if (byte_size <= sizeof(uval))
820    {
821        size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
822        if (bytes_read == byte_size)
823        {
824            DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
825            uint32_t offset = 0;
826            if (byte_size <= 4)
827                scalar = data.GetMaxU32 (&offset, byte_size);
828            else
829                scalar = data.GetMaxU64 (&offset, byte_size);
830
831            if (is_signed)
832                scalar.SignExtend(byte_size * 8);
833            return bytes_read;
834        }
835    }
836    else
837    {
838        error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
839    }
840    return 0;
841}
842
843uint64_t
844Target::ReadUnsignedIntegerFromMemory (const Address& addr,
845                                       bool prefer_file_cache,
846                                       size_t integer_byte_size,
847                                       uint64_t fail_value,
848                                       Error &error)
849{
850    Scalar scalar;
851    if (ReadScalarIntegerFromMemory (addr,
852                                     prefer_file_cache,
853                                     integer_byte_size,
854                                     false,
855                                     scalar,
856                                     error))
857        return scalar.ULongLong(fail_value);
858    return fail_value;
859}
860
861bool
862Target::ReadPointerFromMemory (const Address& addr,
863                               bool prefer_file_cache,
864                               Error &error,
865                               Address &pointer_addr)
866{
867    Scalar scalar;
868    if (ReadScalarIntegerFromMemory (addr,
869                                     prefer_file_cache,
870                                     m_arch.GetAddressByteSize(),
871                                     false,
872                                     scalar,
873                                     error))
874    {
875        addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
876        if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
877        {
878            if (m_section_load_list.IsEmpty())
879            {
880                // No sections are loaded, so we must assume we are not running
881                // yet and anything we are given is a file address.
882                m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
883            }
884            else
885            {
886                // We have at least one section loaded. This can be becuase
887                // we have manually loaded some sections with "target modules load ..."
888                // or because we have have a live process that has sections loaded
889                // through the dynamic loader
890                m_section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
891            }
892            // We weren't able to resolve the pointer value, so just return
893            // an address with no section
894            if (!pointer_addr.IsValid())
895                pointer_addr.SetOffset (pointer_vm_addr);
896            return true;
897
898        }
899    }
900    return false;
901}
902
903ModuleSP
904Target::GetSharedModule
905(
906    const FileSpec& file_spec,
907    const ArchSpec& arch,
908    const lldb_private::UUID *uuid_ptr,
909    const ConstString *object_name,
910    off_t object_offset,
911    Error *error_ptr
912)
913{
914    // Don't pass in the UUID so we can tell if we have a stale value in our list
915    ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
916    bool did_create_module = false;
917    ModuleSP module_sp;
918
919    Error error;
920
921    // If there are image search path entries, try to use them first to acquire a suitable image.
922    if (m_image_search_paths.GetSize())
923    {
924        FileSpec transformed_spec;
925        if (m_image_search_paths.RemapPath (file_spec.GetDirectory(), transformed_spec.GetDirectory()))
926        {
927            transformed_spec.GetFilename() = file_spec.GetFilename();
928            error = ModuleList::GetSharedModule (transformed_spec, arch, uuid_ptr, object_name, object_offset, module_sp, &old_module_sp, &did_create_module);
929        }
930    }
931
932    // The platform is responsible for finding and caching an appropriate
933    // module in the shared module cache.
934    if (m_platform_sp)
935    {
936        FileSpec platform_file_spec;
937        error = m_platform_sp->GetSharedModule (file_spec,
938                                                arch,
939                                                uuid_ptr,
940                                                object_name,
941                                                object_offset,
942                                                module_sp,
943                                                &old_module_sp,
944                                                &did_create_module);
945    }
946    else
947    {
948        error.SetErrorString("no platform is currently set");
949    }
950
951    // If a module hasn't been found yet, use the unmodified path.
952    if (module_sp)
953    {
954        m_images.Append (module_sp);
955        if (did_create_module)
956        {
957            if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
958                ModuleUpdated(old_module_sp, module_sp);
959            else
960                ModuleAdded(module_sp);
961        }
962    }
963    if (error_ptr)
964        *error_ptr = error;
965    return module_sp;
966}
967
968
969Target *
970Target::CalculateTarget ()
971{
972    return this;
973}
974
975Process *
976Target::CalculateProcess ()
977{
978    return NULL;
979}
980
981Thread *
982Target::CalculateThread ()
983{
984    return NULL;
985}
986
987StackFrame *
988Target::CalculateStackFrame ()
989{
990    return NULL;
991}
992
993void
994Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
995{
996    exe_ctx.target = this;
997    exe_ctx.process = NULL; // Do NOT fill in process...
998    exe_ctx.thread = NULL;
999    exe_ctx.frame = NULL;
1000}
1001
1002PathMappingList &
1003Target::GetImageSearchPathList ()
1004{
1005    return m_image_search_paths;
1006}
1007
1008void
1009Target::ImageSearchPathsChanged
1010(
1011    const PathMappingList &path_list,
1012    void *baton
1013)
1014{
1015    Target *target = (Target *)baton;
1016    ModuleSP exe_module_sp (target->GetExecutableModule());
1017    if (exe_module_sp)
1018    {
1019        target->m_images.Clear();
1020        target->SetExecutableModule (exe_module_sp, true);
1021    }
1022}
1023
1024ClangASTContext *
1025Target::GetScratchClangASTContext()
1026{
1027    // Now see if we know the target triple, and if so, create our scratch AST context:
1028    if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid())
1029        m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1030    return m_scratch_ast_context_ap.get();
1031}
1032
1033void
1034Target::SettingsInitialize ()
1035{
1036    UserSettingsControllerSP &usc = GetSettingsController();
1037    usc.reset (new SettingsController);
1038    UserSettingsController::InitializeSettingsController (usc,
1039                                                          SettingsController::global_settings_table,
1040                                                          SettingsController::instance_settings_table);
1041
1042    // Now call SettingsInitialize() on each 'child' setting of Target
1043    Process::SettingsInitialize ();
1044}
1045
1046void
1047Target::SettingsTerminate ()
1048{
1049
1050    // Must call SettingsTerminate() on each settings 'child' of Target, before terminating Target's Settings.
1051
1052    Process::SettingsTerminate ();
1053
1054    // Now terminate Target Settings.
1055
1056    UserSettingsControllerSP &usc = GetSettingsController();
1057    UserSettingsController::FinalizeSettingsController (usc);
1058    usc.reset();
1059}
1060
1061UserSettingsControllerSP &
1062Target::GetSettingsController ()
1063{
1064    static UserSettingsControllerSP g_settings_controller;
1065    return g_settings_controller;
1066}
1067
1068ArchSpec
1069Target::GetDefaultArchitecture ()
1070{
1071    lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController());
1072
1073    if (settings_controller_sp)
1074        return static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture ();
1075    return ArchSpec();
1076}
1077
1078void
1079Target::SetDefaultArchitecture (const ArchSpec& arch)
1080{
1081    lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController());
1082
1083    if (settings_controller_sp)
1084        static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture () = arch;
1085}
1086
1087Target *
1088Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1089{
1090    // The target can either exist in the "process" of ExecutionContext, or in
1091    // the "target_sp" member of SymbolContext. This accessor helper function
1092    // will get the target from one of these locations.
1093
1094    Target *target = NULL;
1095    if (sc_ptr != NULL)
1096        target = sc_ptr->target_sp.get();
1097    if (target == NULL)
1098    {
1099        if (exe_ctx_ptr != NULL && exe_ctx_ptr->process != NULL)
1100            target = &exe_ctx_ptr->process->GetTarget();
1101    }
1102    return target;
1103}
1104
1105
1106void
1107Target::UpdateInstanceName ()
1108{
1109    StreamString sstr;
1110
1111    Module *exe_module = GetExecutableModulePointer();
1112    if (exe_module)
1113    {
1114        sstr.Printf ("%s_%s",
1115                     exe_module->GetFileSpec().GetFilename().AsCString(),
1116                     exe_module->GetArchitecture().GetArchitectureName());
1117        GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), sstr.GetData());
1118    }
1119}
1120
1121const char *
1122Target::GetExpressionPrefixContentsAsCString ()
1123{
1124    if (m_expr_prefix_contents_sp)
1125        return (const char *)m_expr_prefix_contents_sp->GetBytes();
1126    return NULL;
1127}
1128
1129ExecutionResults
1130Target::EvaluateExpression
1131(
1132    const char *expr_cstr,
1133    StackFrame *frame,
1134    bool unwind_on_error,
1135    bool keep_in_memory,
1136    lldb::DynamicValueType use_dynamic,
1137    lldb::ValueObjectSP &result_valobj_sp
1138)
1139{
1140    ExecutionResults execution_results = eExecutionSetupError;
1141
1142    result_valobj_sp.reset();
1143
1144    // We shouldn't run stop hooks in expressions.
1145    // Be sure to reset this if you return anywhere within this function.
1146    bool old_suppress_value = m_suppress_stop_hooks;
1147    m_suppress_stop_hooks = true;
1148
1149    ExecutionContext exe_ctx;
1150    if (frame)
1151    {
1152        frame->CalculateExecutionContext(exe_ctx);
1153        Error error;
1154        const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember |
1155                                           StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
1156                                           StackFrame::eExpressionPathOptionsNoSyntheticChildren;
1157        lldb::VariableSP var_sp;
1158        result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr,
1159                                                                     use_dynamic,
1160                                                                     expr_path_options,
1161                                                                     var_sp,
1162                                                                     error);
1163    }
1164    else if (m_process_sp)
1165    {
1166        m_process_sp->CalculateExecutionContext(exe_ctx);
1167    }
1168    else
1169    {
1170        CalculateExecutionContext(exe_ctx);
1171    }
1172
1173    if (result_valobj_sp)
1174    {
1175        execution_results = eExecutionCompleted;
1176        // We got a result from the frame variable expression path above...
1177        ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName());
1178
1179        lldb::ValueObjectSP const_valobj_sp;
1180
1181        // Check in case our value is already a constant value
1182        if (result_valobj_sp->GetIsConstant())
1183        {
1184            const_valobj_sp = result_valobj_sp;
1185            const_valobj_sp->SetName (persistent_variable_name);
1186        }
1187        else
1188        {
1189            if (use_dynamic != lldb::eNoDynamicValues)
1190            {
1191                ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(use_dynamic);
1192                if (dynamic_sp)
1193                    result_valobj_sp = dynamic_sp;
1194            }
1195
1196            const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name);
1197        }
1198
1199        lldb::ValueObjectSP live_valobj_sp = result_valobj_sp;
1200
1201        result_valobj_sp = const_valobj_sp;
1202
1203        ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp));
1204        assert (clang_expr_variable_sp.get());
1205
1206        // Set flags and live data as appropriate
1207
1208        const Value &result_value = live_valobj_sp->GetValue();
1209
1210        switch (result_value.GetValueType())
1211        {
1212        case Value::eValueTypeHostAddress:
1213        case Value::eValueTypeFileAddress:
1214            // we don't do anything with these for now
1215            break;
1216        case Value::eValueTypeScalar:
1217            clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
1218            clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
1219            break;
1220        case Value::eValueTypeLoadAddress:
1221            clang_expr_variable_sp->m_live_sp = live_valobj_sp;
1222            clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
1223            break;
1224        }
1225    }
1226    else
1227    {
1228        // Make sure we aren't just trying to see the value of a persistent
1229        // variable (something like "$0")
1230        lldb::ClangExpressionVariableSP persistent_var_sp;
1231        // Only check for persistent variables the expression starts with a '$'
1232        if (expr_cstr[0] == '$')
1233            persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1234
1235        if (persistent_var_sp)
1236        {
1237            result_valobj_sp = persistent_var_sp->GetValueObject ();
1238            execution_results = eExecutionCompleted;
1239        }
1240        else
1241        {
1242            const char *prefix = GetExpressionPrefixContentsAsCString();
1243
1244            execution_results = ClangUserExpression::Evaluate (exe_ctx,
1245                                                               unwind_on_error,
1246                                                               expr_cstr,
1247                                                               prefix,
1248                                                               result_valobj_sp);
1249        }
1250    }
1251
1252    m_suppress_stop_hooks = old_suppress_value;
1253
1254    return execution_results;
1255}
1256
1257lldb::addr_t
1258Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1259{
1260    addr_t code_addr = load_addr;
1261    switch (m_arch.GetMachine())
1262    {
1263    case llvm::Triple::arm:
1264    case llvm::Triple::thumb:
1265        switch (addr_class)
1266        {
1267        case eAddressClassData:
1268        case eAddressClassDebug:
1269            return LLDB_INVALID_ADDRESS;
1270
1271        case eAddressClassUnknown:
1272        case eAddressClassInvalid:
1273        case eAddressClassCode:
1274        case eAddressClassCodeAlternateISA:
1275        case eAddressClassRuntime:
1276            // Check if bit zero it no set?
1277            if ((code_addr & 1ull) == 0)
1278            {
1279                // Bit zero isn't set, check if the address is a multiple of 2?
1280                if (code_addr & 2ull)
1281                {
1282                    // The address is a multiple of 2 so it must be thumb, set bit zero
1283                    code_addr |= 1ull;
1284                }
1285                else if (addr_class == eAddressClassCodeAlternateISA)
1286                {
1287                    // We checked the address and the address claims to be the alternate ISA
1288                    // which means thumb, so set bit zero.
1289                    code_addr |= 1ull;
1290                }
1291            }
1292            break;
1293        }
1294        break;
1295
1296    default:
1297        break;
1298    }
1299    return code_addr;
1300}
1301
1302lldb::addr_t
1303Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1304{
1305    addr_t opcode_addr = load_addr;
1306    switch (m_arch.GetMachine())
1307    {
1308    case llvm::Triple::arm:
1309    case llvm::Triple::thumb:
1310        switch (addr_class)
1311        {
1312        case eAddressClassData:
1313        case eAddressClassDebug:
1314            return LLDB_INVALID_ADDRESS;
1315
1316        case eAddressClassInvalid:
1317        case eAddressClassUnknown:
1318        case eAddressClassCode:
1319        case eAddressClassCodeAlternateISA:
1320        case eAddressClassRuntime:
1321            opcode_addr &= ~(1ull);
1322            break;
1323        }
1324        break;
1325
1326    default:
1327        break;
1328    }
1329    return opcode_addr;
1330}
1331
1332lldb::user_id_t
1333Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1334{
1335    lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1336    new_hook_sp.reset (new StopHook(GetSP(), new_uid));
1337    m_stop_hooks[new_uid] = new_hook_sp;
1338    return new_uid;
1339}
1340
1341bool
1342Target::RemoveStopHookByID (lldb::user_id_t user_id)
1343{
1344    size_t num_removed;
1345    num_removed = m_stop_hooks.erase (user_id);
1346    if (num_removed == 0)
1347        return false;
1348    else
1349        return true;
1350}
1351
1352void
1353Target::RemoveAllStopHooks ()
1354{
1355    m_stop_hooks.clear();
1356}
1357
1358Target::StopHookSP
1359Target::GetStopHookByID (lldb::user_id_t user_id)
1360{
1361    StopHookSP found_hook;
1362
1363    StopHookCollection::iterator specified_hook_iter;
1364    specified_hook_iter = m_stop_hooks.find (user_id);
1365    if (specified_hook_iter != m_stop_hooks.end())
1366        found_hook = (*specified_hook_iter).second;
1367    return found_hook;
1368}
1369
1370bool
1371Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
1372{
1373    StopHookCollection::iterator specified_hook_iter;
1374    specified_hook_iter = m_stop_hooks.find (user_id);
1375    if (specified_hook_iter == m_stop_hooks.end())
1376        return false;
1377
1378    (*specified_hook_iter).second->SetIsActive (active_state);
1379    return true;
1380}
1381
1382void
1383Target::SetAllStopHooksActiveState (bool active_state)
1384{
1385    StopHookCollection::iterator pos, end = m_stop_hooks.end();
1386    for (pos = m_stop_hooks.begin(); pos != end; pos++)
1387    {
1388        (*pos).second->SetIsActive (active_state);
1389    }
1390}
1391
1392void
1393Target::RunStopHooks ()
1394{
1395    if (m_suppress_stop_hooks)
1396        return;
1397
1398    if (!m_process_sp)
1399        return;
1400
1401    if (m_stop_hooks.empty())
1402        return;
1403
1404    StopHookCollection::iterator pos, end = m_stop_hooks.end();
1405
1406    // If there aren't any active stop hooks, don't bother either:
1407    bool any_active_hooks = false;
1408    for (pos = m_stop_hooks.begin(); pos != end; pos++)
1409    {
1410        if ((*pos).second->IsActive())
1411        {
1412            any_active_hooks = true;
1413            break;
1414        }
1415    }
1416    if (!any_active_hooks)
1417        return;
1418
1419    CommandReturnObject result;
1420
1421    std::vector<ExecutionContext> exc_ctx_with_reasons;
1422    std::vector<SymbolContext> sym_ctx_with_reasons;
1423
1424    ThreadList &cur_threadlist = m_process_sp->GetThreadList();
1425    size_t num_threads = cur_threadlist.GetSize();
1426    for (size_t i = 0; i < num_threads; i++)
1427    {
1428        lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
1429        if (cur_thread_sp->ThreadStoppedForAReason())
1430        {
1431            lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
1432            exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
1433            sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
1434        }
1435    }
1436
1437    // If no threads stopped for a reason, don't run the stop-hooks.
1438    size_t num_exe_ctx = exc_ctx_with_reasons.size();
1439    if (num_exe_ctx == 0)
1440        return;
1441
1442    result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
1443    result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
1444
1445    bool keep_going = true;
1446    bool hooks_ran = false;
1447    bool print_hook_header;
1448    bool print_thread_header;
1449
1450    if (num_exe_ctx == 1)
1451        print_thread_header = false;
1452    else
1453        print_thread_header = true;
1454
1455    if (m_stop_hooks.size() == 1)
1456        print_hook_header = false;
1457    else
1458        print_hook_header = true;
1459
1460    for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
1461    {
1462        // result.Clear();
1463        StopHookSP cur_hook_sp = (*pos).second;
1464        if (!cur_hook_sp->IsActive())
1465            continue;
1466
1467        bool any_thread_matched = false;
1468        for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
1469        {
1470            if ((cur_hook_sp->GetSpecifier () == NULL
1471                  || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
1472                && (cur_hook_sp->GetThreadSpecifier() == NULL
1473                    || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].thread)))
1474            {
1475                if (!hooks_ran)
1476                {
1477                    result.AppendMessage("\n** Stop Hooks **");
1478                    hooks_ran = true;
1479                }
1480                if (print_hook_header && !any_thread_matched)
1481                {
1482                    result.AppendMessageWithFormat("\n- Hook %d\n", cur_hook_sp->GetID());
1483                    any_thread_matched = true;
1484                }
1485
1486                if (print_thread_header)
1487                    result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].thread->GetIndexID());
1488
1489                bool stop_on_continue = true;
1490                bool stop_on_error = true;
1491                bool echo_commands = false;
1492                bool print_results = true;
1493                GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
1494                                                                      &exc_ctx_with_reasons[i],
1495                                                                      stop_on_continue,
1496                                                                      stop_on_error,
1497                                                                      echo_commands,
1498                                                                      print_results,
1499                                                                      result);
1500
1501                // If the command started the target going again, we should bag out of
1502                // running the stop hooks.
1503                if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
1504                    (result.GetStatus() == eReturnStatusSuccessContinuingResult))
1505                {
1506                    result.AppendMessageWithFormat ("Aborting stop hooks, hook %d set the program running.", cur_hook_sp->GetID());
1507                    keep_going = false;
1508                }
1509            }
1510        }
1511    }
1512    if (hooks_ran)
1513        result.AppendMessage ("\n** End Stop Hooks **\n");
1514
1515    result.GetImmediateOutputStream()->Flush();
1516    result.GetImmediateErrorStream()->Flush();
1517}
1518
1519bool
1520Target::LoadModuleWithSlide (Module *module, lldb::addr_t slide)
1521{
1522    bool changed = false;
1523    if (module)
1524    {
1525        ObjectFile *object_file = module->GetObjectFile();
1526        if (object_file)
1527        {
1528            SectionList *section_list = object_file->GetSectionList ();
1529            if (section_list)
1530            {
1531                // All sections listed in the dyld image info structure will all
1532                // either be fixed up already, or they will all be off by a single
1533                // slide amount that is determined by finding the first segment
1534                // that is at file offset zero which also has bytes (a file size
1535                // that is greater than zero) in the object file.
1536
1537                // Determine the slide amount (if any)
1538                const size_t num_sections = section_list->GetSize();
1539                size_t sect_idx = 0;
1540                for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1541                {
1542                    // Iterate through the object file sections to find the
1543                    // first section that starts of file offset zero and that
1544                    // has bytes in the file...
1545                    Section *section = section_list->GetSectionAtIndex (sect_idx).get();
1546                    if (section)
1547                    {
1548                        if (m_section_load_list.SetSectionLoadAddress (section, section->GetFileAddress() + slide))
1549                            changed = true;
1550                    }
1551                }
1552            }
1553        }
1554    }
1555    return changed;
1556}
1557
1558
1559//--------------------------------------------------------------
1560// class Target::StopHook
1561//--------------------------------------------------------------
1562
1563
1564Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
1565        UserID (uid),
1566        m_target_sp (target_sp),
1567        m_commands (),
1568        m_specifier_sp (),
1569        m_thread_spec_ap(NULL),
1570        m_active (true)
1571{
1572}
1573
1574Target::StopHook::StopHook (const StopHook &rhs) :
1575        UserID (rhs.GetID()),
1576        m_target_sp (rhs.m_target_sp),
1577        m_commands (rhs.m_commands),
1578        m_specifier_sp (rhs.m_specifier_sp),
1579        m_thread_spec_ap (NULL),
1580        m_active (rhs.m_active)
1581{
1582    if (rhs.m_thread_spec_ap.get() != NULL)
1583        m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
1584}
1585
1586
1587Target::StopHook::~StopHook ()
1588{
1589}
1590
1591void
1592Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
1593{
1594    m_thread_spec_ap.reset (specifier);
1595}
1596
1597
1598void
1599Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
1600{
1601    int indent_level = s->GetIndentLevel();
1602
1603    s->SetIndentLevel(indent_level + 2);
1604
1605    s->Printf ("Hook: %d\n", GetID());
1606    if (m_active)
1607        s->Indent ("State: enabled\n");
1608    else
1609        s->Indent ("State: disabled\n");
1610
1611    if (m_specifier_sp)
1612    {
1613        s->Indent();
1614        s->PutCString ("Specifier:\n");
1615        s->SetIndentLevel (indent_level + 4);
1616        m_specifier_sp->GetDescription (s, level);
1617        s->SetIndentLevel (indent_level + 2);
1618    }
1619
1620    if (m_thread_spec_ap.get() != NULL)
1621    {
1622        StreamString tmp;
1623        s->Indent("Thread:\n");
1624        m_thread_spec_ap->GetDescription (&tmp, level);
1625        s->SetIndentLevel (indent_level + 4);
1626        s->Indent (tmp.GetData());
1627        s->PutCString ("\n");
1628        s->SetIndentLevel (indent_level + 2);
1629    }
1630
1631    s->Indent ("Commands: \n");
1632    s->SetIndentLevel (indent_level + 4);
1633    uint32_t num_commands = m_commands.GetSize();
1634    for (uint32_t i = 0; i < num_commands; i++)
1635    {
1636        s->Indent(m_commands.GetStringAtIndex(i));
1637        s->PutCString ("\n");
1638    }
1639    s->SetIndentLevel (indent_level);
1640}
1641
1642
1643//--------------------------------------------------------------
1644// class Target::SettingsController
1645//--------------------------------------------------------------
1646
1647Target::SettingsController::SettingsController () :
1648    UserSettingsController ("target", Debugger::GetSettingsController()),
1649    m_default_architecture ()
1650{
1651    m_default_settings.reset (new TargetInstanceSettings (*this, false,
1652                                                          InstanceSettings::GetDefaultName().AsCString()));
1653}
1654
1655Target::SettingsController::~SettingsController ()
1656{
1657}
1658
1659lldb::InstanceSettingsSP
1660Target::SettingsController::CreateInstanceSettings (const char *instance_name)
1661{
1662    TargetInstanceSettings *new_settings = new TargetInstanceSettings (*GetSettingsController(),
1663                                                                       false,
1664                                                                       instance_name);
1665    lldb::InstanceSettingsSP new_settings_sp (new_settings);
1666    return new_settings_sp;
1667}
1668
1669
1670#define TSC_DEFAULT_ARCH      "default-arch"
1671#define TSC_EXPR_PREFIX       "expr-prefix"
1672#define TSC_PREFER_DYNAMIC    "prefer-dynamic-value"
1673#define TSC_SKIP_PROLOGUE     "skip-prologue"
1674#define TSC_SOURCE_MAP        "source-map"
1675#define TSC_MAX_CHILDREN      "max-children-count"
1676#define TSC_MAX_STRLENSUMMARY "max-string-summary-length"
1677
1678
1679static const ConstString &
1680GetSettingNameForDefaultArch ()
1681{
1682    static ConstString g_const_string (TSC_DEFAULT_ARCH);
1683    return g_const_string;
1684}
1685
1686static const ConstString &
1687GetSettingNameForExpressionPrefix ()
1688{
1689    static ConstString g_const_string (TSC_EXPR_PREFIX);
1690    return g_const_string;
1691}
1692
1693static const ConstString &
1694GetSettingNameForPreferDynamicValue ()
1695{
1696    static ConstString g_const_string (TSC_PREFER_DYNAMIC);
1697    return g_const_string;
1698}
1699
1700static const ConstString &
1701GetSettingNameForSourcePathMap ()
1702{
1703    static ConstString g_const_string (TSC_SOURCE_MAP);
1704    return g_const_string;
1705}
1706
1707static const ConstString &
1708GetSettingNameForSkipPrologue ()
1709{
1710    static ConstString g_const_string (TSC_SKIP_PROLOGUE);
1711    return g_const_string;
1712}
1713
1714static const ConstString &
1715GetSettingNameForMaxChildren ()
1716{
1717    static ConstString g_const_string (TSC_MAX_CHILDREN);
1718    return g_const_string;
1719}
1720
1721static const ConstString &
1722GetSettingNameForMaxStringSummaryLength ()
1723{
1724    static ConstString g_const_string (TSC_MAX_STRLENSUMMARY);
1725    return g_const_string;
1726}
1727
1728bool
1729Target::SettingsController::SetGlobalVariable (const ConstString &var_name,
1730                                               const char *index_value,
1731                                               const char *value,
1732                                               const SettingEntry &entry,
1733                                               const VarSetOperationType op,
1734                                               Error&err)
1735{
1736    if (var_name == GetSettingNameForDefaultArch())
1737    {
1738        m_default_architecture.SetTriple (value, NULL);
1739        if (!m_default_architecture.IsValid())
1740            err.SetErrorStringWithFormat ("'%s' is not a valid architecture or triple.", value);
1741    }
1742    return true;
1743}
1744
1745
1746bool
1747Target::SettingsController::GetGlobalVariable (const ConstString &var_name,
1748                                               StringList &value,
1749                                               Error &err)
1750{
1751    if (var_name == GetSettingNameForDefaultArch())
1752    {
1753        // If the arch is invalid (the default), don't show a string for it
1754        if (m_default_architecture.IsValid())
1755            value.AppendString (m_default_architecture.GetArchitectureName());
1756        return true;
1757    }
1758    else
1759        err.SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
1760
1761    return false;
1762}
1763
1764//--------------------------------------------------------------
1765// class TargetInstanceSettings
1766//--------------------------------------------------------------
1767
1768TargetInstanceSettings::TargetInstanceSettings
1769(
1770    UserSettingsController &owner,
1771    bool live_instance,
1772    const char *name
1773) :
1774    InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
1775    m_expr_prefix_file (),
1776    m_expr_prefix_contents_sp (),
1777    m_prefer_dynamic_value (2),
1778    m_skip_prologue (true, true),
1779    m_source_map (NULL, NULL),
1780    m_max_children_display(256),
1781    m_max_strlen_length(1024)
1782{
1783    // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
1784    // until the vtables for TargetInstanceSettings are properly set up, i.e. AFTER all the initializers.
1785    // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
1786    // This is true for CreateInstanceName() too.
1787
1788    if (GetInstanceName () == InstanceSettings::InvalidName())
1789    {
1790        ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
1791        m_owner.RegisterInstanceSettings (this);
1792    }
1793
1794    if (live_instance)
1795    {
1796        const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1797        CopyInstanceSettings (pending_settings,false);
1798    }
1799}
1800
1801TargetInstanceSettings::TargetInstanceSettings (const TargetInstanceSettings &rhs) :
1802    InstanceSettings (*Target::GetSettingsController(), CreateInstanceName().AsCString()),
1803    m_expr_prefix_file (rhs.m_expr_prefix_file),
1804    m_expr_prefix_contents_sp (rhs.m_expr_prefix_contents_sp),
1805    m_prefer_dynamic_value (rhs.m_prefer_dynamic_value),
1806    m_skip_prologue (rhs.m_skip_prologue),
1807    m_source_map (rhs.m_source_map),
1808    m_max_children_display(rhs.m_max_children_display),
1809    m_max_strlen_length(rhs.m_max_strlen_length)
1810{
1811    if (m_instance_name != InstanceSettings::GetDefaultName())
1812    {
1813        const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1814        CopyInstanceSettings (pending_settings,false);
1815    }
1816}
1817
1818TargetInstanceSettings::~TargetInstanceSettings ()
1819{
1820}
1821
1822TargetInstanceSettings&
1823TargetInstanceSettings::operator= (const TargetInstanceSettings &rhs)
1824{
1825    if (this != &rhs)
1826    {
1827    }
1828
1829    return *this;
1830}
1831
1832void
1833TargetInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
1834                                                        const char *index_value,
1835                                                        const char *value,
1836                                                        const ConstString &instance_name,
1837                                                        const SettingEntry &entry,
1838                                                        VarSetOperationType op,
1839                                                        Error &err,
1840                                                        bool pending)
1841{
1842    if (var_name == GetSettingNameForExpressionPrefix ())
1843    {
1844        err = UserSettingsController::UpdateFileSpecOptionValue (value, op, m_expr_prefix_file);
1845        if (err.Success())
1846        {
1847            switch (op)
1848            {
1849            default:
1850                break;
1851            case eVarSetOperationAssign:
1852            case eVarSetOperationAppend:
1853                {
1854                    if (!m_expr_prefix_file.GetCurrentValue().Exists())
1855                    {
1856                        err.SetErrorToGenericError ();
1857                        err.SetErrorStringWithFormat ("%s does not exist.\n", value);
1858                        return;
1859                    }
1860
1861                    m_expr_prefix_contents_sp = m_expr_prefix_file.GetCurrentValue().ReadFileContents();
1862
1863                    if (!m_expr_prefix_contents_sp && m_expr_prefix_contents_sp->GetByteSize() == 0)
1864                    {
1865                        err.SetErrorStringWithFormat ("Couldn't read data from '%s'\n", value);
1866                        m_expr_prefix_contents_sp.reset();
1867                    }
1868                }
1869                break;
1870            case eVarSetOperationClear:
1871                m_expr_prefix_contents_sp.reset();
1872            }
1873        }
1874    }
1875    else if (var_name == GetSettingNameForPreferDynamicValue())
1876    {
1877        int new_value;
1878        UserSettingsController::UpdateEnumVariable (g_dynamic_value_types, &new_value, value, err);
1879        if (err.Success())
1880            m_prefer_dynamic_value = new_value;
1881    }
1882    else if (var_name == GetSettingNameForSkipPrologue())
1883    {
1884        err = UserSettingsController::UpdateBooleanOptionValue (value, op, m_skip_prologue);
1885    }
1886    else if (var_name == GetSettingNameForMaxChildren())
1887    {
1888        bool ok;
1889        uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok);
1890        if (ok)
1891            m_max_children_display = new_value;
1892    }
1893    else if (var_name == GetSettingNameForMaxStringSummaryLength())
1894    {
1895        bool ok;
1896        uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok);
1897        if (ok)
1898            m_max_strlen_length = new_value;
1899    }
1900    else if (var_name == GetSettingNameForSourcePathMap ())
1901    {
1902        switch (op)
1903        {
1904            case eVarSetOperationReplace:
1905            case eVarSetOperationInsertBefore:
1906            case eVarSetOperationInsertAfter:
1907            case eVarSetOperationRemove:
1908            default:
1909                break;
1910            case eVarSetOperationAssign:
1911                m_source_map.Clear(true);
1912                // Fall through to append....
1913            case eVarSetOperationAppend:
1914                {
1915                    Args args(value);
1916                    const uint32_t argc = args.GetArgumentCount();
1917                    if (argc & 1 || argc == 0)
1918                    {
1919                        err.SetErrorStringWithFormat ("an even number of paths must be supplied to to the source-map setting: %u arguments given", argc);
1920                    }
1921                    else
1922                    {
1923                        char resolved_new_path[PATH_MAX];
1924                        FileSpec file_spec;
1925                        const char *old_path;
1926                        for (uint32_t idx = 0; (old_path = args.GetArgumentAtIndex(idx)) != NULL; idx += 2)
1927                        {
1928                            const char *new_path = args.GetArgumentAtIndex(idx+1);
1929                            assert (new_path); // We have an even number of paths, this shouldn't happen!
1930
1931                            file_spec.SetFile(new_path, true);
1932                            if (file_spec.Exists())
1933                            {
1934                                if (file_spec.GetPath (resolved_new_path, sizeof(resolved_new_path)) >= sizeof(resolved_new_path))
1935                                {
1936                                    err.SetErrorStringWithFormat("new path '%s' is too long", new_path);
1937                                    return;
1938                                }
1939                            }
1940                            else
1941                            {
1942                                err.SetErrorStringWithFormat("new path '%s' doesn't exist", new_path);
1943                                return;
1944                            }
1945                            m_source_map.Append(ConstString (old_path), ConstString (resolved_new_path), true);
1946                        }
1947                    }
1948                }
1949                break;
1950
1951            case eVarSetOperationClear:
1952                m_source_map.Clear(true);
1953                break;
1954        }
1955    }
1956}
1957
1958void
1959TargetInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings, bool pending)
1960{
1961    TargetInstanceSettings *new_settings_ptr = static_cast <TargetInstanceSettings *> (new_settings.get());
1962
1963    if (!new_settings_ptr)
1964        return;
1965
1966    m_expr_prefix_file          = new_settings_ptr->m_expr_prefix_file;
1967    m_expr_prefix_contents_sp   = new_settings_ptr->m_expr_prefix_contents_sp;
1968    m_prefer_dynamic_value      = new_settings_ptr->m_prefer_dynamic_value;
1969    m_skip_prologue             = new_settings_ptr->m_skip_prologue;
1970    m_max_children_display      = new_settings_ptr->m_max_children_display;
1971    m_max_strlen_length         = new_settings_ptr->m_max_strlen_length;
1972}
1973
1974bool
1975TargetInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
1976                                                  const ConstString &var_name,
1977                                                  StringList &value,
1978                                                  Error *err)
1979{
1980    if (var_name == GetSettingNameForExpressionPrefix ())
1981    {
1982        char path[PATH_MAX];
1983        const size_t path_len = m_expr_prefix_file.GetCurrentValue().GetPath (path, sizeof(path));
1984        if (path_len > 0)
1985            value.AppendString (path, path_len);
1986    }
1987    else if (var_name == GetSettingNameForPreferDynamicValue())
1988    {
1989        value.AppendString (g_dynamic_value_types[m_prefer_dynamic_value].string_value);
1990    }
1991    else if (var_name == GetSettingNameForSkipPrologue())
1992    {
1993        if (m_skip_prologue)
1994            value.AppendString ("true");
1995        else
1996            value.AppendString ("false");
1997    }
1998    else if (var_name == GetSettingNameForSourcePathMap ())
1999    {
2000    }
2001    else if (var_name == GetSettingNameForMaxChildren())
2002    {
2003        StreamString count_str;
2004        count_str.Printf ("%d", m_max_children_display);
2005        value.AppendString (count_str.GetData());
2006    }
2007    else if (var_name == GetSettingNameForMaxStringSummaryLength())
2008    {
2009        StreamString count_str;
2010        count_str.Printf ("%d", m_max_strlen_length);
2011        value.AppendString (count_str.GetData());
2012    }
2013    else
2014    {
2015        if (err)
2016            err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2017        return false;
2018    }
2019
2020    return true;
2021}
2022
2023const ConstString
2024TargetInstanceSettings::CreateInstanceName ()
2025{
2026    StreamString sstr;
2027    static int instance_count = 1;
2028
2029    sstr.Printf ("target_%d", instance_count);
2030    ++instance_count;
2031
2032    const ConstString ret_val (sstr.GetData());
2033    return ret_val;
2034}
2035
2036//--------------------------------------------------
2037// Target::SettingsController Variable Tables
2038//--------------------------------------------------
2039OptionEnumValueElement
2040TargetInstanceSettings::g_dynamic_value_types[] =
2041{
2042{ eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2043{ eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2044{ eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2045{ 0, NULL, NULL }
2046};
2047
2048SettingEntry
2049Target::SettingsController::global_settings_table[] =
2050{
2051    // var-name           var-type           default      enum  init'd hidden help-text
2052    // =================  ================== ===========  ====  ====== ====== =========================================================================
2053    { TSC_DEFAULT_ARCH  , eSetVarTypeString , NULL      , NULL, false, false, "Default architecture to choose, when there's a choice." },
2054    { NULL              , eSetVarTypeNone   , NULL      , NULL, false, false, NULL }
2055};
2056
2057SettingEntry
2058Target::SettingsController::instance_settings_table[] =
2059{
2060    // var-name             var-type            default         enum                    init'd hidden help-text
2061    // =================    ==================  =============== ======================= ====== ====== =========================================================================
2062    { TSC_EXPR_PREFIX       , eSetVarTypeString , NULL          , NULL,                  false, false, "Path to a file containing expressions to be prepended to all expressions." },
2063    { TSC_PREFER_DYNAMIC    , eSetVarTypeEnum   , NULL          , g_dynamic_value_types, false, false, "Should printed values be shown as their dynamic value." },
2064    { TSC_SKIP_PROLOGUE     , eSetVarTypeBoolean, "true"        , NULL,                  false, false, "Skip function prologues when setting breakpoints by name." },
2065    { TSC_SOURCE_MAP        , eSetVarTypeArray  , NULL          , NULL,                  false, false, "Source path remappings to use when locating source files from debug information." },
2066    { TSC_MAX_CHILDREN      , eSetVarTypeInt    , "256"         , NULL,                  true,  false, "Maximum number of children to expand in any level of depth." },
2067    { TSC_MAX_STRLENSUMMARY , eSetVarTypeInt    , "1024"        , NULL,                  true,  false, "Maximum number of characters to show when using %s in summary strings." },
2068    { NULL                  , eSetVarTypeNone   , NULL          , NULL,                  false, false, NULL }
2069};
2070