1 //===-- PlatformPOSIX.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 "PlatformPOSIX.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/ModuleSpec.h"
20 #include "lldb/Core/ValueObject.h"
21 #include "lldb/Expression/DiagnosticManager.h"
22 #include "lldb/Expression/FunctionCaller.h"
23 #include "lldb/Expression/UserExpression.h"
24 #include "lldb/Expression/UtilityFunction.h"
25 #include "lldb/Host/File.h"
26 #include "lldb/Host/FileCache.h"
27 #include "lldb/Host/FileSystem.h"
28 #include "lldb/Host/Host.h"
29 #include "lldb/Host/HostInfo.h"
30 #include "lldb/Symbol/ClangASTContext.h"
31 #include "lldb/Target/DynamicLoader.h"
32 #include "lldb/Target/ExecutionContext.h"
33 #include "lldb/Target/Process.h"
34 #include "lldb/Target/ProcessLaunchInfo.h"
35 #include "lldb/Target/Thread.h"
36 #include "lldb/Utility/CleanUp.h"
37 #include "lldb/Utility/DataBufferHeap.h"
38 #include "lldb/Utility/FileSpec.h"
39 #include "lldb/Utility/Log.h"
40 #include "lldb/Utility/StreamString.h"
41 
42 using namespace lldb;
43 using namespace lldb_private;
44 
45 //------------------------------------------------------------------
46 /// Default Constructor
47 //------------------------------------------------------------------
48 PlatformPOSIX::PlatformPOSIX(bool is_host)
49     : Platform(is_host), // This is the local host platform
50       m_option_group_platform_rsync(new OptionGroupPlatformRSync()),
51       m_option_group_platform_ssh(new OptionGroupPlatformSSH()),
52       m_option_group_platform_caching(new OptionGroupPlatformCaching()),
53       m_remote_platform_sp() {}
54 
55 //------------------------------------------------------------------
56 /// Destructor.
57 ///
58 /// The destructor is virtual since this class is designed to be
59 /// inherited from by the plug-in instance.
60 //------------------------------------------------------------------
61 PlatformPOSIX::~PlatformPOSIX() {}
62 
63 bool PlatformPOSIX::GetModuleSpec(const FileSpec &module_file_spec,
64                                   const ArchSpec &arch,
65                                   ModuleSpec &module_spec) {
66   if (m_remote_platform_sp)
67     return m_remote_platform_sp->GetModuleSpec(module_file_spec, arch,
68                                                module_spec);
69 
70   return Platform::GetModuleSpec(module_file_spec, arch, module_spec);
71 }
72 
73 lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions(
74     lldb_private::CommandInterpreter &interpreter) {
75   auto iter = m_options.find(&interpreter), end = m_options.end();
76   if (iter == end) {
77     std::unique_ptr<lldb_private::OptionGroupOptions> options(
78         new OptionGroupOptions());
79     options->Append(m_option_group_platform_rsync.get());
80     options->Append(m_option_group_platform_ssh.get());
81     options->Append(m_option_group_platform_caching.get());
82     m_options[&interpreter] = std::move(options);
83   }
84 
85   return m_options.at(&interpreter).get();
86 }
87 
88 bool PlatformPOSIX::IsConnected() const {
89   if (IsHost())
90     return true;
91   else if (m_remote_platform_sp)
92     return m_remote_platform_sp->IsConnected();
93   return false;
94 }
95 
96 lldb_private::Status PlatformPOSIX::RunShellCommand(
97     const char *command, // Shouldn't be NULL
98     const FileSpec &
99         working_dir, // Pass empty FileSpec to use the current working directory
100     int *status_ptr, // Pass NULL if you don't want the process exit status
101     int *signo_ptr,  // Pass NULL if you don't want the signal that caused the
102                      // process to exit
103     std::string
104         *command_output, // Pass NULL if you don't want the command output
105     const Timeout<std::micro> &timeout) {
106   if (IsHost())
107     return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr,
108                                  command_output, timeout);
109   else {
110     if (m_remote_platform_sp)
111       return m_remote_platform_sp->RunShellCommand(
112           command, working_dir, status_ptr, signo_ptr, command_output, timeout);
113     else
114       return Status("unable to run a remote command without a platform");
115   }
116 }
117 
118 Status
119 PlatformPOSIX::ResolveExecutable(const ModuleSpec &module_spec,
120                                  lldb::ModuleSP &exe_module_sp,
121                                  const FileSpecList *module_search_paths_ptr) {
122   Status error;
123   // Nothing special to do here, just use the actual file and architecture
124 
125   char exe_path[PATH_MAX];
126   ModuleSpec resolved_module_spec(module_spec);
127 
128   if (IsHost()) {
129     // If we have "ls" as the exe_file, resolve the executable location based
130     // on the current path variables
131     if (!resolved_module_spec.GetFileSpec().Exists()) {
132       resolved_module_spec.GetFileSpec().GetPath(exe_path, sizeof(exe_path));
133       resolved_module_spec.GetFileSpec().SetFile(exe_path, true);
134     }
135 
136     if (!resolved_module_spec.GetFileSpec().Exists())
137       resolved_module_spec.GetFileSpec().ResolveExecutableLocation();
138 
139     // Resolve any executable within a bundle on MacOSX
140     Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
141 
142     if (resolved_module_spec.GetFileSpec().Exists())
143       error.Clear();
144     else {
145       const uint32_t permissions =
146           resolved_module_spec.GetFileSpec().GetPermissions();
147       if (permissions && (permissions & eFilePermissionsEveryoneR) == 0)
148         error.SetErrorStringWithFormat(
149             "executable '%s' is not readable",
150             resolved_module_spec.GetFileSpec().GetPath().c_str());
151       else
152         error.SetErrorStringWithFormat(
153             "unable to find executable for '%s'",
154             resolved_module_spec.GetFileSpec().GetPath().c_str());
155     }
156   } else {
157     if (m_remote_platform_sp) {
158       error =
159           GetCachedExecutable(resolved_module_spec, exe_module_sp,
160                               module_search_paths_ptr, *m_remote_platform_sp);
161     } else {
162       // We may connect to a process and use the provided executable (Don't use
163       // local $PATH).
164 
165       // Resolve any executable within a bundle on MacOSX
166       Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
167 
168       if (resolved_module_spec.GetFileSpec().Exists())
169         error.Clear();
170       else
171         error.SetErrorStringWithFormat("the platform is not currently "
172                                        "connected, and '%s' doesn't exist in "
173                                        "the system root.",
174                                        exe_path);
175     }
176   }
177 
178   if (error.Success()) {
179     if (resolved_module_spec.GetArchitecture().IsValid()) {
180       error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
181                                           module_search_paths_ptr, nullptr, nullptr);
182       if (error.Fail()) {
183         // If we failed, it may be because the vendor and os aren't known. If
184 	// that is the case, try setting them to the host architecture and give
185 	// it another try.
186         llvm::Triple &module_triple =
187             resolved_module_spec.GetArchitecture().GetTriple();
188         bool is_vendor_specified =
189             (module_triple.getVendor() != llvm::Triple::UnknownVendor);
190         bool is_os_specified =
191             (module_triple.getOS() != llvm::Triple::UnknownOS);
192         if (!is_vendor_specified || !is_os_specified) {
193           const llvm::Triple &host_triple =
194               HostInfo::GetArchitecture(HostInfo::eArchKindDefault).GetTriple();
195 
196           if (!is_vendor_specified)
197             module_triple.setVendorName(host_triple.getVendorName());
198           if (!is_os_specified)
199             module_triple.setOSName(host_triple.getOSName());
200 
201           error = ModuleList::GetSharedModule(resolved_module_spec,
202                                               exe_module_sp, module_search_paths_ptr, nullptr, nullptr);
203         }
204       }
205 
206       // TODO find out why exe_module_sp might be NULL
207       if (error.Fail() || !exe_module_sp || !exe_module_sp->GetObjectFile()) {
208         exe_module_sp.reset();
209         error.SetErrorStringWithFormat(
210             "'%s' doesn't contain the architecture %s",
211             resolved_module_spec.GetFileSpec().GetPath().c_str(),
212             resolved_module_spec.GetArchitecture().GetArchitectureName());
213       }
214     } else {
215       // No valid architecture was specified, ask the platform for the
216       // architectures that we should be using (in the correct order) and see
217       // if we can find a match that way
218       StreamString arch_names;
219       for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
220                idx, resolved_module_spec.GetArchitecture());
221            ++idx) {
222         error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
223                                             module_search_paths_ptr, nullptr, nullptr);
224         // Did we find an executable using one of the
225         if (error.Success()) {
226           if (exe_module_sp && exe_module_sp->GetObjectFile())
227             break;
228           else
229             error.SetErrorToGenericError();
230         }
231 
232         if (idx > 0)
233           arch_names.PutCString(", ");
234         arch_names.PutCString(
235             resolved_module_spec.GetArchitecture().GetArchitectureName());
236       }
237 
238       if (error.Fail() || !exe_module_sp) {
239         if (resolved_module_spec.GetFileSpec().Readable()) {
240           error.SetErrorStringWithFormat(
241               "'%s' doesn't contain any '%s' platform architectures: %s",
242               resolved_module_spec.GetFileSpec().GetPath().c_str(),
243               GetPluginName().GetCString(), arch_names.GetData());
244         } else {
245           error.SetErrorStringWithFormat(
246               "'%s' is not readable",
247               resolved_module_spec.GetFileSpec().GetPath().c_str());
248         }
249       }
250     }
251   }
252 
253   return error;
254 }
255 
256 Status PlatformPOSIX::GetFileWithUUID(const FileSpec &platform_file,
257                                       const UUID *uuid_ptr,
258                                       FileSpec &local_file) {
259   if (IsRemote() && m_remote_platform_sp)
260       return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr,
261                                                    local_file);
262 
263   // Default to the local case
264   local_file = platform_file;
265   return Status();
266 }
267 
268 bool PlatformPOSIX::GetProcessInfo(lldb::pid_t pid,
269                                      ProcessInstanceInfo &process_info) {
270   if (IsHost())
271     return Platform::GetProcessInfo(pid, process_info);
272   if (m_remote_platform_sp)
273     return m_remote_platform_sp->GetProcessInfo(pid, process_info);
274   return false;
275 }
276 
277 uint32_t
278 PlatformPOSIX::FindProcesses(const ProcessInstanceInfoMatch &match_info,
279                                ProcessInstanceInfoList &process_infos) {
280   if (IsHost())
281     return Platform::FindProcesses(match_info, process_infos);
282   if (m_remote_platform_sp)
283     return
284       m_remote_platform_sp->FindProcesses(match_info, process_infos);
285   return 0;
286 }
287 
288 Status PlatformPOSIX::MakeDirectory(const FileSpec &file_spec,
289                                     uint32_t file_permissions) {
290   if (m_remote_platform_sp)
291     return m_remote_platform_sp->MakeDirectory(file_spec, file_permissions);
292   else
293     return Platform::MakeDirectory(file_spec, file_permissions);
294 }
295 
296 Status PlatformPOSIX::GetFilePermissions(const FileSpec &file_spec,
297                                          uint32_t &file_permissions) {
298   if (m_remote_platform_sp)
299     return m_remote_platform_sp->GetFilePermissions(file_spec,
300                                                     file_permissions);
301   else
302     return Platform::GetFilePermissions(file_spec, file_permissions);
303 }
304 
305 Status PlatformPOSIX::SetFilePermissions(const FileSpec &file_spec,
306                                          uint32_t file_permissions) {
307   if (m_remote_platform_sp)
308     return m_remote_platform_sp->SetFilePermissions(file_spec,
309                                                     file_permissions);
310   else
311     return Platform::SetFilePermissions(file_spec, file_permissions);
312 }
313 
314 lldb::user_id_t PlatformPOSIX::OpenFile(const FileSpec &file_spec,
315                                         uint32_t flags, uint32_t mode,
316                                         Status &error) {
317   if (IsHost())
318     return FileCache::GetInstance().OpenFile(file_spec, flags, mode, error);
319   else if (m_remote_platform_sp)
320     return m_remote_platform_sp->OpenFile(file_spec, flags, mode, error);
321   else
322     return Platform::OpenFile(file_spec, flags, mode, error);
323 }
324 
325 bool PlatformPOSIX::CloseFile(lldb::user_id_t fd, Status &error) {
326   if (IsHost())
327     return FileCache::GetInstance().CloseFile(fd, error);
328   else if (m_remote_platform_sp)
329     return m_remote_platform_sp->CloseFile(fd, error);
330   else
331     return Platform::CloseFile(fd, error);
332 }
333 
334 uint64_t PlatformPOSIX::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
335                                  uint64_t dst_len, Status &error) {
336   if (IsHost())
337     return FileCache::GetInstance().ReadFile(fd, offset, dst, dst_len, error);
338   else if (m_remote_platform_sp)
339     return m_remote_platform_sp->ReadFile(fd, offset, dst, dst_len, error);
340   else
341     return Platform::ReadFile(fd, offset, dst, dst_len, error);
342 }
343 
344 uint64_t PlatformPOSIX::WriteFile(lldb::user_id_t fd, uint64_t offset,
345                                   const void *src, uint64_t src_len,
346                                   Status &error) {
347   if (IsHost())
348     return FileCache::GetInstance().WriteFile(fd, offset, src, src_len, error);
349   else if (m_remote_platform_sp)
350     return m_remote_platform_sp->WriteFile(fd, offset, src, src_len, error);
351   else
352     return Platform::WriteFile(fd, offset, src, src_len, error);
353 }
354 
355 static uint32_t chown_file(Platform *platform, const char *path,
356                            uint32_t uid = UINT32_MAX,
357                            uint32_t gid = UINT32_MAX) {
358   if (!platform || !path || *path == 0)
359     return UINT32_MAX;
360 
361   if (uid == UINT32_MAX && gid == UINT32_MAX)
362     return 0; // pretend I did chown correctly - actually I just didn't care
363 
364   StreamString command;
365   command.PutCString("chown ");
366   if (uid != UINT32_MAX)
367     command.Printf("%d", uid);
368   if (gid != UINT32_MAX)
369     command.Printf(":%d", gid);
370   command.Printf("%s", path);
371   int status;
372   platform->RunShellCommand(command.GetData(), NULL, &status, NULL, NULL,
373                             std::chrono::seconds(10));
374   return status;
375 }
376 
377 lldb_private::Status
378 PlatformPOSIX::PutFile(const lldb_private::FileSpec &source,
379                        const lldb_private::FileSpec &destination, uint32_t uid,
380                        uint32_t gid) {
381   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
382 
383   if (IsHost()) {
384     if (FileSpec::Equal(source, destination, true))
385       return Status();
386     // cp src dst
387     // chown uid:gid dst
388     std::string src_path(source.GetPath());
389     if (src_path.empty())
390       return Status("unable to get file path for source");
391     std::string dst_path(destination.GetPath());
392     if (dst_path.empty())
393       return Status("unable to get file path for destination");
394     StreamString command;
395     command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
396     int status;
397     RunShellCommand(command.GetData(), NULL, &status, NULL, NULL,
398                     std::chrono::seconds(10));
399     if (status != 0)
400       return Status("unable to perform copy");
401     if (uid == UINT32_MAX && gid == UINT32_MAX)
402       return Status();
403     if (chown_file(this, dst_path.c_str(), uid, gid) != 0)
404       return Status("unable to perform chown");
405     return Status();
406   } else if (m_remote_platform_sp) {
407     if (GetSupportsRSync()) {
408       std::string src_path(source.GetPath());
409       if (src_path.empty())
410         return Status("unable to get file path for source");
411       std::string dst_path(destination.GetPath());
412       if (dst_path.empty())
413         return Status("unable to get file path for destination");
414       StreamString command;
415       if (GetIgnoresRemoteHostname()) {
416         if (!GetRSyncPrefix())
417           command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
418                          dst_path.c_str());
419         else
420           command.Printf("rsync %s %s %s%s", GetRSyncOpts(), src_path.c_str(),
421                          GetRSyncPrefix(), dst_path.c_str());
422       } else
423         command.Printf("rsync %s %s %s:%s", GetRSyncOpts(), src_path.c_str(),
424                        GetHostname(), dst_path.c_str());
425       if (log)
426         log->Printf("[PutFile] Running command: %s\n", command.GetData());
427       int retcode;
428       Host::RunShellCommand(command.GetData(), NULL, &retcode, NULL, NULL,
429                             std::chrono::minutes(1));
430       if (retcode == 0) {
431         // Don't chown a local file for a remote system
432         //                if (chown_file(this,dst_path.c_str(),uid,gid) != 0)
433         //                    return Status("unable to perform chown");
434         return Status();
435       }
436       // if we are still here rsync has failed - let's try the slow way before
437       // giving up
438     }
439   }
440   return Platform::PutFile(source, destination, uid, gid);
441 }
442 
443 lldb::user_id_t PlatformPOSIX::GetFileSize(const FileSpec &file_spec) {
444   if (IsHost()) {
445     uint64_t Size;
446     if (llvm::sys::fs::file_size(file_spec.GetPath(), Size))
447       return 0;
448     return Size;
449   } else if (m_remote_platform_sp)
450     return m_remote_platform_sp->GetFileSize(file_spec);
451   else
452     return Platform::GetFileSize(file_spec);
453 }
454 
455 Status PlatformPOSIX::CreateSymlink(const FileSpec &src, const FileSpec &dst) {
456   if (IsHost())
457     return FileSystem::Symlink(src, dst);
458   else if (m_remote_platform_sp)
459     return m_remote_platform_sp->CreateSymlink(src, dst);
460   else
461     return Platform::CreateSymlink(src, dst);
462 }
463 
464 bool PlatformPOSIX::GetFileExists(const FileSpec &file_spec) {
465   if (IsHost())
466     return file_spec.Exists();
467   else if (m_remote_platform_sp)
468     return m_remote_platform_sp->GetFileExists(file_spec);
469   else
470     return Platform::GetFileExists(file_spec);
471 }
472 
473 Status PlatformPOSIX::Unlink(const FileSpec &file_spec) {
474   if (IsHost())
475     return llvm::sys::fs::remove(file_spec.GetPath());
476   else if (m_remote_platform_sp)
477     return m_remote_platform_sp->Unlink(file_spec);
478   else
479     return Platform::Unlink(file_spec);
480 }
481 
482 lldb_private::Status PlatformPOSIX::GetFile(
483     const lldb_private::FileSpec &source,      // remote file path
484     const lldb_private::FileSpec &destination) // local file path
485 {
486   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
487 
488   // Check the args, first.
489   std::string src_path(source.GetPath());
490   if (src_path.empty())
491     return Status("unable to get file path for source");
492   std::string dst_path(destination.GetPath());
493   if (dst_path.empty())
494     return Status("unable to get file path for destination");
495   if (IsHost()) {
496     if (FileSpec::Equal(source, destination, true))
497       return Status("local scenario->source and destination are the same file "
498                     "path: no operation performed");
499     // cp src dst
500     StreamString cp_command;
501     cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
502     int status;
503     RunShellCommand(cp_command.GetData(), NULL, &status, NULL, NULL,
504                     std::chrono::seconds(10));
505     if (status != 0)
506       return Status("unable to perform copy");
507     return Status();
508   } else if (m_remote_platform_sp) {
509     if (GetSupportsRSync()) {
510       StreamString command;
511       if (GetIgnoresRemoteHostname()) {
512         if (!GetRSyncPrefix())
513           command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
514                          dst_path.c_str());
515         else
516           command.Printf("rsync %s %s%s %s", GetRSyncOpts(), GetRSyncPrefix(),
517                          src_path.c_str(), dst_path.c_str());
518       } else
519         command.Printf("rsync %s %s:%s %s", GetRSyncOpts(),
520                        m_remote_platform_sp->GetHostname(), src_path.c_str(),
521                        dst_path.c_str());
522       if (log)
523         log->Printf("[GetFile] Running command: %s\n", command.GetData());
524       int retcode;
525       Host::RunShellCommand(command.GetData(), NULL, &retcode, NULL, NULL,
526                             std::chrono::minutes(1));
527       if (retcode == 0)
528         return Status();
529       // If we are here, rsync has failed - let's try the slow way before
530       // giving up
531     }
532     // open src and dst
533     // read/write, read/write, read/write, ...
534     // close src
535     // close dst
536     if (log)
537       log->Printf("[GetFile] Using block by block transfer....\n");
538     Status error;
539     user_id_t fd_src = OpenFile(source, File::eOpenOptionRead,
540                                 lldb::eFilePermissionsFileDefault, error);
541 
542     if (fd_src == UINT64_MAX)
543       return Status("unable to open source file");
544 
545     uint32_t permissions = 0;
546     error = GetFilePermissions(source, permissions);
547 
548     if (permissions == 0)
549       permissions = lldb::eFilePermissionsFileDefault;
550 
551     user_id_t fd_dst = FileCache::GetInstance().OpenFile(
552         destination, File::eOpenOptionCanCreate | File::eOpenOptionWrite |
553                          File::eOpenOptionTruncate,
554         permissions, error);
555 
556     if (fd_dst == UINT64_MAX) {
557       if (error.Success())
558         error.SetErrorString("unable to open destination file");
559     }
560 
561     if (error.Success()) {
562       lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
563       uint64_t offset = 0;
564       error.Clear();
565       while (error.Success()) {
566         const uint64_t n_read = ReadFile(fd_src, offset, buffer_sp->GetBytes(),
567                                          buffer_sp->GetByteSize(), error);
568         if (error.Fail())
569           break;
570         if (n_read == 0)
571           break;
572         if (FileCache::GetInstance().WriteFile(fd_dst, offset,
573                                                buffer_sp->GetBytes(), n_read,
574                                                error) != n_read) {
575           if (!error.Fail())
576             error.SetErrorString("unable to write to destination file");
577           break;
578         }
579         offset += n_read;
580       }
581     }
582     // Ignore the close error of src.
583     if (fd_src != UINT64_MAX)
584       CloseFile(fd_src, error);
585     // And close the dst file descriptot.
586     if (fd_dst != UINT64_MAX &&
587         !FileCache::GetInstance().CloseFile(fd_dst, error)) {
588       if (!error.Fail())
589         error.SetErrorString("unable to close destination file");
590     }
591     return error;
592   }
593   return Platform::GetFile(source, destination);
594 }
595 
596 std::string PlatformPOSIX::GetPlatformSpecificConnectionInformation() {
597   StreamString stream;
598   if (GetSupportsRSync()) {
599     stream.PutCString("rsync");
600     if ((GetRSyncOpts() && *GetRSyncOpts()) ||
601         (GetRSyncPrefix() && *GetRSyncPrefix()) || GetIgnoresRemoteHostname()) {
602       stream.Printf(", options: ");
603       if (GetRSyncOpts() && *GetRSyncOpts())
604         stream.Printf("'%s' ", GetRSyncOpts());
605       stream.Printf(", prefix: ");
606       if (GetRSyncPrefix() && *GetRSyncPrefix())
607         stream.Printf("'%s' ", GetRSyncPrefix());
608       if (GetIgnoresRemoteHostname())
609         stream.Printf("ignore remote-hostname ");
610     }
611   }
612   if (GetSupportsSSH()) {
613     stream.PutCString("ssh");
614     if (GetSSHOpts() && *GetSSHOpts())
615       stream.Printf(", options: '%s' ", GetSSHOpts());
616   }
617   if (GetLocalCacheDirectory() && *GetLocalCacheDirectory())
618     stream.Printf("cache dir: %s", GetLocalCacheDirectory());
619   if (stream.GetSize())
620     return stream.GetString();
621   else
622     return "";
623 }
624 
625 bool PlatformPOSIX::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
626                                  uint64_t &high) {
627   if (IsHost())
628     return Platform::CalculateMD5(file_spec, low, high);
629   if (m_remote_platform_sp)
630     return m_remote_platform_sp->CalculateMD5(file_spec, low, high);
631   return false;
632 }
633 
634 const lldb::UnixSignalsSP &PlatformPOSIX::GetRemoteUnixSignals() {
635   if (IsRemote() && m_remote_platform_sp)
636     return m_remote_platform_sp->GetRemoteUnixSignals();
637   return Platform::GetRemoteUnixSignals();
638 }
639 
640 FileSpec PlatformPOSIX::GetRemoteWorkingDirectory() {
641   if (IsRemote() && m_remote_platform_sp)
642     return m_remote_platform_sp->GetRemoteWorkingDirectory();
643   else
644     return Platform::GetRemoteWorkingDirectory();
645 }
646 
647 bool PlatformPOSIX::SetRemoteWorkingDirectory(const FileSpec &working_dir) {
648   if (IsRemote() && m_remote_platform_sp)
649     return m_remote_platform_sp->SetRemoteWorkingDirectory(working_dir);
650   else
651     return Platform::SetRemoteWorkingDirectory(working_dir);
652 }
653 
654 bool PlatformPOSIX::GetRemoteOSVersion() {
655   if (m_remote_platform_sp)
656     return m_remote_platform_sp->GetOSVersion(
657         m_major_os_version, m_minor_os_version, m_update_os_version);
658   return false;
659 }
660 
661 bool PlatformPOSIX::GetRemoteOSBuildString(std::string &s) {
662   if (m_remote_platform_sp)
663     return m_remote_platform_sp->GetRemoteOSBuildString(s);
664   s.clear();
665   return false;
666 }
667 
668 Environment PlatformPOSIX::GetEnvironment() {
669   if (IsRemote()) {
670     if (m_remote_platform_sp)
671       return m_remote_platform_sp->GetEnvironment();
672     return Environment();
673   }
674   return Host::GetEnvironment();
675 }
676 
677 bool PlatformPOSIX::GetRemoteOSKernelDescription(std::string &s) {
678   if (m_remote_platform_sp)
679     return m_remote_platform_sp->GetRemoteOSKernelDescription(s);
680   s.clear();
681   return false;
682 }
683 
684 // Remote Platform subclasses need to override this function
685 ArchSpec PlatformPOSIX::GetRemoteSystemArchitecture() {
686   if (m_remote_platform_sp)
687     return m_remote_platform_sp->GetRemoteSystemArchitecture();
688   return ArchSpec();
689 }
690 
691 const char *PlatformPOSIX::GetHostname() {
692   if (IsHost())
693     return Platform::GetHostname();
694 
695   if (m_remote_platform_sp)
696     return m_remote_platform_sp->GetHostname();
697   return NULL;
698 }
699 
700 const char *PlatformPOSIX::GetUserName(uint32_t uid) {
701   // Check the cache in Platform in case we have already looked this uid up
702   const char *user_name = Platform::GetUserName(uid);
703   if (user_name)
704     return user_name;
705 
706   if (IsRemote() && m_remote_platform_sp)
707     return m_remote_platform_sp->GetUserName(uid);
708   return NULL;
709 }
710 
711 const char *PlatformPOSIX::GetGroupName(uint32_t gid) {
712   const char *group_name = Platform::GetGroupName(gid);
713   if (group_name)
714     return group_name;
715 
716   if (IsRemote() && m_remote_platform_sp)
717     return m_remote_platform_sp->GetGroupName(gid);
718   return NULL;
719 }
720 
721 Status PlatformPOSIX::ConnectRemote(Args &args) {
722   Status error;
723   if (IsHost()) {
724     error.SetErrorStringWithFormat(
725         "can't connect to the host platform '%s', always connected",
726         GetPluginName().GetCString());
727   } else {
728     if (!m_remote_platform_sp)
729       m_remote_platform_sp =
730           Platform::Create(ConstString("remote-gdb-server"), error);
731 
732     if (m_remote_platform_sp && error.Success())
733       error = m_remote_platform_sp->ConnectRemote(args);
734     else
735       error.SetErrorString("failed to create a 'remote-gdb-server' platform");
736 
737     if (error.Fail())
738       m_remote_platform_sp.reset();
739   }
740 
741   if (error.Success() && m_remote_platform_sp) {
742     if (m_option_group_platform_rsync.get() &&
743         m_option_group_platform_ssh.get() &&
744         m_option_group_platform_caching.get()) {
745       if (m_option_group_platform_rsync->m_rsync) {
746         SetSupportsRSync(true);
747         SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str());
748         SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str());
749         SetIgnoresRemoteHostname(
750             m_option_group_platform_rsync->m_ignores_remote_hostname);
751       }
752       if (m_option_group_platform_ssh->m_ssh) {
753         SetSupportsSSH(true);
754         SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str());
755       }
756       SetLocalCacheDirectory(
757           m_option_group_platform_caching->m_cache_dir.c_str());
758     }
759   }
760 
761   return error;
762 }
763 
764 Status PlatformPOSIX::DisconnectRemote() {
765   Status error;
766 
767   if (IsHost()) {
768     error.SetErrorStringWithFormat(
769         "can't disconnect from the host platform '%s', always connected",
770         GetPluginName().GetCString());
771   } else {
772     if (m_remote_platform_sp)
773       error = m_remote_platform_sp->DisconnectRemote();
774     else
775       error.SetErrorString("the platform is not currently connected");
776   }
777   return error;
778 }
779 
780 Status PlatformPOSIX::LaunchProcess(ProcessLaunchInfo &launch_info) {
781   Status error;
782 
783   if (IsHost()) {
784     error = Platform::LaunchProcess(launch_info);
785   } else {
786     if (m_remote_platform_sp)
787       error = m_remote_platform_sp->LaunchProcess(launch_info);
788     else
789       error.SetErrorString("the platform is not currently connected");
790   }
791   return error;
792 }
793 
794 lldb_private::Status PlatformPOSIX::KillProcess(const lldb::pid_t pid) {
795   if (IsHost())
796     return Platform::KillProcess(pid);
797 
798   if (m_remote_platform_sp)
799     return m_remote_platform_sp->KillProcess(pid);
800 
801   return Status("the platform is not currently connected");
802 }
803 
804 lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info,
805                                       Debugger &debugger, Target *target,
806                                       Status &error) {
807   lldb::ProcessSP process_sp;
808   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
809 
810   if (IsHost()) {
811     if (target == NULL) {
812       TargetSP new_target_sp;
813 
814       error = debugger.GetTargetList().CreateTarget(debugger, "", "", false,
815                                                     NULL, new_target_sp);
816       target = new_target_sp.get();
817       if (log)
818         log->Printf("PlatformPOSIX::%s created new target", __FUNCTION__);
819     } else {
820       error.Clear();
821       if (log)
822         log->Printf("PlatformPOSIX::%s target already existed, setting target",
823                     __FUNCTION__);
824     }
825 
826     if (target && error.Success()) {
827       debugger.GetTargetList().SetSelectedTarget(target);
828       if (log) {
829         ModuleSP exe_module_sp = target->GetExecutableModule();
830         log->Printf("PlatformPOSIX::%s set selected target to %p %s",
831                     __FUNCTION__, (void *)target,
832                     exe_module_sp
833                         ? exe_module_sp->GetFileSpec().GetPath().c_str()
834                         : "<null>");
835       }
836 
837       process_sp =
838           target->CreateProcess(attach_info.GetListenerForProcess(debugger),
839                                 attach_info.GetProcessPluginName(), NULL);
840 
841       if (process_sp) {
842         ListenerSP listener_sp = attach_info.GetHijackListener();
843         if (listener_sp == nullptr) {
844           listener_sp =
845               Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
846           attach_info.SetHijackListener(listener_sp);
847         }
848         process_sp->HijackProcessEvents(listener_sp);
849         error = process_sp->Attach(attach_info);
850       }
851     }
852   } else {
853     if (m_remote_platform_sp)
854       process_sp =
855           m_remote_platform_sp->Attach(attach_info, debugger, target, error);
856     else
857       error.SetErrorString("the platform is not currently connected");
858   }
859   return process_sp;
860 }
861 
862 lldb::ProcessSP
863 PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
864                             Target *target, // Can be NULL, if NULL create a new
865                                             // target, else use existing one
866                             Status &error) {
867   ProcessSP process_sp;
868 
869   if (IsHost()) {
870     // We are going to hand this process off to debugserver which will be in
871     // charge of setting the exit status. We still need to reap it from lldb
872     // but if we let the monitor thread also set the exit status, we set up a
873     // race between debugserver & us for who will find out about the debugged
874     // process's death.
875     launch_info.GetFlags().Set(eLaunchFlagDontSetExitStatus);
876     process_sp = Platform::DebugProcess(launch_info, debugger, target, error);
877   } else {
878     if (m_remote_platform_sp)
879       process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
880                                                       target, error);
881     else
882       error.SetErrorString("the platform is not currently connected");
883   }
884   return process_sp;
885 }
886 
887 void PlatformPOSIX::CalculateTrapHandlerSymbolNames() {
888   m_trap_handlers.push_back(ConstString("_sigtramp"));
889 }
890 
891 Status PlatformPOSIX::EvaluateLibdlExpression(
892     lldb_private::Process *process, const char *expr_cstr,
893     llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
894   DynamicLoader *loader = process->GetDynamicLoader();
895   if (loader) {
896     Status error = loader->CanLoadImage();
897     if (error.Fail())
898       return error;
899   }
900 
901   ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread());
902   if (!thread_sp)
903     return Status("Selected thread isn't valid");
904 
905   StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
906   if (!frame_sp)
907     return Status("Frame 0 isn't valid");
908 
909   ExecutionContext exe_ctx;
910   frame_sp->CalculateExecutionContext(exe_ctx);
911   EvaluateExpressionOptions expr_options;
912   expr_options.SetUnwindOnError(true);
913   expr_options.SetIgnoreBreakpoints(true);
914   expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
915   expr_options.SetLanguage(eLanguageTypeC_plus_plus);
916   expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
917                                          // don't do the work to trap them.
918   expr_options.SetTimeout(std::chrono::seconds(2));
919 
920   Status expr_error;
921   ExpressionResults result =
922       UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix,
923                                result_valobj_sp, expr_error);
924   if (result != eExpressionCompleted)
925     return expr_error;
926 
927   if (result_valobj_sp->GetError().Fail())
928     return result_valobj_sp->GetError();
929   return Status();
930 }
931 
932 UtilityFunction *
933 PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx,
934                                             Status &error)
935 {
936   // Remember to prepend this with the prefix from
937   // GetLibdlFunctionDeclarations. The returned values are all in
938   // __lldb_dlopen_result for consistency. The wrapper returns a void * but
939   // doesn't use it because UtilityFunctions don't work with void returns at
940   // present.
941   static const char *dlopen_wrapper_code = R"(
942   struct __lldb_dlopen_result {
943     void *image_ptr;
944     const char *error_str;
945   };
946 
947   void * __lldb_dlopen_wrapper (const char *path,
948                                 __lldb_dlopen_result *result_ptr)
949   {
950     result_ptr->image_ptr = dlopen(path, 2);
951     if (result_ptr->image_ptr == (void *) 0x0)
952       result_ptr->error_str = dlerror();
953     return nullptr;
954   }
955   )";
956 
957   static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
958   Process *process = exe_ctx.GetProcessSP().get();
959   // Insert the dlopen shim defines into our generic expression:
960   std::string expr(GetLibdlFunctionDeclarations(process));
961   expr.append(dlopen_wrapper_code);
962   Status utility_error;
963   DiagnosticManager diagnostics;
964 
965   std::unique_ptr<UtilityFunction> dlopen_utility_func_up(process
966       ->GetTarget().GetUtilityFunctionForLanguage(expr.c_str(),
967                                                   eLanguageTypeObjC,
968                                                   dlopen_wrapper_name,
969                                                   utility_error));
970   if (utility_error.Fail()) {
971     error.SetErrorStringWithFormat("dlopen error: could not make utility"
972                                    "function: %s", utility_error.AsCString());
973     return nullptr;
974   }
975   if (!dlopen_utility_func_up->Install(diagnostics, exe_ctx)) {
976     error.SetErrorStringWithFormat("dlopen error: could not install utility"
977                                    "function: %s",
978                                    diagnostics.GetString().c_str());
979     return nullptr;
980   }
981 
982   Value value;
983   ValueList arguments;
984   FunctionCaller *do_dlopen_function = nullptr;
985   UtilityFunction *dlopen_utility_func = nullptr;
986 
987   // Fetch the clang types we will need:
988   ClangASTContext *ast = process->GetTarget().GetScratchClangASTContext();
989 
990   CompilerType clang_void_pointer_type
991       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
992   CompilerType clang_char_pointer_type
993         = ast->GetBasicType(eBasicTypeChar).GetPointerType();
994 
995   // We are passing two arguments, the path to dlopen, and a pointer to the
996   // storage we've made for the result:
997   value.SetValueType(Value::eValueTypeScalar);
998   value.SetCompilerType(clang_void_pointer_type);
999   arguments.PushValue(value);
1000   value.SetCompilerType(clang_char_pointer_type);
1001   arguments.PushValue(value);
1002 
1003   do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
1004       clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
1005   if (utility_error.Fail()) {
1006     error.SetErrorStringWithFormat("dlopen error: could not make function"
1007                                    "caller: %s", utility_error.AsCString());
1008     return nullptr;
1009   }
1010 
1011   do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
1012   if (!do_dlopen_function) {
1013     error.SetErrorString("dlopen error: could not get function caller.");
1014     return nullptr;
1015   }
1016 
1017   // We made a good utility function, so cache it in the process:
1018   dlopen_utility_func = dlopen_utility_func_up.get();
1019   process->SetLoadImageUtilityFunction(std::move(dlopen_utility_func_up));
1020   return dlopen_utility_func;
1021 }
1022 
1023 uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process,
1024                                     const lldb_private::FileSpec &remote_file,
1025                                     lldb_private::Status &error) {
1026   std::string path;
1027   path = remote_file.GetPath();
1028 
1029   ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
1030   if (!thread_sp) {
1031     error.SetErrorString("dlopen error: no thread available to call dlopen.");
1032     return LLDB_INVALID_IMAGE_TOKEN;
1033   }
1034 
1035   DiagnosticManager diagnostics;
1036 
1037   ExecutionContext exe_ctx;
1038   thread_sp->CalculateExecutionContext(exe_ctx);
1039 
1040   Status utility_error;
1041 
1042   // The UtilityFunction is held in the Process.  Platforms don't track the
1043   // lifespan of the Targets that use them, we can't put this in the Platform.
1044   UtilityFunction *dlopen_utility_func
1045       = process->GetLoadImageUtilityFunction(this);
1046   ValueList arguments;
1047   FunctionCaller *do_dlopen_function = nullptr;
1048 
1049   if (!dlopen_utility_func) {
1050     // Make the UtilityFunction:
1051     dlopen_utility_func = MakeLoadImageUtilityFunction(exe_ctx, error);
1052   }
1053   // If we couldn't make it, the error will be in error, so we can exit here.
1054   if (!dlopen_utility_func)
1055     return LLDB_INVALID_IMAGE_TOKEN;
1056 
1057   do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
1058   if (!do_dlopen_function) {
1059     error.SetErrorString("dlopen error: could not get function caller.");
1060     return LLDB_INVALID_IMAGE_TOKEN;
1061   }
1062   arguments = do_dlopen_function->GetArgumentValues();
1063 
1064   // Now insert the path we are searching for and the result structure into the
1065   // target.
1066   uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
1067   size_t path_len = path.size() + 1;
1068   lldb::addr_t path_addr = process->AllocateMemory(path_len,
1069                                                    permissions,
1070                                                    utility_error);
1071   if (path_addr == LLDB_INVALID_ADDRESS) {
1072     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1073                                     "for path: %s", utility_error.AsCString());
1074     return LLDB_INVALID_IMAGE_TOKEN;
1075   }
1076 
1077   // Make sure we deallocate the input string memory:
1078   CleanUp path_cleanup([process, path_addr] {
1079       process->DeallocateMemory(path_addr);
1080   });
1081 
1082   process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
1083   if (utility_error.Fail()) {
1084     error.SetErrorStringWithFormat("dlopen error: could not write path string:"
1085                                     " %s", utility_error.AsCString());
1086     return LLDB_INVALID_IMAGE_TOKEN;
1087   }
1088 
1089   // Make space for our return structure.  It is two pointers big: the token
1090   // and the error string.
1091   const uint32_t addr_size = process->GetAddressByteSize();
1092   lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
1093                                                       permissions,
1094                                                       utility_error);
1095   if (utility_error.Fail()) {
1096     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1097                                     "for path: %s", utility_error.AsCString());
1098     return LLDB_INVALID_IMAGE_TOKEN;
1099   }
1100 
1101   // Make sure we deallocate the result structure memory
1102   CleanUp return_cleanup([process, return_addr] {
1103       process->DeallocateMemory(return_addr);
1104   });
1105 
1106   // Set the values into our args and write them to the target:
1107   arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
1108   arguments.GetValueAtIndex(1)->GetScalar() = return_addr;
1109 
1110   lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
1111 
1112   diagnostics.Clear();
1113   if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
1114                                                  func_args_addr,
1115                                                  arguments,
1116                                                  diagnostics)) {
1117     error.SetErrorStringWithFormat("dlopen error: could not write function "
1118                                    "arguments: %s",
1119                                    diagnostics.GetString().c_str());
1120     return LLDB_INVALID_IMAGE_TOKEN;
1121   }
1122 
1123   // Make sure we clean up the args structure.  We can't reuse it because the
1124   // Platform lives longer than the process and the Platforms don't get a
1125   // signal to clean up cached data when a process goes away.
1126   CleanUp args_cleanup([do_dlopen_function, &exe_ctx, func_args_addr] {
1127     do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
1128   });
1129 
1130   // Now run the caller:
1131   EvaluateExpressionOptions options;
1132   options.SetExecutionPolicy(eExecutionPolicyAlways);
1133   options.SetLanguage(eLanguageTypeC_plus_plus);
1134   options.SetIgnoreBreakpoints(true);
1135   options.SetUnwindOnError(true);
1136   options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
1137                                     // don't do the work to trap them.
1138   options.SetTimeout(std::chrono::seconds(2));
1139 
1140   Value return_value;
1141   // Fetch the clang types we will need:
1142   ClangASTContext *ast = process->GetTarget().GetScratchClangASTContext();
1143 
1144   CompilerType clang_void_pointer_type
1145       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
1146 
1147   return_value.SetCompilerType(clang_void_pointer_type);
1148 
1149   ExpressionResults results = do_dlopen_function->ExecuteFunction(
1150       exe_ctx, &func_args_addr, options, diagnostics, return_value);
1151   if (results != eExpressionCompleted) {
1152     error.SetErrorStringWithFormat("dlopen error: could write execute "
1153                                    "dlopen wrapper function: %s",
1154                                    diagnostics.GetString().c_str());
1155     return LLDB_INVALID_IMAGE_TOKEN;
1156   }
1157 
1158   // Read the dlopen token from the return area:
1159   lldb::addr_t token = process->ReadPointerFromMemory(return_addr,
1160                                                       utility_error);
1161   if (utility_error.Fail()) {
1162     error.SetErrorStringWithFormat("dlopen error: could not read the return "
1163                                     "struct: %s", utility_error.AsCString());
1164     return LLDB_INVALID_IMAGE_TOKEN;
1165   }
1166 
1167   // The dlopen succeeded!
1168   if (token != 0x0)
1169     return process->AddImageToken(token);
1170 
1171   // We got an error, lets read in the error string:
1172   std::string dlopen_error_str;
1173   lldb::addr_t error_addr
1174     = process->ReadPointerFromMemory(return_addr + addr_size, utility_error);
1175   if (utility_error.Fail()) {
1176     error.SetErrorStringWithFormat("dlopen error: could not read error string: "
1177                                     "%s", utility_error.AsCString());
1178     return LLDB_INVALID_IMAGE_TOKEN;
1179   }
1180 
1181   size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size,
1182                                                     dlopen_error_str,
1183                                                     utility_error);
1184   if (utility_error.Success() && num_chars > 0)
1185     error.SetErrorStringWithFormat("dlopen error: %s",
1186                                    dlopen_error_str.c_str());
1187   else
1188     error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
1189 
1190   return LLDB_INVALID_IMAGE_TOKEN;
1191 }
1192 
1193 Status PlatformPOSIX::UnloadImage(lldb_private::Process *process,
1194                                   uint32_t image_token) {
1195   const addr_t image_addr = process->GetImagePtrFromToken(image_token);
1196   if (image_addr == LLDB_INVALID_ADDRESS)
1197     return Status("Invalid image token");
1198 
1199   StreamString expr;
1200   expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
1201   llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
1202   lldb::ValueObjectSP result_valobj_sp;
1203   Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
1204                                          result_valobj_sp);
1205   if (error.Fail())
1206     return error;
1207 
1208   if (result_valobj_sp->GetError().Fail())
1209     return result_valobj_sp->GetError();
1210 
1211   Scalar scalar;
1212   if (result_valobj_sp->ResolveValue(scalar)) {
1213     if (scalar.UInt(1))
1214       return Status("expression failed: \"%s\"", expr.GetData());
1215     process->ResetImageToken(image_token);
1216   }
1217   return Status();
1218 }
1219 
1220 lldb::ProcessSP PlatformPOSIX::ConnectProcess(llvm::StringRef connect_url,
1221                                               llvm::StringRef plugin_name,
1222                                               lldb_private::Debugger &debugger,
1223                                               lldb_private::Target *target,
1224                                               lldb_private::Status &error) {
1225   if (m_remote_platform_sp)
1226     return m_remote_platform_sp->ConnectProcess(connect_url, plugin_name,
1227                                                 debugger, target, error);
1228 
1229   return Platform::ConnectProcess(connect_url, plugin_name, debugger, target,
1230                                   error);
1231 }
1232 
1233 llvm::StringRef
1234 PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
1235   return R"(
1236               extern "C" void* dlopen(const char*, int);
1237               extern "C" void* dlsym(void*, const char*);
1238               extern "C" int   dlclose(void*);
1239               extern "C" char* dlerror(void);
1240              )";
1241 }
1242 
1243 size_t PlatformPOSIX::ConnectToWaitingProcesses(Debugger &debugger,
1244                                                 Status &error) {
1245   if (m_remote_platform_sp)
1246     return m_remote_platform_sp->ConnectToWaitingProcesses(debugger, error);
1247   return Platform::ConnectToWaitingProcesses(debugger, error);
1248 }
1249 
1250 ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) {
1251   if (basename.IsEmpty())
1252     return basename;
1253 
1254   StreamString stream;
1255   stream.Printf("lib%s.so", basename.GetCString());
1256   return ConstString(stream.GetString());
1257 }
1258