Target.h revision c0fa53324d62a48257c092a3347d6e7236aa3152
1//===-- Target.h ------------------------------------------------*- 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#ifndef liblldb_Target_h_
11#define liblldb_Target_h_
12
13// C Includes
14// C++ Includes
15
16// Other libraries and framework includes
17// Project includes
18#include "lldb/lldb-public.h"
19#include "lldb/Breakpoint/BreakpointList.h"
20#include "lldb/Breakpoint/BreakpointLocationCollection.h"
21#include "lldb/Core/Broadcaster.h"
22#include "lldb/Core/Event.h"
23#include "lldb/Core/ModuleList.h"
24#include "lldb/Core/UserSettingsController.h"
25#include "lldb/Expression/ClangPersistentVariables.h"
26#include "lldb/Interpreter/NamedOptionValue.h"
27#include "lldb/Symbol/SymbolContext.h"
28#include "lldb/Target/ABI.h"
29#include "lldb/Target/ExecutionContextScope.h"
30#include "lldb/Target/PathMappingList.h"
31#include "lldb/Target/SectionLoadList.h"
32
33#include "lldb/API/SBTarget.h"
34
35namespace lldb_private {
36
37//----------------------------------------------------------------------
38// TargetInstanceSettings
39//----------------------------------------------------------------------
40class TargetInstanceSettings : public InstanceSettings
41{
42public:
43    static OptionEnumValueElement g_dynamic_value_types[];
44
45    TargetInstanceSettings (UserSettingsController &owner, bool live_instance = true, const char *name = NULL);
46
47    TargetInstanceSettings (const TargetInstanceSettings &rhs);
48
49    virtual
50    ~TargetInstanceSettings ();
51
52    TargetInstanceSettings&
53    operator= (const TargetInstanceSettings &rhs);
54
55    void
56    UpdateInstanceSettingsVariable (const ConstString &var_name,
57                                    const char *index_value,
58                                    const char *value,
59                                    const ConstString &instance_name,
60                                    const SettingEntry &entry,
61                                    VarSetOperationType op,
62                                    Error &err,
63                                    bool pending);
64
65    bool
66    GetInstanceSettingsValue (const SettingEntry &entry,
67                              const ConstString &var_name,
68                              StringList &value,
69                              Error *err);
70
71    lldb::DynamicValueType
72    GetPreferDynamicValue()
73    {
74        return (lldb::DynamicValueType) g_dynamic_value_types[m_prefer_dynamic_value].value;
75    }
76
77    bool
78    GetSkipPrologue()
79    {
80        return m_skip_prologue;
81    }
82
83    PathMappingList &
84    GetSourcePathMap ()
85    {
86        return m_source_map;
87    }
88
89protected:
90
91    void
92    CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
93                          bool pending);
94
95    const ConstString
96    CreateInstanceName ();
97
98    OptionValueFileSpec m_expr_prefix_file;
99    lldb::DataBufferSP m_expr_prefix_contents_sp;
100    int                m_prefer_dynamic_value;
101    OptionValueBoolean m_skip_prologue;
102    PathMappingList m_source_map;
103
104
105};
106
107//----------------------------------------------------------------------
108// Target
109//----------------------------------------------------------------------
110class Target :
111    public Broadcaster,
112    public ExecutionContextScope,
113    public TargetInstanceSettings
114{
115public:
116    friend class TargetList;
117
118    //------------------------------------------------------------------
119    /// Broadcaster event bits definitions.
120    //------------------------------------------------------------------
121    enum
122    {
123        eBroadcastBitBreakpointChanged  = (1 << 0),
124        eBroadcastBitModulesLoaded      = (1 << 1),
125        eBroadcastBitModulesUnloaded    = (1 << 2)
126    };
127
128    static void
129    SettingsInitialize ();
130
131    static void
132    SettingsTerminate ();
133
134    static lldb::UserSettingsControllerSP &
135    GetSettingsController ();
136
137    static ArchSpec
138    GetDefaultArchitecture ();
139
140    static void
141    SetDefaultArchitecture (const ArchSpec &arch);
142
143    void
144    UpdateInstanceName ();
145
146    lldb::ModuleSP
147    GetSharedModule (const FileSpec& file_spec,
148                     const ArchSpec& arch,
149                     const lldb_private::UUID *uuid = NULL,
150                     const ConstString *object_name = NULL,
151                     off_t object_offset = 0,
152                     Error *error_ptr = NULL);
153private:
154    //------------------------------------------------------------------
155    /// Construct with optional file and arch.
156    ///
157    /// This member is private. Clients must use
158    /// TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
159    /// so all targets can be tracked from the central target list.
160    ///
161    /// @see TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
162    //------------------------------------------------------------------
163    Target (Debugger &debugger,
164            const ArchSpec &target_arch,
165            const lldb::PlatformSP &platform_sp);
166
167public:
168    ~Target();
169
170    Mutex &
171    GetAPIMutex ()
172    {
173        return m_mutex;
174    }
175
176    void
177    DeleteCurrentProcess ();
178
179    //------------------------------------------------------------------
180    /// Dump a description of this object to a Stream.
181    ///
182    /// Dump a description of the contents of this object to the
183    /// supplied stream \a s. The dumped content will be only what has
184    /// been loaded or parsed up to this point at which this function
185    /// is called, so this is a good way to see what has been parsed
186    /// in a target.
187    ///
188    /// @param[in] s
189    ///     The stream to which to dump the object descripton.
190    //------------------------------------------------------------------
191    void
192    Dump (Stream *s, lldb::DescriptionLevel description_level);
193
194    const lldb::ProcessSP &
195    CreateProcess (Listener &listener, const char *plugin_name = NULL);
196
197    const lldb::ProcessSP &
198    GetProcessSP () const;
199
200    lldb::TargetSP
201    GetSP();
202
203    //------------------------------------------------------------------
204    // This part handles the breakpoints.
205    //------------------------------------------------------------------
206
207    BreakpointList &
208    GetBreakpointList(bool internal = false);
209
210    const BreakpointList &
211    GetBreakpointList(bool internal = false) const;
212
213    lldb::BreakpointSP
214    GetLastCreatedBreakpoint ()
215    {
216        return m_last_created_breakpoint;
217    }
218
219    lldb::BreakpointSP
220    GetBreakpointByID (lldb::break_id_t break_id);
221
222    // Use this to create a file and line breakpoint to a given module or all module it is NULL
223    lldb::BreakpointSP
224    CreateBreakpoint (const FileSpec *containingModule,
225                      const FileSpec &file,
226                      uint32_t line_no,
227                      bool check_inlines,
228                      bool internal = false);
229
230    // Use this to create a breakpoint from a load address
231    lldb::BreakpointSP
232    CreateBreakpoint (lldb::addr_t load_addr,
233                      bool internal = false);
234
235    // Use this to create Address breakpoints:
236    lldb::BreakpointSP
237    CreateBreakpoint (Address &addr,
238                      bool internal = false);
239
240    // Use this to create a function breakpoint by regexp in containingModule, or all modules if it is NULL
241    lldb::BreakpointSP
242    CreateBreakpoint (FileSpec *containingModule,
243                      RegularExpression &func_regexp,
244                      bool internal = false);
245
246    // Use this to create a function breakpoint by name in containingModule, or all modules if it is NULL
247    lldb::BreakpointSP
248    CreateBreakpoint (FileSpec *containingModule,
249                      const char *func_name,
250                      uint32_t func_name_type_mask,
251                      bool internal = false);
252
253    // Use this to create a general breakpoint:
254    lldb::BreakpointSP
255    CreateBreakpoint (lldb::SearchFilterSP &filter_sp,
256                      lldb::BreakpointResolverSP &resolver_sp,
257                      bool internal = false);
258
259    void
260    RemoveAllBreakpoints (bool internal_also = false);
261
262    void
263    DisableAllBreakpoints (bool internal_also = false);
264
265    void
266    EnableAllBreakpoints (bool internal_also = false);
267
268    bool
269    DisableBreakpointByID (lldb::break_id_t break_id);
270
271    bool
272    EnableBreakpointByID (lldb::break_id_t break_id);
273
274    bool
275    RemoveBreakpointByID (lldb::break_id_t break_id);
276
277    void
278    ModulesDidLoad (ModuleList &module_list);
279
280    void
281    ModulesDidUnload (ModuleList &module_list);
282
283
284    //------------------------------------------------------------------
285    /// Get \a load_addr as a callable code load address for this target
286    ///
287    /// Take \a load_addr and potentially add any address bits that are
288    /// needed to make the address callable. For ARM this can set bit
289    /// zero (if it already isn't) if \a load_addr is a thumb function.
290    /// If \a addr_class is set to eAddressClassInvalid, then the address
291    /// adjustment will always happen. If it is set to an address class
292    /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
293    /// returned.
294    //------------------------------------------------------------------
295    lldb::addr_t
296    GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class = lldb_private::eAddressClassInvalid) const;
297
298    //------------------------------------------------------------------
299    /// Get \a load_addr as an opcode for this target.
300    ///
301    /// Take \a load_addr and potentially strip any address bits that are
302    /// needed to make the address point to an opcode. For ARM this can
303    /// clear bit zero (if it already isn't) if \a load_addr is a
304    /// thumb function and load_addr is in code.
305    /// If \a addr_class is set to eAddressClassInvalid, then the address
306    /// adjustment will always happen. If it is set to an address class
307    /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
308    /// returned.
309    //------------------------------------------------------------------
310    lldb::addr_t
311    GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class = lldb_private::eAddressClassInvalid) const;
312
313protected:
314    void
315    ModuleAdded (lldb::ModuleSP &module_sp);
316
317    void
318    ModuleUpdated (lldb::ModuleSP &old_module_sp, lldb::ModuleSP &new_module_sp);
319
320public:
321    //------------------------------------------------------------------
322    /// Gets the module for the main executable.
323    ///
324    /// Each process has a notion of a main executable that is the file
325    /// that will be executed or attached to. Executable files can have
326    /// dependent modules that are discovered from the object files, or
327    /// discovered at runtime as things are dynamically loaded.
328    ///
329    /// @return
330    ///     The shared pointer to the executable module which can
331    ///     contains a NULL Module object if no executable has been
332    ///     set.
333    ///
334    /// @see DynamicLoader
335    /// @see ObjectFile::GetDependentModules (FileSpecList&)
336    /// @see Process::SetExecutableModule(lldb::ModuleSP&)
337    //------------------------------------------------------------------
338    lldb::ModuleSP
339    GetExecutableModule ();
340
341    //------------------------------------------------------------------
342    /// Set the main executable module.
343    ///
344    /// Each process has a notion of a main executable that is the file
345    /// that will be executed or attached to. Executable files can have
346    /// dependent modules that are discovered from the object files, or
347    /// discovered at runtime as things are dynamically loaded.
348    ///
349    /// Setting the executable causes any of the current dependant
350    /// image information to be cleared and replaced with the static
351    /// dependent image information found by calling
352    /// ObjectFile::GetDependentModules (FileSpecList&) on the main
353    /// executable and any modules on which it depends. Calling
354    /// Process::GetImages() will return the newly found images that
355    /// were obtained from all of the object files.
356    ///
357    /// @param[in] module_sp
358    ///     A shared pointer reference to the module that will become
359    ///     the main executable for this process.
360    ///
361    /// @param[in] get_dependent_files
362    ///     If \b true then ask the object files to track down any
363    ///     known dependent files.
364    ///
365    /// @see ObjectFile::GetDependentModules (FileSpecList&)
366    /// @see Process::GetImages()
367    //------------------------------------------------------------------
368    void
369    SetExecutableModule (lldb::ModuleSP& module_sp, bool get_dependent_files);
370
371    //------------------------------------------------------------------
372    /// Get accessor for the images for this process.
373    ///
374    /// Each process has a notion of a main executable that is the file
375    /// that will be executed or attached to. Executable files can have
376    /// dependent modules that are discovered from the object files, or
377    /// discovered at runtime as things are dynamically loaded. After
378    /// a main executable has been set, the images will contain a list
379    /// of all the files that the executable depends upon as far as the
380    /// object files know. These images will usually contain valid file
381    /// virtual addresses only. When the process is launched or attached
382    /// to, the DynamicLoader plug-in will discover where these images
383    /// were loaded in memory and will resolve the load virtual
384    /// addresses is each image, and also in images that are loaded by
385    /// code.
386    ///
387    /// @return
388    ///     A list of Module objects in a module list.
389    //------------------------------------------------------------------
390    ModuleList&
391    GetImages ()
392    {
393        return m_images;
394    }
395
396    const ModuleList&
397    GetImages () const
398    {
399        return m_images;
400    }
401
402    ArchSpec &
403    GetArchitecture ()
404    {
405        return m_arch;
406    }
407
408    const ArchSpec &
409    GetArchitecture () const
410    {
411        return m_arch;
412    }
413
414    //------------------------------------------------------------------
415    /// Set the architecture for this target.
416    ///
417    /// If the current target has no Images read in, then this just sets the architecture, which will
418    /// be used to select the architecture of the ExecutableModule when that is set.
419    /// If the current target has an ExecutableModule, then calling SetArchitecture with a different
420    /// architecture from the currently selected one will reset the ExecutableModule to that slice
421    /// of the file backing the ExecutableModule.  If the file backing the ExecutableModule does not
422    /// contain a fork of this architecture, then this code will return false, and the architecture
423    /// won't be changed.
424    /// If the input arch_spec is the same as the already set architecture, this is a no-op.
425    ///
426    /// @param[in] arch_spec
427    ///     The new architecture.
428    ///
429    /// @return
430    ///     \b true if the architecture was successfully set, \bfalse otherwise.
431    //------------------------------------------------------------------
432    bool
433    SetArchitecture (const ArchSpec &arch_spec);
434
435    Debugger &
436    GetDebugger ()
437    {
438        return m_debugger;
439    }
440
441    size_t
442    ReadMemoryFromFileCache (const Address& addr,
443                             void *dst,
444                             size_t dst_len,
445                             Error &error);
446
447    // Reading memory through the target allows us to skip going to the process
448    // for reading memory if possible and it allows us to try and read from
449    // any constant sections in our object files on disk. If you always want
450    // live program memory, read straight from the process. If you possibly
451    // want to read from const sections in object files, read from the target.
452    // This version of ReadMemory will try and read memory from the process
453    // if the process is alive. The order is:
454    // 1 - if (prefer_file_cache == true) then read from object file cache
455    // 2 - if there is a valid process, try and read from its memory
456    // 3 - if (prefer_file_cache == false) then read from object file cache
457    size_t
458    ReadMemory (const Address& addr,
459                bool prefer_file_cache,
460                void *dst,
461                size_t dst_len,
462                Error &error);
463
464    SectionLoadList&
465    GetSectionLoadList()
466    {
467        return m_section_load_list;
468    }
469
470    const SectionLoadList&
471    GetSectionLoadList() const
472    {
473        return m_section_load_list;
474    }
475
476
477    static Target *
478    GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr,
479                           const SymbolContext *sc_ptr);
480
481    //------------------------------------------------------------------
482    // lldb::ExecutionContextScope pure virtual functions
483    //------------------------------------------------------------------
484    virtual Target *
485    CalculateTarget ();
486
487    virtual Process *
488    CalculateProcess ();
489
490    virtual Thread *
491    CalculateThread ();
492
493    virtual StackFrame *
494    CalculateStackFrame ();
495
496    virtual void
497    CalculateExecutionContext (ExecutionContext &exe_ctx);
498
499    PathMappingList &
500    GetImageSearchPathList ();
501
502    ClangASTContext *
503    GetScratchClangASTContext();
504
505    const char *
506    GetExpressionPrefixContentsAsCString ();
507
508    // Since expressions results can persist beyond the lifetime of a process,
509    // and the const expression results are available after a process is gone,
510    // we provide a way for expressions to be evaluated from the Target itself.
511    // If an expression is going to be run, then it should have a frame filled
512    // in in th execution context.
513    ExecutionResults
514    EvaluateExpression (const char *expression,
515                        StackFrame *frame,
516                        bool unwind_on_error,
517                        bool keep_in_memory,
518                        lldb::DynamicValueType use_dynamic,
519                        lldb::ValueObjectSP &result_valobj_sp);
520
521    ClangPersistentVariables &
522    GetPersistentVariables()
523    {
524        return m_persistent_variables;
525    }
526
527    //------------------------------------------------------------------
528    // Target Stop Hooks
529    //------------------------------------------------------------------
530    class StopHook : public UserID
531    {
532    public:
533        ~StopHook ();
534
535        StopHook (const StopHook &rhs);
536
537        StringList *
538        GetCommandPointer ()
539        {
540            return &m_commands;
541        }
542
543        const StringList &
544        GetCommands()
545        {
546            return m_commands;
547        }
548
549        lldb::TargetSP &
550        GetTarget()
551        {
552            return m_target_sp;
553        }
554
555        void
556        SetCommands (StringList &in_commands)
557        {
558            m_commands = in_commands;
559        }
560
561        // Set the specifier.  The stop hook will own the specifier, and is responsible for deleting it when we're done.
562        void
563        SetSpecifier (SymbolContextSpecifier *specifier)
564        {
565            m_specifier_sp.reset (specifier);
566        }
567
568        SymbolContextSpecifier *
569        GetSpecifier ()
570        {
571            return m_specifier_sp.get();
572        }
573
574        // Set the Thread Specifier.  The stop hook will own the thread specifier, and is responsible for deleting it when we're done.
575        void
576        SetThreadSpecifier (ThreadSpec *specifier);
577
578        ThreadSpec *
579        GetThreadSpecifier()
580        {
581            return m_thread_spec_ap.get();
582        }
583
584        bool
585        IsActive()
586        {
587            return m_active;
588        }
589
590        void
591        SetIsActive (bool is_active)
592        {
593            m_active = is_active;
594        }
595
596        void
597        GetDescription (Stream *s, lldb::DescriptionLevel level) const;
598
599    private:
600        lldb::TargetSP m_target_sp;
601        StringList   m_commands;
602        lldb::SymbolContextSpecifierSP m_specifier_sp;
603        std::auto_ptr<ThreadSpec> m_thread_spec_ap;
604        bool m_active;
605
606        // Use AddStopHook to make a new empty stop hook.  The GetCommandPointer and fill it with commands,
607        // and SetSpecifier to set the specifier shared pointer (can be null, that will match anything.)
608        StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid);
609        friend class Target;
610    };
611    typedef lldb::SharedPtr<StopHook>::Type StopHookSP;
612
613    // Add an empty stop hook to the Target's stop hook list, and returns a shared pointer to it in new_hook.
614    // Returns the id of the new hook.
615    lldb::user_id_t
616    AddStopHook (StopHookSP &new_hook);
617
618    void
619    RunStopHooks ();
620
621    size_t
622    GetStopHookSize();
623
624    bool
625    SetSuppresStopHooks (bool suppress)
626    {
627        bool old_value = m_suppress_stop_hooks;
628        m_suppress_stop_hooks = suppress;
629        return old_value;
630    }
631
632    bool
633    GetSuppressStopHooks ()
634    {
635        return m_suppress_stop_hooks;
636    }
637
638//    StopHookSP &
639//    GetStopHookByIndex (size_t index);
640//
641    bool
642    RemoveStopHookByID (lldb::user_id_t uid);
643
644    void
645    RemoveAllStopHooks ();
646
647    StopHookSP
648    GetStopHookByID (lldb::user_id_t uid);
649
650    bool
651    SetStopHookActiveStateByID (lldb::user_id_t uid, bool active_state);
652
653    void
654    SetAllStopHooksActiveState (bool active_state);
655
656    size_t GetNumStopHooks () const
657    {
658        return m_stop_hooks.size();
659    }
660
661    StopHookSP
662    GetStopHookAtIndex (size_t index)
663    {
664        if (index >= GetNumStopHooks())
665            return StopHookSP();
666        StopHookCollection::iterator pos = m_stop_hooks.begin();
667
668        while (index > 0)
669        {
670            pos++;
671            index--;
672        }
673        return (*pos).second;
674    }
675
676    lldb::PlatformSP
677    GetPlatform ()
678    {
679        return m_platform_sp;
680    }
681
682    //------------------------------------------------------------------
683    // Target::SettingsController
684    //------------------------------------------------------------------
685    class SettingsController : public UserSettingsController
686    {
687    public:
688        SettingsController ();
689
690        virtual
691        ~SettingsController ();
692
693        bool
694        SetGlobalVariable (const ConstString &var_name,
695                           const char *index_value,
696                           const char *value,
697                           const SettingEntry &entry,
698                           const VarSetOperationType op,
699                           Error&err);
700
701        bool
702        GetGlobalVariable (const ConstString &var_name,
703                           StringList &value,
704                           Error &err);
705
706        static SettingEntry global_settings_table[];
707        static SettingEntry instance_settings_table[];
708
709        ArchSpec &
710        GetArchitecture ()
711        {
712            return m_default_architecture;
713        }
714    protected:
715
716        lldb::InstanceSettingsSP
717        CreateInstanceSettings (const char *instance_name);
718
719    private:
720
721        // Class-wide settings.
722        ArchSpec m_default_architecture;
723
724        DISALLOW_COPY_AND_ASSIGN (SettingsController);
725    };
726
727
728protected:
729    friend class lldb::SBTarget;
730
731    //------------------------------------------------------------------
732    // Member variables.
733    //------------------------------------------------------------------
734    Debugger &      m_debugger;
735    lldb::PlatformSP m_platform_sp;     ///< The platform for this target.
736    Mutex           m_mutex;            ///< An API mutex that is used by the lldb::SB* classes make the SB interface thread safe
737    ArchSpec        m_arch;
738    ModuleList      m_images;           ///< The list of images for this process (shared libraries and anything dynamically loaded).
739    SectionLoadList m_section_load_list;
740    BreakpointList  m_breakpoint_list;
741    BreakpointList  m_internal_breakpoint_list;
742    lldb::BreakpointSP m_last_created_breakpoint;
743    // We want to tightly control the process destruction process so
744    // we can correctly tear down everything that we need to, so the only
745    // class that knows about the process lifespan is this target class.
746    lldb::ProcessSP m_process_sp;
747    lldb::SearchFilterSP  m_search_filter_sp;
748    PathMappingList m_image_search_paths;
749    std::auto_ptr<ClangASTContext> m_scratch_ast_context_ap;
750    ClangPersistentVariables m_persistent_variables;      ///< These are the persistent variables associated with this process for the expression parser.
751
752
753    typedef std::map<lldb::user_id_t, StopHookSP> StopHookCollection;
754    StopHookCollection      m_stop_hooks;
755    lldb::user_id_t         m_stop_hook_next_id;
756    bool                    m_suppress_stop_hooks;
757
758    //------------------------------------------------------------------
759    // Methods.
760    //------------------------------------------------------------------
761    lldb::SearchFilterSP
762    GetSearchFilterForModule (const FileSpec *containingModule);
763
764    static void
765    ImageSearchPathsChanged (const PathMappingList &path_list,
766                             void *baton);
767
768private:
769    DISALLOW_COPY_AND_ASSIGN (Target);
770};
771
772} // namespace lldb_private
773
774#endif  // liblldb_Target_h_
775