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::GetFile (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 {
260     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
261     if (log)
262         log->Printf ("%p Platform::Platform()", this);
263 }
264 
265 //------------------------------------------------------------------
266 /// Destructor.
267 ///
268 /// The destructor is virtual since this class is designed to be
269 /// inherited from by the plug-in instance.
270 //------------------------------------------------------------------
271 Platform::~Platform()
272 {
273     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
274     if (log)
275         log->Printf ("%p Platform::~Platform()", this);
276 }
277 
278 void
279 Platform::GetStatus (Stream &strm)
280 {
281     uint32_t major = UINT32_MAX;
282     uint32_t minor = UINT32_MAX;
283     uint32_t update = UINT32_MAX;
284     std::string s;
285     strm.Printf ("  Platform: %s\n", GetPluginName().GetCString());
286 
287     ArchSpec arch (GetSystemArchitecture());
288     if (arch.IsValid())
289     {
290         if (!arch.GetTriple().str().empty())
291         strm.Printf("    Triple: %s\n", arch.GetTriple().str().c_str());
292     }
293 
294     if (GetOSVersion(major, minor, update))
295     {
296         strm.Printf("OS Version: %u", major);
297         if (minor != UINT32_MAX)
298             strm.Printf(".%u", minor);
299         if (update != UINT32_MAX)
300             strm.Printf(".%u", update);
301 
302         if (GetOSBuildString (s))
303             strm.Printf(" (%s)", s.c_str());
304 
305         strm.EOL();
306     }
307 
308     if (GetOSKernelDescription (s))
309         strm.Printf("    Kernel: %s\n", s.c_str());
310 
311     if (IsHost())
312     {
313         strm.Printf("  Hostname: %s\n", GetHostname());
314     }
315     else
316     {
317         const bool is_connected = IsConnected();
318         if (is_connected)
319             strm.Printf("  Hostname: %s\n", GetHostname());
320         strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no");
321     }
322 
323     if (GetWorkingDirectory())
324     {
325         strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetCString());
326     }
327     if (!IsConnected())
328         return;
329 
330     std::string specific_info(GetPlatformSpecificConnectionInformation());
331 
332     if (specific_info.empty() == false)
333         strm.Printf("Platform-specific connection: %s\n", specific_info.c_str());
334 }
335 
336 
337 bool
338 Platform::GetOSVersion (uint32_t &major,
339                         uint32_t &minor,
340                         uint32_t &update)
341 {
342     bool success = m_major_os_version != UINT32_MAX;
343     if (IsHost())
344     {
345         if (!success)
346         {
347             // We have a local host platform
348             success = Host::GetOSVersion (m_major_os_version,
349                                           m_minor_os_version,
350                                           m_update_os_version);
351             m_os_version_set_while_connected = success;
352         }
353     }
354     else
355     {
356         // We have a remote platform. We can only fetch the remote
357         // OS version if we are connected, and we don't want to do it
358         // more than once.
359 
360         const bool is_connected = IsConnected();
361 
362         bool fetch = false;
363         if (success)
364         {
365             // We have valid OS version info, check to make sure it wasn't
366             // manually set prior to connecting. If it was manually set prior
367             // to connecting, then lets fetch the actual OS version info
368             // if we are now connected.
369             if (is_connected && !m_os_version_set_while_connected)
370                 fetch = true;
371         }
372         else
373         {
374             // We don't have valid OS version info, fetch it if we are connected
375             fetch = is_connected;
376         }
377 
378         if (fetch)
379         {
380             success = GetRemoteOSVersion ();
381             m_os_version_set_while_connected = success;
382         }
383     }
384 
385     if (success)
386     {
387         major = m_major_os_version;
388         minor = m_minor_os_version;
389         update = m_update_os_version;
390     }
391     return success;
392 }
393 
394 bool
395 Platform::GetOSBuildString (std::string &s)
396 {
397     if (IsHost())
398         return Host::GetOSBuildString (s);
399     else
400         return GetRemoteOSBuildString (s);
401 }
402 
403 bool
404 Platform::GetOSKernelDescription (std::string &s)
405 {
406     if (IsHost())
407         return Host::GetOSKernelDescription (s);
408     else
409         return GetRemoteOSKernelDescription (s);
410 }
411 
412 ConstString
413 Platform::GetWorkingDirectory ()
414 {
415     if (IsHost())
416     {
417         char cwd[PATH_MAX];
418         if (getcwd(cwd, sizeof(cwd)))
419             return ConstString(cwd);
420         else
421             return ConstString();
422     }
423     else
424     {
425         if (!m_working_dir)
426             m_working_dir = GetRemoteWorkingDirectory();
427         return m_working_dir;
428     }
429 }
430 
431 
432 struct RecurseCopyBaton
433 {
434     const FileSpec& dst;
435     Platform *platform_ptr;
436     Error error;
437 };
438 
439 
440 static FileSpec::EnumerateDirectoryResult
441 RecurseCopy_Callback (void *baton,
442                       FileSpec::FileType file_type,
443                       const FileSpec &src)
444 {
445     RecurseCopyBaton* rc_baton = (RecurseCopyBaton*)baton;
446     switch (file_type)
447     {
448         case FileSpec::eFileTypePipe:
449         case FileSpec::eFileTypeSocket:
450             // we have no way to copy pipes and sockets - ignore them and continue
451             return FileSpec::eEnumerateDirectoryResultNext;
452             break;
453 
454         case FileSpec::eFileTypeDirectory:
455             {
456                 // make the new directory and get in there
457                 FileSpec dst_dir = rc_baton->dst;
458                 if (!dst_dir.GetFilename())
459                     dst_dir.GetFilename() = src.GetLastPathComponent();
460                 std::string dst_dir_path (dst_dir.GetPath());
461                 Error error = rc_baton->platform_ptr->MakeDirectory(dst_dir_path.c_str(), lldb::eFilePermissionsDirectoryDefault);
462                 if (error.Fail())
463                 {
464                     rc_baton->error.SetErrorStringWithFormat("unable to setup directory %s on remote end", dst_dir_path.c_str());
465                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
466                 }
467 
468                 // now recurse
469                 std::string src_dir_path (src.GetPath());
470 
471                 // Make a filespec that only fills in the directory of a FileSpec so
472                 // when we enumerate we can quickly fill in the filename for dst copies
473                 FileSpec recurse_dst;
474                 recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str());
475                 RecurseCopyBaton rc_baton2 = { recurse_dst, rc_baton->platform_ptr, Error() };
476                 FileSpec::EnumerateDirectory(src_dir_path.c_str(), true, true, true, RecurseCopy_Callback, &rc_baton2);
477                 if (rc_baton2.error.Fail())
478                 {
479                     rc_baton->error.SetErrorString(rc_baton2.error.AsCString());
480                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
481                 }
482                 return FileSpec::eEnumerateDirectoryResultNext;
483             }
484             break;
485 
486         case FileSpec::eFileTypeSymbolicLink:
487             {
488                 // copy the file and keep going
489                 FileSpec dst_file = rc_baton->dst;
490                 if (!dst_file.GetFilename())
491                     dst_file.GetFilename() = src.GetFilename();
492 
493                 char buf[PATH_MAX];
494 
495                 rc_baton->error = Host::Readlink (src.GetPath().c_str(), buf, sizeof(buf));
496 
497                 if (rc_baton->error.Fail())
498                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
499 
500                 rc_baton->error = rc_baton->platform_ptr->CreateSymlink(dst_file.GetPath().c_str(), buf);
501 
502                 if (rc_baton->error.Fail())
503                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
504 
505                 return FileSpec::eEnumerateDirectoryResultNext;
506             }
507             break;
508         case FileSpec::eFileTypeRegular:
509             {
510                 // copy the file and keep going
511                 FileSpec dst_file = rc_baton->dst;
512                 if (!dst_file.GetFilename())
513                     dst_file.GetFilename() = src.GetFilename();
514                 Error err = rc_baton->platform_ptr->PutFile(src, dst_file);
515                 if (err.Fail())
516                 {
517                     rc_baton->error.SetErrorString(err.AsCString());
518                     return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
519                 }
520                 return FileSpec::eEnumerateDirectoryResultNext;
521             }
522             break;
523 
524         case FileSpec::eFileTypeInvalid:
525         case FileSpec::eFileTypeOther:
526         case FileSpec::eFileTypeUnknown:
527             rc_baton->error.SetErrorStringWithFormat("invalid file detected during copy: %s", src.GetPath().c_str());
528             return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
529             break;
530     }
531 }
532 
533 Error
534 Platform::Install (const FileSpec& src, const FileSpec& dst)
535 {
536     Error error;
537 
538     Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
539     if (log)
540         log->Printf ("Platform::Install (src='%s', dst='%s')", src.GetPath().c_str(), dst.GetPath().c_str());
541     FileSpec fixed_dst(dst);
542 
543     if (!fixed_dst.GetFilename())
544         fixed_dst.GetFilename() = src.GetFilename();
545 
546     ConstString working_dir = GetWorkingDirectory();
547 
548     if (dst)
549     {
550         if (dst.GetDirectory())
551         {
552             const char first_dst_dir_char = dst.GetDirectory().GetCString()[0];
553             if (first_dst_dir_char == '/' || first_dst_dir_char  == '\\')
554             {
555                 fixed_dst.GetDirectory() = dst.GetDirectory();
556             }
557             // If the fixed destination file doesn't have a directory yet,
558             // then we must have a relative path. We will resolve this relative
559             // path against the platform's working directory
560             if (!fixed_dst.GetDirectory())
561             {
562                 FileSpec relative_spec;
563                 std::string path;
564                 if (working_dir)
565                 {
566                     relative_spec.SetFile(working_dir.GetCString(), false);
567                     relative_spec.AppendPathComponent(dst.GetPath().c_str());
568                     fixed_dst.GetDirectory() = relative_spec.GetDirectory();
569                 }
570                 else
571                 {
572                     error.SetErrorStringWithFormat("platform working directory must be valid for relative path '%s'", dst.GetPath().c_str());
573                     return error;
574                 }
575             }
576         }
577         else
578         {
579             if (working_dir)
580             {
581                 fixed_dst.GetDirectory() = working_dir;
582             }
583             else
584             {
585                 error.SetErrorStringWithFormat("platform working directory must be valid for relative path '%s'", dst.GetPath().c_str());
586                 return error;
587             }
588         }
589     }
590     else
591     {
592         if (working_dir)
593         {
594             fixed_dst.GetDirectory() = working_dir;
595         }
596         else
597         {
598             error.SetErrorStringWithFormat("platform working directory must be valid when destination directory is empty");
599             return error;
600         }
601     }
602 
603     if (log)
604         log->Printf ("Platform::Install (src='%s', dst='%s') fixed_dst='%s'", src.GetPath().c_str(), dst.GetPath().c_str(), fixed_dst.GetPath().c_str());
605 
606     if (GetSupportsRSync())
607     {
608         error = PutFile(src, dst);
609     }
610     else
611     {
612         switch (src.GetFileType())
613         {
614             case FileSpec::eFileTypeDirectory:
615                 {
616                     if (GetFileExists (fixed_dst))
617                         Unlink (fixed_dst.GetPath().c_str());
618                     uint32_t permissions = src.GetPermissions();
619                     if (permissions == 0)
620                         permissions = eFilePermissionsDirectoryDefault;
621                     std::string dst_dir_path(fixed_dst.GetPath());
622                     error = MakeDirectory(dst_dir_path.c_str(), permissions);
623                     if (error.Success())
624                     {
625                         // Make a filespec that only fills in the directory of a FileSpec so
626                         // when we enumerate we can quickly fill in the filename for dst copies
627                         FileSpec recurse_dst;
628                         recurse_dst.GetDirectory().SetCString(dst_dir_path.c_str());
629                         std::string src_dir_path (src.GetPath());
630                         RecurseCopyBaton baton = { recurse_dst, this, Error() };
631                         FileSpec::EnumerateDirectory(src_dir_path.c_str(), true, true, true, RecurseCopy_Callback, &baton);
632                         return baton.error;
633                     }
634                 }
635                 break;
636 
637             case FileSpec::eFileTypeRegular:
638                 if (GetFileExists (fixed_dst))
639                     Unlink (fixed_dst.GetPath().c_str());
640                 error = PutFile(src, fixed_dst);
641                 break;
642 
643             case FileSpec::eFileTypeSymbolicLink:
644                 {
645                     if (GetFileExists (fixed_dst))
646                         Unlink (fixed_dst.GetPath().c_str());
647                     char buf[PATH_MAX];
648                     error = Host::Readlink(src.GetPath().c_str(), buf, sizeof(buf));
649                     if (error.Success())
650                         error = CreateSymlink(dst.GetPath().c_str(), buf);
651                 }
652                 break;
653             case FileSpec::eFileTypePipe:
654                 error.SetErrorString("platform install doesn't handle pipes");
655                 break;
656             case FileSpec::eFileTypeSocket:
657                 error.SetErrorString("platform install doesn't handle sockets");
658                 break;
659             case FileSpec::eFileTypeInvalid:
660             case FileSpec::eFileTypeUnknown:
661             case FileSpec::eFileTypeOther:
662                 error.SetErrorString("platform install doesn't handle non file or directory items");
663                 break;
664         }
665     }
666     return error;
667 }
668 
669 bool
670 Platform::SetWorkingDirectory (const ConstString &path)
671 {
672     if (IsHost())
673     {
674         if (path)
675         {
676             if (chdir(path.GetCString()) == 0)
677                 return true;
678         }
679         return false;
680     }
681     else
682     {
683         return SetRemoteWorkingDirectory(path);
684     }
685 }
686 
687 Error
688 Platform::MakeDirectory (const char *path, uint32_t permissions)
689 {
690     if (IsHost())
691         return Host::MakeDirectory (path, permissions);
692     else
693     {
694         Error error;
695         error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), __PRETTY_FUNCTION__);
696         return error;
697     }
698 }
699 
700 Error
701 Platform::GetFilePermissions (const char *path, uint32_t &file_permissions)
702 {
703     if (IsHost())
704         return Host::GetFilePermissions(path, file_permissions);
705     else
706     {
707         Error error;
708         error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), __PRETTY_FUNCTION__);
709         return error;
710     }
711 }
712 
713 Error
714 Platform::SetFilePermissions (const char *path, uint32_t file_permissions)
715 {
716     if (IsHost())
717         return Host::SetFilePermissions(path, file_permissions);
718     else
719     {
720         Error error;
721         error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), __PRETTY_FUNCTION__);
722         return error;
723     }
724 }
725 
726 ConstString
727 Platform::GetName ()
728 {
729     return GetPluginName();
730 }
731 
732 const char *
733 Platform::GetHostname ()
734 {
735     if (IsHost())
736         return "localhost";
737 
738     if (m_name.empty())
739         return NULL;
740     return m_name.c_str();
741 }
742 
743 const char *
744 Platform::GetUserName (uint32_t uid)
745 {
746     const char *user_name = GetCachedUserName(uid);
747     if (user_name)
748         return user_name;
749     if (IsHost())
750     {
751         std::string name;
752         if (Host::GetUserName(uid, name))
753             return SetCachedUserName (uid, name.c_str(), name.size());
754     }
755     return NULL;
756 }
757 
758 const char *
759 Platform::GetGroupName (uint32_t gid)
760 {
761     const char *group_name = GetCachedGroupName(gid);
762     if (group_name)
763         return group_name;
764     if (IsHost())
765     {
766         std::string name;
767         if (Host::GetGroupName(gid, name))
768             return SetCachedGroupName (gid, name.c_str(), name.size());
769     }
770     return NULL;
771 }
772 
773 bool
774 Platform::SetOSVersion (uint32_t major,
775                         uint32_t minor,
776                         uint32_t update)
777 {
778     if (IsHost())
779     {
780         // We don't need anyone setting the OS version for the host platform,
781         // we should be able to figure it out by calling Host::GetOSVersion(...).
782         return false;
783     }
784     else
785     {
786         // We have a remote platform, allow setting the target OS version if
787         // we aren't connected, since if we are connected, we should be able to
788         // request the remote OS version from the connected platform.
789         if (IsConnected())
790             return false;
791         else
792         {
793             // We aren't connected and we might want to set the OS version
794             // ahead of time before we connect so we can peruse files and
795             // use a local SDK or PDK cache of support files to disassemble
796             // or do other things.
797             m_major_os_version = major;
798             m_minor_os_version = minor;
799             m_update_os_version = update;
800             return true;
801         }
802     }
803     return false;
804 }
805 
806 
807 Error
808 Platform::ResolveExecutable (const FileSpec &exe_file,
809                              const ArchSpec &exe_arch,
810                              lldb::ModuleSP &exe_module_sp,
811                              const FileSpecList *module_search_paths_ptr)
812 {
813     Error error;
814     if (exe_file.Exists())
815     {
816         ModuleSpec module_spec (exe_file, exe_arch);
817         if (module_spec.GetArchitecture().IsValid())
818         {
819             error = ModuleList::GetSharedModule (module_spec,
820                                                  exe_module_sp,
821                                                  module_search_paths_ptr,
822                                                  NULL,
823                                                  NULL);
824         }
825         else
826         {
827             // No valid architecture was specified, ask the platform for
828             // the architectures that we should be using (in the correct order)
829             // and see if we can find a match that way
830             for (uint32_t idx = 0; GetSupportedArchitectureAtIndex (idx, module_spec.GetArchitecture()); ++idx)
831             {
832                 error = ModuleList::GetSharedModule (module_spec,
833                                                      exe_module_sp,
834                                                      module_search_paths_ptr,
835                                                      NULL,
836                                                      NULL);
837                 // Did we find an executable using one of the
838                 if (error.Success() && exe_module_sp)
839                     break;
840             }
841         }
842     }
843     else
844     {
845         error.SetErrorStringWithFormat ("'%s' does not exist",
846                                         exe_file.GetPath().c_str());
847     }
848     return error;
849 }
850 
851 Error
852 Platform::ResolveSymbolFile (Target &target,
853                              const ModuleSpec &sym_spec,
854                              FileSpec &sym_file)
855 {
856     Error error;
857     if (sym_spec.GetSymbolFileSpec().Exists())
858         sym_file = sym_spec.GetSymbolFileSpec();
859     else
860         error.SetErrorString("unable to resolve symbol file");
861     return error;
862 
863 }
864 
865 
866 
867 bool
868 Platform::ResolveRemotePath (const FileSpec &platform_path,
869                              FileSpec &resolved_platform_path)
870 {
871     resolved_platform_path = platform_path;
872     return resolved_platform_path.ResolvePath();
873 }
874 
875 
876 const ArchSpec &
877 Platform::GetSystemArchitecture()
878 {
879     if (IsHost())
880     {
881         if (!m_system_arch.IsValid())
882         {
883             // We have a local host platform
884             m_system_arch = Host::GetArchitecture();
885             m_system_arch_set_while_connected = m_system_arch.IsValid();
886         }
887     }
888     else
889     {
890         // We have a remote platform. We can only fetch the remote
891         // system architecture if we are connected, and we don't want to do it
892         // more than once.
893 
894         const bool is_connected = IsConnected();
895 
896         bool fetch = false;
897         if (m_system_arch.IsValid())
898         {
899             // We have valid OS version info, check to make sure it wasn't
900             // manually set prior to connecting. If it was manually set prior
901             // to connecting, then lets fetch the actual OS version info
902             // if we are now connected.
903             if (is_connected && !m_system_arch_set_while_connected)
904                 fetch = true;
905         }
906         else
907         {
908             // We don't have valid OS version info, fetch it if we are connected
909             fetch = is_connected;
910         }
911 
912         if (fetch)
913         {
914             m_system_arch = GetRemoteSystemArchitecture ();
915             m_system_arch_set_while_connected = m_system_arch.IsValid();
916         }
917     }
918     return m_system_arch;
919 }
920 
921 
922 Error
923 Platform::ConnectRemote (Args& args)
924 {
925     Error error;
926     if (IsHost())
927         error.SetErrorStringWithFormat ("The currently selected platform (%s) is the host platform and is always connected.", GetPluginName().GetCString());
928     else
929         error.SetErrorStringWithFormat ("Platform::ConnectRemote() is not supported by %s", GetPluginName().GetCString());
930     return error;
931 }
932 
933 Error
934 Platform::DisconnectRemote ()
935 {
936     Error error;
937     if (IsHost())
938         error.SetErrorStringWithFormat ("The currently selected platform (%s) is the host platform and is always connected.", GetPluginName().GetCString());
939     else
940         error.SetErrorStringWithFormat ("Platform::DisconnectRemote() is not supported by %s", GetPluginName().GetCString());
941     return error;
942 }
943 
944 bool
945 Platform::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
946 {
947     // Take care of the host case so that each subclass can just
948     // call this function to get the host functionality.
949     if (IsHost())
950         return Host::GetProcessInfo (pid, process_info);
951     return false;
952 }
953 
954 uint32_t
955 Platform::FindProcesses (const ProcessInstanceInfoMatch &match_info,
956                          ProcessInstanceInfoList &process_infos)
957 {
958     // Take care of the host case so that each subclass can just
959     // call this function to get the host functionality.
960     uint32_t match_count = 0;
961     if (IsHost())
962         match_count = Host::FindProcesses (match_info, process_infos);
963     return match_count;
964 }
965 
966 
967 Error
968 Platform::LaunchProcess (ProcessLaunchInfo &launch_info)
969 {
970     Error error;
971     // Take care of the host case so that each subclass can just
972     // call this function to get the host functionality.
973     if (IsHost())
974     {
975         if (::getenv ("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
976             launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
977 
978         if (launch_info.GetFlags().Test (eLaunchFlagLaunchInShell))
979         {
980             const bool is_localhost = true;
981             const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
982             const bool first_arg_is_full_shell_command = false;
983             uint32_t num_resumes = GetResumeCountForLaunchInfo (launch_info);
984             if (!launch_info.ConvertArgumentsForLaunchingInShell (error,
985                                                                   is_localhost,
986                                                                   will_debug,
987                                                                   first_arg_is_full_shell_command,
988                                                                   num_resumes))
989                 return error;
990         }
991 
992         error = Host::LaunchProcess (launch_info);
993     }
994     else
995         error.SetErrorString ("base lldb_private::Platform class can't launch remote processes");
996     return error;
997 }
998 
999 lldb::ProcessSP
1000 Platform::DebugProcess (ProcessLaunchInfo &launch_info,
1001                         Debugger &debugger,
1002                         Target *target,       // Can be NULL, if NULL create a new target, else use existing one
1003                         Listener &listener,
1004                         Error &error)
1005 {
1006     ProcessSP process_sp;
1007     // Make sure we stop at the entry point
1008     launch_info.GetFlags ().Set (eLaunchFlagDebug);
1009     // We always launch the process we are going to debug in a separate process
1010     // group, since then we can handle ^C interrupts ourselves w/o having to worry
1011     // about the target getting them as well.
1012     launch_info.SetLaunchInSeparateProcessGroup(true);
1013 
1014     error = LaunchProcess (launch_info);
1015     if (error.Success())
1016     {
1017         if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1018         {
1019             ProcessAttachInfo attach_info (launch_info);
1020             process_sp = Attach (attach_info, debugger, target, listener, error);
1021             if (process_sp)
1022             {
1023                 // Since we attached to the process, it will think it needs to detach
1024                 // if the process object just goes away without an explicit call to
1025                 // Process::Kill() or Process::Detach(), so let it know to kill the
1026                 // process if this happens.
1027                 process_sp->SetShouldDetach (false);
1028 
1029                 // If we didn't have any file actions, the pseudo terminal might
1030                 // have been used where the slave side was given as the file to
1031                 // open for stdin/out/err after we have already opened the master
1032                 // so we can read/write stdin/out/err.
1033                 int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
1034                 if (pty_fd != lldb_utility::PseudoTerminal::invalid_fd)
1035                 {
1036                     process_sp->SetSTDIOFileDescriptor(pty_fd);
1037                 }
1038             }
1039         }
1040     }
1041     return process_sp;
1042 }
1043 
1044 
1045 lldb::PlatformSP
1046 Platform::GetPlatformForArchitecture (const ArchSpec &arch, ArchSpec *platform_arch_ptr)
1047 {
1048     lldb::PlatformSP platform_sp;
1049     Error error;
1050     if (arch.IsValid())
1051         platform_sp = Platform::Create (arch, platform_arch_ptr, error);
1052     return platform_sp;
1053 }
1054 
1055 
1056 //------------------------------------------------------------------
1057 /// Lets a platform answer if it is compatible with a given
1058 /// architecture and the target triple contained within.
1059 //------------------------------------------------------------------
1060 bool
1061 Platform::IsCompatibleArchitecture (const ArchSpec &arch, bool exact_arch_match, ArchSpec *compatible_arch_ptr)
1062 {
1063     // If the architecture is invalid, we must answer true...
1064     if (arch.IsValid())
1065     {
1066         ArchSpec platform_arch;
1067         // Try for an exact architecture match first.
1068         if (exact_arch_match)
1069         {
1070             for (uint32_t arch_idx=0; GetSupportedArchitectureAtIndex (arch_idx, platform_arch); ++arch_idx)
1071             {
1072                 if (arch.IsExactMatch(platform_arch))
1073                 {
1074                     if (compatible_arch_ptr)
1075                         *compatible_arch_ptr = platform_arch;
1076                     return true;
1077                 }
1078             }
1079         }
1080         else
1081         {
1082             for (uint32_t arch_idx=0; GetSupportedArchitectureAtIndex (arch_idx, platform_arch); ++arch_idx)
1083             {
1084                 if (arch.IsCompatibleMatch(platform_arch))
1085                 {
1086                     if (compatible_arch_ptr)
1087                         *compatible_arch_ptr = platform_arch;
1088                     return true;
1089                 }
1090             }
1091         }
1092     }
1093     if (compatible_arch_ptr)
1094         compatible_arch_ptr->Clear();
1095     return false;
1096 }
1097 
1098 Error
1099 Platform::PutFile (const FileSpec& source,
1100                    const FileSpec& destination,
1101                    uint32_t uid,
1102                    uint32_t gid)
1103 {
1104     Error error("unimplemented");
1105     return error;
1106 }
1107 
1108 Error
1109 Platform::GetFile (const FileSpec& source,
1110                    const FileSpec& destination)
1111 {
1112     Error error("unimplemented");
1113     return error;
1114 }
1115 
1116 Error
1117 Platform::CreateSymlink (const char *src, // The name of the link is in src
1118                          const char *dst)// The symlink points to dst
1119 {
1120     Error error("unimplemented");
1121     return error;
1122 }
1123 
1124 bool
1125 Platform::GetFileExists (const lldb_private::FileSpec& file_spec)
1126 {
1127     return false;
1128 }
1129 
1130 Error
1131 Platform::Unlink (const char *path)
1132 {
1133     Error error("unimplemented");
1134     return error;
1135 }
1136 
1137 
1138 
1139 lldb_private::Error
1140 Platform::RunShellCommand (const char *command,           // Shouldn't be NULL
1141                            const char *working_dir,       // Pass NULL to use the current working directory
1142                            int *status_ptr,               // Pass NULL if you don't want the process exit status
1143                            int *signo_ptr,                // Pass NULL if you don't want the signal that caused the process to exit
1144                            std::string *command_output,   // Pass NULL if you don't want the command output
1145                            uint32_t timeout_sec)          // Timeout in seconds to wait for shell program to finish
1146 {
1147     if (IsHost())
1148         return Host::RunShellCommand (command, working_dir, status_ptr, signo_ptr, command_output, timeout_sec);
1149     else
1150         return Error("unimplemented");
1151 }
1152 
1153 
1154 bool
1155 Platform::CalculateMD5 (const FileSpec& file_spec,
1156                         uint64_t &low,
1157                         uint64_t &high)
1158 {
1159     if (IsHost())
1160         return Host::CalculateMD5(file_spec, low, high);
1161     else
1162         return false;
1163 }
1164 
1165 void
1166 Platform::SetLocalCacheDirectory (const char* local)
1167 {
1168     m_local_cache_directory.assign(local);
1169 }
1170 
1171 const char*
1172 Platform::GetLocalCacheDirectory ()
1173 {
1174     return m_local_cache_directory.c_str();
1175 }
1176 
1177 static OptionDefinition
1178 g_rsync_option_table[] =
1179 {
1180     {   LLDB_OPT_SET_ALL, false, "rsync"                  , 'r', OptionParser::eNoArgument,       NULL, 0, eArgTypeNone         , "Enable rsync." },
1181     {   LLDB_OPT_SET_ALL, false, "rsync-opts"             , 'R', OptionParser::eRequiredArgument, NULL, 0, eArgTypeCommandName  , "Platform-specific options required for rsync to work." },
1182     {   LLDB_OPT_SET_ALL, false, "rsync-prefix"           , 'P', OptionParser::eRequiredArgument, NULL, 0, eArgTypeCommandName  , "Platform-specific rsync prefix put before the remote path." },
1183     {   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." },
1184 };
1185 
1186 static OptionDefinition
1187 g_ssh_option_table[] =
1188 {
1189     {   LLDB_OPT_SET_ALL, false, "ssh"                    , 's', OptionParser::eNoArgument,       NULL, 0, eArgTypeNone         , "Enable SSH." },
1190     {   LLDB_OPT_SET_ALL, false, "ssh-opts"               , 'S', OptionParser::eRequiredArgument, NULL, 0, eArgTypeCommandName  , "Platform-specific options required for SSH to work." },
1191 };
1192 
1193 static OptionDefinition
1194 g_caching_option_table[] =
1195 {
1196     {   LLDB_OPT_SET_ALL, false, "local-cache-dir"        , 'c', OptionParser::eRequiredArgument, NULL, 0, eArgTypePath         , "Path in which to store local copies of files." },
1197 };
1198 
1199 OptionGroupPlatformRSync::OptionGroupPlatformRSync ()
1200 {
1201 }
1202 
1203 OptionGroupPlatformRSync::~OptionGroupPlatformRSync ()
1204 {
1205 }
1206 
1207 const lldb_private::OptionDefinition*
1208 OptionGroupPlatformRSync::GetDefinitions ()
1209 {
1210     return g_rsync_option_table;
1211 }
1212 
1213 void
1214 OptionGroupPlatformRSync::OptionParsingStarting (CommandInterpreter &interpreter)
1215 {
1216     m_rsync = false;
1217     m_rsync_opts.clear();
1218     m_rsync_prefix.clear();
1219     m_ignores_remote_hostname = false;
1220 }
1221 
1222 lldb_private::Error
1223 OptionGroupPlatformRSync::SetOptionValue (CommandInterpreter &interpreter,
1224                 uint32_t option_idx,
1225                 const char *option_arg)
1226 {
1227     Error error;
1228     char short_option = (char) GetDefinitions()[option_idx].short_option;
1229     switch (short_option)
1230     {
1231         case 'r':
1232             m_rsync = true;
1233             break;
1234 
1235         case 'R':
1236             m_rsync_opts.assign(option_arg);
1237             break;
1238 
1239         case 'P':
1240             m_rsync_prefix.assign(option_arg);
1241             break;
1242 
1243         case 'i':
1244             m_ignores_remote_hostname = true;
1245             break;
1246 
1247         default:
1248             error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1249             break;
1250     }
1251 
1252     return error;
1253 }
1254 
1255 uint32_t
1256 OptionGroupPlatformRSync::GetNumDefinitions ()
1257 {
1258     return llvm::array_lengthof(g_rsync_option_table);
1259 }
1260 
1261 lldb::BreakpointSP
1262 Platform::SetThreadCreationBreakpoint (lldb_private::Target &target)
1263 {
1264     return lldb::BreakpointSP();
1265 }
1266 
1267 OptionGroupPlatformSSH::OptionGroupPlatformSSH ()
1268 {
1269 }
1270 
1271 OptionGroupPlatformSSH::~OptionGroupPlatformSSH ()
1272 {
1273 }
1274 
1275 const lldb_private::OptionDefinition*
1276 OptionGroupPlatformSSH::GetDefinitions ()
1277 {
1278     return g_ssh_option_table;
1279 }
1280 
1281 void
1282 OptionGroupPlatformSSH::OptionParsingStarting (CommandInterpreter &interpreter)
1283 {
1284     m_ssh = false;
1285     m_ssh_opts.clear();
1286 }
1287 
1288 lldb_private::Error
1289 OptionGroupPlatformSSH::SetOptionValue (CommandInterpreter &interpreter,
1290                                           uint32_t option_idx,
1291                                           const char *option_arg)
1292 {
1293     Error error;
1294     char short_option = (char) GetDefinitions()[option_idx].short_option;
1295     switch (short_option)
1296     {
1297         case 's':
1298             m_ssh = true;
1299             break;
1300 
1301         case 'S':
1302             m_ssh_opts.assign(option_arg);
1303             break;
1304 
1305         default:
1306             error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1307             break;
1308     }
1309 
1310     return error;
1311 }
1312 
1313 uint32_t
1314 OptionGroupPlatformSSH::GetNumDefinitions ()
1315 {
1316     return llvm::array_lengthof(g_ssh_option_table);
1317 }
1318 
1319 OptionGroupPlatformCaching::OptionGroupPlatformCaching ()
1320 {
1321 }
1322 
1323 OptionGroupPlatformCaching::~OptionGroupPlatformCaching ()
1324 {
1325 }
1326 
1327 const lldb_private::OptionDefinition*
1328 OptionGroupPlatformCaching::GetDefinitions ()
1329 {
1330     return g_caching_option_table;
1331 }
1332 
1333 void
1334 OptionGroupPlatformCaching::OptionParsingStarting (CommandInterpreter &interpreter)
1335 {
1336     m_cache_dir.clear();
1337 }
1338 
1339 lldb_private::Error
1340 OptionGroupPlatformCaching::SetOptionValue (CommandInterpreter &interpreter,
1341                                         uint32_t option_idx,
1342                                         const char *option_arg)
1343 {
1344     Error error;
1345     char short_option = (char) GetDefinitions()[option_idx].short_option;
1346     switch (short_option)
1347     {
1348         case 'c':
1349             m_cache_dir.assign(option_arg);
1350             break;
1351 
1352         default:
1353             error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1354             break;
1355     }
1356 
1357     return error;
1358 }
1359 
1360 uint32_t
1361 OptionGroupPlatformCaching::GetNumDefinitions ()
1362 {
1363     return llvm::array_lengthof(g_caching_option_table);
1364 }
1365 
1366 size_t
1367 Platform::GetEnvironment (StringList &environment)
1368 {
1369     environment.Clear();
1370     return false;
1371 }
1372