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