1 //===-- Platform.cpp --------------------------------------------*- 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 #include "lldb/Target/Platform.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/Breakpoint/BreakpointIDList.h"
17 #include "lldb/Core/Error.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/ModuleSpec.h"
20 #include "lldb/Core/PluginManager.h"
21 #include "lldb/Host/FileSpec.h"
22 #include "lldb/Host/Host.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Target/Target.h"
25 #include "lldb/Utility/Utils.h"
26 
27 using namespace lldb;
28 using namespace lldb_private;
29 
30 // Use a singleton function for g_local_platform_sp to avoid init
31 // constructors since LLDB is often part of a shared library
32 static PlatformSP&
33 GetDefaultPlatformSP ()
34 {
35     static PlatformSP g_default_platform_sp;
36     return g_default_platform_sp;
37 }
38 
39 static Mutex &
40 GetConnectedPlatformListMutex ()
41 {
42     static Mutex g_remote_connected_platforms_mutex (Mutex::eMutexTypeRecursive);
43     return g_remote_connected_platforms_mutex;
44 }
45 static std::vector<PlatformSP> &
46 GetConnectedPlatformList ()
47 {
48     static std::vector<PlatformSP> g_remote_connected_platforms;
49     return g_remote_connected_platforms;
50 }
51 
52 
53 const char *
54 Platform::GetHostPlatformName ()
55 {
56     return "host";
57 }
58 
59 //------------------------------------------------------------------
60 /// Get the native host platform plug-in.
61 ///
62 /// There should only be one of these for each host that LLDB runs
63 /// upon that should be statically compiled in and registered using
64 /// preprocessor macros or other similar build mechanisms.
65 ///
66 /// This platform will be used as the default platform when launching
67 /// or attaching to processes unless another platform is specified.
68 //------------------------------------------------------------------
69 PlatformSP
70 Platform::GetDefaultPlatform ()
71 {
72     return GetDefaultPlatformSP ();
73 }
74 
75 void
76 Platform::SetDefaultPlatform (const lldb::PlatformSP &platform_sp)
77 {
78     // The native platform should use its static void Platform::Initialize()
79     // function to register itself as the native platform.
80     GetDefaultPlatformSP () = platform_sp;
81 }
82 
83 Error
84 Platform::GetFileWithUUID (const FileSpec &platform_file,
85                            const UUID *uuid_ptr,
86                            FileSpec &local_file)
87 {
88     // Default to the local case
89     local_file = platform_file;
90     return Error();
91 }
92 
93 FileSpecList
94 Platform::LocateExecutableScriptingResources (Target *target, Module &module)
95 {
96     return FileSpecList();
97 }
98 
99 Platform*
100 Platform::FindPlugin (Process *process, const ConstString &plugin_name)
101 {
102     PlatformCreateInstance create_callback = NULL;
103     if (plugin_name)
104     {
105         create_callback  = PluginManager::GetPlatformCreateCallbackForPluginName (plugin_name);
106         if (create_callback)
107         {
108             ArchSpec arch;
109             if (process)
110             {
111                 arch = process->GetTarget().GetArchitecture();
112             }
113             std::unique_ptr<Platform> instance_ap(create_callback(process, &arch));
114             if (instance_ap.get())
115                 return instance_ap.release();
116         }
117     }
118     else
119     {
120         for (uint32_t idx = 0; (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex(idx)) != NULL; ++idx)
121         {
122             std::unique_ptr<Platform> instance_ap(create_callback(process, nullptr));
123             if (instance_ap.get())
124                 return instance_ap.release();
125         }
126     }
127     return NULL;
128 }
129 
130 Error
131 Platform::GetSharedModule (const ModuleSpec &module_spec,
132                            ModuleSP &module_sp,
133                            const FileSpecList *module_search_paths_ptr,
134                            ModuleSP *old_module_sp_ptr,
135                            bool *did_create_ptr)
136 {
137     // Don't do any path remapping for the default implementation
138     // of the platform GetSharedModule function, just call through
139     // to our static ModuleList function. Platform subclasses that
140     // implement remote debugging, might have a developer kits
141     // installed that have cached versions of the files for the
142     // remote target, or might implement a download and cache
143     // locally implementation.
144     const bool always_create = false;
145     return ModuleList::GetSharedModule (module_spec,
146                                         module_sp,
147                                         module_search_paths_ptr,
148                                         old_module_sp_ptr,
149                                         did_create_ptr,
150                                         always_create);
151 }
152 
153 PlatformSP
154 Platform::Create (const char *platform_name, Error &error)
155 {
156     PlatformCreateInstance create_callback = NULL;
157     lldb::PlatformSP platform_sp;
158     if (platform_name && platform_name[0])
159     {
160         ConstString const_platform_name (platform_name);
161         create_callback = PluginManager::GetPlatformCreateCallbackForPluginName (const_platform_name);
162         if (create_callback)
163             platform_sp.reset(create_callback(true, NULL));
164         else
165             error.SetErrorStringWithFormat ("unable to find a plug-in for the platform named \"%s\"", platform_name);
166     }
167     else
168         error.SetErrorString ("invalid platform name");
169     return platform_sp;
170 }
171 
172 
173 PlatformSP
174 Platform::Create (const ArchSpec &arch, ArchSpec *platform_arch_ptr, Error &error)
175 {
176     lldb::PlatformSP platform_sp;
177     if (arch.IsValid())
178     {
179         uint32_t idx;
180         PlatformCreateInstance create_callback;
181         // First try exact arch matches across all platform plug-ins
182         bool exact = true;
183         for (idx = 0; (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex (idx)); ++idx)
184         {
185             if (create_callback)
186             {
187                 platform_sp.reset(create_callback(false, &arch));
188                 if (platform_sp && platform_sp->IsCompatibleArchitecture(arch, exact, platform_arch_ptr))
189                     return platform_sp;
190             }
191         }
192         // Next try compatible arch matches across all platform plug-ins
193         exact = false;
194         for (idx = 0; (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex (idx)); ++idx)
195         {
196             if (create_callback)
197             {
198                 platform_sp.reset(create_callback(false, &arch));
199                 if (platform_sp && platform_sp->IsCompatibleArchitecture(arch, exact, platform_arch_ptr))
200                     return platform_sp;
201             }
202         }
203     }
204     else
205         error.SetErrorString ("invalid platform name");
206     if (platform_arch_ptr)
207         platform_arch_ptr->Clear();
208     platform_sp.reset();
209     return platform_sp;
210 }
211 
212 uint32_t
213 Platform::GetNumConnectedRemotePlatforms ()
214 {
215     Mutex::Locker locker (GetConnectedPlatformListMutex ());
216     return GetConnectedPlatformList().size();
217 }
218 
219 PlatformSP
220 Platform::GetConnectedRemotePlatformAtIndex (uint32_t idx)
221 {
222     PlatformSP platform_sp;
223     {
224         Mutex::Locker locker (GetConnectedPlatformListMutex ());
225         if (idx < GetConnectedPlatformList().size())
226             platform_sp = GetConnectedPlatformList ()[idx];
227     }
228     return platform_sp;
229 }
230 
231 //------------------------------------------------------------------
232 /// Default Constructor
233 //------------------------------------------------------------------
234 Platform::Platform (bool is_host) :
235     m_is_host (is_host),
236     m_os_version_set_while_connected (false),
237     m_system_arch_set_while_connected (false),
238     m_sdk_sysroot (),
239     m_sdk_build (),
240     m_working_dir (),
241     m_remote_url (),
242     m_name (),
243     m_major_os_version (UINT32_MAX),
244     m_minor_os_version (UINT32_MAX),
245     m_update_os_version (UINT32_MAX),
246     m_system_arch(),
247     m_uid_map_mutex (Mutex::eMutexTypeNormal),
248     m_gid_map_mutex (Mutex::eMutexTypeNormal),
249     m_uid_map(),
250     m_gid_map(),
251     m_max_uid_name_len (0),
252     m_max_gid_name_len (0),
253     m_supports_rsync (false),
254     m_rsync_opts (),
255     m_rsync_prefix (),
256     m_supports_ssh (false),
257     m_ssh_opts (),
258     m_ignores_remote_hostname (false),
259     m_trap_handlers(),
260     m_calculated_trap_handlers (false),
261     m_trap_handler_mutex()
262 {
263     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
264     if (log)
265         log->Printf ("%p Platform::Platform()", static_cast<void*>(this));
266 }
267 
268 //------------------------------------------------------------------
269 /// Destructor.
270 ///
271 /// The destructor is virtual since this class is designed to be
272 /// inherited from by the plug-in instance.
273 //------------------------------------------------------------------
274 Platform::~Platform()
275 {
276     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
277     if (log)
278         log->Printf ("%p Platform::~Platform()", static_cast<void*>(this));
279 }
280 
281 void
282 Platform::GetStatus (Stream &strm)
283 {
284     uint32_t major = UINT32_MAX;
285     uint32_t minor = UINT32_MAX;
286     uint32_t update = UINT32_MAX;
287     std::string s;
288     strm.Printf ("  Platform: %s\n", GetPluginName().GetCString());
289 
290     ArchSpec arch (GetSystemArchitecture());
291     if (arch.IsValid())
292     {
293         if (!arch.GetTriple().str().empty())
294         strm.Printf("    Triple: %s\n", arch.GetTriple().str().c_str());
295     }
296 
297     if (GetOSVersion(major, minor, update))
298     {
299         strm.Printf("OS Version: %u", major);
300         if (minor != UINT32_MAX)
301             strm.Printf(".%u", minor);
302         if (update != UINT32_MAX)
303             strm.Printf(".%u", update);
304 
305         if (GetOSBuildString (s))
306             strm.Printf(" (%s)", s.c_str());
307 
308         strm.EOL();
309     }
310 
311     if (GetOSKernelDescription (s))
312         strm.Printf("    Kernel: %s\n", s.c_str());
313 
314     if (IsHost())
315     {
316         strm.Printf("  Hostname: %s\n", GetHostname());
317     }
318     else
319     {
320         const bool is_connected = IsConnected();
321         if (is_connected)
322             strm.Printf("  Hostname: %s\n", GetHostname());
323         strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no");
324     }
325 
326     if (GetWorkingDirectory())
327     {
328         strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetCString());
329     }
330     if (!IsConnected())
331         return;
332 
333     std::string specific_info(GetPlatformSpecificConnectionInformation());
334 
335     if (specific_info.empty() == false)
336         strm.Printf("Platform-specific connection: %s\n", specific_info.c_str());
337 }
338 
339 
340 bool
341 Platform::GetOSVersion (uint32_t &major,
342                         uint32_t &minor,
343                         uint32_t &update)
344 {
345     bool success = m_major_os_version != UINT32_MAX;
346     if (IsHost())
347     {
348         if (!success)
349         {
350             // We have a local host platform
351             success = Host::GetOSVersion (m_major_os_version,
352                                           m_minor_os_version,
353                                           m_update_os_version);
354             m_os_version_set_while_connected = success;
355         }
356     }
357     else
358     {
359         // We have a remote platform. We can only fetch the remote
360         // OS version if we are connected, and we don't want to do it
361         // more than once.
362 
363         const bool is_connected = IsConnected();
364 
365         bool fetch = false;
366         if (success)
367         {
368             // We have valid OS version info, check to make sure it wasn't
369             // manually set prior to connecting. If it was manually set prior
370             // to connecting, then lets fetch the actual OS version info
371             // if we are now connected.
372             if (is_connected && !m_os_version_set_while_connected)
373                 fetch = true;
374         }
375         else
376         {
377             // We don't have valid OS version info, fetch it if we are connected
378             fetch = is_connected;
379         }
380 
381         if (fetch)
382         {
383             success = GetRemoteOSVersion ();
384             m_os_version_set_while_connected = success;
385         }
386     }
387 
388     if (success)
389     {
390         major = m_major_os_version;
391         minor = m_minor_os_version;
392         update = m_update_os_version;
393     }
394     return success;
395 }
396 
397 bool
398 Platform::GetOSBuildString (std::string &s)
399 {
400     if (IsHost())
401         return Host::GetOSBuildString (s);
402     else
403         return GetRemoteOSBuildString (s);
404 }
405 
406 bool
407 Platform::GetOSKernelDescription (std::string &s)
408 {
409     if (IsHost())
410         return Host::GetOSKernelDescription (s);
411     else
412         return GetRemoteOSKernelDescription (s);
413 }
414 
415 ConstString
416 Platform::GetWorkingDirectory ()
417 {
418     if (IsHost())
419     {
420         char cwd[PATH_MAX];
421         if (getcwd(cwd, sizeof(cwd)))
422             return ConstString(cwd);
423         else
424             return ConstString();
425     }
426     else
427     {
428         if (!m_working_dir)
429             m_working_dir = GetRemoteWorkingDirectory();
430         return m_working_dir;
431     }
432 }
433 
434 
435 struct RecurseCopyBaton
436 {
437     const FileSpec& dst;
438     Platform *platform_ptr;
439     Error error;
440 };
441 
442 
443 static FileSpec::EnumerateDirectoryResult
444 RecurseCopy_Callback (void *baton,
445                       FileSpec::FileType file_type,
446                       const FileSpec &src)
447 {
448     RecurseCopyBaton* rc_baton = (RecurseCopyBaton*)baton;
449     switch (file_type)
450     {
451         case FileSpec::eFileTypePipe:
452         case FileSpec::eFileTypeSocket:
453             // we have no way to copy pipes and sockets - ignore them and continue
454             return FileSpec::eEnumerateDirectoryResultNext;
455             break;
456 
457         case FileSpec::eFileTypeDirectory:
458             {
459                 // make the new directory and get in there
460                 FileSpec dst_dir = rc_baton->dst;
461                 if (!dst_dir.GetFilename())
462                     dst_dir.GetFilename() = src.GetLastPathComponent();
463                 std::string dst_dir_path (dst_dir.GetPath());
464                 Error error = rc_baton->platform_ptr->MakeDirectory(dst_dir_path.c_str(), lldb::eFilePermissionsDirectoryDefault);
465                 if (error.Fail())
466                 {
467                     rc_baton->error.SetErrorStringWithFormat("unable to setup directory %s on remote end", dst_dir_path.c_str());
468                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
469                 }
470 
471                 // now recurse
472                 std::string src_dir_path (src.GetPath());
473 
474                 // Make a filespec that only fills in the directory of a FileSpec so
475                 // when we enumerate we can quickly fill in the filename for dst copies
476                 FileSpec recurse_dst;
477                 recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str());
478                 RecurseCopyBaton rc_baton2 = { recurse_dst, rc_baton->platform_ptr, Error() };
479                 FileSpec::EnumerateDirectory(src_dir_path.c_str(), true, true, true, RecurseCopy_Callback, &rc_baton2);
480                 if (rc_baton2.error.Fail())
481                 {
482                     rc_baton->error.SetErrorString(rc_baton2.error.AsCString());
483                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
484                 }
485                 return FileSpec::eEnumerateDirectoryResultNext;
486             }
487             break;
488 
489         case FileSpec::eFileTypeSymbolicLink:
490             {
491                 // copy the file and keep going
492                 FileSpec dst_file = rc_baton->dst;
493                 if (!dst_file.GetFilename())
494                     dst_file.GetFilename() = src.GetFilename();
495 
496                 char buf[PATH_MAX];
497 
498                 rc_baton->error = Host::Readlink (src.GetPath().c_str(), buf, sizeof(buf));
499 
500                 if (rc_baton->error.Fail())
501                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
502 
503                 rc_baton->error = rc_baton->platform_ptr->CreateSymlink(dst_file.GetPath().c_str(), buf);
504 
505                 if (rc_baton->error.Fail())
506                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
507 
508                 return FileSpec::eEnumerateDirectoryResultNext;
509             }
510             break;
511         case FileSpec::eFileTypeRegular:
512             {
513                 // copy the file and keep going
514                 FileSpec dst_file = rc_baton->dst;
515                 if (!dst_file.GetFilename())
516                     dst_file.GetFilename() = src.GetFilename();
517                 Error err = rc_baton->platform_ptr->PutFile(src, dst_file);
518                 if (err.Fail())
519                 {
520                     rc_baton->error.SetErrorString(err.AsCString());
521                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
522                 }
523                 return FileSpec::eEnumerateDirectoryResultNext;
524             }
525             break;
526 
527         case FileSpec::eFileTypeInvalid:
528         case FileSpec::eFileTypeOther:
529         case FileSpec::eFileTypeUnknown:
530             rc_baton->error.SetErrorStringWithFormat("invalid file detected during copy: %s", src.GetPath().c_str());
531             return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
532             break;
533         default:
534             return FileSpec::eEnumerateDirectoryResultQuit; // unsupported file type, bail out
535             break;
536     }
537 }
538 
539 Error
540 Platform::Install (const FileSpec& src, const FileSpec& dst)
541 {
542     Error error;
543 
544     Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
545     if (log)
546         log->Printf ("Platform::Install (src='%s', dst='%s')", src.GetPath().c_str(), dst.GetPath().c_str());
547     FileSpec fixed_dst(dst);
548 
549     if (!fixed_dst.GetFilename())
550         fixed_dst.GetFilename() = src.GetFilename();
551 
552     ConstString working_dir = GetWorkingDirectory();
553 
554     if (dst)
555     {
556         if (dst.GetDirectory())
557         {
558             const char first_dst_dir_char = dst.GetDirectory().GetCString()[0];
559             if (first_dst_dir_char == '/' || first_dst_dir_char  == '\\')
560             {
561                 fixed_dst.GetDirectory() = dst.GetDirectory();
562             }
563             // If the fixed destination file doesn't have a directory yet,
564             // then we must have a relative path. We will resolve this relative
565             // path against the platform's working directory
566             if (!fixed_dst.GetDirectory())
567             {
568                 FileSpec relative_spec;
569                 std::string path;
570                 if (working_dir)
571                 {
572                     relative_spec.SetFile(working_dir.GetCString(), false);
573                     relative_spec.AppendPathComponent(dst.GetPath().c_str());
574                     fixed_dst.GetDirectory() = relative_spec.GetDirectory();
575                 }
576                 else
577                 {
578                     error.SetErrorStringWithFormat("platform working directory must be valid for relative path '%s'", dst.GetPath().c_str());
579                     return error;
580                 }
581             }
582         }
583         else
584         {
585             if (working_dir)
586             {
587                 fixed_dst.GetDirectory() = working_dir;
588             }
589             else
590             {
591                 error.SetErrorStringWithFormat("platform working directory must be valid for relative path '%s'", dst.GetPath().c_str());
592                 return error;
593             }
594         }
595     }
596     else
597     {
598         if (working_dir)
599         {
600             fixed_dst.GetDirectory() = working_dir;
601         }
602         else
603         {
604             error.SetErrorStringWithFormat("platform working directory must be valid when destination directory is empty");
605             return error;
606         }
607     }
608 
609     if (log)
610         log->Printf ("Platform::Install (src='%s', dst='%s') fixed_dst='%s'", src.GetPath().c_str(), dst.GetPath().c_str(), fixed_dst.GetPath().c_str());
611 
612     if (GetSupportsRSync())
613     {
614         error = PutFile(src, dst);
615     }
616     else
617     {
618         switch (src.GetFileType())
619         {
620             case FileSpec::eFileTypeDirectory:
621                 {
622                     if (GetFileExists (fixed_dst))
623                         Unlink (fixed_dst.GetPath().c_str());
624                     uint32_t permissions = src.GetPermissions();
625                     if (permissions == 0)
626                         permissions = eFilePermissionsDirectoryDefault;
627                     std::string dst_dir_path(fixed_dst.GetPath());
628                     error = MakeDirectory(dst_dir_path.c_str(), permissions);
629                     if (error.Success())
630                     {
631                         // Make a filespec that only fills in the directory of a FileSpec so
632                         // when we enumerate we can quickly fill in the filename for dst copies
633                         FileSpec recurse_dst;
634                         recurse_dst.GetDirectory().SetCString(dst_dir_path.c_str());
635                         std::string src_dir_path (src.GetPath());
636                         RecurseCopyBaton baton = { recurse_dst, this, Error() };
637                         FileSpec::EnumerateDirectory(src_dir_path.c_str(), true, true, true, RecurseCopy_Callback, &baton);
638                         return baton.error;
639                     }
640                 }
641                 break;
642 
643             case FileSpec::eFileTypeRegular:
644                 if (GetFileExists (fixed_dst))
645                     Unlink (fixed_dst.GetPath().c_str());
646                 error = PutFile(src, fixed_dst);
647                 break;
648 
649             case FileSpec::eFileTypeSymbolicLink:
650                 {
651                     if (GetFileExists (fixed_dst))
652                         Unlink (fixed_dst.GetPath().c_str());
653                     char buf[PATH_MAX];
654                     error = Host::Readlink(src.GetPath().c_str(), buf, sizeof(buf));
655                     if (error.Success())
656                         error = CreateSymlink(dst.GetPath().c_str(), buf);
657                 }
658                 break;
659             case FileSpec::eFileTypePipe:
660                 error.SetErrorString("platform install doesn't handle pipes");
661                 break;
662             case FileSpec::eFileTypeSocket:
663                 error.SetErrorString("platform install doesn't handle sockets");
664                 break;
665             case FileSpec::eFileTypeInvalid:
666             case FileSpec::eFileTypeUnknown:
667             case FileSpec::eFileTypeOther:
668                 error.SetErrorString("platform install doesn't handle non file or directory items");
669                 break;
670         }
671     }
672     return error;
673 }
674 
675 bool
676 Platform::SetWorkingDirectory (const ConstString &path)
677 {
678     if (IsHost())
679     {
680         Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
681         if (log)
682             log->Printf("Platform::SetWorkingDirectory('%s')", path.GetCString());
683 #ifdef _WIN32
684         // Not implemented on Windows
685         return false;
686 #else
687         if (path)
688         {
689             if (chdir(path.GetCString()) == 0)
690                 return true;
691         }
692         return false;
693 #endif
694     }
695     else
696     {
697         m_working_dir.Clear();
698         return SetRemoteWorkingDirectory(path);
699     }
700 }
701 
702 Error
703 Platform::MakeDirectory (const char *path, uint32_t permissions)
704 {
705     if (IsHost())
706         return Host::MakeDirectory (path, permissions);
707     else
708     {
709         Error error;
710         error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), __PRETTY_FUNCTION__);
711         return error;
712     }
713 }
714 
715 Error
716 Platform::GetFilePermissions (const char *path, uint32_t &file_permissions)
717 {
718     if (IsHost())
719         return Host::GetFilePermissions(path, file_permissions);
720     else
721     {
722         Error error;
723         error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), __PRETTY_FUNCTION__);
724         return error;
725     }
726 }
727 
728 Error
729 Platform::SetFilePermissions (const char *path, uint32_t file_permissions)
730 {
731     if (IsHost())
732         return Host::SetFilePermissions(path, file_permissions);
733     else
734     {
735         Error error;
736         error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), __PRETTY_FUNCTION__);
737         return error;
738     }
739 }
740 
741 ConstString
742 Platform::GetName ()
743 {
744     return GetPluginName();
745 }
746 
747 const char *
748 Platform::GetHostname ()
749 {
750     if (IsHost())
751         return "127.0.0.1";
752 
753     if (m_name.empty())
754         return NULL;
755     return m_name.c_str();
756 }
757 
758 bool
759 Platform::SetRemoteWorkingDirectory(const ConstString &path)
760 {
761     Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
762     if (log)
763         log->Printf("Platform::SetRemoteWorkingDirectory('%s')", path.GetCString());
764     m_working_dir = path;
765     return true;
766 }
767 
768 const char *
769 Platform::GetUserName (uint32_t uid)
770 {
771     const char *user_name = GetCachedUserName(uid);
772     if (user_name)
773         return user_name;
774     if (IsHost())
775     {
776         std::string name;
777         if (Host::GetUserName(uid, name))
778             return SetCachedUserName (uid, name.c_str(), name.size());
779     }
780     return NULL;
781 }
782 
783 const char *
784 Platform::GetGroupName (uint32_t gid)
785 {
786     const char *group_name = GetCachedGroupName(gid);
787     if (group_name)
788         return group_name;
789     if (IsHost())
790     {
791         std::string name;
792         if (Host::GetGroupName(gid, name))
793             return SetCachedGroupName (gid, name.c_str(), name.size());
794     }
795     return NULL;
796 }
797 
798 bool
799 Platform::SetOSVersion (uint32_t major,
800                         uint32_t minor,
801                         uint32_t update)
802 {
803     if (IsHost())
804     {
805         // We don't need anyone setting the OS version for the host platform,
806         // we should be able to figure it out by calling Host::GetOSVersion(...).
807         return false;
808     }
809     else
810     {
811         // We have a remote platform, allow setting the target OS version if
812         // we aren't connected, since if we are connected, we should be able to
813         // request the remote OS version from the connected platform.
814         if (IsConnected())
815             return false;
816         else
817         {
818             // We aren't connected and we might want to set the OS version
819             // ahead of time before we connect so we can peruse files and
820             // use a local SDK or PDK cache of support files to disassemble
821             // or do other things.
822             m_major_os_version = major;
823             m_minor_os_version = minor;
824             m_update_os_version = update;
825             return true;
826         }
827     }
828     return false;
829 }
830 
831 
832 Error
833 Platform::ResolveExecutable (const FileSpec &exe_file,
834                              const ArchSpec &exe_arch,
835                              lldb::ModuleSP &exe_module_sp,
836                              const FileSpecList *module_search_paths_ptr)
837 {
838     Error error;
839     if (exe_file.Exists())
840     {
841         ModuleSpec module_spec (exe_file, exe_arch);
842         if (module_spec.GetArchitecture().IsValid())
843         {
844             error = ModuleList::GetSharedModule (module_spec,
845                                                  exe_module_sp,
846                                                  module_search_paths_ptr,
847                                                  NULL,
848                                                  NULL);
849         }
850         else
851         {
852             // No valid architecture was specified, ask the platform for
853             // the architectures that we should be using (in the correct order)
854             // and see if we can find a match that way
855             for (uint32_t idx = 0; GetSupportedArchitectureAtIndex (idx, module_spec.GetArchitecture()); ++idx)
856             {
857                 error = ModuleList::GetSharedModule (module_spec,
858                                                      exe_module_sp,
859                                                      module_search_paths_ptr,
860                                                      NULL,
861                                                      NULL);
862                 // Did we find an executable using one of the
863                 if (error.Success() && exe_module_sp)
864                     break;
865             }
866         }
867     }
868     else
869     {
870         error.SetErrorStringWithFormat ("'%s' does not exist",
871                                         exe_file.GetPath().c_str());
872     }
873     return error;
874 }
875 
876 Error
877 Platform::ResolveSymbolFile (Target &target,
878                              const ModuleSpec &sym_spec,
879                              FileSpec &sym_file)
880 {
881     Error error;
882     if (sym_spec.GetSymbolFileSpec().Exists())
883         sym_file = sym_spec.GetSymbolFileSpec();
884     else
885         error.SetErrorString("unable to resolve symbol file");
886     return error;
887 
888 }
889 
890 
891 
892 bool
893 Platform::ResolveRemotePath (const FileSpec &platform_path,
894                              FileSpec &resolved_platform_path)
895 {
896     resolved_platform_path = platform_path;
897     return resolved_platform_path.ResolvePath();
898 }
899 
900 
901 const ArchSpec &
902 Platform::GetSystemArchitecture()
903 {
904     if (IsHost())
905     {
906         if (!m_system_arch.IsValid())
907         {
908             // We have a local host platform
909             m_system_arch = Host::GetArchitecture();
910             m_system_arch_set_while_connected = m_system_arch.IsValid();
911         }
912     }
913     else
914     {
915         // We have a remote platform. We can only fetch the remote
916         // system architecture if we are connected, and we don't want to do it
917         // more than once.
918 
919         const bool is_connected = IsConnected();
920 
921         bool fetch = false;
922         if (m_system_arch.IsValid())
923         {
924             // We have valid OS version info, check to make sure it wasn't
925             // manually set prior to connecting. If it was manually set prior
926             // to connecting, then lets fetch the actual OS version info
927             // if we are now connected.
928             if (is_connected && !m_system_arch_set_while_connected)
929                 fetch = true;
930         }
931         else
932         {
933             // We don't have valid OS version info, fetch it if we are connected
934             fetch = is_connected;
935         }
936 
937         if (fetch)
938         {
939             m_system_arch = GetRemoteSystemArchitecture ();
940             m_system_arch_set_while_connected = m_system_arch.IsValid();
941         }
942     }
943     return m_system_arch;
944 }
945 
946 
947 Error
948 Platform::ConnectRemote (Args& args)
949 {
950     Error error;
951     if (IsHost())
952         error.SetErrorStringWithFormat ("The currently selected platform (%s) is the host platform and is always connected.", GetPluginName().GetCString());
953     else
954         error.SetErrorStringWithFormat ("Platform::ConnectRemote() is not supported by %s", GetPluginName().GetCString());
955     return error;
956 }
957 
958 Error
959 Platform::DisconnectRemote ()
960 {
961     Error error;
962     if (IsHost())
963         error.SetErrorStringWithFormat ("The currently selected platform (%s) is the host platform and is always connected.", GetPluginName().GetCString());
964     else
965         error.SetErrorStringWithFormat ("Platform::DisconnectRemote() is not supported by %s", GetPluginName().GetCString());
966     return error;
967 }
968 
969 bool
970 Platform::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
971 {
972     // Take care of the host case so that each subclass can just
973     // call this function to get the host functionality.
974     if (IsHost())
975         return Host::GetProcessInfo (pid, process_info);
976     return false;
977 }
978 
979 uint32_t
980 Platform::FindProcesses (const ProcessInstanceInfoMatch &match_info,
981                          ProcessInstanceInfoList &process_infos)
982 {
983     // Take care of the host case so that each subclass can just
984     // call this function to get the host functionality.
985     uint32_t match_count = 0;
986     if (IsHost())
987         match_count = Host::FindProcesses (match_info, process_infos);
988     return match_count;
989 }
990 
991 
992 Error
993 Platform::LaunchProcess (ProcessLaunchInfo &launch_info)
994 {
995     Error error;
996     // Take care of the host case so that each subclass can just
997     // call this function to get the host functionality.
998     if (IsHost())
999     {
1000         if (::getenv ("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
1001             launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
1002 
1003         if (launch_info.GetFlags().Test (eLaunchFlagLaunchInShell))
1004         {
1005             const bool is_localhost = true;
1006             const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
1007             const bool first_arg_is_full_shell_command = false;
1008             uint32_t num_resumes = GetResumeCountForLaunchInfo (launch_info);
1009             if (!launch_info.ConvertArgumentsForLaunchingInShell (error,
1010                                                                   is_localhost,
1011                                                                   will_debug,
1012                                                                   first_arg_is_full_shell_command,
1013                                                                   num_resumes))
1014                 return error;
1015         }
1016 
1017         error = Host::LaunchProcess (launch_info);
1018     }
1019     else
1020         error.SetErrorString ("base lldb_private::Platform class can't launch remote processes");
1021     return error;
1022 }
1023 
1024 lldb::ProcessSP
1025 Platform::DebugProcess (ProcessLaunchInfo &launch_info,
1026                         Debugger &debugger,
1027                         Target *target,       // Can be NULL, if NULL create a new target, else use existing one
1028                         Listener &listener,
1029                         Error &error)
1030 {
1031     ProcessSP process_sp;
1032     // Make sure we stop at the entry point
1033     launch_info.GetFlags ().Set (eLaunchFlagDebug);
1034     // We always launch the process we are going to debug in a separate process
1035     // group, since then we can handle ^C interrupts ourselves w/o having to worry
1036     // about the target getting them as well.
1037     launch_info.SetLaunchInSeparateProcessGroup(true);
1038 
1039     error = LaunchProcess (launch_info);
1040     if (error.Success())
1041     {
1042         if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1043         {
1044             ProcessAttachInfo attach_info (launch_info);
1045             process_sp = Attach (attach_info, debugger, target, listener, error);
1046             if (process_sp)
1047             {
1048                 launch_info.SetHijackListener(attach_info.GetHijackListener());
1049 
1050                 // Since we attached to the process, it will think it needs to detach
1051                 // if the process object just goes away without an explicit call to
1052                 // Process::Kill() or Process::Detach(), so let it know to kill the
1053                 // process if this happens.
1054                 process_sp->SetShouldDetach (false);
1055 
1056                 // If we didn't have any file actions, the pseudo terminal might
1057                 // have been used where the slave side was given as the file to
1058                 // open for stdin/out/err after we have already opened the master
1059                 // so we can read/write stdin/out/err.
1060                 int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
1061                 if (pty_fd != lldb_utility::PseudoTerminal::invalid_fd)
1062                 {
1063                     process_sp->SetSTDIOFileDescriptor(pty_fd);
1064                 }
1065             }
1066         }
1067     }
1068     return process_sp;
1069 }
1070 
1071 
1072 lldb::PlatformSP
1073 Platform::GetPlatformForArchitecture (const ArchSpec &arch, ArchSpec *platform_arch_ptr)
1074 {
1075     lldb::PlatformSP platform_sp;
1076     Error error;
1077     if (arch.IsValid())
1078         platform_sp = Platform::Create (arch, platform_arch_ptr, error);
1079     return platform_sp;
1080 }
1081 
1082 
1083 //------------------------------------------------------------------
1084 /// Lets a platform answer if it is compatible with a given
1085 /// architecture and the target triple contained within.
1086 //------------------------------------------------------------------
1087 bool
1088 Platform::IsCompatibleArchitecture (const ArchSpec &arch, bool exact_arch_match, ArchSpec *compatible_arch_ptr)
1089 {
1090     // If the architecture is invalid, we must answer true...
1091     if (arch.IsValid())
1092     {
1093         ArchSpec platform_arch;
1094         // Try for an exact architecture match first.
1095         if (exact_arch_match)
1096         {
1097             for (uint32_t arch_idx=0; GetSupportedArchitectureAtIndex (arch_idx, platform_arch); ++arch_idx)
1098             {
1099                 if (arch.IsExactMatch(platform_arch))
1100                 {
1101                     if (compatible_arch_ptr)
1102                         *compatible_arch_ptr = platform_arch;
1103                     return true;
1104                 }
1105             }
1106         }
1107         else
1108         {
1109             for (uint32_t arch_idx=0; GetSupportedArchitectureAtIndex (arch_idx, platform_arch); ++arch_idx)
1110             {
1111                 if (arch.IsCompatibleMatch(platform_arch))
1112                 {
1113                     if (compatible_arch_ptr)
1114                         *compatible_arch_ptr = platform_arch;
1115                     return true;
1116                 }
1117             }
1118         }
1119     }
1120     if (compatible_arch_ptr)
1121         compatible_arch_ptr->Clear();
1122     return false;
1123 }
1124 
1125 Error
1126 Platform::PutFile (const FileSpec& source,
1127                    const FileSpec& destination,
1128                    uint32_t uid,
1129                    uint32_t gid)
1130 {
1131     Error error("unimplemented");
1132     return error;
1133 }
1134 
1135 Error
1136 Platform::GetFile (const FileSpec& source,
1137                    const FileSpec& destination)
1138 {
1139     Error error("unimplemented");
1140     return error;
1141 }
1142 
1143 Error
1144 Platform::CreateSymlink (const char *src, // The name of the link is in src
1145                          const char *dst)// The symlink points to dst
1146 {
1147     Error error("unimplemented");
1148     return error;
1149 }
1150 
1151 bool
1152 Platform::GetFileExists (const lldb_private::FileSpec& file_spec)
1153 {
1154     return false;
1155 }
1156 
1157 Error
1158 Platform::Unlink (const char *path)
1159 {
1160     Error error("unimplemented");
1161     return error;
1162 }
1163 
1164 
1165 
1166 lldb_private::Error
1167 Platform::RunShellCommand (const char *command,           // Shouldn't be NULL
1168                            const char *working_dir,       // Pass NULL to use the current working directory
1169                            int *status_ptr,               // Pass NULL if you don't want the process exit status
1170                            int *signo_ptr,                // Pass NULL if you don't want the signal that caused the process to exit
1171                            std::string *command_output,   // Pass NULL if you don't want the command output
1172                            uint32_t timeout_sec)          // Timeout in seconds to wait for shell program to finish
1173 {
1174     if (IsHost())
1175         return Host::RunShellCommand (command, working_dir, status_ptr, signo_ptr, command_output, timeout_sec);
1176     else
1177         return Error("unimplemented");
1178 }
1179 
1180 
1181 bool
1182 Platform::CalculateMD5 (const FileSpec& file_spec,
1183                         uint64_t &low,
1184                         uint64_t &high)
1185 {
1186     if (IsHost())
1187         return Host::CalculateMD5(file_spec, low, high);
1188     else
1189         return false;
1190 }
1191 
1192 void
1193 Platform::SetLocalCacheDirectory (const char* local)
1194 {
1195     m_local_cache_directory.assign(local);
1196 }
1197 
1198 const char*
1199 Platform::GetLocalCacheDirectory ()
1200 {
1201     return m_local_cache_directory.c_str();
1202 }
1203 
1204 static OptionDefinition
1205 g_rsync_option_table[] =
1206 {
1207     {   LLDB_OPT_SET_ALL, false, "rsync"                  , 'r', OptionParser::eNoArgument,       NULL, 0, eArgTypeNone         , "Enable rsync." },
1208     {   LLDB_OPT_SET_ALL, false, "rsync-opts"             , 'R', OptionParser::eRequiredArgument, NULL, 0, eArgTypeCommandName  , "Platform-specific options required for rsync to work." },
1209     {   LLDB_OPT_SET_ALL, false, "rsync-prefix"           , 'P', OptionParser::eRequiredArgument, NULL, 0, eArgTypeCommandName  , "Platform-specific rsync prefix put before the remote path." },
1210     {   LLDB_OPT_SET_ALL, false, "ignore-remote-hostname" , 'i', OptionParser::eNoArgument,       NULL, 0, eArgTypeNone         , "Do not automatically fill in the remote hostname when composing the rsync command." },
1211 };
1212 
1213 static OptionDefinition
1214 g_ssh_option_table[] =
1215 {
1216     {   LLDB_OPT_SET_ALL, false, "ssh"                    , 's', OptionParser::eNoArgument,       NULL, 0, eArgTypeNone         , "Enable SSH." },
1217     {   LLDB_OPT_SET_ALL, false, "ssh-opts"               , 'S', OptionParser::eRequiredArgument, NULL, 0, eArgTypeCommandName  , "Platform-specific options required for SSH to work." },
1218 };
1219 
1220 static OptionDefinition
1221 g_caching_option_table[] =
1222 {
1223     {   LLDB_OPT_SET_ALL, false, "local-cache-dir"        , 'c', OptionParser::eRequiredArgument, NULL, 0, eArgTypePath         , "Path in which to store local copies of files." },
1224 };
1225 
1226 OptionGroupPlatformRSync::OptionGroupPlatformRSync ()
1227 {
1228 }
1229 
1230 OptionGroupPlatformRSync::~OptionGroupPlatformRSync ()
1231 {
1232 }
1233 
1234 const lldb_private::OptionDefinition*
1235 OptionGroupPlatformRSync::GetDefinitions ()
1236 {
1237     return g_rsync_option_table;
1238 }
1239 
1240 void
1241 OptionGroupPlatformRSync::OptionParsingStarting (CommandInterpreter &interpreter)
1242 {
1243     m_rsync = false;
1244     m_rsync_opts.clear();
1245     m_rsync_prefix.clear();
1246     m_ignores_remote_hostname = false;
1247 }
1248 
1249 lldb_private::Error
1250 OptionGroupPlatformRSync::SetOptionValue (CommandInterpreter &interpreter,
1251                 uint32_t option_idx,
1252                 const char *option_arg)
1253 {
1254     Error error;
1255     char short_option = (char) GetDefinitions()[option_idx].short_option;
1256     switch (short_option)
1257     {
1258         case 'r':
1259             m_rsync = true;
1260             break;
1261 
1262         case 'R':
1263             m_rsync_opts.assign(option_arg);
1264             break;
1265 
1266         case 'P':
1267             m_rsync_prefix.assign(option_arg);
1268             break;
1269 
1270         case 'i':
1271             m_ignores_remote_hostname = true;
1272             break;
1273 
1274         default:
1275             error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1276             break;
1277     }
1278 
1279     return error;
1280 }
1281 
1282 uint32_t
1283 OptionGroupPlatformRSync::GetNumDefinitions ()
1284 {
1285     return llvm::array_lengthof(g_rsync_option_table);
1286 }
1287 
1288 lldb::BreakpointSP
1289 Platform::SetThreadCreationBreakpoint (lldb_private::Target &target)
1290 {
1291     return lldb::BreakpointSP();
1292 }
1293 
1294 OptionGroupPlatformSSH::OptionGroupPlatformSSH ()
1295 {
1296 }
1297 
1298 OptionGroupPlatformSSH::~OptionGroupPlatformSSH ()
1299 {
1300 }
1301 
1302 const lldb_private::OptionDefinition*
1303 OptionGroupPlatformSSH::GetDefinitions ()
1304 {
1305     return g_ssh_option_table;
1306 }
1307 
1308 void
1309 OptionGroupPlatformSSH::OptionParsingStarting (CommandInterpreter &interpreter)
1310 {
1311     m_ssh = false;
1312     m_ssh_opts.clear();
1313 }
1314 
1315 lldb_private::Error
1316 OptionGroupPlatformSSH::SetOptionValue (CommandInterpreter &interpreter,
1317                                           uint32_t option_idx,
1318                                           const char *option_arg)
1319 {
1320     Error error;
1321     char short_option = (char) GetDefinitions()[option_idx].short_option;
1322     switch (short_option)
1323     {
1324         case 's':
1325             m_ssh = true;
1326             break;
1327 
1328         case 'S':
1329             m_ssh_opts.assign(option_arg);
1330             break;
1331 
1332         default:
1333             error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1334             break;
1335     }
1336 
1337     return error;
1338 }
1339 
1340 uint32_t
1341 OptionGroupPlatformSSH::GetNumDefinitions ()
1342 {
1343     return llvm::array_lengthof(g_ssh_option_table);
1344 }
1345 
1346 OptionGroupPlatformCaching::OptionGroupPlatformCaching ()
1347 {
1348 }
1349 
1350 OptionGroupPlatformCaching::~OptionGroupPlatformCaching ()
1351 {
1352 }
1353 
1354 const lldb_private::OptionDefinition*
1355 OptionGroupPlatformCaching::GetDefinitions ()
1356 {
1357     return g_caching_option_table;
1358 }
1359 
1360 void
1361 OptionGroupPlatformCaching::OptionParsingStarting (CommandInterpreter &interpreter)
1362 {
1363     m_cache_dir.clear();
1364 }
1365 
1366 lldb_private::Error
1367 OptionGroupPlatformCaching::SetOptionValue (CommandInterpreter &interpreter,
1368                                         uint32_t option_idx,
1369                                         const char *option_arg)
1370 {
1371     Error error;
1372     char short_option = (char) GetDefinitions()[option_idx].short_option;
1373     switch (short_option)
1374     {
1375         case 'c':
1376             m_cache_dir.assign(option_arg);
1377             break;
1378 
1379         default:
1380             error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1381             break;
1382     }
1383 
1384     return error;
1385 }
1386 
1387 uint32_t
1388 OptionGroupPlatformCaching::GetNumDefinitions ()
1389 {
1390     return llvm::array_lengthof(g_caching_option_table);
1391 }
1392 
1393 size_t
1394 Platform::GetEnvironment (StringList &environment)
1395 {
1396     environment.Clear();
1397     return false;
1398 }
1399 
1400 const std::vector<ConstString> &
1401 Platform::GetTrapHandlerSymbolNames ()
1402 {
1403     if (!m_calculated_trap_handlers)
1404     {
1405         Mutex::Locker locker (m_trap_handler_mutex);
1406         if (!m_calculated_trap_handlers)
1407         {
1408             CalculateTrapHandlerSymbolNames();
1409             m_calculated_trap_handlers = true;
1410         }
1411     }
1412     return m_trap_handlers;
1413 }
1414 
1415