xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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() = default;
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::eOpenOptionReadOnly,
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::eOpenOptionWriteOnly |
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.SetErrorStringWithFormatv(
304         "can't connect to the host platform '{0}', always connected",
305         GetPluginName());
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.SetErrorStringWithFormatv(
348         "can't disconnect from the host platform '{0}', always connected",
349         GetPluginName());
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       if (log) {
381         ModuleSP exe_module_sp = target->GetExecutableModule();
382         LLDB_LOGF(log, "PlatformPOSIX::%s set selected target to %p %s",
383                   __FUNCTION__, (void *)target,
384                   exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
385                                 : "<null>");
386       }
387 
388       process_sp =
389           target->CreateProcess(attach_info.GetListenerForProcess(debugger),
390                                 "gdb-remote", nullptr, true);
391 
392       if (process_sp) {
393         ListenerSP listener_sp = attach_info.GetHijackListener();
394         if (listener_sp == nullptr) {
395           listener_sp =
396               Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
397           attach_info.SetHijackListener(listener_sp);
398         }
399         process_sp->HijackProcessEvents(listener_sp);
400         error = process_sp->Attach(attach_info);
401       }
402     }
403   } else {
404     if (m_remote_platform_sp)
405       process_sp =
406           m_remote_platform_sp->Attach(attach_info, debugger, target, error);
407     else
408       error.SetErrorString("the platform is not currently connected");
409   }
410   return process_sp;
411 }
412 
413 lldb::ProcessSP PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info,
414                                             Debugger &debugger, Target &target,
415                                             Status &error) {
416   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
417   LLDB_LOG(log, "target {0}", &target);
418 
419   ProcessSP process_sp;
420 
421   if (!IsHost()) {
422     if (m_remote_platform_sp)
423       process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
424                                                       target, error);
425     else
426       error.SetErrorString("the platform is not currently connected");
427     return process_sp;
428   }
429 
430   //
431   // For local debugging, we'll insist on having ProcessGDBRemote create the
432   // process.
433   //
434 
435   // Make sure we stop at the entry point
436   launch_info.GetFlags().Set(eLaunchFlagDebug);
437 
438   // We always launch the process we are going to debug in a separate process
439   // group, since then we can handle ^C interrupts ourselves w/o having to
440   // worry about the target getting them as well.
441   launch_info.SetLaunchInSeparateProcessGroup(true);
442 
443   // Now create the gdb-remote process.
444   LLDB_LOG(log, "having target create process with gdb-remote plugin");
445   process_sp =
446       target.CreateProcess(launch_info.GetListener(), "gdb-remote", nullptr,
447                             true);
448 
449   if (!process_sp) {
450     error.SetErrorString("CreateProcess() failed for gdb-remote process");
451     LLDB_LOG(log, "error: {0}", error);
452     return process_sp;
453   }
454 
455   LLDB_LOG(log, "successfully created process");
456   // Adjust launch for a hijacker.
457   ListenerSP listener_sp;
458   if (!launch_info.GetHijackListener()) {
459     LLDB_LOG(log, "setting up hijacker");
460     listener_sp =
461         Listener::MakeListener("lldb.PlatformLinux.DebugProcess.hijack");
462     launch_info.SetHijackListener(listener_sp);
463     process_sp->HijackProcessEvents(listener_sp);
464   }
465 
466   // Log file actions.
467   if (log) {
468     LLDB_LOG(log, "launching process with the following file actions:");
469     StreamString stream;
470     size_t i = 0;
471     const FileAction *file_action;
472     while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) {
473       file_action->Dump(stream);
474       LLDB_LOG(log, "{0}", stream.GetData());
475       stream.Clear();
476     }
477   }
478 
479   // Do the launch.
480   error = process_sp->Launch(launch_info);
481   if (error.Success()) {
482     // Handle the hijacking of process events.
483     if (listener_sp) {
484       const StateType state = process_sp->WaitForProcessToStop(
485           llvm::None, nullptr, false, listener_sp);
486 
487       LLDB_LOG(log, "pid {0} state {0}", process_sp->GetID(), state);
488     }
489 
490     // Hook up process PTY if we have one (which we should for local debugging
491     // with llgs).
492     int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
493     if (pty_fd != PseudoTerminal::invalid_fd) {
494       process_sp->SetSTDIOFileDescriptor(pty_fd);
495       LLDB_LOG(log, "hooked up STDIO pty to process");
496     } else
497       LLDB_LOG(log, "not using process STDIO pty");
498   } else {
499     LLDB_LOG(log, "{0}", error);
500     // FIXME figure out appropriate cleanup here. Do we delete the process?
501     // Does our caller do that?
502   }
503 
504   return process_sp;
505 }
506 
507 void PlatformPOSIX::CalculateTrapHandlerSymbolNames() {
508   m_trap_handlers.push_back(ConstString("_sigtramp"));
509 }
510 
511 Status PlatformPOSIX::EvaluateLibdlExpression(
512     lldb_private::Process *process, const char *expr_cstr,
513     llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
514   DynamicLoader *loader = process->GetDynamicLoader();
515   if (loader) {
516     Status error = loader->CanLoadImage();
517     if (error.Fail())
518       return error;
519   }
520 
521   ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread());
522   if (!thread_sp)
523     return Status("Selected thread isn't valid");
524 
525   StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
526   if (!frame_sp)
527     return Status("Frame 0 isn't valid");
528 
529   ExecutionContext exe_ctx;
530   frame_sp->CalculateExecutionContext(exe_ctx);
531   EvaluateExpressionOptions expr_options;
532   expr_options.SetUnwindOnError(true);
533   expr_options.SetIgnoreBreakpoints(true);
534   expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
535   expr_options.SetLanguage(eLanguageTypeC_plus_plus);
536   expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
537                                          // don't do the work to trap them.
538   expr_options.SetTimeout(process->GetUtilityExpressionTimeout());
539 
540   Status expr_error;
541   ExpressionResults result =
542       UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix,
543                                result_valobj_sp, expr_error);
544   if (result != eExpressionCompleted)
545     return expr_error;
546 
547   if (result_valobj_sp->GetError().Fail())
548     return result_valobj_sp->GetError();
549   return Status();
550 }
551 
552 std::unique_ptr<UtilityFunction>
553 PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx,
554                                             Status &error) {
555   // Remember to prepend this with the prefix from
556   // GetLibdlFunctionDeclarations. The returned values are all in
557   // __lldb_dlopen_result for consistency. The wrapper returns a void * but
558   // doesn't use it because UtilityFunctions don't work with void returns at
559   // present.
560   //
561   // Use lazy binding so as to not make dlopen()'s success conditional on
562   // forcing every symbol in the library.
563   //
564   // In general, the debugger should allow programs to load & run with
565   // libraries as far as they can, instead of defaulting to being super-picky
566   // about unavailable symbols.
567   //
568   // The value "1" appears to imply lazy binding (RTLD_LAZY) on both Darwin
569   // and other POSIX OSes.
570   static const char *dlopen_wrapper_code = R"(
571   const int RTLD_LAZY = 1;
572 
573   struct __lldb_dlopen_result {
574     void *image_ptr;
575     const char *error_str;
576   };
577 
578   extern void *memcpy(void *, const void *, size_t size);
579   extern size_t strlen(const char *);
580 
581 
582   void * __lldb_dlopen_wrapper (const char *name,
583                                 const char *path_strings,
584                                 char *buffer,
585                                 __lldb_dlopen_result *result_ptr)
586   {
587     // This is the case where the name is the full path:
588     if (!path_strings) {
589       result_ptr->image_ptr = dlopen(name, RTLD_LAZY);
590       if (result_ptr->image_ptr)
591         result_ptr->error_str = nullptr;
592       return nullptr;
593     }
594 
595     // This is the case where we have a list of paths:
596     size_t name_len = strlen(name);
597     while (path_strings && path_strings[0] != '\0') {
598       size_t path_len = strlen(path_strings);
599       memcpy((void *) buffer, (void *) path_strings, path_len);
600       buffer[path_len] = '/';
601       char *target_ptr = buffer+path_len+1;
602       memcpy((void *) target_ptr, (void *) name, name_len + 1);
603       result_ptr->image_ptr = dlopen(buffer, RTLD_LAZY);
604       if (result_ptr->image_ptr) {
605         result_ptr->error_str = nullptr;
606         break;
607       }
608       result_ptr->error_str = dlerror();
609       path_strings = path_strings + path_len + 1;
610     }
611     return nullptr;
612   }
613   )";
614 
615   static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
616   Process *process = exe_ctx.GetProcessSP().get();
617   // Insert the dlopen shim defines into our generic expression:
618   std::string expr(std::string(GetLibdlFunctionDeclarations(process)));
619   expr.append(dlopen_wrapper_code);
620   Status utility_error;
621   DiagnosticManager diagnostics;
622 
623   auto utility_fn_or_error = process->GetTarget().CreateUtilityFunction(
624       std::move(expr), dlopen_wrapper_name, eLanguageTypeObjC, exe_ctx);
625   if (!utility_fn_or_error) {
626     std::string error_str = llvm::toString(utility_fn_or_error.takeError());
627     error.SetErrorStringWithFormat("dlopen error: could not create utility"
628                                    "function: %s",
629                                    error_str.c_str());
630     return nullptr;
631   }
632   std::unique_ptr<UtilityFunction> dlopen_utility_func_up =
633       std::move(*utility_fn_or_error);
634 
635   Value value;
636   ValueList arguments;
637   FunctionCaller *do_dlopen_function = nullptr;
638 
639   // Fetch the clang types we will need:
640   TypeSystemClang *ast =
641       ScratchTypeSystemClang::GetForTarget(process->GetTarget());
642   if (!ast)
643     return nullptr;
644 
645   CompilerType clang_void_pointer_type
646       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
647   CompilerType clang_char_pointer_type
648         = ast->GetBasicType(eBasicTypeChar).GetPointerType();
649 
650   // We are passing four arguments, the basename, the list of places to look,
651   // a buffer big enough for all the path + name combos, and
652   // a pointer to the storage we've made for the result:
653   value.SetValueType(Value::ValueType::Scalar);
654   value.SetCompilerType(clang_void_pointer_type);
655   arguments.PushValue(value);
656   value.SetCompilerType(clang_char_pointer_type);
657   arguments.PushValue(value);
658   arguments.PushValue(value);
659   arguments.PushValue(value);
660 
661   do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
662       clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
663   if (utility_error.Fail()) {
664     error.SetErrorStringWithFormat("dlopen error: could not make function"
665                                    "caller: %s", utility_error.AsCString());
666     return nullptr;
667   }
668 
669   do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
670   if (!do_dlopen_function) {
671     error.SetErrorString("dlopen error: could not get function caller.");
672     return nullptr;
673   }
674 
675   // We made a good utility function, so cache it in the process:
676   return dlopen_utility_func_up;
677 }
678 
679 uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process,
680                                     const lldb_private::FileSpec &remote_file,
681                                     const std::vector<std::string> *paths,
682                                     lldb_private::Status &error,
683                                     lldb_private::FileSpec *loaded_image) {
684   if (loaded_image)
685     loaded_image->Clear();
686 
687   std::string path;
688   path = remote_file.GetPath();
689 
690   ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
691   if (!thread_sp) {
692     error.SetErrorString("dlopen error: no thread available to call dlopen.");
693     return LLDB_INVALID_IMAGE_TOKEN;
694   }
695 
696   DiagnosticManager diagnostics;
697 
698   ExecutionContext exe_ctx;
699   thread_sp->CalculateExecutionContext(exe_ctx);
700 
701   Status utility_error;
702   UtilityFunction *dlopen_utility_func;
703   ValueList arguments;
704   FunctionCaller *do_dlopen_function = nullptr;
705 
706   // The UtilityFunction is held in the Process.  Platforms don't track the
707   // lifespan of the Targets that use them, we can't put this in the Platform.
708   dlopen_utility_func = process->GetLoadImageUtilityFunction(
709       this, [&]() -> std::unique_ptr<UtilityFunction> {
710         return MakeLoadImageUtilityFunction(exe_ctx, error);
711       });
712   // If we couldn't make it, the error will be in error, so we can exit here.
713   if (!dlopen_utility_func)
714     return LLDB_INVALID_IMAGE_TOKEN;
715 
716   do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
717   if (!do_dlopen_function) {
718     error.SetErrorString("dlopen error: could not get function caller.");
719     return LLDB_INVALID_IMAGE_TOKEN;
720   }
721   arguments = do_dlopen_function->GetArgumentValues();
722 
723   // Now insert the path we are searching for and the result structure into the
724   // target.
725   uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
726   size_t path_len = path.size() + 1;
727   lldb::addr_t path_addr = process->AllocateMemory(path_len,
728                                                    permissions,
729                                                    utility_error);
730   if (path_addr == LLDB_INVALID_ADDRESS) {
731     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
732                                     "for path: %s", utility_error.AsCString());
733     return LLDB_INVALID_IMAGE_TOKEN;
734   }
735 
736   // Make sure we deallocate the input string memory:
737   auto path_cleanup = llvm::make_scope_exit([process, path_addr] {
738     // Deallocate the buffer.
739     process->DeallocateMemory(path_addr);
740   });
741 
742   process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
743   if (utility_error.Fail()) {
744     error.SetErrorStringWithFormat("dlopen error: could not write path string:"
745                                     " %s", utility_error.AsCString());
746     return LLDB_INVALID_IMAGE_TOKEN;
747   }
748 
749   // Make space for our return structure.  It is two pointers big: the token
750   // and the error string.
751   const uint32_t addr_size = process->GetAddressByteSize();
752   lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
753                                                       permissions,
754                                                       utility_error);
755   if (utility_error.Fail()) {
756     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
757                                     "for path: %s", utility_error.AsCString());
758     return LLDB_INVALID_IMAGE_TOKEN;
759   }
760 
761   // Make sure we deallocate the result structure memory
762   auto return_cleanup = llvm::make_scope_exit([process, return_addr] {
763     // Deallocate the buffer
764     process->DeallocateMemory(return_addr);
765   });
766 
767   // This will be the address of the storage for paths, if we are using them,
768   // or nullptr to signal we aren't.
769   lldb::addr_t path_array_addr = 0x0;
770   llvm::Optional<llvm::detail::scope_exit<std::function<void()>>>
771       path_array_cleanup;
772 
773   // This is the address to a buffer large enough to hold the largest path
774   // conjoined with the library name we're passing in.  This is a convenience
775   // to avoid having to call malloc in the dlopen function.
776   lldb::addr_t buffer_addr = 0x0;
777   llvm::Optional<llvm::detail::scope_exit<std::function<void()>>>
778       buffer_cleanup;
779 
780   // Set the values into our args and write them to the target:
781   if (paths != nullptr) {
782     // First insert the paths into the target.  This is expected to be a
783     // continuous buffer with the strings laid out null terminated and
784     // end to end with an empty string terminating the buffer.
785     // We also compute the buffer's required size as we go.
786     size_t buffer_size = 0;
787     std::string path_array;
788     for (auto path : *paths) {
789       // Don't insert empty paths, they will make us abort the path
790       // search prematurely.
791       if (path.empty())
792         continue;
793       size_t path_size = path.size();
794       path_array.append(path);
795       path_array.push_back('\0');
796       if (path_size > buffer_size)
797         buffer_size = path_size;
798     }
799     path_array.push_back('\0');
800 
801     path_array_addr = process->AllocateMemory(path_array.size(),
802                                               permissions,
803                                               utility_error);
804     if (path_array_addr == LLDB_INVALID_ADDRESS) {
805       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
806                                       "for path array: %s",
807                                       utility_error.AsCString());
808       return LLDB_INVALID_IMAGE_TOKEN;
809     }
810 
811     // Make sure we deallocate the paths array.
812     path_array_cleanup.emplace([process, path_array_addr]() {
813       // Deallocate the path array.
814       process->DeallocateMemory(path_array_addr);
815     });
816 
817     process->WriteMemory(path_array_addr, path_array.data(),
818                          path_array.size(), utility_error);
819 
820     if (utility_error.Fail()) {
821       error.SetErrorStringWithFormat("dlopen error: could not write path array:"
822                                      " %s", utility_error.AsCString());
823       return LLDB_INVALID_IMAGE_TOKEN;
824     }
825     // Now make spaces in the target for the buffer.  We need to add one for
826     // the '/' that the utility function will insert and one for the '\0':
827     buffer_size += path.size() + 2;
828 
829     buffer_addr = process->AllocateMemory(buffer_size,
830                                           permissions,
831                                           utility_error);
832     if (buffer_addr == LLDB_INVALID_ADDRESS) {
833       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
834                                       "for buffer: %s",
835                                       utility_error.AsCString());
836       return LLDB_INVALID_IMAGE_TOKEN;
837     }
838 
839     // Make sure we deallocate the buffer memory:
840     buffer_cleanup.emplace([process, buffer_addr]() {
841       // Deallocate the buffer.
842       process->DeallocateMemory(buffer_addr);
843     });
844   }
845 
846   arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
847   arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
848   arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
849   arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
850 
851   lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
852 
853   diagnostics.Clear();
854   if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
855                                                  func_args_addr,
856                                                  arguments,
857                                                  diagnostics)) {
858     error.SetErrorStringWithFormat("dlopen error: could not write function "
859                                    "arguments: %s",
860                                    diagnostics.GetString().c_str());
861     return LLDB_INVALID_IMAGE_TOKEN;
862   }
863 
864   // Make sure we clean up the args structure.  We can't reuse it because the
865   // Platform lives longer than the process and the Platforms don't get a
866   // signal to clean up cached data when a process goes away.
867   auto args_cleanup =
868       llvm::make_scope_exit([do_dlopen_function, &exe_ctx, func_args_addr] {
869         do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
870       });
871 
872   // Now run the caller:
873   EvaluateExpressionOptions options;
874   options.SetExecutionPolicy(eExecutionPolicyAlways);
875   options.SetLanguage(eLanguageTypeC_plus_plus);
876   options.SetIgnoreBreakpoints(true);
877   options.SetUnwindOnError(true);
878   options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
879                                     // don't do the work to trap them.
880   options.SetTimeout(process->GetUtilityExpressionTimeout());
881   options.SetIsForUtilityExpr(true);
882 
883   Value return_value;
884   // Fetch the clang types we will need:
885   TypeSystemClang *ast =
886       ScratchTypeSystemClang::GetForTarget(process->GetTarget());
887   if (!ast) {
888     error.SetErrorString("dlopen error: Unable to get TypeSystemClang");
889     return LLDB_INVALID_IMAGE_TOKEN;
890   }
891 
892   CompilerType clang_void_pointer_type
893       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
894 
895   return_value.SetCompilerType(clang_void_pointer_type);
896 
897   ExpressionResults results = do_dlopen_function->ExecuteFunction(
898       exe_ctx, &func_args_addr, options, diagnostics, return_value);
899   if (results != eExpressionCompleted) {
900     error.SetErrorStringWithFormat("dlopen error: failed executing "
901                                    "dlopen wrapper function: %s",
902                                    diagnostics.GetString().c_str());
903     return LLDB_INVALID_IMAGE_TOKEN;
904   }
905 
906   // Read the dlopen token from the return area:
907   lldb::addr_t token = process->ReadPointerFromMemory(return_addr,
908                                                       utility_error);
909   if (utility_error.Fail()) {
910     error.SetErrorStringWithFormat("dlopen error: could not read the return "
911                                     "struct: %s", utility_error.AsCString());
912     return LLDB_INVALID_IMAGE_TOKEN;
913   }
914 
915   // The dlopen succeeded!
916   if (token != 0x0) {
917     if (loaded_image && buffer_addr != 0x0)
918     {
919       // Capture the image which was loaded.  We leave it in the buffer on
920       // exit from the dlopen function, so we can just read it from there:
921       std::string name_string;
922       process->ReadCStringFromMemory(buffer_addr, name_string, utility_error);
923       if (utility_error.Success())
924         loaded_image->SetFile(name_string, llvm::sys::path::Style::posix);
925     }
926     return process->AddImageToken(token);
927   }
928 
929   // We got an error, lets read in the error string:
930   std::string dlopen_error_str;
931   lldb::addr_t error_addr
932     = process->ReadPointerFromMemory(return_addr + addr_size, utility_error);
933   if (utility_error.Fail()) {
934     error.SetErrorStringWithFormat("dlopen error: could not read error string: "
935                                     "%s", utility_error.AsCString());
936     return LLDB_INVALID_IMAGE_TOKEN;
937   }
938 
939   size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size,
940                                                     dlopen_error_str,
941                                                     utility_error);
942   if (utility_error.Success() && num_chars > 0)
943     error.SetErrorStringWithFormat("dlopen error: %s",
944                                    dlopen_error_str.c_str());
945   else
946     error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
947 
948   return LLDB_INVALID_IMAGE_TOKEN;
949 }
950 
951 Status PlatformPOSIX::UnloadImage(lldb_private::Process *process,
952                                   uint32_t image_token) {
953   const addr_t image_addr = process->GetImagePtrFromToken(image_token);
954   if (image_addr == LLDB_INVALID_ADDRESS)
955     return Status("Invalid image token");
956 
957   StreamString expr;
958   expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
959   llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
960   lldb::ValueObjectSP result_valobj_sp;
961   Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
962                                          result_valobj_sp);
963   if (error.Fail())
964     return error;
965 
966   if (result_valobj_sp->GetError().Fail())
967     return result_valobj_sp->GetError();
968 
969   Scalar scalar;
970   if (result_valobj_sp->ResolveValue(scalar)) {
971     if (scalar.UInt(1))
972       return Status("expression failed: \"%s\"", expr.GetData());
973     process->ResetImageToken(image_token);
974   }
975   return Status();
976 }
977 
978 llvm::StringRef
979 PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
980   return R"(
981               extern "C" void* dlopen(const char*, int);
982               extern "C" void* dlsym(void*, const char*);
983               extern "C" int   dlclose(void*);
984               extern "C" char* dlerror(void);
985              )";
986 }
987 
988 ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) {
989   if (basename.IsEmpty())
990     return basename;
991 
992   StreamString stream;
993   stream.Printf("lib%s.so", basename.GetCString());
994   return ConstString(stream.GetString());
995 }
996