]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Plugins / Platform / POSIX / PlatformPOSIX.cpp
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
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleSpec.h"
16 #include "lldb/Core/ValueObject.h"
17 #include "lldb/Expression/DiagnosticManager.h"
18 #include "lldb/Expression/FunctionCaller.h"
19 #include "lldb/Expression/UserExpression.h"
20 #include "lldb/Expression/UtilityFunction.h"
21 #include "lldb/Host/File.h"
22 #include "lldb/Host/FileCache.h"
23 #include "lldb/Host/FileSystem.h"
24 #include "lldb/Host/Host.h"
25 #include "lldb/Host/HostInfo.h"
26 #include "lldb/Symbol/ClangASTContext.h"
27 #include "lldb/Target/DynamicLoader.h"
28 #include "lldb/Target/ExecutionContext.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/ProcessLaunchInfo.h"
31 #include "lldb/Target/Thread.h"
32 #include "lldb/Utility/CleanUp.h"
33 #include "lldb/Utility/DataBufferHeap.h"
34 #include "lldb/Utility/FileSpec.h"
35 #include "lldb/Utility/Log.h"
36 #include "lldb/Utility/StreamString.h"
37
38 using namespace lldb;
39 using namespace lldb_private;
40
41 //------------------------------------------------------------------
42 /// Default Constructor
43 //------------------------------------------------------------------
44 PlatformPOSIX::PlatformPOSIX(bool is_host)
45     : Platform(is_host), // This is the local host platform
46       m_option_group_platform_rsync(new OptionGroupPlatformRSync()),
47       m_option_group_platform_ssh(new OptionGroupPlatformSSH()),
48       m_option_group_platform_caching(new OptionGroupPlatformCaching()),
49       m_remote_platform_sp() {}
50
51 //------------------------------------------------------------------
52 /// Destructor.
53 ///
54 /// The destructor is virtual since this class is designed to be
55 /// inherited from by the plug-in instance.
56 //------------------------------------------------------------------
57 PlatformPOSIX::~PlatformPOSIX() {}
58
59 bool PlatformPOSIX::GetModuleSpec(const FileSpec &module_file_spec,
60                                   const ArchSpec &arch,
61                                   ModuleSpec &module_spec) {
62   if (m_remote_platform_sp)
63     return m_remote_platform_sp->GetModuleSpec(module_file_spec, arch,
64                                                module_spec);
65
66   return Platform::GetModuleSpec(module_file_spec, arch, module_spec);
67 }
68
69 lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions(
70     lldb_private::CommandInterpreter &interpreter) {
71   auto iter = m_options.find(&interpreter), end = m_options.end();
72   if (iter == end) {
73     std::unique_ptr<lldb_private::OptionGroupOptions> options(
74         new OptionGroupOptions());
75     options->Append(m_option_group_platform_rsync.get());
76     options->Append(m_option_group_platform_ssh.get());
77     options->Append(m_option_group_platform_caching.get());
78     m_options[&interpreter] = std::move(options);
79   }
80
81   return m_options.at(&interpreter).get();
82 }
83
84 bool PlatformPOSIX::IsConnected() const {
85   if (IsHost())
86     return true;
87   else if (m_remote_platform_sp)
88     return m_remote_platform_sp->IsConnected();
89   return false;
90 }
91
92 lldb_private::Status PlatformPOSIX::RunShellCommand(
93     const char *command, // Shouldn't be NULL
94     const FileSpec &
95         working_dir, // Pass empty FileSpec to use the current working directory
96     int *status_ptr, // Pass NULL if you don't want the process exit status
97     int *signo_ptr,  // Pass NULL if you don't want the signal that caused the
98                      // process to exit
99     std::string
100         *command_output, // Pass NULL if you don't want the command output
101     const Timeout<std::micro> &timeout) {
102   if (IsHost())
103     return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr,
104                                  command_output, timeout);
105   else {
106     if (m_remote_platform_sp)
107       return m_remote_platform_sp->RunShellCommand(
108           command, working_dir, status_ptr, signo_ptr, command_output, timeout);
109     else
110       return Status("unable to run a remote command without a platform");
111   }
112 }
113
114 Status
115 PlatformPOSIX::ResolveExecutable(const ModuleSpec &module_spec,
116                                  lldb::ModuleSP &exe_module_sp,
117                                  const FileSpecList *module_search_paths_ptr) {
118   Status error;
119   // Nothing special to do here, just use the actual file and architecture
120
121   char exe_path[PATH_MAX];
122   ModuleSpec resolved_module_spec(module_spec);
123
124   if (IsHost()) {
125     // If we have "ls" as the exe_file, resolve the executable location based
126     // on the current path variables
127     if (!FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec())) {
128       resolved_module_spec.GetFileSpec().GetPath(exe_path, sizeof(exe_path));
129       resolved_module_spec.GetFileSpec().SetFile(exe_path,
130                                                  FileSpec::Style::native);
131       FileSystem::Instance().Resolve(resolved_module_spec.GetFileSpec());
132     }
133
134     if (!FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()))
135       FileSystem::Instance().ResolveExecutableLocation(
136           resolved_module_spec.GetFileSpec());
137
138     // Resolve any executable within a bundle on MacOSX
139     Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
140
141     if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()))
142       error.Clear();
143     else {
144       const uint32_t permissions = FileSystem::Instance().GetPermissions(
145           resolved_module_spec.GetFileSpec());
146       if (permissions && (permissions & eFilePermissionsEveryoneR) == 0)
147         error.SetErrorStringWithFormat(
148             "executable '%s' is not readable",
149             resolved_module_spec.GetFileSpec().GetPath().c_str());
150       else
151         error.SetErrorStringWithFormat(
152             "unable to find executable for '%s'",
153             resolved_module_spec.GetFileSpec().GetPath().c_str());
154     }
155   } else {
156     if (m_remote_platform_sp) {
157       error =
158           GetCachedExecutable(resolved_module_spec, exe_module_sp,
159                               module_search_paths_ptr, *m_remote_platform_sp);
160     } else {
161       // We may connect to a process and use the provided executable (Don't use
162       // local $PATH).
163
164       // Resolve any executable within a bundle on MacOSX
165       Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
166
167       if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()))
168         error.Clear();
169       else
170         error.SetErrorStringWithFormat("the platform is not currently "
171                                        "connected, and '%s' doesn't exist in "
172                                        "the system root.",
173                                        exe_path);
174     }
175   }
176
177   if (error.Success()) {
178     if (resolved_module_spec.GetArchitecture().IsValid()) {
179       error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
180                                           module_search_paths_ptr, nullptr, nullptr);
181       if (error.Fail()) {
182         // If we failed, it may be because the vendor and os aren't known. If
183         // that is the case, try setting them to the host architecture and give
184         // it another try.
185         llvm::Triple &module_triple =
186             resolved_module_spec.GetArchitecture().GetTriple();
187         bool is_vendor_specified =
188             (module_triple.getVendor() != llvm::Triple::UnknownVendor);
189         bool is_os_specified =
190             (module_triple.getOS() != llvm::Triple::UnknownOS);
191         if (!is_vendor_specified || !is_os_specified) {
192           const llvm::Triple &host_triple =
193               HostInfo::GetArchitecture(HostInfo::eArchKindDefault).GetTriple();
194
195           if (!is_vendor_specified)
196             module_triple.setVendorName(host_triple.getVendorName());
197           if (!is_os_specified)
198             module_triple.setOSName(host_triple.getOSName());
199
200           error = ModuleList::GetSharedModule(resolved_module_spec,
201                                               exe_module_sp, module_search_paths_ptr, nullptr, nullptr);
202         }
203       }
204
205       // TODO find out why exe_module_sp might be NULL
206       if (error.Fail() || !exe_module_sp || !exe_module_sp->GetObjectFile()) {
207         exe_module_sp.reset();
208         error.SetErrorStringWithFormat(
209             "'%s' doesn't contain the architecture %s",
210             resolved_module_spec.GetFileSpec().GetPath().c_str(),
211             resolved_module_spec.GetArchitecture().GetArchitectureName());
212       }
213     } else {
214       // No valid architecture was specified, ask the platform for the
215       // architectures that we should be using (in the correct order) and see
216       // if we can find a match that way
217       StreamString arch_names;
218       for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
219                idx, resolved_module_spec.GetArchitecture());
220            ++idx) {
221         error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
222                                             module_search_paths_ptr, nullptr, nullptr);
223         // Did we find an executable using one of the
224         if (error.Success()) {
225           if (exe_module_sp && exe_module_sp->GetObjectFile())
226             break;
227           else
228             error.SetErrorToGenericError();
229         }
230
231         if (idx > 0)
232           arch_names.PutCString(", ");
233         arch_names.PutCString(
234             resolved_module_spec.GetArchitecture().GetArchitectureName());
235       }
236
237       if (error.Fail() || !exe_module_sp) {
238         if (FileSystem::Instance().Readable(
239                 resolved_module_spec.GetFileSpec())) {
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::Instance().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 FileSystem::Instance().Exists(file_spec);
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     m_os_version = m_remote_platform_sp->GetOSVersion();
657     return !m_os_version.empty();
658   }
659   return false;
660 }
661
662 bool PlatformPOSIX::GetRemoteOSBuildString(std::string &s) {
663   if (m_remote_platform_sp)
664     return m_remote_platform_sp->GetRemoteOSBuildString(s);
665   s.clear();
666   return false;
667 }
668
669 Environment PlatformPOSIX::GetEnvironment() {
670   if (IsRemote()) {
671     if (m_remote_platform_sp)
672       return m_remote_platform_sp->GetEnvironment();
673     return Environment();
674   }
675   return Host::GetEnvironment();
676 }
677
678 bool PlatformPOSIX::GetRemoteOSKernelDescription(std::string &s) {
679   if (m_remote_platform_sp)
680     return m_remote_platform_sp->GetRemoteOSKernelDescription(s);
681   s.clear();
682   return false;
683 }
684
685 // Remote Platform subclasses need to override this function
686 ArchSpec PlatformPOSIX::GetRemoteSystemArchitecture() {
687   if (m_remote_platform_sp)
688     return m_remote_platform_sp->GetRemoteSystemArchitecture();
689   return ArchSpec();
690 }
691
692 const char *PlatformPOSIX::GetHostname() {
693   if (IsHost())
694     return Platform::GetHostname();
695
696   if (m_remote_platform_sp)
697     return m_remote_platform_sp->GetHostname();
698   return NULL;
699 }
700
701 const char *PlatformPOSIX::GetUserName(uint32_t uid) {
702   // Check the cache in Platform in case we have already looked this uid up
703   const char *user_name = Platform::GetUserName(uid);
704   if (user_name)
705     return user_name;
706
707   if (IsRemote() && m_remote_platform_sp)
708     return m_remote_platform_sp->GetUserName(uid);
709   return NULL;
710 }
711
712 const char *PlatformPOSIX::GetGroupName(uint32_t gid) {
713   const char *group_name = Platform::GetGroupName(gid);
714   if (group_name)
715     return group_name;
716
717   if (IsRemote() && m_remote_platform_sp)
718     return m_remote_platform_sp->GetGroupName(gid);
719   return NULL;
720 }
721
722 Status PlatformPOSIX::ConnectRemote(Args &args) {
723   Status error;
724   if (IsHost()) {
725     error.SetErrorStringWithFormat(
726         "can't connect to the host platform '%s', always connected",
727         GetPluginName().GetCString());
728   } else {
729     if (!m_remote_platform_sp)
730       m_remote_platform_sp =
731           Platform::Create(ConstString("remote-gdb-server"), error);
732
733     if (m_remote_platform_sp && error.Success())
734       error = m_remote_platform_sp->ConnectRemote(args);
735     else
736       error.SetErrorString("failed to create a 'remote-gdb-server' platform");
737
738     if (error.Fail())
739       m_remote_platform_sp.reset();
740   }
741
742   if (error.Success() && m_remote_platform_sp) {
743     if (m_option_group_platform_rsync.get() &&
744         m_option_group_platform_ssh.get() &&
745         m_option_group_platform_caching.get()) {
746       if (m_option_group_platform_rsync->m_rsync) {
747         SetSupportsRSync(true);
748         SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str());
749         SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str());
750         SetIgnoresRemoteHostname(
751             m_option_group_platform_rsync->m_ignores_remote_hostname);
752       }
753       if (m_option_group_platform_ssh->m_ssh) {
754         SetSupportsSSH(true);
755         SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str());
756       }
757       SetLocalCacheDirectory(
758           m_option_group_platform_caching->m_cache_dir.c_str());
759     }
760   }
761
762   return error;
763 }
764
765 Status PlatformPOSIX::DisconnectRemote() {
766   Status error;
767
768   if (IsHost()) {
769     error.SetErrorStringWithFormat(
770         "can't disconnect from the host platform '%s', always connected",
771         GetPluginName().GetCString());
772   } else {
773     if (m_remote_platform_sp)
774       error = m_remote_platform_sp->DisconnectRemote();
775     else
776       error.SetErrorString("the platform is not currently connected");
777   }
778   return error;
779 }
780
781 Status PlatformPOSIX::LaunchProcess(ProcessLaunchInfo &launch_info) {
782   Status error;
783
784   if (IsHost()) {
785     error = Platform::LaunchProcess(launch_info);
786   } else {
787     if (m_remote_platform_sp)
788       error = m_remote_platform_sp->LaunchProcess(launch_info);
789     else
790       error.SetErrorString("the platform is not currently connected");
791   }
792   return error;
793 }
794
795 lldb_private::Status PlatformPOSIX::KillProcess(const lldb::pid_t pid) {
796   if (IsHost())
797     return Platform::KillProcess(pid);
798
799   if (m_remote_platform_sp)
800     return m_remote_platform_sp->KillProcess(pid);
801
802   return Status("the platform is not currently connected");
803 }
804
805 lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info,
806                                       Debugger &debugger, Target *target,
807                                       Status &error) {
808   lldb::ProcessSP process_sp;
809   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
810
811   if (IsHost()) {
812     if (target == NULL) {
813       TargetSP new_target_sp;
814
815       error = debugger.GetTargetList().CreateTarget(
816           debugger, "", "", eLoadDependentsNo, NULL, new_target_sp);
817       target = new_target_sp.get();
818       if (log)
819         log->Printf("PlatformPOSIX::%s created new target", __FUNCTION__);
820     } else {
821       error.Clear();
822       if (log)
823         log->Printf("PlatformPOSIX::%s target already existed, setting target",
824                     __FUNCTION__);
825     }
826
827     if (target && error.Success()) {
828       debugger.GetTargetList().SetSelectedTarget(target);
829       if (log) {
830         ModuleSP exe_module_sp = target->GetExecutableModule();
831         log->Printf("PlatformPOSIX::%s set selected target to %p %s",
832                     __FUNCTION__, (void *)target,
833                     exe_module_sp
834                         ? exe_module_sp->GetFileSpec().GetPath().c_str()
835                         : "<null>");
836       }
837
838       process_sp =
839           target->CreateProcess(attach_info.GetListenerForProcess(debugger),
840                                 attach_info.GetProcessPluginName(), NULL);
841
842       if (process_sp) {
843         ListenerSP listener_sp = attach_info.GetHijackListener();
844         if (listener_sp == nullptr) {
845           listener_sp =
846               Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
847           attach_info.SetHijackListener(listener_sp);
848         }
849         process_sp->HijackProcessEvents(listener_sp);
850         error = process_sp->Attach(attach_info);
851       }
852     }
853   } else {
854     if (m_remote_platform_sp)
855       process_sp =
856           m_remote_platform_sp->Attach(attach_info, debugger, target, error);
857     else
858       error.SetErrorString("the platform is not currently connected");
859   }
860   return process_sp;
861 }
862
863 lldb::ProcessSP
864 PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
865                             Target *target, // Can be NULL, if NULL create a new
866                                             // target, else use existing one
867                             Status &error) {
868   ProcessSP process_sp;
869
870   if (IsHost()) {
871     // We are going to hand this process off to debugserver which will be in
872     // charge of setting the exit status.  However, we still need to reap it
873     // from lldb. So, make sure we use a exit callback which does not set exit
874     // status.
875     const bool monitor_signals = false;
876     launch_info.SetMonitorProcessCallback(
877         &ProcessLaunchInfo::NoOpMonitorCallback, monitor_signals);
878     process_sp = Platform::DebugProcess(launch_info, debugger, target, error);
879   } else {
880     if (m_remote_platform_sp)
881       process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
882                                                       target, error);
883     else
884       error.SetErrorString("the platform is not currently connected");
885   }
886   return process_sp;
887 }
888
889 void PlatformPOSIX::CalculateTrapHandlerSymbolNames() {
890   m_trap_handlers.push_back(ConstString("_sigtramp"));
891 }
892
893 Status PlatformPOSIX::EvaluateLibdlExpression(
894     lldb_private::Process *process, const char *expr_cstr,
895     llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
896   DynamicLoader *loader = process->GetDynamicLoader();
897   if (loader) {
898     Status error = loader->CanLoadImage();
899     if (error.Fail())
900       return error;
901   }
902
903   ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread());
904   if (!thread_sp)
905     return Status("Selected thread isn't valid");
906
907   StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
908   if (!frame_sp)
909     return Status("Frame 0 isn't valid");
910
911   ExecutionContext exe_ctx;
912   frame_sp->CalculateExecutionContext(exe_ctx);
913   EvaluateExpressionOptions expr_options;
914   expr_options.SetUnwindOnError(true);
915   expr_options.SetIgnoreBreakpoints(true);
916   expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
917   expr_options.SetLanguage(eLanguageTypeC_plus_plus);
918   expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
919                                          // don't do the work to trap them.
920   expr_options.SetTimeout(std::chrono::seconds(2));
921
922   Status expr_error;
923   ExpressionResults result =
924       UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix,
925                                result_valobj_sp, expr_error);
926   if (result != eExpressionCompleted)
927     return expr_error;
928
929   if (result_valobj_sp->GetError().Fail())
930     return result_valobj_sp->GetError();
931   return Status();
932 }
933
934 std::unique_ptr<UtilityFunction>
935 PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx,
936                                             Status &error) {
937   // Remember to prepend this with the prefix from
938   // GetLibdlFunctionDeclarations. The returned values are all in
939   // __lldb_dlopen_result for consistency. The wrapper returns a void * but
940   // doesn't use it because UtilityFunctions don't work with void returns at
941   // present.
942   static const char *dlopen_wrapper_code = R"(
943   struct __lldb_dlopen_result {
944     void *image_ptr;
945     const char *error_str;
946   };
947   
948   extern void *memcpy(void *, const void *, size_t size);
949   extern size_t strlen(const char *);
950   
951
952   void * __lldb_dlopen_wrapper (const char *name, 
953                                 const char *path_strings,
954                                 char *buffer,
955                                 __lldb_dlopen_result *result_ptr)
956   {
957     // This is the case where the name is the full path:
958     if (!path_strings) {
959       result_ptr->image_ptr = dlopen(name, 2);
960       if (result_ptr->image_ptr)
961         result_ptr->error_str = nullptr;
962       return nullptr;
963     }
964     
965     // This is the case where we have a list of paths:
966     size_t name_len = strlen(name);
967     while (path_strings && path_strings[0] != '\0') {
968       size_t path_len = strlen(path_strings);
969       memcpy((void *) buffer, (void *) path_strings, path_len);
970       buffer[path_len] = '/';
971       char *target_ptr = buffer+path_len+1; 
972       memcpy((void *) target_ptr, (void *) name, name_len + 1);
973       result_ptr->image_ptr = dlopen(buffer, 2);
974       if (result_ptr->image_ptr) {
975         result_ptr->error_str = nullptr;
976         break;
977       }
978       result_ptr->error_str = dlerror();
979       path_strings = path_strings + path_len + 1;
980     }
981     return nullptr;
982   }
983   )";
984
985   static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
986   Process *process = exe_ctx.GetProcessSP().get();
987   // Insert the dlopen shim defines into our generic expression:
988   std::string expr(GetLibdlFunctionDeclarations(process));
989   expr.append(dlopen_wrapper_code);
990   Status utility_error;
991   DiagnosticManager diagnostics;
992   
993   std::unique_ptr<UtilityFunction> dlopen_utility_func_up(process
994       ->GetTarget().GetUtilityFunctionForLanguage(expr.c_str(),
995                                                   eLanguageTypeObjC,
996                                                   dlopen_wrapper_name,
997                                                   utility_error));
998   if (utility_error.Fail()) {
999     error.SetErrorStringWithFormat("dlopen error: could not make utility"
1000                                    "function: %s", utility_error.AsCString());
1001     return nullptr;
1002   }
1003   if (!dlopen_utility_func_up->Install(diagnostics, exe_ctx)) {
1004     error.SetErrorStringWithFormat("dlopen error: could not install utility"
1005                                    "function: %s", 
1006                                    diagnostics.GetString().c_str());
1007     return nullptr;
1008   }
1009
1010   Value value;
1011   ValueList arguments;
1012   FunctionCaller *do_dlopen_function = nullptr;
1013
1014   // Fetch the clang types we will need:
1015   ClangASTContext *ast = process->GetTarget().GetScratchClangASTContext();
1016
1017   CompilerType clang_void_pointer_type
1018       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
1019   CompilerType clang_char_pointer_type
1020         = ast->GetBasicType(eBasicTypeChar).GetPointerType();
1021
1022   // We are passing four arguments, the basename, the list of places to look,
1023   // a buffer big enough for all the path + name combos, and
1024   // a pointer to the storage we've made for the result:
1025   value.SetValueType(Value::eValueTypeScalar);
1026   value.SetCompilerType(clang_void_pointer_type);
1027   arguments.PushValue(value);
1028   value.SetCompilerType(clang_char_pointer_type);
1029   arguments.PushValue(value);
1030   arguments.PushValue(value);
1031   arguments.PushValue(value);
1032   
1033   do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
1034       clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
1035   if (utility_error.Fail()) {
1036     error.SetErrorStringWithFormat("dlopen error: could not make function"
1037                                    "caller: %s", utility_error.AsCString());
1038     return nullptr;
1039   }
1040   
1041   do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
1042   if (!do_dlopen_function) {
1043     error.SetErrorString("dlopen error: could not get function caller.");
1044     return nullptr;
1045   }
1046   
1047   // We made a good utility function, so cache it in the process:
1048   return dlopen_utility_func_up;
1049 }
1050
1051 uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process,
1052                                     const lldb_private::FileSpec &remote_file,
1053                                     const std::vector<std::string> *paths,
1054                                     lldb_private::Status &error,
1055                                     lldb_private::FileSpec *loaded_image) {
1056   if (loaded_image)
1057     loaded_image->Clear();
1058
1059   std::string path;
1060   path = remote_file.GetPath();
1061   
1062   ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
1063   if (!thread_sp) {
1064     error.SetErrorString("dlopen error: no thread available to call dlopen.");
1065     return LLDB_INVALID_IMAGE_TOKEN;
1066   }
1067   
1068   DiagnosticManager diagnostics;
1069   
1070   ExecutionContext exe_ctx;
1071   thread_sp->CalculateExecutionContext(exe_ctx);
1072
1073   Status utility_error;
1074   UtilityFunction *dlopen_utility_func;
1075   ValueList arguments;
1076   FunctionCaller *do_dlopen_function = nullptr;
1077
1078   // The UtilityFunction is held in the Process.  Platforms don't track the
1079   // lifespan of the Targets that use them, we can't put this in the Platform.
1080   dlopen_utility_func = process->GetLoadImageUtilityFunction(
1081       this, [&]() -> std::unique_ptr<UtilityFunction> {
1082         return MakeLoadImageUtilityFunction(exe_ctx, error);
1083       });
1084   // If we couldn't make it, the error will be in error, so we can exit here.
1085   if (!dlopen_utility_func)
1086     return LLDB_INVALID_IMAGE_TOKEN;
1087     
1088   do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
1089   if (!do_dlopen_function) {
1090     error.SetErrorString("dlopen error: could not get function caller.");
1091     return LLDB_INVALID_IMAGE_TOKEN;
1092   }
1093   arguments = do_dlopen_function->GetArgumentValues();
1094   
1095   // Now insert the path we are searching for and the result structure into the
1096   // target.
1097   uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
1098   size_t path_len = path.size() + 1;
1099   lldb::addr_t path_addr = process->AllocateMemory(path_len, 
1100                                                    permissions,
1101                                                    utility_error);
1102   if (path_addr == LLDB_INVALID_ADDRESS) {
1103     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1104                                     "for path: %s", utility_error.AsCString());
1105     return LLDB_INVALID_IMAGE_TOKEN;
1106   }
1107   
1108   // Make sure we deallocate the input string memory:
1109   CleanUp path_cleanup([process, path_addr] { 
1110       process->DeallocateMemory(path_addr); 
1111   });
1112   
1113   process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
1114   if (utility_error.Fail()) {
1115     error.SetErrorStringWithFormat("dlopen error: could not write path string:"
1116                                     " %s", utility_error.AsCString());
1117     return LLDB_INVALID_IMAGE_TOKEN;
1118   }
1119   
1120   // Make space for our return structure.  It is two pointers big: the token
1121   // and the error string.
1122   const uint32_t addr_size = process->GetAddressByteSize();
1123   lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
1124                                                       permissions,
1125                                                       utility_error);
1126   if (utility_error.Fail()) {
1127     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1128                                     "for path: %s", utility_error.AsCString());
1129     return LLDB_INVALID_IMAGE_TOKEN;
1130   }
1131   
1132   // Make sure we deallocate the result structure memory
1133   CleanUp return_cleanup([process, return_addr] {
1134       process->DeallocateMemory(return_addr);
1135   });
1136   
1137   // This will be the address of the storage for paths, if we are using them,
1138   // or nullptr to signal we aren't.
1139   lldb::addr_t path_array_addr = 0x0;
1140   llvm::Optional<CleanUp> path_array_cleanup;
1141
1142   // This is the address to a buffer large enough to hold the largest path
1143   // conjoined with the library name we're passing in.  This is a convenience 
1144   // to avoid having to call malloc in the dlopen function.
1145   lldb::addr_t buffer_addr = 0x0;
1146   llvm::Optional<CleanUp> buffer_cleanup;
1147   
1148   // Set the values into our args and write them to the target:
1149   if (paths != nullptr) {
1150     // First insert the paths into the target.  This is expected to be a 
1151     // continuous buffer with the strings laid out null terminated and
1152     // end to end with an empty string terminating the buffer.
1153     // We also compute the buffer's required size as we go.
1154     size_t buffer_size = 0;
1155     std::string path_array;
1156     for (auto path : *paths) {
1157       // Don't insert empty paths, they will make us abort the path
1158       // search prematurely.
1159       if (path.empty())
1160         continue;
1161       size_t path_size = path.size();
1162       path_array.append(path);
1163       path_array.push_back('\0');
1164       if (path_size > buffer_size)
1165         buffer_size = path_size;
1166     }
1167     path_array.push_back('\0');
1168     
1169     path_array_addr = process->AllocateMemory(path_array.size(), 
1170                                               permissions,
1171                                               utility_error);
1172     if (path_array_addr == LLDB_INVALID_ADDRESS) {
1173       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1174                                       "for path array: %s", 
1175                                       utility_error.AsCString());
1176       return LLDB_INVALID_IMAGE_TOKEN;
1177     }
1178     
1179     // Make sure we deallocate the paths array.
1180     path_array_cleanup.emplace([process, path_array_addr] { 
1181         process->DeallocateMemory(path_array_addr); 
1182     });
1183
1184     process->WriteMemory(path_array_addr, path_array.data(), 
1185                          path_array.size(), utility_error);
1186
1187     if (utility_error.Fail()) {
1188       error.SetErrorStringWithFormat("dlopen error: could not write path array:"
1189                                      " %s", utility_error.AsCString());
1190       return LLDB_INVALID_IMAGE_TOKEN;
1191     }
1192     // Now make spaces in the target for the buffer.  We need to add one for
1193     // the '/' that the utility function will insert and one for the '\0':
1194     buffer_size += path.size() + 2;
1195     
1196     buffer_addr = process->AllocateMemory(buffer_size, 
1197                                           permissions,
1198                                           utility_error);
1199     if (buffer_addr == LLDB_INVALID_ADDRESS) {
1200       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1201                                       "for buffer: %s", 
1202                                       utility_error.AsCString());
1203       return LLDB_INVALID_IMAGE_TOKEN;
1204     }
1205   
1206     // Make sure we deallocate the buffer memory:
1207     buffer_cleanup.emplace([process, buffer_addr] { 
1208         process->DeallocateMemory(buffer_addr); 
1209     });
1210   }
1211     
1212   arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
1213   arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
1214   arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
1215   arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
1216
1217   lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
1218   
1219   diagnostics.Clear();
1220   if (!do_dlopen_function->WriteFunctionArguments(exe_ctx, 
1221                                                  func_args_addr,
1222                                                  arguments,
1223                                                  diagnostics)) {
1224     error.SetErrorStringWithFormat("dlopen error: could not write function "
1225                                    "arguments: %s", 
1226                                    diagnostics.GetString().c_str());
1227     return LLDB_INVALID_IMAGE_TOKEN;
1228   }
1229   
1230   // Make sure we clean up the args structure.  We can't reuse it because the
1231   // Platform lives longer than the process and the Platforms don't get a
1232   // signal to clean up cached data when a process goes away.
1233   CleanUp args_cleanup([do_dlopen_function, &exe_ctx, func_args_addr] {
1234     do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
1235   });
1236   
1237   // Now run the caller:
1238   EvaluateExpressionOptions options;
1239   options.SetExecutionPolicy(eExecutionPolicyAlways);
1240   options.SetLanguage(eLanguageTypeC_plus_plus);
1241   options.SetIgnoreBreakpoints(true);
1242   options.SetUnwindOnError(true);
1243   options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
1244                                     // don't do the work to trap them.
1245   options.SetTimeout(std::chrono::seconds(2));
1246   options.SetIsForUtilityExpr(true);
1247
1248   Value return_value;
1249   // Fetch the clang types we will need:
1250   ClangASTContext *ast = process->GetTarget().GetScratchClangASTContext();
1251
1252   CompilerType clang_void_pointer_type
1253       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
1254
1255   return_value.SetCompilerType(clang_void_pointer_type);
1256   
1257   ExpressionResults results = do_dlopen_function->ExecuteFunction(
1258       exe_ctx, &func_args_addr, options, diagnostics, return_value);
1259   if (results != eExpressionCompleted) {
1260     error.SetErrorStringWithFormat("dlopen error: failed executing "
1261                                    "dlopen wrapper function: %s", 
1262                                    diagnostics.GetString().c_str());
1263     return LLDB_INVALID_IMAGE_TOKEN;
1264   }
1265   
1266   // Read the dlopen token from the return area:
1267   lldb::addr_t token = process->ReadPointerFromMemory(return_addr, 
1268                                                       utility_error);
1269   if (utility_error.Fail()) {
1270     error.SetErrorStringWithFormat("dlopen error: could not read the return "
1271                                     "struct: %s", utility_error.AsCString());
1272     return LLDB_INVALID_IMAGE_TOKEN;
1273   }
1274   
1275   // The dlopen succeeded!
1276   if (token != 0x0) {
1277     if (loaded_image && buffer_addr != 0x0)
1278     {
1279       // Capture the image which was loaded.  We leave it in the buffer on
1280       // exit from the dlopen function, so we can just read it from there:
1281       std::string name_string;
1282       process->ReadCStringFromMemory(buffer_addr, name_string, utility_error);
1283       if (utility_error.Success())
1284         loaded_image->SetFile(name_string, llvm::sys::path::Style::posix);
1285     }
1286     return process->AddImageToken(token);
1287   }
1288     
1289   // We got an error, lets read in the error string:
1290   std::string dlopen_error_str;
1291   lldb::addr_t error_addr 
1292     = process->ReadPointerFromMemory(return_addr + addr_size, utility_error);
1293   if (utility_error.Fail()) {
1294     error.SetErrorStringWithFormat("dlopen error: could not read error string: "
1295                                     "%s", utility_error.AsCString());
1296     return LLDB_INVALID_IMAGE_TOKEN;
1297   }
1298   
1299   size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size, 
1300                                                     dlopen_error_str, 
1301                                                     utility_error);
1302   if (utility_error.Success() && num_chars > 0)
1303     error.SetErrorStringWithFormat("dlopen error: %s",
1304                                    dlopen_error_str.c_str());
1305   else
1306     error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
1307
1308   return LLDB_INVALID_IMAGE_TOKEN;
1309 }
1310
1311 Status PlatformPOSIX::UnloadImage(lldb_private::Process *process,
1312                                   uint32_t image_token) {
1313   const addr_t image_addr = process->GetImagePtrFromToken(image_token);
1314   if (image_addr == LLDB_INVALID_ADDRESS)
1315     return Status("Invalid image token");
1316
1317   StreamString expr;
1318   expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
1319   llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
1320   lldb::ValueObjectSP result_valobj_sp;
1321   Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
1322                                          result_valobj_sp);
1323   if (error.Fail())
1324     return error;
1325
1326   if (result_valobj_sp->GetError().Fail())
1327     return result_valobj_sp->GetError();
1328
1329   Scalar scalar;
1330   if (result_valobj_sp->ResolveValue(scalar)) {
1331     if (scalar.UInt(1))
1332       return Status("expression failed: \"%s\"", expr.GetData());
1333     process->ResetImageToken(image_token);
1334   }
1335   return Status();
1336 }
1337
1338 lldb::ProcessSP PlatformPOSIX::ConnectProcess(llvm::StringRef connect_url,
1339                                               llvm::StringRef plugin_name,
1340                                               lldb_private::Debugger &debugger,
1341                                               lldb_private::Target *target,
1342                                               lldb_private::Status &error) {
1343   if (m_remote_platform_sp)
1344     return m_remote_platform_sp->ConnectProcess(connect_url, plugin_name,
1345                                                 debugger, target, error);
1346
1347   return Platform::ConnectProcess(connect_url, plugin_name, debugger, target,
1348                                   error);
1349 }
1350
1351 llvm::StringRef
1352 PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
1353   return R"(
1354               extern "C" void* dlopen(const char*, int);
1355               extern "C" void* dlsym(void*, const char*);
1356               extern "C" int   dlclose(void*);
1357               extern "C" char* dlerror(void);
1358              )";
1359 }
1360
1361 size_t PlatformPOSIX::ConnectToWaitingProcesses(Debugger &debugger,
1362                                                 Status &error) {
1363   if (m_remote_platform_sp)
1364     return m_remote_platform_sp->ConnectToWaitingProcesses(debugger, error);
1365   return Platform::ConnectToWaitingProcesses(debugger, error);
1366 }
1367
1368 ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) {
1369   if (basename.IsEmpty())
1370     return basename;
1371
1372   StreamString stream;
1373   stream.Printf("lib%s.so", basename.GetCString());
1374   return ConstString(stream.GetString());
1375 }