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