Platform.h revision aad2b0f2e5da0ecbf22ab7fead4c06671f64c6c5
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        //----------------------------------------------------------------------
295        // Locate the scripting resource given a module specification.
296        //
297        // Locating the file should happen only on the local computer or using
298        // the current computers global settings.
299        //----------------------------------------------------------------------
300        virtual FileSpec
301        LocateExecutableScriptingResource (const ModuleSpec &module_spec);
302
303        virtual Error
304        GetSharedModule (const ModuleSpec &module_spec,
305                         lldb::ModuleSP &module_sp,
306                         const FileSpecList *module_search_paths_ptr,
307                         lldb::ModuleSP *old_module_sp_ptr,
308                         bool *did_create_ptr);
309
310        virtual Error
311        ConnectRemote (Args& args);
312
313        virtual Error
314        DisconnectRemote ();
315
316        //------------------------------------------------------------------
317        /// Get the platform's supported architectures in the order in which
318        /// they should be searched.
319        ///
320        /// @param[in] idx
321        ///     A zero based architecture index
322        ///
323        /// @param[out] arch
324        ///     A copy of the archgitecture at index if the return value is
325        ///     \b true.
326        ///
327        /// @return
328        ///     \b true if \a arch was filled in and is valid, \b false
329        ///     otherwise.
330        //------------------------------------------------------------------
331        virtual bool
332        GetSupportedArchitectureAtIndex (uint32_t idx, ArchSpec &arch) = 0;
333
334        virtual size_t
335        GetSoftwareBreakpointTrapOpcode (Target &target,
336                                         BreakpointSite *bp_site) = 0;
337
338        //------------------------------------------------------------------
339        /// Launch a new process on a platform, not necessarily for
340        /// debugging, it could be just for running the process.
341        //------------------------------------------------------------------
342        virtual Error
343        LaunchProcess (ProcessLaunchInfo &launch_info);
344
345        //------------------------------------------------------------------
346        /// Lets a platform answer if it is compatible with a given
347        /// architecture and the target triple contained within.
348        //------------------------------------------------------------------
349        virtual bool
350        IsCompatibleArchitecture (const ArchSpec &arch,
351                                  bool exact_arch_match,
352                                  ArchSpec *compatible_arch_ptr);
353
354        //------------------------------------------------------------------
355        /// Not all platforms will support debugging a process by spawning
356        /// somehow halted for a debugger (specified using the
357        /// "eLaunchFlagDebug" launch flag) and then attaching. If your
358        /// platform doesn't support this, override this function and return
359        /// false.
360        //------------------------------------------------------------------
361        virtual bool
362        CanDebugProcess ()
363        {
364            return true;
365        }
366
367        //------------------------------------------------------------------
368        /// Subclasses should NOT need to implement this function as it uses
369        /// the Platform::LaunchProcess() followed by Platform::Attach ()
370        //------------------------------------------------------------------
371        lldb::ProcessSP
372        DebugProcess (ProcessLaunchInfo &launch_info,
373                      Debugger &debugger,
374                      Target *target,       // Can be NULL, if NULL create a new target, else use existing one
375                      Listener &listener,
376                      Error &error);
377
378        //------------------------------------------------------------------
379        /// Attach to an existing process using a process ID.
380        ///
381        /// Each platform subclass needs to implement this function and
382        /// attempt to attach to the process with the process ID of \a pid.
383        /// The platform subclass should return an appropriate ProcessSP
384        /// subclass that is attached to the process, or an empty shared
385        /// pointer with an appriopriate error.
386        ///
387        /// @param[in] pid
388        ///     The process ID that we should attempt to attach to.
389        ///
390        /// @return
391        ///     An appropriate ProcessSP containing a valid shared pointer
392        ///     to the default Process subclass for the platform that is
393        ///     attached to the process, or an empty shared pointer with an
394        ///     appriopriate error fill into the \a error object.
395        //------------------------------------------------------------------
396        virtual lldb::ProcessSP
397        Attach (ProcessAttachInfo &attach_info,
398                Debugger &debugger,
399                Target *target,       // Can be NULL, if NULL create a new target, else use existing one
400                Listener &listener,
401                Error &error) = 0;
402
403        //------------------------------------------------------------------
404        /// Attach to an existing process by process name.
405        ///
406        /// This function is not meant to be overridden by Process
407        /// subclasses. It will first call
408        /// Process::WillAttach (const char *) and if that returns \b
409        /// true, Process::DoAttach (const char *) will be called to
410        /// actually do the attach. If DoAttach returns \b true, then
411        /// Process::DidAttach() will be called.
412        ///
413        /// @param[in] process_name
414        ///     A process name to match against the current process list.
415        ///
416        /// @return
417        ///     Returns \a pid if attaching was successful, or
418        ///     LLDB_INVALID_PROCESS_ID if attaching fails.
419        //------------------------------------------------------------------
420//        virtual lldb::ProcessSP
421//        Attach (const char *process_name,
422//                bool wait_for_launch,
423//                Error &error) = 0;
424
425        //------------------------------------------------------------------
426        // The base class Platform will take care of the host platform.
427        // Subclasses will need to fill in the remote case.
428        //------------------------------------------------------------------
429        virtual uint32_t
430        FindProcesses (const ProcessInstanceInfoMatch &match_info,
431                       ProcessInstanceInfoList &proc_infos);
432
433        virtual bool
434        GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &proc_info);
435
436        //------------------------------------------------------------------
437        // Set a breakpoint on all functions that can end up creating a thread
438        // for this platform. This is needed when running expressions and
439        // also for process control.
440        //------------------------------------------------------------------
441        virtual lldb::BreakpointSP
442        SetThreadCreationBreakpoint (Target &target);
443
444
445        const std::string &
446        GetRemoteURL () const
447        {
448            return m_remote_url;
449        }
450
451        bool
452        IsHost () const
453        {
454            return m_is_host;    // Is this the default host platform?
455        }
456
457        bool
458        IsRemote () const
459        {
460            return !m_is_host;
461        }
462
463        virtual bool
464        IsConnected () const
465        {
466            // Remote subclasses should override this function
467            return IsHost();
468        }
469
470        const ArchSpec &
471        GetSystemArchitecture();
472
473        void
474        SetSystemArchitecture (const ArchSpec &arch)
475        {
476            m_system_arch = arch;
477            if (IsHost())
478                m_os_version_set_while_connected = m_system_arch.IsValid();
479        }
480
481        // Used for column widths
482        uint32_t
483        GetMaxUserIDNameLength() const
484        {
485            return m_max_uid_name_len;
486        }
487        // Used for column widths
488        uint32_t
489        GetMaxGroupIDNameLength() const
490        {
491            return m_max_gid_name_len;
492        }
493
494        const ConstString &
495        GetSDKRootDirectory () const
496        {
497            return m_sdk_sysroot;
498        }
499
500        void
501        SetSDKRootDirectory (const ConstString &dir)
502        {
503            m_sdk_sysroot = dir;
504        }
505
506        const ConstString &
507        GetSDKBuild () const
508        {
509            return m_sdk_build;
510        }
511
512        void
513        SetSDKBuild (const ConstString &sdk_build)
514        {
515            m_sdk_build = sdk_build;
516        }
517
518        // There may be modules that we don't want to find by default for operations like "setting breakpoint by name".
519        // The platform will return "true" from this call if the passed in module happens to be one of these.
520
521        virtual bool
522        ModuleIsExcludedForNonModuleSpecificSearches (Target &target, const lldb::ModuleSP &module_sp)
523        {
524            return false;
525        }
526
527        virtual size_t
528        GetEnvironment (StringList &environment);
529
530    protected:
531        bool m_is_host;
532        // Set to true when we are able to actually set the OS version while
533        // being connected. For remote platforms, we might set the version ahead
534        // of time before we actually connect and this version might change when
535        // we actually connect to a remote platform. For the host platform this
536        // will be set to the once we call Host::GetOSVersion().
537        bool m_os_version_set_while_connected;
538        bool m_system_arch_set_while_connected;
539        ConstString m_sdk_sysroot; // the root location of where the SDK files are all located
540        ConstString m_sdk_build;
541        std::string m_remote_url;
542        std::string m_name;
543        uint32_t m_major_os_version;
544        uint32_t m_minor_os_version;
545        uint32_t m_update_os_version;
546        ArchSpec m_system_arch; // The architecture of the kernel or the remote platform
547        typedef std::map<uint32_t, ConstString> IDToNameMap;
548        Mutex m_uid_map_mutex;
549        Mutex m_gid_map_mutex;
550        IDToNameMap m_uid_map;
551        IDToNameMap m_gid_map;
552        uint32_t m_max_uid_name_len;
553        uint32_t m_max_gid_name_len;
554
555        const char *
556        GetCachedUserName (uint32_t uid)
557        {
558            Mutex::Locker locker (m_uid_map_mutex);
559            IDToNameMap::iterator pos = m_uid_map.find (uid);
560            if (pos != m_uid_map.end())
561            {
562                // return the empty string if our string is NULL
563                // so we can tell when things were in the negative
564                // cached (didn't find a valid user name, don't keep
565                // trying)
566                return pos->second.AsCString("");
567            }
568            return NULL;
569        }
570
571        const char *
572        SetCachedUserName (uint32_t uid, const char *name, size_t name_len)
573        {
574            Mutex::Locker locker (m_uid_map_mutex);
575            ConstString const_name (name);
576            m_uid_map[uid] = const_name;
577            if (m_max_uid_name_len < name_len)
578                m_max_uid_name_len = name_len;
579            // Const strings lives forever in our const string pool, so we can return the const char *
580            return const_name.GetCString();
581        }
582
583        void
584        SetUserNameNotFound (uint32_t uid)
585        {
586            Mutex::Locker locker (m_uid_map_mutex);
587            m_uid_map[uid] = ConstString();
588        }
589
590
591        void
592        ClearCachedUserNames ()
593        {
594            Mutex::Locker locker (m_uid_map_mutex);
595            m_uid_map.clear();
596        }
597
598        const char *
599        GetCachedGroupName (uint32_t gid)
600        {
601            Mutex::Locker locker (m_gid_map_mutex);
602            IDToNameMap::iterator pos = m_gid_map.find (gid);
603            if (pos != m_gid_map.end())
604            {
605                // return the empty string if our string is NULL
606                // so we can tell when things were in the negative
607                // cached (didn't find a valid group name, don't keep
608                // trying)
609                return pos->second.AsCString("");
610            }
611            return NULL;
612        }
613
614        const char *
615        SetCachedGroupName (uint32_t gid, const char *name, size_t name_len)
616        {
617            Mutex::Locker locker (m_gid_map_mutex);
618            ConstString const_name (name);
619            m_gid_map[gid] = const_name;
620            if (m_max_gid_name_len < name_len)
621                m_max_gid_name_len = name_len;
622            // Const strings lives forever in our const string pool, so we can return the const char *
623            return const_name.GetCString();
624        }
625
626        void
627        SetGroupNameNotFound (uint32_t gid)
628        {
629            Mutex::Locker locker (m_gid_map_mutex);
630            m_gid_map[gid] = ConstString();
631        }
632
633        void
634        ClearCachedGroupNames ()
635        {
636            Mutex::Locker locker (m_gid_map_mutex);
637            m_gid_map.clear();
638        }
639
640    private:
641        DISALLOW_COPY_AND_ASSIGN (Platform);
642    };
643
644
645    class PlatformList
646    {
647    public:
648        PlatformList() :
649            m_mutex (Mutex::eMutexTypeRecursive),
650            m_platforms (),
651            m_selected_platform_sp()
652        {
653        }
654
655        ~PlatformList()
656        {
657        }
658
659        void
660        Append (const lldb::PlatformSP &platform_sp, bool set_selected)
661        {
662            Mutex::Locker locker (m_mutex);
663            m_platforms.push_back (platform_sp);
664            if (set_selected)
665                m_selected_platform_sp = m_platforms.back();
666        }
667
668        size_t
669        GetSize()
670        {
671            Mutex::Locker locker (m_mutex);
672            return m_platforms.size();
673        }
674
675        lldb::PlatformSP
676        GetAtIndex (uint32_t idx)
677        {
678            lldb::PlatformSP platform_sp;
679            {
680                Mutex::Locker locker (m_mutex);
681                if (idx < m_platforms.size())
682                    platform_sp = m_platforms[idx];
683            }
684            return platform_sp;
685        }
686
687        //------------------------------------------------------------------
688        /// Select the active platform.
689        ///
690        /// In order to debug remotely, other platform's can be remotely
691        /// connected to and set as the selected platform for any subsequent
692        /// debugging. This allows connection to remote targets and allows
693        /// the ability to discover process info, launch and attach to remote
694        /// processes.
695        //------------------------------------------------------------------
696        lldb::PlatformSP
697        GetSelectedPlatform ()
698        {
699            Mutex::Locker locker (m_mutex);
700            if (!m_selected_platform_sp && !m_platforms.empty())
701                m_selected_platform_sp = m_platforms.front();
702
703            return m_selected_platform_sp;
704        }
705
706        void
707        SetSelectedPlatform (const lldb::PlatformSP &platform_sp)
708        {
709            if (platform_sp)
710            {
711                Mutex::Locker locker (m_mutex);
712                const size_t num_platforms = m_platforms.size();
713                for (size_t idx=0; idx<num_platforms; ++idx)
714                {
715                    if (m_platforms[idx].get() == platform_sp.get())
716                    {
717                        m_selected_platform_sp = m_platforms[idx];
718                        return;
719                    }
720                }
721                m_platforms.push_back (platform_sp);
722                m_selected_platform_sp = m_platforms.back();
723            }
724        }
725
726    protected:
727        typedef std::vector<lldb::PlatformSP> collection;
728        mutable Mutex m_mutex;
729        collection m_platforms;
730        lldb::PlatformSP m_selected_platform_sp;
731
732    private:
733        DISALLOW_COPY_AND_ASSIGN (PlatformList);
734    };
735} // namespace lldb_private
736
737#endif  // liblldb_Platform_h_
738