xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp (revision 4e1ee0786f11cc571bd0be17d38e46f635c719fc)
1 //===-- PlatformPOSIX.cpp -------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "PlatformPOSIX.h"
10 
11 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
12 #include "lldb/Core/Debugger.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/ValueObject.h"
15 #include "lldb/Expression/DiagnosticManager.h"
16 #include "lldb/Expression/FunctionCaller.h"
17 #include "lldb/Expression/UserExpression.h"
18 #include "lldb/Expression/UtilityFunction.h"
19 #include "lldb/Host/File.h"
20 #include "lldb/Host/FileCache.h"
21 #include "lldb/Host/FileSystem.h"
22 #include "lldb/Host/Host.h"
23 #include "lldb/Host/HostInfo.h"
24 #include "lldb/Host/ProcessLaunchInfo.h"
25 #include "lldb/Target/DynamicLoader.h"
26 #include "lldb/Target/ExecutionContext.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/Thread.h"
29 #include "lldb/Utility/DataBufferHeap.h"
30 #include "lldb/Utility/FileSpec.h"
31 #include "lldb/Utility/Log.h"
32 #include "lldb/Utility/StreamString.h"
33 #include "llvm/ADT/ScopeExit.h"
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 
38 /// Default Constructor
39 PlatformPOSIX::PlatformPOSIX(bool is_host)
40     : RemoteAwarePlatform(is_host), // This is the local host platform
41       m_option_group_platform_rsync(new OptionGroupPlatformRSync()),
42       m_option_group_platform_ssh(new OptionGroupPlatformSSH()),
43       m_option_group_platform_caching(new OptionGroupPlatformCaching()) {}
44 
45 /// Destructor.
46 ///
47 /// The destructor is virtual since this class is designed to be
48 /// inherited from by the plug-in instance.
49 PlatformPOSIX::~PlatformPOSIX() {}
50 
51 lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions(
52     lldb_private::CommandInterpreter &interpreter) {
53   auto iter = m_options.find(&interpreter), end = m_options.end();
54   if (iter == end) {
55     std::unique_ptr<lldb_private::OptionGroupOptions> options(
56         new OptionGroupOptions());
57     options->Append(m_option_group_platform_rsync.get());
58     options->Append(m_option_group_platform_ssh.get());
59     options->Append(m_option_group_platform_caching.get());
60     m_options[&interpreter] = std::move(options);
61   }
62 
63   return m_options.at(&interpreter).get();
64 }
65 
66 static uint32_t chown_file(Platform *platform, const char *path,
67                            uint32_t uid = UINT32_MAX,
68                            uint32_t gid = UINT32_MAX) {
69   if (!platform || !path || *path == 0)
70     return UINT32_MAX;
71 
72   if (uid == UINT32_MAX && gid == UINT32_MAX)
73     return 0; // pretend I did chown correctly - actually I just didn't care
74 
75   StreamString command;
76   command.PutCString("chown ");
77   if (uid != UINT32_MAX)
78     command.Printf("%d", uid);
79   if (gid != UINT32_MAX)
80     command.Printf(":%d", gid);
81   command.Printf("%s", path);
82   int status;
83   platform->RunShellCommand(command.GetData(), FileSpec(), &status, nullptr,
84                             nullptr, std::chrono::seconds(10));
85   return status;
86 }
87 
88 lldb_private::Status
89 PlatformPOSIX::PutFile(const lldb_private::FileSpec &source,
90                        const lldb_private::FileSpec &destination, uint32_t uid,
91                        uint32_t gid) {
92   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
93 
94   if (IsHost()) {
95     if (source == destination)
96       return Status();
97     // cp src dst
98     // chown uid:gid dst
99     std::string src_path(source.GetPath());
100     if (src_path.empty())
101       return Status("unable to get file path for source");
102     std::string dst_path(destination.GetPath());
103     if (dst_path.empty())
104       return Status("unable to get file path for destination");
105     StreamString command;
106     command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
107     int status;
108     RunShellCommand(command.GetData(), FileSpec(), &status, nullptr, nullptr,
109                     std::chrono::seconds(10));
110     if (status != 0)
111       return Status("unable to perform copy");
112     if (uid == UINT32_MAX && gid == UINT32_MAX)
113       return Status();
114     if (chown_file(this, dst_path.c_str(), uid, gid) != 0)
115       return Status("unable to perform chown");
116     return Status();
117   } else if (m_remote_platform_sp) {
118     if (GetSupportsRSync()) {
119       std::string src_path(source.GetPath());
120       if (src_path.empty())
121         return Status("unable to get file path for source");
122       std::string dst_path(destination.GetPath());
123       if (dst_path.empty())
124         return Status("unable to get file path for destination");
125       StreamString command;
126       if (GetIgnoresRemoteHostname()) {
127         if (!GetRSyncPrefix())
128           command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
129                          dst_path.c_str());
130         else
131           command.Printf("rsync %s %s %s%s", GetRSyncOpts(), src_path.c_str(),
132                          GetRSyncPrefix(), dst_path.c_str());
133       } else
134         command.Printf("rsync %s %s %s:%s", GetRSyncOpts(), src_path.c_str(),
135                        GetHostname(), dst_path.c_str());
136       LLDB_LOGF(log, "[PutFile] Running command: %s\n", command.GetData());
137       int retcode;
138       Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
139                             nullptr, std::chrono::minutes(1));
140       if (retcode == 0) {
141         // Don't chown a local file for a remote system
142         //                if (chown_file(this,dst_path.c_str(),uid,gid) != 0)
143         //                    return Status("unable to perform chown");
144         return Status();
145       }
146       // if we are still here rsync has failed - let's try the slow way before
147       // giving up
148     }
149   }
150   return Platform::PutFile(source, destination, uid, gid);
151 }
152 
153 lldb_private::Status PlatformPOSIX::GetFile(
154     const lldb_private::FileSpec &source,      // remote file path
155     const lldb_private::FileSpec &destination) // local file path
156 {
157   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
158 
159   // Check the args, first.
160   std::string src_path(source.GetPath());
161   if (src_path.empty())
162     return Status("unable to get file path for source");
163   std::string dst_path(destination.GetPath());
164   if (dst_path.empty())
165     return Status("unable to get file path for destination");
166   if (IsHost()) {
167     if (source == destination)
168       return Status("local scenario->source and destination are the same file "
169                     "path: no operation performed");
170     // cp src dst
171     StreamString cp_command;
172     cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
173     int status;
174     RunShellCommand(cp_command.GetData(), FileSpec(), &status, nullptr, nullptr,
175                     std::chrono::seconds(10));
176     if (status != 0)
177       return Status("unable to perform copy");
178     return Status();
179   } else if (m_remote_platform_sp) {
180     if (GetSupportsRSync()) {
181       StreamString command;
182       if (GetIgnoresRemoteHostname()) {
183         if (!GetRSyncPrefix())
184           command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
185                          dst_path.c_str());
186         else
187           command.Printf("rsync %s %s%s %s", GetRSyncOpts(), GetRSyncPrefix(),
188                          src_path.c_str(), dst_path.c_str());
189       } else
190         command.Printf("rsync %s %s:%s %s", GetRSyncOpts(),
191                        m_remote_platform_sp->GetHostname(), src_path.c_str(),
192                        dst_path.c_str());
193       LLDB_LOGF(log, "[GetFile] Running command: %s\n", command.GetData());
194       int retcode;
195       Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
196                             nullptr, std::chrono::minutes(1));
197       if (retcode == 0)
198         return Status();
199       // If we are here, rsync has failed - let's try the slow way before
200       // giving up
201     }
202     // open src and dst
203     // read/write, read/write, read/write, ...
204     // close src
205     // close dst
206     LLDB_LOGF(log, "[GetFile] Using block by block transfer....\n");
207     Status error;
208     user_id_t fd_src = OpenFile(source, File::eOpenOptionRead,
209                                 lldb::eFilePermissionsFileDefault, error);
210 
211     if (fd_src == UINT64_MAX)
212       return Status("unable to open source file");
213 
214     uint32_t permissions = 0;
215     error = GetFilePermissions(source, permissions);
216 
217     if (permissions == 0)
218       permissions = lldb::eFilePermissionsFileDefault;
219 
220     user_id_t fd_dst = FileCache::GetInstance().OpenFile(
221         destination, File::eOpenOptionCanCreate | File::eOpenOptionWrite |
222                          File::eOpenOptionTruncate,
223         permissions, error);
224 
225     if (fd_dst == UINT64_MAX) {
226       if (error.Success())
227         error.SetErrorString("unable to open destination file");
228     }
229 
230     if (error.Success()) {
231       lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
232       uint64_t offset = 0;
233       error.Clear();
234       while (error.Success()) {
235         const uint64_t n_read = ReadFile(fd_src, offset, buffer_sp->GetBytes(),
236                                          buffer_sp->GetByteSize(), error);
237         if (error.Fail())
238           break;
239         if (n_read == 0)
240           break;
241         if (FileCache::GetInstance().WriteFile(fd_dst, offset,
242                                                buffer_sp->GetBytes(), n_read,
243                                                error) != n_read) {
244           if (!error.Fail())
245             error.SetErrorString("unable to write to destination file");
246           break;
247         }
248         offset += n_read;
249       }
250     }
251     // Ignore the close error of src.
252     if (fd_src != UINT64_MAX)
253       CloseFile(fd_src, error);
254     // And close the dst file descriptot.
255     if (fd_dst != UINT64_MAX &&
256         !FileCache::GetInstance().CloseFile(fd_dst, error)) {
257       if (!error.Fail())
258         error.SetErrorString("unable to close destination file");
259     }
260     return error;
261   }
262   return Platform::GetFile(source, destination);
263 }
264 
265 std::string PlatformPOSIX::GetPlatformSpecificConnectionInformation() {
266   StreamString stream;
267   if (GetSupportsRSync()) {
268     stream.PutCString("rsync");
269     if ((GetRSyncOpts() && *GetRSyncOpts()) ||
270         (GetRSyncPrefix() && *GetRSyncPrefix()) || GetIgnoresRemoteHostname()) {
271       stream.Printf(", options: ");
272       if (GetRSyncOpts() && *GetRSyncOpts())
273         stream.Printf("'%s' ", GetRSyncOpts());
274       stream.Printf(", prefix: ");
275       if (GetRSyncPrefix() && *GetRSyncPrefix())
276         stream.Printf("'%s' ", GetRSyncPrefix());
277       if (GetIgnoresRemoteHostname())
278         stream.Printf("ignore remote-hostname ");
279     }
280   }
281   if (GetSupportsSSH()) {
282     stream.PutCString("ssh");
283     if (GetSSHOpts() && *GetSSHOpts())
284       stream.Printf(", options: '%s' ", GetSSHOpts());
285   }
286   if (GetLocalCacheDirectory() && *GetLocalCacheDirectory())
287     stream.Printf("cache dir: %s", GetLocalCacheDirectory());
288   if (stream.GetSize())
289     return std::string(stream.GetString());
290   else
291     return "";
292 }
293 
294 const lldb::UnixSignalsSP &PlatformPOSIX::GetRemoteUnixSignals() {
295   if (IsRemote() && m_remote_platform_sp)
296     return m_remote_platform_sp->GetRemoteUnixSignals();
297   return Platform::GetRemoteUnixSignals();
298 }
299 
300 Status PlatformPOSIX::ConnectRemote(Args &args) {
301   Status error;
302   if (IsHost()) {
303     error.SetErrorStringWithFormat(
304         "can't connect to the host platform '%s', always connected",
305         GetPluginName().GetCString());
306   } else {
307     if (!m_remote_platform_sp)
308       m_remote_platform_sp =
309           Platform::Create(ConstString("remote-gdb-server"), error);
310 
311     if (m_remote_platform_sp && error.Success())
312       error = m_remote_platform_sp->ConnectRemote(args);
313     else
314       error.SetErrorString("failed to create a 'remote-gdb-server' platform");
315 
316     if (error.Fail())
317       m_remote_platform_sp.reset();
318   }
319 
320   if (error.Success() && m_remote_platform_sp) {
321     if (m_option_group_platform_rsync.get() &&
322         m_option_group_platform_ssh.get() &&
323         m_option_group_platform_caching.get()) {
324       if (m_option_group_platform_rsync->m_rsync) {
325         SetSupportsRSync(true);
326         SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str());
327         SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str());
328         SetIgnoresRemoteHostname(
329             m_option_group_platform_rsync->m_ignores_remote_hostname);
330       }
331       if (m_option_group_platform_ssh->m_ssh) {
332         SetSupportsSSH(true);
333         SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str());
334       }
335       SetLocalCacheDirectory(
336           m_option_group_platform_caching->m_cache_dir.c_str());
337     }
338   }
339 
340   return error;
341 }
342 
343 Status PlatformPOSIX::DisconnectRemote() {
344   Status error;
345 
346   if (IsHost()) {
347     error.SetErrorStringWithFormat(
348         "can't disconnect from the host platform '%s', always connected",
349         GetPluginName().GetCString());
350   } else {
351     if (m_remote_platform_sp)
352       error = m_remote_platform_sp->DisconnectRemote();
353     else
354       error.SetErrorString("the platform is not currently connected");
355   }
356   return error;
357 }
358 
359 lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info,
360                                       Debugger &debugger, Target *target,
361                                       Status &error) {
362   lldb::ProcessSP process_sp;
363   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
364 
365   if (IsHost()) {
366     if (target == nullptr) {
367       TargetSP new_target_sp;
368 
369       error = debugger.GetTargetList().CreateTarget(
370           debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
371       target = new_target_sp.get();
372       LLDB_LOGF(log, "PlatformPOSIX::%s created new target", __FUNCTION__);
373     } else {
374       error.Clear();
375       LLDB_LOGF(log, "PlatformPOSIX::%s target already existed, setting target",
376                 __FUNCTION__);
377     }
378 
379     if (target && error.Success()) {
380       debugger.GetTargetList().SetSelectedTarget(target);
381       if (log) {
382         ModuleSP exe_module_sp = target->GetExecutableModule();
383         LLDB_LOGF(log, "PlatformPOSIX::%s set selected target to %p %s",
384                   __FUNCTION__, (void *)target,
385                   exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
386                                 : "<null>");
387       }
388 
389       process_sp =
390           target->CreateProcess(attach_info.GetListenerForProcess(debugger),
391                                 attach_info.GetProcessPluginName(), nullptr);
392 
393       if (process_sp) {
394         ListenerSP listener_sp = attach_info.GetHijackListener();
395         if (listener_sp == nullptr) {
396           listener_sp =
397               Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
398           attach_info.SetHijackListener(listener_sp);
399         }
400         process_sp->HijackProcessEvents(listener_sp);
401         error = process_sp->Attach(attach_info);
402       }
403     }
404   } else {
405     if (m_remote_platform_sp)
406       process_sp =
407           m_remote_platform_sp->Attach(attach_info, debugger, target, error);
408     else
409       error.SetErrorString("the platform is not currently connected");
410   }
411   return process_sp;
412 }
413 
414 lldb::ProcessSP
415 PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
416                             Target *target, // Can be NULL, if NULL create a new
417                                             // target, else use existing one
418                             Status &error) {
419   ProcessSP process_sp;
420 
421   if (IsHost()) {
422     // We are going to hand this process off to debugserver which will be in
423     // charge of setting the exit status.  However, we still need to reap it
424     // from lldb. So, make sure we use a exit callback which does not set exit
425     // status.
426     const bool monitor_signals = false;
427     launch_info.SetMonitorProcessCallback(
428         &ProcessLaunchInfo::NoOpMonitorCallback, monitor_signals);
429     process_sp = Platform::DebugProcess(launch_info, debugger, target, error);
430   } else {
431     if (m_remote_platform_sp)
432       process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
433                                                       target, error);
434     else
435       error.SetErrorString("the platform is not currently connected");
436   }
437   return process_sp;
438 }
439 
440 void PlatformPOSIX::CalculateTrapHandlerSymbolNames() {
441   m_trap_handlers.push_back(ConstString("_sigtramp"));
442 }
443 
444 Status PlatformPOSIX::EvaluateLibdlExpression(
445     lldb_private::Process *process, const char *expr_cstr,
446     llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
447   DynamicLoader *loader = process->GetDynamicLoader();
448   if (loader) {
449     Status error = loader->CanLoadImage();
450     if (error.Fail())
451       return error;
452   }
453 
454   ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread());
455   if (!thread_sp)
456     return Status("Selected thread isn't valid");
457 
458   StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
459   if (!frame_sp)
460     return Status("Frame 0 isn't valid");
461 
462   ExecutionContext exe_ctx;
463   frame_sp->CalculateExecutionContext(exe_ctx);
464   EvaluateExpressionOptions expr_options;
465   expr_options.SetUnwindOnError(true);
466   expr_options.SetIgnoreBreakpoints(true);
467   expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
468   expr_options.SetLanguage(eLanguageTypeC_plus_plus);
469   expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
470                                          // don't do the work to trap them.
471   expr_options.SetTimeout(process->GetUtilityExpressionTimeout());
472 
473   Status expr_error;
474   ExpressionResults result =
475       UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix,
476                                result_valobj_sp, expr_error);
477   if (result != eExpressionCompleted)
478     return expr_error;
479 
480   if (result_valobj_sp->GetError().Fail())
481     return result_valobj_sp->GetError();
482   return Status();
483 }
484 
485 std::unique_ptr<UtilityFunction>
486 PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx,
487                                             Status &error) {
488   // Remember to prepend this with the prefix from
489   // GetLibdlFunctionDeclarations. The returned values are all in
490   // __lldb_dlopen_result for consistency. The wrapper returns a void * but
491   // doesn't use it because UtilityFunctions don't work with void returns at
492   // present.
493   static const char *dlopen_wrapper_code = R"(
494   struct __lldb_dlopen_result {
495     void *image_ptr;
496     const char *error_str;
497   };
498 
499   extern void *memcpy(void *, const void *, size_t size);
500   extern size_t strlen(const char *);
501 
502 
503   void * __lldb_dlopen_wrapper (const char *name,
504                                 const char *path_strings,
505                                 char *buffer,
506                                 __lldb_dlopen_result *result_ptr)
507   {
508     // This is the case where the name is the full path:
509     if (!path_strings) {
510       result_ptr->image_ptr = dlopen(name, 2);
511       if (result_ptr->image_ptr)
512         result_ptr->error_str = nullptr;
513       return nullptr;
514     }
515 
516     // This is the case where we have a list of paths:
517     size_t name_len = strlen(name);
518     while (path_strings && path_strings[0] != '\0') {
519       size_t path_len = strlen(path_strings);
520       memcpy((void *) buffer, (void *) path_strings, path_len);
521       buffer[path_len] = '/';
522       char *target_ptr = buffer+path_len+1;
523       memcpy((void *) target_ptr, (void *) name, name_len + 1);
524       result_ptr->image_ptr = dlopen(buffer, 2);
525       if (result_ptr->image_ptr) {
526         result_ptr->error_str = nullptr;
527         break;
528       }
529       result_ptr->error_str = dlerror();
530       path_strings = path_strings + path_len + 1;
531     }
532     return nullptr;
533   }
534   )";
535 
536   static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
537   Process *process = exe_ctx.GetProcessSP().get();
538   // Insert the dlopen shim defines into our generic expression:
539   std::string expr(std::string(GetLibdlFunctionDeclarations(process)));
540   expr.append(dlopen_wrapper_code);
541   Status utility_error;
542   DiagnosticManager diagnostics;
543 
544   std::unique_ptr<UtilityFunction> dlopen_utility_func_up(process
545       ->GetTarget().GetUtilityFunctionForLanguage(expr.c_str(),
546                                                   eLanguageTypeObjC,
547                                                   dlopen_wrapper_name,
548                                                   utility_error));
549   if (utility_error.Fail()) {
550     error.SetErrorStringWithFormat("dlopen error: could not make utility"
551                                    "function: %s", utility_error.AsCString());
552     return nullptr;
553   }
554   if (!dlopen_utility_func_up->Install(diagnostics, exe_ctx)) {
555     error.SetErrorStringWithFormat("dlopen error: could not install utility"
556                                    "function: %s",
557                                    diagnostics.GetString().c_str());
558     return nullptr;
559   }
560 
561   Value value;
562   ValueList arguments;
563   FunctionCaller *do_dlopen_function = nullptr;
564 
565   // Fetch the clang types we will need:
566   TypeSystemClang *ast = TypeSystemClang::GetScratch(process->GetTarget());
567   if (!ast)
568     return nullptr;
569 
570   CompilerType clang_void_pointer_type
571       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
572   CompilerType clang_char_pointer_type
573         = ast->GetBasicType(eBasicTypeChar).GetPointerType();
574 
575   // We are passing four arguments, the basename, the list of places to look,
576   // a buffer big enough for all the path + name combos, and
577   // a pointer to the storage we've made for the result:
578   value.SetValueType(Value::eValueTypeScalar);
579   value.SetCompilerType(clang_void_pointer_type);
580   arguments.PushValue(value);
581   value.SetCompilerType(clang_char_pointer_type);
582   arguments.PushValue(value);
583   arguments.PushValue(value);
584   arguments.PushValue(value);
585 
586   do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
587       clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
588   if (utility_error.Fail()) {
589     error.SetErrorStringWithFormat("dlopen error: could not make function"
590                                    "caller: %s", utility_error.AsCString());
591     return nullptr;
592   }
593 
594   do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
595   if (!do_dlopen_function) {
596     error.SetErrorString("dlopen error: could not get function caller.");
597     return nullptr;
598   }
599 
600   // We made a good utility function, so cache it in the process:
601   return dlopen_utility_func_up;
602 }
603 
604 uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process,
605                                     const lldb_private::FileSpec &remote_file,
606                                     const std::vector<std::string> *paths,
607                                     lldb_private::Status &error,
608                                     lldb_private::FileSpec *loaded_image) {
609   if (loaded_image)
610     loaded_image->Clear();
611 
612   std::string path;
613   path = remote_file.GetPath();
614 
615   ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
616   if (!thread_sp) {
617     error.SetErrorString("dlopen error: no thread available to call dlopen.");
618     return LLDB_INVALID_IMAGE_TOKEN;
619   }
620 
621   DiagnosticManager diagnostics;
622 
623   ExecutionContext exe_ctx;
624   thread_sp->CalculateExecutionContext(exe_ctx);
625 
626   Status utility_error;
627   UtilityFunction *dlopen_utility_func;
628   ValueList arguments;
629   FunctionCaller *do_dlopen_function = nullptr;
630 
631   // The UtilityFunction is held in the Process.  Platforms don't track the
632   // lifespan of the Targets that use them, we can't put this in the Platform.
633   dlopen_utility_func = process->GetLoadImageUtilityFunction(
634       this, [&]() -> std::unique_ptr<UtilityFunction> {
635         return MakeLoadImageUtilityFunction(exe_ctx, error);
636       });
637   // If we couldn't make it, the error will be in error, so we can exit here.
638   if (!dlopen_utility_func)
639     return LLDB_INVALID_IMAGE_TOKEN;
640 
641   do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
642   if (!do_dlopen_function) {
643     error.SetErrorString("dlopen error: could not get function caller.");
644     return LLDB_INVALID_IMAGE_TOKEN;
645   }
646   arguments = do_dlopen_function->GetArgumentValues();
647 
648   // Now insert the path we are searching for and the result structure into the
649   // target.
650   uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
651   size_t path_len = path.size() + 1;
652   lldb::addr_t path_addr = process->AllocateMemory(path_len,
653                                                    permissions,
654                                                    utility_error);
655   if (path_addr == LLDB_INVALID_ADDRESS) {
656     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
657                                     "for path: %s", utility_error.AsCString());
658     return LLDB_INVALID_IMAGE_TOKEN;
659   }
660 
661   // Make sure we deallocate the input string memory:
662   auto path_cleanup = llvm::make_scope_exit([process, path_addr] {
663     // Deallocate the buffer.
664     process->DeallocateMemory(path_addr);
665   });
666 
667   process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
668   if (utility_error.Fail()) {
669     error.SetErrorStringWithFormat("dlopen error: could not write path string:"
670                                     " %s", utility_error.AsCString());
671     return LLDB_INVALID_IMAGE_TOKEN;
672   }
673 
674   // Make space for our return structure.  It is two pointers big: the token
675   // and the error string.
676   const uint32_t addr_size = process->GetAddressByteSize();
677   lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
678                                                       permissions,
679                                                       utility_error);
680   if (utility_error.Fail()) {
681     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
682                                     "for path: %s", utility_error.AsCString());
683     return LLDB_INVALID_IMAGE_TOKEN;
684   }
685 
686   // Make sure we deallocate the result structure memory
687   auto return_cleanup = llvm::make_scope_exit([process, return_addr] {
688     // Deallocate the buffer
689     process->DeallocateMemory(return_addr);
690   });
691 
692   // This will be the address of the storage for paths, if we are using them,
693   // or nullptr to signal we aren't.
694   lldb::addr_t path_array_addr = 0x0;
695   llvm::Optional<llvm::detail::scope_exit<std::function<void()>>>
696       path_array_cleanup;
697 
698   // This is the address to a buffer large enough to hold the largest path
699   // conjoined with the library name we're passing in.  This is a convenience
700   // to avoid having to call malloc in the dlopen function.
701   lldb::addr_t buffer_addr = 0x0;
702   llvm::Optional<llvm::detail::scope_exit<std::function<void()>>>
703       buffer_cleanup;
704 
705   // Set the values into our args and write them to the target:
706   if (paths != nullptr) {
707     // First insert the paths into the target.  This is expected to be a
708     // continuous buffer with the strings laid out null terminated and
709     // end to end with an empty string terminating the buffer.
710     // We also compute the buffer's required size as we go.
711     size_t buffer_size = 0;
712     std::string path_array;
713     for (auto path : *paths) {
714       // Don't insert empty paths, they will make us abort the path
715       // search prematurely.
716       if (path.empty())
717         continue;
718       size_t path_size = path.size();
719       path_array.append(path);
720       path_array.push_back('\0');
721       if (path_size > buffer_size)
722         buffer_size = path_size;
723     }
724     path_array.push_back('\0');
725 
726     path_array_addr = process->AllocateMemory(path_array.size(),
727                                               permissions,
728                                               utility_error);
729     if (path_array_addr == LLDB_INVALID_ADDRESS) {
730       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
731                                       "for path array: %s",
732                                       utility_error.AsCString());
733       return LLDB_INVALID_IMAGE_TOKEN;
734     }
735 
736     // Make sure we deallocate the paths array.
737     path_array_cleanup.emplace([process, path_array_addr]() {
738       // Deallocate the path array.
739       process->DeallocateMemory(path_array_addr);
740     });
741 
742     process->WriteMemory(path_array_addr, path_array.data(),
743                          path_array.size(), utility_error);
744 
745     if (utility_error.Fail()) {
746       error.SetErrorStringWithFormat("dlopen error: could not write path array:"
747                                      " %s", utility_error.AsCString());
748       return LLDB_INVALID_IMAGE_TOKEN;
749     }
750     // Now make spaces in the target for the buffer.  We need to add one for
751     // the '/' that the utility function will insert and one for the '\0':
752     buffer_size += path.size() + 2;
753 
754     buffer_addr = process->AllocateMemory(buffer_size,
755                                           permissions,
756                                           utility_error);
757     if (buffer_addr == LLDB_INVALID_ADDRESS) {
758       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
759                                       "for buffer: %s",
760                                       utility_error.AsCString());
761       return LLDB_INVALID_IMAGE_TOKEN;
762     }
763 
764     // Make sure we deallocate the buffer memory:
765     buffer_cleanup.emplace([process, buffer_addr]() {
766       // Deallocate the buffer.
767       process->DeallocateMemory(buffer_addr);
768     });
769   }
770 
771   arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
772   arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
773   arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
774   arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
775 
776   lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
777 
778   diagnostics.Clear();
779   if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
780                                                  func_args_addr,
781                                                  arguments,
782                                                  diagnostics)) {
783     error.SetErrorStringWithFormat("dlopen error: could not write function "
784                                    "arguments: %s",
785                                    diagnostics.GetString().c_str());
786     return LLDB_INVALID_IMAGE_TOKEN;
787   }
788 
789   // Make sure we clean up the args structure.  We can't reuse it because the
790   // Platform lives longer than the process and the Platforms don't get a
791   // signal to clean up cached data when a process goes away.
792   auto args_cleanup =
793       llvm::make_scope_exit([do_dlopen_function, &exe_ctx, func_args_addr] {
794         do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
795       });
796 
797   // Now run the caller:
798   EvaluateExpressionOptions options;
799   options.SetExecutionPolicy(eExecutionPolicyAlways);
800   options.SetLanguage(eLanguageTypeC_plus_plus);
801   options.SetIgnoreBreakpoints(true);
802   options.SetUnwindOnError(true);
803   options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
804                                     // don't do the work to trap them.
805   options.SetTimeout(process->GetUtilityExpressionTimeout());
806   options.SetIsForUtilityExpr(true);
807 
808   Value return_value;
809   // Fetch the clang types we will need:
810   TypeSystemClang *ast = TypeSystemClang::GetScratch(process->GetTarget());
811   if (!ast) {
812     error.SetErrorString("dlopen error: Unable to get TypeSystemClang");
813     return LLDB_INVALID_IMAGE_TOKEN;
814   }
815 
816   CompilerType clang_void_pointer_type
817       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
818 
819   return_value.SetCompilerType(clang_void_pointer_type);
820 
821   ExpressionResults results = do_dlopen_function->ExecuteFunction(
822       exe_ctx, &func_args_addr, options, diagnostics, return_value);
823   if (results != eExpressionCompleted) {
824     error.SetErrorStringWithFormat("dlopen error: failed executing "
825                                    "dlopen wrapper function: %s",
826                                    diagnostics.GetString().c_str());
827     return LLDB_INVALID_IMAGE_TOKEN;
828   }
829 
830   // Read the dlopen token from the return area:
831   lldb::addr_t token = process->ReadPointerFromMemory(return_addr,
832                                                       utility_error);
833   if (utility_error.Fail()) {
834     error.SetErrorStringWithFormat("dlopen error: could not read the return "
835                                     "struct: %s", utility_error.AsCString());
836     return LLDB_INVALID_IMAGE_TOKEN;
837   }
838 
839   // The dlopen succeeded!
840   if (token != 0x0) {
841     if (loaded_image && buffer_addr != 0x0)
842     {
843       // Capture the image which was loaded.  We leave it in the buffer on
844       // exit from the dlopen function, so we can just read it from there:
845       std::string name_string;
846       process->ReadCStringFromMemory(buffer_addr, name_string, utility_error);
847       if (utility_error.Success())
848         loaded_image->SetFile(name_string, llvm::sys::path::Style::posix);
849     }
850     return process->AddImageToken(token);
851   }
852 
853   // We got an error, lets read in the error string:
854   std::string dlopen_error_str;
855   lldb::addr_t error_addr
856     = process->ReadPointerFromMemory(return_addr + addr_size, utility_error);
857   if (utility_error.Fail()) {
858     error.SetErrorStringWithFormat("dlopen error: could not read error string: "
859                                     "%s", utility_error.AsCString());
860     return LLDB_INVALID_IMAGE_TOKEN;
861   }
862 
863   size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size,
864                                                     dlopen_error_str,
865                                                     utility_error);
866   if (utility_error.Success() && num_chars > 0)
867     error.SetErrorStringWithFormat("dlopen error: %s",
868                                    dlopen_error_str.c_str());
869   else
870     error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
871 
872   return LLDB_INVALID_IMAGE_TOKEN;
873 }
874 
875 Status PlatformPOSIX::UnloadImage(lldb_private::Process *process,
876                                   uint32_t image_token) {
877   const addr_t image_addr = process->GetImagePtrFromToken(image_token);
878   if (image_addr == LLDB_INVALID_ADDRESS)
879     return Status("Invalid image token");
880 
881   StreamString expr;
882   expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
883   llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
884   lldb::ValueObjectSP result_valobj_sp;
885   Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
886                                          result_valobj_sp);
887   if (error.Fail())
888     return error;
889 
890   if (result_valobj_sp->GetError().Fail())
891     return result_valobj_sp->GetError();
892 
893   Scalar scalar;
894   if (result_valobj_sp->ResolveValue(scalar)) {
895     if (scalar.UInt(1))
896       return Status("expression failed: \"%s\"", expr.GetData());
897     process->ResetImageToken(image_token);
898   }
899   return Status();
900 }
901 
902 llvm::StringRef
903 PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
904   return R"(
905               extern "C" void* dlopen(const char*, int);
906               extern "C" void* dlsym(void*, const char*);
907               extern "C" int   dlclose(void*);
908               extern "C" char* dlerror(void);
909              )";
910 }
911 
912 size_t PlatformPOSIX::ConnectToWaitingProcesses(Debugger &debugger,
913                                                 Status &error) {
914   if (m_remote_platform_sp)
915     return m_remote_platform_sp->ConnectToWaitingProcesses(debugger, error);
916   return Platform::ConnectToWaitingProcesses(debugger, error);
917 }
918 
919 ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) {
920   if (basename.IsEmpty())
921     return basename;
922 
923   StreamString stream;
924   stream.Printf("lib%s.so", basename.GetCString());
925   return ConstString(stream.GetString());
926 }
927