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