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