Platform.h revision b170aee2daacc83e3d71c3e3acc9d56c89893a7b
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        /// Resolves the FileSpec to a (possibly) remote path. Remote
123        /// platforms must override this to resolve to a path on the remote
124        /// side.
125        //------------------------------------------------------------------
126        virtual bool
127        ResolveRemotePath (const FileSpec &platform_path,
128                           FileSpec &resolved_platform_path);
129
130        bool
131        GetOSVersion (uint32_t &major,
132                      uint32_t &minor,
133                      uint32_t &update);
134
135        bool
136        SetOSVersion (uint32_t major,
137                      uint32_t minor,
138                      uint32_t update);
139
140        bool
141        GetOSBuildString (std::string &s);
142
143        bool
144        GetOSKernelDescription (std::string &s);
145
146        // Returns the the hostname if we are connected, else the short plugin
147        // name.
148        const char *
149        GetName ();
150
151        virtual const char *
152        GetHostname ();
153
154        virtual const char *
155        GetDescription () = 0;
156
157        //------------------------------------------------------------------
158        /// Report the current status for this platform.
159        ///
160        /// The returned string usually involves returning the OS version
161        /// (if available), and any SDK directory that might be being used
162        /// for local file caching, and if connected a quick blurb about
163        /// what this platform is connected to.
164        //------------------------------------------------------------------
165        virtual void
166        GetStatus (Stream &strm);
167
168        //------------------------------------------------------------------
169        // Subclasses must be able to fetch the current OS version
170        //
171        // Remote classes must be connected for this to succeed. Local
172        // subclasses don't need to override this function as it will just
173        // call the Host::GetOSVersion().
174        //------------------------------------------------------------------
175        virtual bool
176        GetRemoteOSVersion ()
177        {
178            return false;
179        }
180
181        virtual bool
182        GetRemoteOSBuildString (std::string &s)
183        {
184            s.clear();
185            return false;
186        }
187
188        virtual bool
189        GetRemoteOSKernelDescription (std::string &s)
190        {
191            s.clear();
192            return false;
193        }
194
195        // Remote Platform subclasses need to override this function
196        virtual ArchSpec
197        GetRemoteSystemArchitecture ()
198        {
199            return ArchSpec(); // Return an invalid architecture
200        }
201
202        virtual const char *
203        GetUserName (uint32_t uid);
204
205        virtual const char *
206        GetGroupName (uint32_t gid);
207
208        //------------------------------------------------------------------
209        /// Locate a file for a platform.
210        ///
211        /// The default implementation of this function will return the same
212        /// file patch in \a local_file as was in \a platform_file.
213        ///
214        /// @param[in] platform_file
215        ///     The platform file path to locate and cache locally.
216        ///
217        /// @param[in] uuid_ptr
218        ///     If we know the exact UUID of the file we are looking for, it
219        ///     can be specified. If it is not specified, we might now know
220        ///     the exact file. The UUID is usually some sort of MD5 checksum
221        ///     for the file and is sometimes known by dynamic linkers/loaders.
222        ///     If the UUID is known, it is best to supply it to platform
223        ///     file queries to ensure we are finding the correct file, not
224        ///     just a file at the correct path.
225        ///
226        /// @param[out] local_file
227        ///     A locally cached version of the platform file. For platforms
228        ///     that describe the current host computer, this will just be
229        ///     the same file. For remote platforms, this file might come from
230        ///     and SDK directory, or might need to be sync'ed over to the
231        ///     current machine for efficient debugging access.
232        ///
233        /// @return
234        ///     An error object.
235        //------------------------------------------------------------------
236        virtual Error
237        GetFile (const FileSpec &platform_file,
238                 const UUID *uuid_ptr,
239                 FileSpec &local_file);
240
241        virtual Error
242        GetSharedModule (const ModuleSpec &module_spec,
243                         lldb::ModuleSP &module_sp,
244                         const FileSpecList *module_search_paths_ptr,
245                         lldb::ModuleSP *old_module_sp_ptr,
246                         bool *did_create_ptr);
247
248        virtual Error
249        ConnectRemote (Args& args);
250
251        virtual Error
252        DisconnectRemote ();
253
254        //------------------------------------------------------------------
255        /// Get the platform's supported architectures in the order in which
256        /// they should be searched.
257        ///
258        /// @param[in] idx
259        ///     A zero based architecture index
260        ///
261        /// @param[out] arch
262        ///     A copy of the archgitecture at index if the return value is
263        ///     \b true.
264        ///
265        /// @return
266        ///     \b true if \a arch was filled in and is valid, \b false
267        ///     otherwise.
268        //------------------------------------------------------------------
269        virtual bool
270        GetSupportedArchitectureAtIndex (uint32_t idx, ArchSpec &arch) = 0;
271
272        virtual size_t
273        GetSoftwareBreakpointTrapOpcode (Target &target,
274                                         BreakpointSite *bp_site) = 0;
275
276        //------------------------------------------------------------------
277        /// Launch a new process on a platform, not necessarily for
278        /// debugging, it could be just for running the process.
279        //------------------------------------------------------------------
280        virtual Error
281        LaunchProcess (ProcessLaunchInfo &launch_info);
282
283        //------------------------------------------------------------------
284        /// Lets a platform answer if it is compatible with a given
285        /// architecture and the target triple contained within.
286        //------------------------------------------------------------------
287        virtual bool
288        IsCompatibleArchitecture (const ArchSpec &arch, ArchSpec *compatible_arch_ptr = NULL);
289
290        //------------------------------------------------------------------
291        /// Not all platforms will support debugging a process by spawning
292        /// somehow halted for a debugger (specified using the
293        /// "eLaunchFlagDebug" launch flag) and then attaching. If your
294        /// platform doesn't support this, override this function and return
295        /// false.
296        //------------------------------------------------------------------
297        virtual bool
298        CanDebugProcess ()
299        {
300            return true;
301        }
302
303        //------------------------------------------------------------------
304        /// Subclasses should NOT need to implement this function as it uses
305        /// the Platform::LaunchProcess() followed by Platform::Attach ()
306        //------------------------------------------------------------------
307        lldb::ProcessSP
308        DebugProcess (ProcessLaunchInfo &launch_info,
309                      Debugger &debugger,
310                      Target *target,       // Can be NULL, if NULL create a new target, else use existing one
311                      Listener &listener,
312                      Error &error);
313
314        //------------------------------------------------------------------
315        /// Attach to an existing process using a process ID.
316        ///
317        /// Each platform subclass needs to implement this function and
318        /// attempt to attach to the process with the process ID of \a pid.
319        /// The platform subclass should return an appropriate ProcessSP
320        /// subclass that is attached to the process, or an empty shared
321        /// pointer with an appriopriate error.
322        ///
323        /// @param[in] pid
324        ///     The process ID that we should attempt to attach to.
325        ///
326        /// @return
327        ///     An appropriate ProcessSP containing a valid shared pointer
328        ///     to the default Process subclass for the platform that is
329        ///     attached to the process, or an empty shared pointer with an
330        ///     appriopriate error fill into the \a error object.
331        //------------------------------------------------------------------
332        virtual lldb::ProcessSP
333        Attach (ProcessAttachInfo &attach_info,
334                Debugger &debugger,
335                Target *target,       // Can be NULL, if NULL create a new target, else use existing one
336                Listener &listener,
337                Error &error) = 0;
338
339        //------------------------------------------------------------------
340        /// Attach to an existing process by process name.
341        ///
342        /// This function is not meant to be overridden by Process
343        /// subclasses. It will first call
344        /// Process::WillAttach (const char *) and if that returns \b
345        /// true, Process::DoAttach (const char *) will be called to
346        /// actually do the attach. If DoAttach returns \b true, then
347        /// Process::DidAttach() will be called.
348        ///
349        /// @param[in] process_name
350        ///     A process name to match against the current process list.
351        ///
352        /// @return
353        ///     Returns \a pid if attaching was successful, or
354        ///     LLDB_INVALID_PROCESS_ID if attaching fails.
355        //------------------------------------------------------------------
356//        virtual lldb::ProcessSP
357//        Attach (const char *process_name,
358//                bool wait_for_launch,
359//                Error &error) = 0;
360
361        //------------------------------------------------------------------
362        // The base class Platform will take care of the host platform.
363        // Subclasses will need to fill in the remote case.
364        //------------------------------------------------------------------
365        virtual uint32_t
366        FindProcesses (const ProcessInstanceInfoMatch &match_info,
367                       ProcessInstanceInfoList &proc_infos);
368
369        virtual bool
370        GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &proc_info);
371
372        const std::string &
373        GetRemoteURL () const
374        {
375            return m_remote_url;
376        }
377
378        bool
379        IsHost () const
380        {
381            return m_is_host;    // Is this the default host platform?
382        }
383
384        bool
385        IsRemote () const
386        {
387            return !m_is_host;
388        }
389
390        virtual bool
391        IsConnected () const
392        {
393            // Remote subclasses should override this function
394            return IsHost();
395        }
396
397        const ArchSpec &
398        GetSystemArchitecture();
399
400        void
401        SetSystemArchitecture (const ArchSpec &arch)
402        {
403            m_system_arch = arch;
404            if (IsHost())
405                m_os_version_set_while_connected = m_system_arch.IsValid();
406        }
407
408        // Used for column widths
409        uint32_t
410        GetMaxUserIDNameLength() const
411        {
412            return m_max_uid_name_len;
413        }
414        // Used for column widths
415        uint32_t
416        GetMaxGroupIDNameLength() const
417        {
418            return m_max_gid_name_len;
419        }
420
421        const ConstString &
422        GetSDKRootDirectory () const
423        {
424            return m_sdk_sysroot;
425        }
426
427        void
428        SetSDKRootDirectory (const ConstString &dir)
429        {
430            m_sdk_sysroot = dir;
431        }
432
433        const ConstString &
434        GetSDKBuild () const
435        {
436            return m_sdk_build;
437        }
438
439        void
440        SetSDKBuild (const ConstString &sdk_build)
441        {
442            m_sdk_build = sdk_build;
443        }
444
445        // There may be modules that we don't want to find by default for operations like "setting breakpoint by name".
446        // The platform will return "true" from this call if the passed in module happens to be one of these.
447
448        virtual bool
449        ModuleIsExcludedForNonModuleSpecificSearches (Target &target, const lldb::ModuleSP &module_sp)
450        {
451            return false;
452        }
453
454    protected:
455        bool m_is_host;
456        // Set to true when we are able to actually set the OS version while
457        // being connected. For remote platforms, we might set the version ahead
458        // of time before we actually connect and this version might change when
459        // we actually connect to a remote platform. For the host platform this
460        // will be set to the once we call Host::GetOSVersion().
461        bool m_os_version_set_while_connected;
462        bool m_system_arch_set_while_connected;
463        ConstString m_sdk_sysroot; // the root location of where the SDK files are all located
464        ConstString m_sdk_build;
465        std::string m_remote_url;
466        std::string m_name;
467        uint32_t m_major_os_version;
468        uint32_t m_minor_os_version;
469        uint32_t m_update_os_version;
470        ArchSpec m_system_arch; // The architecture of the kernel or the remote platform
471        typedef std::map<uint32_t, ConstString> IDToNameMap;
472        Mutex m_uid_map_mutex;
473        Mutex m_gid_map_mutex;
474        IDToNameMap m_uid_map;
475        IDToNameMap m_gid_map;
476        uint32_t m_max_uid_name_len;
477        uint32_t m_max_gid_name_len;
478
479        const char *
480        GetCachedUserName (uint32_t uid)
481        {
482            Mutex::Locker locker (m_uid_map_mutex);
483            IDToNameMap::iterator pos = m_uid_map.find (uid);
484            if (pos != m_uid_map.end())
485            {
486                // return the empty string if our string is NULL
487                // so we can tell when things were in the negative
488                // cached (didn't find a valid user name, don't keep
489                // trying)
490                return pos->second.AsCString("");
491            }
492            return NULL;
493        }
494
495        const char *
496        SetCachedUserName (uint32_t uid, const char *name, size_t name_len)
497        {
498            Mutex::Locker locker (m_uid_map_mutex);
499            ConstString const_name (name);
500            m_uid_map[uid] = const_name;
501            if (m_max_uid_name_len < name_len)
502                m_max_uid_name_len = name_len;
503            // Const strings lives forever in our const string pool, so we can return the const char *
504            return const_name.GetCString();
505        }
506
507        void
508        SetUserNameNotFound (uint32_t uid)
509        {
510            Mutex::Locker locker (m_uid_map_mutex);
511            m_uid_map[uid] = ConstString();
512        }
513
514
515        void
516        ClearCachedUserNames ()
517        {
518            Mutex::Locker locker (m_uid_map_mutex);
519            m_uid_map.clear();
520        }
521
522        const char *
523        GetCachedGroupName (uint32_t gid)
524        {
525            Mutex::Locker locker (m_gid_map_mutex);
526            IDToNameMap::iterator pos = m_gid_map.find (gid);
527            if (pos != m_gid_map.end())
528            {
529                // return the empty string if our string is NULL
530                // so we can tell when things were in the negative
531                // cached (didn't find a valid group name, don't keep
532                // trying)
533                return pos->second.AsCString("");
534            }
535            return NULL;
536        }
537
538        const char *
539        SetCachedGroupName (uint32_t gid, const char *name, size_t name_len)
540        {
541            Mutex::Locker locker (m_gid_map_mutex);
542            ConstString const_name (name);
543            m_gid_map[gid] = const_name;
544            if (m_max_gid_name_len < name_len)
545                m_max_gid_name_len = name_len;
546            // Const strings lives forever in our const string pool, so we can return the const char *
547            return const_name.GetCString();
548        }
549
550        void
551        SetGroupNameNotFound (uint32_t gid)
552        {
553            Mutex::Locker locker (m_gid_map_mutex);
554            m_gid_map[gid] = ConstString();
555        }
556
557        void
558        ClearCachedGroupNames ()
559        {
560            Mutex::Locker locker (m_gid_map_mutex);
561            m_gid_map.clear();
562        }
563
564    private:
565        DISALLOW_COPY_AND_ASSIGN (Platform);
566    };
567
568
569    class PlatformList
570    {
571    public:
572        PlatformList() :
573            m_mutex (Mutex::eMutexTypeRecursive),
574            m_platforms (),
575            m_selected_platform_sp()
576        {
577        }
578
579        ~PlatformList()
580        {
581        }
582
583        void
584        Append (const lldb::PlatformSP &platform_sp, bool set_selected)
585        {
586            Mutex::Locker locker (m_mutex);
587            m_platforms.push_back (platform_sp);
588            if (set_selected)
589                m_selected_platform_sp = m_platforms.back();
590        }
591
592        size_t
593        GetSize()
594        {
595            Mutex::Locker locker (m_mutex);
596            return m_platforms.size();
597        }
598
599        lldb::PlatformSP
600        GetAtIndex (uint32_t idx)
601        {
602            lldb::PlatformSP platform_sp;
603            {
604                Mutex::Locker locker (m_mutex);
605                if (idx < m_platforms.size())
606                    platform_sp = m_platforms[idx];
607            }
608            return platform_sp;
609        }
610
611        //------------------------------------------------------------------
612        /// Select the active platform.
613        ///
614        /// In order to debug remotely, other platform's can be remotely
615        /// connected to and set as the selected platform for any subsequent
616        /// debugging. This allows connection to remote targets and allows
617        /// the ability to discover process info, launch and attach to remote
618        /// processes.
619        //------------------------------------------------------------------
620        lldb::PlatformSP
621        GetSelectedPlatform ()
622        {
623            Mutex::Locker locker (m_mutex);
624            if (!m_selected_platform_sp && !m_platforms.empty())
625                m_selected_platform_sp = m_platforms.front();
626
627            return m_selected_platform_sp;
628        }
629
630        void
631        SetSelectedPlatform (const lldb::PlatformSP &platform_sp)
632        {
633            if (platform_sp)
634            {
635                Mutex::Locker locker (m_mutex);
636                const size_t num_platforms = m_platforms.size();
637                for (size_t idx=0; idx<num_platforms; ++idx)
638                {
639                    if (m_platforms[idx].get() == platform_sp.get())
640                    {
641                        m_selected_platform_sp = m_platforms[idx];
642                        return;
643                    }
644                }
645                m_platforms.push_back (platform_sp);
646                m_selected_platform_sp = m_platforms.back();
647            }
648        }
649
650    protected:
651        typedef std::vector<lldb::PlatformSP> collection;
652        mutable Mutex m_mutex;
653        collection m_platforms;
654        lldb::PlatformSP m_selected_platform_sp;
655
656    private:
657        DISALLOW_COPY_AND_ASSIGN (PlatformList);
658    };
659} // namespace lldb_private
660
661#endif  // liblldb_Platform_h_
662