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