Platform.h revision 95b765e8000b44644d021e95bc58eac95028573b
1//===-- Platform.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_Platform_h_
11#define liblldb_Platform_h_
12
13// C Includes
14// C++ Includes
15#include <map>
16#include <string>
17#include <vector>
18
19// Other libraries and framework includes
20// Project includes
21#include "lldb/lldb-public.h"
22#include "lldb/Core/ArchSpec.h"
23#include "lldb/Core/ConstString.h"
24#include "lldb/Core/PluginInterface.h"
25#include "lldb/Host/Mutex.h"
26
27namespace lldb_private {
28
29    //----------------------------------------------------------------------
30    /// @class Platform Platform.h "lldb/Target/Platform.h"
31    /// @brief A plug-in interface definition class for debug platform that
32    /// includes many platform abilities such as:
33    ///     @li getting platform information such as supported architectures,
34    ///         supported binary file formats and more
35    ///     @li launching new processes
36    ///     @li attaching to existing processes
37    ///     @li download/upload files
38    ///     @li execute shell commands
39    ///     @li listing and getting info for existing processes
40    ///     @li attaching and possibly debugging the platform's kernel
41    //----------------------------------------------------------------------
42    class Platform : public PluginInterface
43    {
44    public:
45
46        //------------------------------------------------------------------
47        /// Get the native host platform plug-in.
48        ///
49        /// There should only be one of these for each host that LLDB runs
50        /// upon that should be statically compiled in and registered using
51        /// preprocessor macros or other similar build mechanisms in a
52        /// PlatformSubclass::Initialize() function.
53        ///
54        /// This platform will be used as the default platform when launching
55        /// or attaching to processes unless another platform is specified.
56        //------------------------------------------------------------------
57        static lldb::PlatformSP
58        GetDefaultPlatform ();
59
60        static lldb::PlatformSP
61        GetPlatformForArchitecture (const ArchSpec &arch,
62                                    ArchSpec *platform_arch_ptr);
63
64        static const char *
65        GetHostPlatformName ();
66
67        static void
68        SetDefaultPlatform (const lldb::PlatformSP &platform_sp);
69
70        static lldb::PlatformSP
71        Create (const char *platform_name, Error &error);
72
73        static lldb::PlatformSP
74        Create (const ArchSpec &arch, ArchSpec *platform_arch_ptr, Error &error);
75
76        static uint32_t
77        GetNumConnectedRemotePlatforms ();
78
79        static lldb::PlatformSP
80        GetConnectedRemotePlatformAtIndex (uint32_t idx);
81
82        //------------------------------------------------------------------
83        /// Default Constructor
84        //------------------------------------------------------------------
85        Platform (bool is_host_platform);
86
87        //------------------------------------------------------------------
88        /// Destructor.
89        ///
90        /// The destructor is virtual since this class is designed to be
91        /// inherited from by the plug-in instance.
92        //------------------------------------------------------------------
93        virtual
94        ~Platform();
95
96        //------------------------------------------------------------------
97        /// Set the target's executable based off of the existing
98        /// architecture information in \a target given a path to an
99        /// executable \a exe_file.
100        ///
101        /// Each platform knows the architectures that it supports and can
102        /// select the correct architecture slice within \a exe_file by
103        /// inspecting the architecture in \a target. If the target had an
104        /// architecture specified, then in can try and obey that request
105        /// and optionally fail if the architecture doesn't match up.
106        /// If no architecture is specified, the platform should select the
107        /// default architecture from \a exe_file. Any application bundles
108        /// or executable wrappers can also be inspected for the actual
109        /// application binary within the bundle that should be used.
110        ///
111        /// @return
112        ///     Returns \b true if this Platform plug-in was able to find
113        ///     a suitable executable, \b false otherwise.
114        //------------------------------------------------------------------
115        virtual Error
116        ResolveExecutable (const FileSpec &exe_file,
117                           const ArchSpec &arch,
118                           lldb::ModuleSP &module_sp,
119                           const FileSpecList *module_search_paths_ptr);
120
121
122        //------------------------------------------------------------------
123        /// Find a symbol file given a symbol file module specification.
124        ///
125        /// Each platform might have tricks to find symbol files for an
126        /// executable given information in a symbol file ModuleSpec. Some
127        /// platforms might also support symbol files that are bundles and
128        /// know how to extract the right symbol file given a bundle.
129        ///
130        /// @param[in] target
131        ///     The target in which we are trying to resolve the symbol file.
132        ///     The target has a list of modules that we might be able to
133        ///     use in order to help find the right symbol file. If the
134        ///     "m_file" or "m_platform_file" entries in the \a sym_spec
135        ///     are filled in, then we might be able to locate a module in
136        ///     the target, extract its UUID and locate a symbol file.
137        ///     If just the "m_uuid" is specified, then we might be able
138        ///     to find the module in the target that matches that UUID
139        ///     and pair the symbol file along with it. If just "m_symbol_file"
140        ///     is specified, we can use a variety of tricks to locate the
141        ///     symbols in an SDK, PDK, or other development kit location.
142        ///
143        /// @param[in] sym_spec
144        ///     A module spec that describes some information about the
145        ///     symbol file we are trying to resolve. The ModuleSpec might
146        ///     contain the following:
147        ///     m_file - A full or partial path to an executable from the
148        ///              target (might be empty).
149        ///     m_platform_file - Another executable hint that contains
150        ///                       the path to the file as known on the
151        ///                       local/remote platform.
152        ///     m_symbol_file - A full or partial path to a symbol file
153        ///                     or symbol bundle that should be used when
154        ///                     trying to resolve the symbol file.
155        ///     m_arch - The architecture we are looking for when resolving
156        ///              the symbol file.
157        ///     m_uuid - The UUID of the executable and symbol file. This
158        ///              can often be used to match up an exectuable with
159        ///              a symbol file, or resolve an symbol file in a
160        ///              symbol file bundle.
161        ///
162        /// @param[out] sym_file
163        ///     The resolved symbol file spec if the returned error
164        ///     indicates succes.
165        ///
166        /// @return
167        ///     Returns an error that describes success or failure.
168        //------------------------------------------------------------------
169        virtual Error
170        ResolveSymbolFile (Target &target,
171                           const ModuleSpec &sym_spec,
172                           FileSpec &sym_file);
173
174        //------------------------------------------------------------------
175        /// Resolves the FileSpec to a (possibly) remote path. Remote
176        /// platforms must override this to resolve to a path on the remote
177        /// side.
178        //------------------------------------------------------------------
179        virtual bool
180        ResolveRemotePath (const FileSpec &platform_path,
181                           FileSpec &resolved_platform_path);
182
183        bool
184        GetOSVersion (uint32_t &major,
185                      uint32_t &minor,
186                      uint32_t &update);
187
188        bool
189        SetOSVersion (uint32_t major,
190                      uint32_t minor,
191                      uint32_t update);
192
193        bool
194        GetOSBuildString (std::string &s);
195
196        bool
197        GetOSKernelDescription (std::string &s);
198
199        // Returns the the hostname if we are connected, else the short plugin
200        // name.
201        const char *
202        GetName ();
203
204        virtual const char *
205        GetHostname ();
206
207        virtual const char *
208        GetDescription () = 0;
209
210        //------------------------------------------------------------------
211        /// Report the current status for this platform.
212        ///
213        /// The returned string usually involves returning the OS version
214        /// (if available), and any SDK directory that might be being used
215        /// for local file caching, and if connected a quick blurb about
216        /// what this platform is connected to.
217        //------------------------------------------------------------------
218        virtual void
219        GetStatus (Stream &strm);
220
221        //------------------------------------------------------------------
222        // Subclasses must be able to fetch the current OS version
223        //
224        // Remote classes must be connected for this to succeed. Local
225        // subclasses don't need to override this function as it will just
226        // call the Host::GetOSVersion().
227        //------------------------------------------------------------------
228        virtual bool
229        GetRemoteOSVersion ()
230        {
231            return false;
232        }
233
234        virtual bool
235        GetRemoteOSBuildString (std::string &s)
236        {
237            s.clear();
238            return false;
239        }
240
241        virtual bool
242        GetRemoteOSKernelDescription (std::string &s)
243        {
244            s.clear();
245            return false;
246        }
247
248        // Remote Platform subclasses need to override this function
249        virtual ArchSpec
250        GetRemoteSystemArchitecture ()
251        {
252            return ArchSpec(); // Return an invalid architecture
253        }
254
255        virtual const char *
256        GetUserName (uint32_t uid);
257
258        virtual const char *
259        GetGroupName (uint32_t gid);
260
261        //------------------------------------------------------------------
262        /// Locate a file for a platform.
263        ///
264        /// The default implementation of this function will return the same
265        /// file patch in \a local_file as was in \a platform_file.
266        ///
267        /// @param[in] platform_file
268        ///     The platform file path to locate and cache locally.
269        ///
270        /// @param[in] uuid_ptr
271        ///     If we know the exact UUID of the file we are looking for, it
272        ///     can be specified. If it is not specified, we might now know
273        ///     the exact file. The UUID is usually some sort of MD5 checksum
274        ///     for the file and is sometimes known by dynamic linkers/loaders.
275        ///     If the UUID is known, it is best to supply it to platform
276        ///     file queries to ensure we are finding the correct file, not
277        ///     just a file at the correct path.
278        ///
279        /// @param[out] local_file
280        ///     A locally cached version of the platform file. For platforms
281        ///     that describe the current host computer, this will just be
282        ///     the same file. For remote platforms, this file might come from
283        ///     and SDK directory, or might need to be sync'ed over to the
284        ///     current machine for efficient debugging access.
285        ///
286        /// @return
287        ///     An error object.
288        //------------------------------------------------------------------
289        virtual Error
290        GetFile (const FileSpec &platform_file,
291                 const UUID *uuid_ptr,
292                 FileSpec &local_file);
293
294        virtual Error
295        GetSharedModule (const ModuleSpec &module_spec,
296                         lldb::ModuleSP &module_sp,
297                         const FileSpecList *module_search_paths_ptr,
298                         lldb::ModuleSP *old_module_sp_ptr,
299                         bool *did_create_ptr);
300
301        virtual Error
302        ConnectRemote (Args& args);
303
304        virtual Error
305        DisconnectRemote ();
306
307        //------------------------------------------------------------------
308        /// Get the platform's supported architectures in the order in which
309        /// they should be searched.
310        ///
311        /// @param[in] idx
312        ///     A zero based architecture index
313        ///
314        /// @param[out] arch
315        ///     A copy of the archgitecture at index if the return value is
316        ///     \b true.
317        ///
318        /// @return
319        ///     \b true if \a arch was filled in and is valid, \b false
320        ///     otherwise.
321        //------------------------------------------------------------------
322        virtual bool
323        GetSupportedArchitectureAtIndex (uint32_t idx, ArchSpec &arch) = 0;
324
325        virtual size_t
326        GetSoftwareBreakpointTrapOpcode (Target &target,
327                                         BreakpointSite *bp_site) = 0;
328
329        //------------------------------------------------------------------
330        /// Launch a new process on a platform, not necessarily for
331        /// debugging, it could be just for running the process.
332        //------------------------------------------------------------------
333        virtual Error
334        LaunchProcess (ProcessLaunchInfo &launch_info);
335
336        //------------------------------------------------------------------
337        /// Lets a platform answer if it is compatible with a given
338        /// architecture and the target triple contained within.
339        //------------------------------------------------------------------
340        virtual bool
341        IsCompatibleArchitecture (const ArchSpec &arch, ArchSpec *compatible_arch_ptr = NULL);
342
343        //------------------------------------------------------------------
344        /// Not all platforms will support debugging a process by spawning
345        /// somehow halted for a debugger (specified using the
346        /// "eLaunchFlagDebug" launch flag) and then attaching. If your
347        /// platform doesn't support this, override this function and return
348        /// false.
349        //------------------------------------------------------------------
350        virtual bool
351        CanDebugProcess ()
352        {
353            return true;
354        }
355
356        //------------------------------------------------------------------
357        /// Subclasses should NOT need to implement this function as it uses
358        /// the Platform::LaunchProcess() followed by Platform::Attach ()
359        //------------------------------------------------------------------
360        lldb::ProcessSP
361        DebugProcess (ProcessLaunchInfo &launch_info,
362                      Debugger &debugger,
363                      Target *target,       // Can be NULL, if NULL create a new target, else use existing one
364                      Listener &listener,
365                      Error &error);
366
367        //------------------------------------------------------------------
368        /// Attach to an existing process using a process ID.
369        ///
370        /// Each platform subclass needs to implement this function and
371        /// attempt to attach to the process with the process ID of \a pid.
372        /// The platform subclass should return an appropriate ProcessSP
373        /// subclass that is attached to the process, or an empty shared
374        /// pointer with an appriopriate error.
375        ///
376        /// @param[in] pid
377        ///     The process ID that we should attempt to attach to.
378        ///
379        /// @return
380        ///     An appropriate ProcessSP containing a valid shared pointer
381        ///     to the default Process subclass for the platform that is
382        ///     attached to the process, or an empty shared pointer with an
383        ///     appriopriate error fill into the \a error object.
384        //------------------------------------------------------------------
385        virtual lldb::ProcessSP
386        Attach (ProcessAttachInfo &attach_info,
387                Debugger &debugger,
388                Target *target,       // Can be NULL, if NULL create a new target, else use existing one
389                Listener &listener,
390                Error &error) = 0;
391
392        //------------------------------------------------------------------
393        /// Attach to an existing process by process name.
394        ///
395        /// This function is not meant to be overridden by Process
396        /// subclasses. It will first call
397        /// Process::WillAttach (const char *) and if that returns \b
398        /// true, Process::DoAttach (const char *) will be called to
399        /// actually do the attach. If DoAttach returns \b true, then
400        /// Process::DidAttach() will be called.
401        ///
402        /// @param[in] process_name
403        ///     A process name to match against the current process list.
404        ///
405        /// @return
406        ///     Returns \a pid if attaching was successful, or
407        ///     LLDB_INVALID_PROCESS_ID if attaching fails.
408        //------------------------------------------------------------------
409//        virtual lldb::ProcessSP
410//        Attach (const char *process_name,
411//                bool wait_for_launch,
412//                Error &error) = 0;
413
414        //------------------------------------------------------------------
415        // The base class Platform will take care of the host platform.
416        // Subclasses will need to fill in the remote case.
417        //------------------------------------------------------------------
418        virtual uint32_t
419        FindProcesses (const ProcessInstanceInfoMatch &match_info,
420                       ProcessInstanceInfoList &proc_infos);
421
422        virtual bool
423        GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &proc_info);
424
425        //------------------------------------------------------------------
426        // Set a breakpoint on all functions that can end up creating a thread
427        // for this platform. This is needed when running expressions and
428        // also for process control.
429        //------------------------------------------------------------------
430        virtual lldb::BreakpointSP
431        SetThreadCreationBreakpoint (Target &target);
432
433
434        const std::string &
435        GetRemoteURL () const
436        {
437            return m_remote_url;
438        }
439
440        bool
441        IsHost () const
442        {
443            return m_is_host;    // Is this the default host platform?
444        }
445
446        bool
447        IsRemote () const
448        {
449            return !m_is_host;
450        }
451
452        virtual bool
453        IsConnected () const
454        {
455            // Remote subclasses should override this function
456            return IsHost();
457        }
458
459        const ArchSpec &
460        GetSystemArchitecture();
461
462        void
463        SetSystemArchitecture (const ArchSpec &arch)
464        {
465            m_system_arch = arch;
466            if (IsHost())
467                m_os_version_set_while_connected = m_system_arch.IsValid();
468        }
469
470        // Used for column widths
471        uint32_t
472        GetMaxUserIDNameLength() const
473        {
474            return m_max_uid_name_len;
475        }
476        // Used for column widths
477        uint32_t
478        GetMaxGroupIDNameLength() const
479        {
480            return m_max_gid_name_len;
481        }
482
483        const ConstString &
484        GetSDKRootDirectory () const
485        {
486            return m_sdk_sysroot;
487        }
488
489        void
490        SetSDKRootDirectory (const ConstString &dir)
491        {
492            m_sdk_sysroot = dir;
493        }
494
495        const ConstString &
496        GetSDKBuild () const
497        {
498            return m_sdk_build;
499        }
500
501        void
502        SetSDKBuild (const ConstString &sdk_build)
503        {
504            m_sdk_build = sdk_build;
505        }
506
507        // There may be modules that we don't want to find by default for operations like "setting breakpoint by name".
508        // The platform will return "true" from this call if the passed in module happens to be one of these.
509
510        virtual bool
511        ModuleIsExcludedForNonModuleSpecificSearches (Target &target, const lldb::ModuleSP &module_sp)
512        {
513            return false;
514        }
515
516        virtual size_t
517        GetEnvironment (StringList &environment);
518
519    protected:
520        bool m_is_host;
521        // Set to true when we are able to actually set the OS version while
522        // being connected. For remote platforms, we might set the version ahead
523        // of time before we actually connect and this version might change when
524        // we actually connect to a remote platform. For the host platform this
525        // will be set to the once we call Host::GetOSVersion().
526        bool m_os_version_set_while_connected;
527        bool m_system_arch_set_while_connected;
528        ConstString m_sdk_sysroot; // the root location of where the SDK files are all located
529        ConstString m_sdk_build;
530        std::string m_remote_url;
531        std::string m_name;
532        uint32_t m_major_os_version;
533        uint32_t m_minor_os_version;
534        uint32_t m_update_os_version;
535        ArchSpec m_system_arch; // The architecture of the kernel or the remote platform
536        typedef std::map<uint32_t, ConstString> IDToNameMap;
537        Mutex m_uid_map_mutex;
538        Mutex m_gid_map_mutex;
539        IDToNameMap m_uid_map;
540        IDToNameMap m_gid_map;
541        uint32_t m_max_uid_name_len;
542        uint32_t m_max_gid_name_len;
543
544        const char *
545        GetCachedUserName (uint32_t uid)
546        {
547            Mutex::Locker locker (m_uid_map_mutex);
548            IDToNameMap::iterator pos = m_uid_map.find (uid);
549            if (pos != m_uid_map.end())
550            {
551                // return the empty string if our string is NULL
552                // so we can tell when things were in the negative
553                // cached (didn't find a valid user name, don't keep
554                // trying)
555                return pos->second.AsCString("");
556            }
557            return NULL;
558        }
559
560        const char *
561        SetCachedUserName (uint32_t uid, const char *name, size_t name_len)
562        {
563            Mutex::Locker locker (m_uid_map_mutex);
564            ConstString const_name (name);
565            m_uid_map[uid] = const_name;
566            if (m_max_uid_name_len < name_len)
567                m_max_uid_name_len = name_len;
568            // Const strings lives forever in our const string pool, so we can return the const char *
569            return const_name.GetCString();
570        }
571
572        void
573        SetUserNameNotFound (uint32_t uid)
574        {
575            Mutex::Locker locker (m_uid_map_mutex);
576            m_uid_map[uid] = ConstString();
577        }
578
579
580        void
581        ClearCachedUserNames ()
582        {
583            Mutex::Locker locker (m_uid_map_mutex);
584            m_uid_map.clear();
585        }
586
587        const char *
588        GetCachedGroupName (uint32_t gid)
589        {
590            Mutex::Locker locker (m_gid_map_mutex);
591            IDToNameMap::iterator pos = m_gid_map.find (gid);
592            if (pos != m_gid_map.end())
593            {
594                // return the empty string if our string is NULL
595                // so we can tell when things were in the negative
596                // cached (didn't find a valid group name, don't keep
597                // trying)
598                return pos->second.AsCString("");
599            }
600            return NULL;
601        }
602
603        const char *
604        SetCachedGroupName (uint32_t gid, const char *name, size_t name_len)
605        {
606            Mutex::Locker locker (m_gid_map_mutex);
607            ConstString const_name (name);
608            m_gid_map[gid] = const_name;
609            if (m_max_gid_name_len < name_len)
610                m_max_gid_name_len = name_len;
611            // Const strings lives forever in our const string pool, so we can return the const char *
612            return const_name.GetCString();
613        }
614
615        void
616        SetGroupNameNotFound (uint32_t gid)
617        {
618            Mutex::Locker locker (m_gid_map_mutex);
619            m_gid_map[gid] = ConstString();
620        }
621
622        void
623        ClearCachedGroupNames ()
624        {
625            Mutex::Locker locker (m_gid_map_mutex);
626            m_gid_map.clear();
627        }
628
629    private:
630        DISALLOW_COPY_AND_ASSIGN (Platform);
631    };
632
633
634    class PlatformList
635    {
636    public:
637        PlatformList() :
638            m_mutex (Mutex::eMutexTypeRecursive),
639            m_platforms (),
640            m_selected_platform_sp()
641        {
642        }
643
644        ~PlatformList()
645        {
646        }
647
648        void
649        Append (const lldb::PlatformSP &platform_sp, bool set_selected)
650        {
651            Mutex::Locker locker (m_mutex);
652            m_platforms.push_back (platform_sp);
653            if (set_selected)
654                m_selected_platform_sp = m_platforms.back();
655        }
656
657        size_t
658        GetSize()
659        {
660            Mutex::Locker locker (m_mutex);
661            return m_platforms.size();
662        }
663
664        lldb::PlatformSP
665        GetAtIndex (uint32_t idx)
666        {
667            lldb::PlatformSP platform_sp;
668            {
669                Mutex::Locker locker (m_mutex);
670                if (idx < m_platforms.size())
671                    platform_sp = m_platforms[idx];
672            }
673            return platform_sp;
674        }
675
676        //------------------------------------------------------------------
677        /// Select the active platform.
678        ///
679        /// In order to debug remotely, other platform's can be remotely
680        /// connected to and set as the selected platform for any subsequent
681        /// debugging. This allows connection to remote targets and allows
682        /// the ability to discover process info, launch and attach to remote
683        /// processes.
684        //------------------------------------------------------------------
685        lldb::PlatformSP
686        GetSelectedPlatform ()
687        {
688            Mutex::Locker locker (m_mutex);
689            if (!m_selected_platform_sp && !m_platforms.empty())
690                m_selected_platform_sp = m_platforms.front();
691
692            return m_selected_platform_sp;
693        }
694
695        void
696        SetSelectedPlatform (const lldb::PlatformSP &platform_sp)
697        {
698            if (platform_sp)
699            {
700                Mutex::Locker locker (m_mutex);
701                const size_t num_platforms = m_platforms.size();
702                for (size_t idx=0; idx<num_platforms; ++idx)
703                {
704                    if (m_platforms[idx].get() == platform_sp.get())
705                    {
706                        m_selected_platform_sp = m_platforms[idx];
707                        return;
708                    }
709                }
710                m_platforms.push_back (platform_sp);
711                m_selected_platform_sp = m_platforms.back();
712            }
713        }
714
715    protected:
716        typedef std::vector<lldb::PlatformSP> collection;
717        mutable Mutex m_mutex;
718        collection m_platforms;
719        lldb::PlatformSP m_selected_platform_sp;
720
721    private:
722        DISALLOW_COPY_AND_ASSIGN (PlatformList);
723    };
724} // namespace lldb_private
725
726#endif  // liblldb_Platform_h_
727