180814287SRaphael Isemann //===-- PlatformPOSIX.cpp -------------------------------------------------===//
2e0f8f574SDaniel Malea //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e0f8f574SDaniel Malea //
7e0f8f574SDaniel Malea //===----------------------------------------------------------------------===//
8e0f8f574SDaniel Malea 
9e0f8f574SDaniel Malea #include "PlatformPOSIX.h"
10e0f8f574SDaniel Malea 
118be30215SAlex Langford #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
12348fb385STodd Fiala #include "lldb/Core/Debugger.h"
13348fb385STodd Fiala #include "lldb/Core/Module.h"
143cb132a0STamas Berghammer #include "lldb/Core/ValueObject.h"
151ecb34f4SJim Ingham #include "lldb/Expression/DiagnosticManager.h"
161ecb34f4SJim Ingham #include "lldb/Expression/FunctionCaller.h"
173cb132a0STamas Berghammer #include "lldb/Expression/UserExpression.h"
181ecb34f4SJim Ingham #include "lldb/Expression/UtilityFunction.h"
19e0f8f574SDaniel Malea #include "lldb/Host/File.h"
20c00cf4a0SZachary Turner #include "lldb/Host/FileCache.h"
21c00cf4a0SZachary Turner #include "lldb/Host/FileSystem.h"
22e0f8f574SDaniel Malea #include "lldb/Host/Host.h"
23fc89bbccSPavel Labath #include "lldb/Host/HostInfo.h"
24eef758e9SPavel Labath #include "lldb/Host/ProcessLaunchInfo.h"
253cb132a0STamas Berghammer #include "lldb/Target/DynamicLoader.h"
263cb132a0STamas Berghammer #include "lldb/Target/ExecutionContext.h"
27a78bd7ffSZachary Turner #include "lldb/Target/Process.h"
283cb132a0STamas Berghammer #include "lldb/Target/Thread.h"
29666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h"
305713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
316f9e6901SZachary Turner #include "lldb/Utility/Log.h"
32bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
33e0ea8d87SJonas Devlieghere #include "llvm/ADT/ScopeExit.h"
34e0f8f574SDaniel Malea 
35e0f8f574SDaniel Malea using namespace lldb;
36e0f8f574SDaniel Malea using namespace lldb_private;
37e0f8f574SDaniel Malea 
38e0f8f574SDaniel Malea /// Default Constructor
39b9c1b51eSKate Stone PlatformPOSIX::PlatformPOSIX(bool is_host)
4052d9c62aSPavel Labath     : RemoteAwarePlatform(is_host), // This is the local host platform
410a66e2f1SEnrico Granata       m_option_group_platform_rsync(new OptionGroupPlatformRSync()),
420a66e2f1SEnrico Granata       m_option_group_platform_ssh(new OptionGroupPlatformSSH()),
4352d9c62aSPavel Labath       m_option_group_platform_caching(new OptionGroupPlatformCaching()) {}
44e0f8f574SDaniel Malea 
45e0f8f574SDaniel Malea /// Destructor.
46e0f8f574SDaniel Malea ///
47e0f8f574SDaniel Malea /// The destructor is virtual since this class is designed to be
48e0f8f574SDaniel Malea /// inherited from by the plug-in instance.
49*fd2433e1SJonas Devlieghere PlatformPOSIX::~PlatformPOSIX() = default;
50e0f8f574SDaniel Malea 
51b9c1b51eSKate Stone lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions(
52b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
530a66e2f1SEnrico Granata   auto iter = m_options.find(&interpreter), end = m_options.end();
54b9c1b51eSKate Stone   if (iter == end) {
55b9c1b51eSKate Stone     std::unique_ptr<lldb_private::OptionGroupOptions> options(
56b9c1b51eSKate Stone         new OptionGroupOptions());
570a66e2f1SEnrico Granata     options->Append(m_option_group_platform_rsync.get());
580a66e2f1SEnrico Granata     options->Append(m_option_group_platform_ssh.get());
590a66e2f1SEnrico Granata     options->Append(m_option_group_platform_caching.get());
600a66e2f1SEnrico Granata     m_options[&interpreter] = std::move(options);
61e0f8f574SDaniel Malea   }
620a66e2f1SEnrico Granata 
630a66e2f1SEnrico Granata   return m_options.at(&interpreter).get();
64e0f8f574SDaniel Malea }
65e0f8f574SDaniel Malea 
66b9c1b51eSKate Stone static uint32_t chown_file(Platform *platform, const char *path,
67e0f8f574SDaniel Malea                            uint32_t uid = UINT32_MAX,
68b9c1b51eSKate Stone                            uint32_t gid = UINT32_MAX) {
69e0f8f574SDaniel Malea   if (!platform || !path || *path == 0)
70e0f8f574SDaniel Malea     return UINT32_MAX;
71e0f8f574SDaniel Malea 
72e0f8f574SDaniel Malea   if (uid == UINT32_MAX && gid == UINT32_MAX)
73e0f8f574SDaniel Malea     return 0; // pretend I did chown correctly - actually I just didn't care
74e0f8f574SDaniel Malea 
75e0f8f574SDaniel Malea   StreamString command;
76e0f8f574SDaniel Malea   command.PutCString("chown ");
77e0f8f574SDaniel Malea   if (uid != UINT32_MAX)
78e0f8f574SDaniel Malea     command.Printf("%d", uid);
79e0f8f574SDaniel Malea   if (gid != UINT32_MAX)
80e0f8f574SDaniel Malea     command.Printf(":%d", gid);
81e0f8f574SDaniel Malea   command.Printf("%s", path);
82e0f8f574SDaniel Malea   int status;
8328e4942bSPavel Labath   platform->RunShellCommand(command.GetData(), FileSpec(), &status, nullptr,
84248a1305SKonrad Kleine                             nullptr, std::chrono::seconds(10));
85e0f8f574SDaniel Malea   return status;
86e0f8f574SDaniel Malea }
87e0f8f574SDaniel Malea 
8897206d57SZachary Turner lldb_private::Status
89e0f8f574SDaniel Malea PlatformPOSIX::PutFile(const lldb_private::FileSpec &source,
90b9c1b51eSKate Stone                        const lldb_private::FileSpec &destination, uint32_t uid,
91b9c1b51eSKate Stone                        uint32_t gid) {
92fbb76349SGreg Clayton   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
93fbb76349SGreg Clayton 
94b9c1b51eSKate Stone   if (IsHost()) {
95532290e6SPavel Labath     if (source == destination)
9697206d57SZachary Turner       return Status();
97e0f8f574SDaniel Malea     // cp src dst
98e0f8f574SDaniel Malea     // chown uid:gid dst
99e0f8f574SDaniel Malea     std::string src_path(source.GetPath());
100e0f8f574SDaniel Malea     if (src_path.empty())
10197206d57SZachary Turner       return Status("unable to get file path for source");
102e0f8f574SDaniel Malea     std::string dst_path(destination.GetPath());
103e0f8f574SDaniel Malea     if (dst_path.empty())
10497206d57SZachary Turner       return Status("unable to get file path for destination");
105e0f8f574SDaniel Malea     StreamString command;
106e0f8f574SDaniel Malea     command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
107e0f8f574SDaniel Malea     int status;
10828e4942bSPavel Labath     RunShellCommand(command.GetData(), FileSpec(), &status, nullptr, nullptr,
10919dd1a0eSPavel Labath                     std::chrono::seconds(10));
110e0f8f574SDaniel Malea     if (status != 0)
11197206d57SZachary Turner       return Status("unable to perform copy");
112e0f8f574SDaniel Malea     if (uid == UINT32_MAX && gid == UINT32_MAX)
11397206d57SZachary Turner       return Status();
114e0f8f574SDaniel Malea     if (chown_file(this, dst_path.c_str(), uid, gid) != 0)
11597206d57SZachary Turner       return Status("unable to perform chown");
11697206d57SZachary Turner     return Status();
117b9c1b51eSKate Stone   } else if (m_remote_platform_sp) {
118b9c1b51eSKate Stone     if (GetSupportsRSync()) {
119e0f8f574SDaniel Malea       std::string src_path(source.GetPath());
120e0f8f574SDaniel Malea       if (src_path.empty())
12197206d57SZachary Turner         return Status("unable to get file path for source");
122e0f8f574SDaniel Malea       std::string dst_path(destination.GetPath());
123e0f8f574SDaniel Malea       if (dst_path.empty())
12497206d57SZachary Turner         return Status("unable to get file path for destination");
125e0f8f574SDaniel Malea       StreamString command;
126b9c1b51eSKate Stone       if (GetIgnoresRemoteHostname()) {
127e0f8f574SDaniel Malea         if (!GetRSyncPrefix())
128b9c1b51eSKate Stone           command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
129e0f8f574SDaniel Malea                          dst_path.c_str());
130e0f8f574SDaniel Malea         else
131b9c1b51eSKate Stone           command.Printf("rsync %s %s %s%s", GetRSyncOpts(), src_path.c_str(),
132b9c1b51eSKate Stone                          GetRSyncPrefix(), dst_path.c_str());
133b9c1b51eSKate Stone       } else
134b9c1b51eSKate Stone         command.Printf("rsync %s %s %s:%s", GetRSyncOpts(), src_path.c_str(),
135b9c1b51eSKate Stone                        GetHostname(), dst_path.c_str());
13663e5fb76SJonas Devlieghere       LLDB_LOGF(log, "[PutFile] Running command: %s\n", command.GetData());
137e0f8f574SDaniel Malea       int retcode;
13828e4942bSPavel Labath       Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
139248a1305SKonrad Kleine                             nullptr, std::chrono::minutes(1));
140b9c1b51eSKate Stone       if (retcode == 0) {
141e0f8f574SDaniel Malea         // Don't chown a local file for a remote system
142e0f8f574SDaniel Malea         //                if (chown_file(this,dst_path.c_str(),uid,gid) != 0)
14397206d57SZachary Turner         //                    return Status("unable to perform chown");
14497206d57SZachary Turner         return Status();
145e0f8f574SDaniel Malea       }
146b9c1b51eSKate Stone       // if we are still here rsync has failed - let's try the slow way before
147b9c1b51eSKate Stone       // giving up
148e0f8f574SDaniel Malea     }
149e0f8f574SDaniel Malea   }
150e0f8f574SDaniel Malea   return Platform::PutFile(source, destination, uid, gid);
151e0f8f574SDaniel Malea }
152e0f8f574SDaniel Malea 
15397206d57SZachary Turner lldb_private::Status PlatformPOSIX::GetFile(
154b9c1b51eSKate Stone     const lldb_private::FileSpec &source,      // remote file path
155d3173f34SChaoren Lin     const lldb_private::FileSpec &destination) // local file path
156e0f8f574SDaniel Malea {
157fbb76349SGreg Clayton   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
158fbb76349SGreg Clayton 
159e0f8f574SDaniel Malea   // Check the args, first.
160e0f8f574SDaniel Malea   std::string src_path(source.GetPath());
161e0f8f574SDaniel Malea   if (src_path.empty())
16297206d57SZachary Turner     return Status("unable to get file path for source");
163e0f8f574SDaniel Malea   std::string dst_path(destination.GetPath());
164e0f8f574SDaniel Malea   if (dst_path.empty())
16597206d57SZachary Turner     return Status("unable to get file path for destination");
166b9c1b51eSKate Stone   if (IsHost()) {
167532290e6SPavel Labath     if (source == destination)
16897206d57SZachary Turner       return Status("local scenario->source and destination are the same file "
169b9c1b51eSKate Stone                     "path: no operation performed");
170e0f8f574SDaniel Malea     // cp src dst
171e0f8f574SDaniel Malea     StreamString cp_command;
172e0f8f574SDaniel Malea     cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
173e0f8f574SDaniel Malea     int status;
17428e4942bSPavel Labath     RunShellCommand(cp_command.GetData(), FileSpec(), &status, nullptr, nullptr,
17519dd1a0eSPavel Labath                     std::chrono::seconds(10));
176e0f8f574SDaniel Malea     if (status != 0)
17797206d57SZachary Turner       return Status("unable to perform copy");
17897206d57SZachary Turner     return Status();
179b9c1b51eSKate Stone   } else if (m_remote_platform_sp) {
180b9c1b51eSKate Stone     if (GetSupportsRSync()) {
181e0f8f574SDaniel Malea       StreamString command;
182b9c1b51eSKate Stone       if (GetIgnoresRemoteHostname()) {
183e0f8f574SDaniel Malea         if (!GetRSyncPrefix())
184b9c1b51eSKate Stone           command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
185e0f8f574SDaniel Malea                          dst_path.c_str());
186e0f8f574SDaniel Malea         else
187b9c1b51eSKate Stone           command.Printf("rsync %s %s%s %s", GetRSyncOpts(), GetRSyncPrefix(),
188b9c1b51eSKate Stone                          src_path.c_str(), dst_path.c_str());
189b9c1b51eSKate Stone       } else
190b9c1b51eSKate Stone         command.Printf("rsync %s %s:%s %s", GetRSyncOpts(),
191b9c1b51eSKate Stone                        m_remote_platform_sp->GetHostname(), src_path.c_str(),
192e0f8f574SDaniel Malea                        dst_path.c_str());
19363e5fb76SJonas Devlieghere       LLDB_LOGF(log, "[GetFile] Running command: %s\n", command.GetData());
194e0f8f574SDaniel Malea       int retcode;
19528e4942bSPavel Labath       Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
196248a1305SKonrad Kleine                             nullptr, std::chrono::minutes(1));
197e0f8f574SDaniel Malea       if (retcode == 0)
19897206d57SZachary Turner         return Status();
19905097246SAdrian Prantl       // If we are here, rsync has failed - let's try the slow way before
20005097246SAdrian Prantl       // giving up
201e0f8f574SDaniel Malea     }
202e0f8f574SDaniel Malea     // open src and dst
203e0f8f574SDaniel Malea     // read/write, read/write, read/write, ...
204e0f8f574SDaniel Malea     // close src
205e0f8f574SDaniel Malea     // close dst
20663e5fb76SJonas Devlieghere     LLDB_LOGF(log, "[GetFile] Using block by block transfer....\n");
20797206d57SZachary Turner     Status error;
208b9c1b51eSKate Stone     user_id_t fd_src = OpenFile(source, File::eOpenOptionRead,
209b9c1b51eSKate Stone                                 lldb::eFilePermissionsFileDefault, error);
210e0f8f574SDaniel Malea 
211e0f8f574SDaniel Malea     if (fd_src == UINT64_MAX)
21297206d57SZachary Turner       return Status("unable to open source file");
213e0f8f574SDaniel Malea 
214fbb76349SGreg Clayton     uint32_t permissions = 0;
215d3173f34SChaoren Lin     error = GetFilePermissions(source, permissions);
216e0f8f574SDaniel Malea 
217e0f8f574SDaniel Malea     if (permissions == 0)
218fbb76349SGreg Clayton       permissions = lldb::eFilePermissionsFileDefault;
219e0f8f574SDaniel Malea 
220c00cf4a0SZachary Turner     user_id_t fd_dst = FileCache::GetInstance().OpenFile(
221b9c1b51eSKate Stone         destination, File::eOpenOptionCanCreate | File::eOpenOptionWrite |
222b9c1b51eSKate Stone                          File::eOpenOptionTruncate,
223b9c1b51eSKate Stone         permissions, error);
224e0f8f574SDaniel Malea 
225b9c1b51eSKate Stone     if (fd_dst == UINT64_MAX) {
226e0f8f574SDaniel Malea       if (error.Success())
227e0f8f574SDaniel Malea         error.SetErrorString("unable to open destination file");
228e0f8f574SDaniel Malea     }
229e0f8f574SDaniel Malea 
230b9c1b51eSKate Stone     if (error.Success()) {
231e0f8f574SDaniel Malea       lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
232e0f8f574SDaniel Malea       uint64_t offset = 0;
233e0f8f574SDaniel Malea       error.Clear();
234b9c1b51eSKate Stone       while (error.Success()) {
235b9c1b51eSKate Stone         const uint64_t n_read = ReadFile(fd_src, offset, buffer_sp->GetBytes(),
236b9c1b51eSKate Stone                                          buffer_sp->GetByteSize(), error);
237e0f8f574SDaniel Malea         if (error.Fail())
238e0f8f574SDaniel Malea           break;
239e0f8f574SDaniel Malea         if (n_read == 0)
240e0f8f574SDaniel Malea           break;
241b9c1b51eSKate Stone         if (FileCache::GetInstance().WriteFile(fd_dst, offset,
242b9c1b51eSKate Stone                                                buffer_sp->GetBytes(), n_read,
243b9c1b51eSKate Stone                                                error) != n_read) {
244e0f8f574SDaniel Malea           if (!error.Fail())
245e0f8f574SDaniel Malea             error.SetErrorString("unable to write to destination file");
246e0f8f574SDaniel Malea           break;
247e0f8f574SDaniel Malea         }
248e0f8f574SDaniel Malea         offset += n_read;
249e0f8f574SDaniel Malea       }
250e0f8f574SDaniel Malea     }
251e0f8f574SDaniel Malea     // Ignore the close error of src.
252e0f8f574SDaniel Malea     if (fd_src != UINT64_MAX)
253e0f8f574SDaniel Malea       CloseFile(fd_src, error);
254e0f8f574SDaniel Malea     // And close the dst file descriptot.
255b9c1b51eSKate Stone     if (fd_dst != UINT64_MAX &&
256b9c1b51eSKate Stone         !FileCache::GetInstance().CloseFile(fd_dst, error)) {
257e0f8f574SDaniel Malea       if (!error.Fail())
258e0f8f574SDaniel Malea         error.SetErrorString("unable to close destination file");
259e0f8f574SDaniel Malea     }
260e0f8f574SDaniel Malea     return error;
261e0f8f574SDaniel Malea   }
262e0f8f574SDaniel Malea   return Platform::GetFile(source, destination);
263e0f8f574SDaniel Malea }
264e0f8f574SDaniel Malea 
265b9c1b51eSKate Stone std::string PlatformPOSIX::GetPlatformSpecificConnectionInformation() {
266e0f8f574SDaniel Malea   StreamString stream;
267b9c1b51eSKate Stone   if (GetSupportsRSync()) {
268e0f8f574SDaniel Malea     stream.PutCString("rsync");
269e0f8f574SDaniel Malea     if ((GetRSyncOpts() && *GetRSyncOpts()) ||
270b9c1b51eSKate Stone         (GetRSyncPrefix() && *GetRSyncPrefix()) || GetIgnoresRemoteHostname()) {
271e0f8f574SDaniel Malea       stream.Printf(", options: ");
272e0f8f574SDaniel Malea       if (GetRSyncOpts() && *GetRSyncOpts())
273e0f8f574SDaniel Malea         stream.Printf("'%s' ", GetRSyncOpts());
274e0f8f574SDaniel Malea       stream.Printf(", prefix: ");
275e0f8f574SDaniel Malea       if (GetRSyncPrefix() && *GetRSyncPrefix())
276e0f8f574SDaniel Malea         stream.Printf("'%s' ", GetRSyncPrefix());
277e0f8f574SDaniel Malea       if (GetIgnoresRemoteHostname())
278e0f8f574SDaniel Malea         stream.Printf("ignore remote-hostname ");
279e0f8f574SDaniel Malea     }
280e0f8f574SDaniel Malea   }
281b9c1b51eSKate Stone   if (GetSupportsSSH()) {
282e0f8f574SDaniel Malea     stream.PutCString("ssh");
283e0f8f574SDaniel Malea     if (GetSSHOpts() && *GetSSHOpts())
284e0f8f574SDaniel Malea       stream.Printf(", options: '%s' ", GetSSHOpts());
285e0f8f574SDaniel Malea   }
286e0f8f574SDaniel Malea   if (GetLocalCacheDirectory() && *GetLocalCacheDirectory())
287e0f8f574SDaniel Malea     stream.Printf("cache dir: %s", GetLocalCacheDirectory());
288e0f8f574SDaniel Malea   if (stream.GetSize())
289adcd0268SBenjamin Kramer     return std::string(stream.GetString());
290e0f8f574SDaniel Malea   else
291e0f8f574SDaniel Malea     return "";
292e0f8f574SDaniel Malea }
293e0f8f574SDaniel Malea 
294b9c1b51eSKate Stone const lldb::UnixSignalsSP &PlatformPOSIX::GetRemoteUnixSignals() {
29598d0a4b3SChaoren Lin   if (IsRemote() && m_remote_platform_sp)
29698d0a4b3SChaoren Lin     return m_remote_platform_sp->GetRemoteUnixSignals();
29798d0a4b3SChaoren Lin   return Platform::GetRemoteUnixSignals();
29898d0a4b3SChaoren Lin }
29998d0a4b3SChaoren Lin 
30097206d57SZachary Turner Status PlatformPOSIX::ConnectRemote(Args &args) {
30197206d57SZachary Turner   Status error;
302b9c1b51eSKate Stone   if (IsHost()) {
303b9c1b51eSKate Stone     error.SetErrorStringWithFormat(
304b9c1b51eSKate Stone         "can't connect to the host platform '%s', always connected",
305b9c1b51eSKate Stone         GetPluginName().GetCString());
306b9c1b51eSKate Stone   } else {
307015d818bSTodd Fiala     if (!m_remote_platform_sp)
308b9c1b51eSKate Stone       m_remote_platform_sp =
309b9c1b51eSKate Stone           Platform::Create(ConstString("remote-gdb-server"), error);
310015d818bSTodd Fiala 
311015d818bSTodd Fiala     if (m_remote_platform_sp && error.Success())
312015d818bSTodd Fiala       error = m_remote_platform_sp->ConnectRemote(args);
313015d818bSTodd Fiala     else
314015d818bSTodd Fiala       error.SetErrorString("failed to create a 'remote-gdb-server' platform");
315015d818bSTodd Fiala 
316015d818bSTodd Fiala     if (error.Fail())
317015d818bSTodd Fiala       m_remote_platform_sp.reset();
318015d818bSTodd Fiala   }
319015d818bSTodd Fiala 
320b9c1b51eSKate Stone   if (error.Success() && m_remote_platform_sp) {
321b9c1b51eSKate Stone     if (m_option_group_platform_rsync.get() &&
322b9c1b51eSKate Stone         m_option_group_platform_ssh.get() &&
323b9c1b51eSKate Stone         m_option_group_platform_caching.get()) {
324b9c1b51eSKate Stone       if (m_option_group_platform_rsync->m_rsync) {
325015d818bSTodd Fiala         SetSupportsRSync(true);
3260a66e2f1SEnrico Granata         SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str());
3270a66e2f1SEnrico Granata         SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str());
328b9c1b51eSKate Stone         SetIgnoresRemoteHostname(
329b9c1b51eSKate Stone             m_option_group_platform_rsync->m_ignores_remote_hostname);
330015d818bSTodd Fiala       }
331b9c1b51eSKate Stone       if (m_option_group_platform_ssh->m_ssh) {
332015d818bSTodd Fiala         SetSupportsSSH(true);
3330a66e2f1SEnrico Granata         SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str());
334015d818bSTodd Fiala       }
335b9c1b51eSKate Stone       SetLocalCacheDirectory(
336b9c1b51eSKate Stone           m_option_group_platform_caching->m_cache_dir.c_str());
337015d818bSTodd Fiala     }
338015d818bSTodd Fiala   }
339015d818bSTodd Fiala 
340015d818bSTodd Fiala   return error;
341015d818bSTodd Fiala }
342015d818bSTodd Fiala 
34397206d57SZachary Turner Status PlatformPOSIX::DisconnectRemote() {
34497206d57SZachary Turner   Status error;
345015d818bSTodd Fiala 
346b9c1b51eSKate Stone   if (IsHost()) {
347b9c1b51eSKate Stone     error.SetErrorStringWithFormat(
348b9c1b51eSKate Stone         "can't disconnect from the host platform '%s', always connected",
349b9c1b51eSKate Stone         GetPluginName().GetCString());
350b9c1b51eSKate Stone   } else {
351015d818bSTodd Fiala     if (m_remote_platform_sp)
352015d818bSTodd Fiala       error = m_remote_platform_sp->DisconnectRemote();
353015d818bSTodd Fiala     else
354015d818bSTodd Fiala       error.SetErrorString("the platform is not currently connected");
355015d818bSTodd Fiala   }
356015d818bSTodd Fiala   return error;
357015d818bSTodd Fiala }
358015d818bSTodd Fiala 
359b9c1b51eSKate Stone lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info,
360b9c1b51eSKate Stone                                       Debugger &debugger, Target *target,
36197206d57SZachary Turner                                       Status &error) {
362348fb385STodd Fiala   lldb::ProcessSP process_sp;
363348fb385STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
364348fb385STodd Fiala 
365b9c1b51eSKate Stone   if (IsHost()) {
366248a1305SKonrad Kleine     if (target == nullptr) {
367348fb385STodd Fiala       TargetSP new_target_sp;
368348fb385STodd Fiala 
369f9a07e9fSJonas Devlieghere       error = debugger.GetTargetList().CreateTarget(
370248a1305SKonrad Kleine           debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
371348fb385STodd Fiala       target = new_target_sp.get();
37263e5fb76SJonas Devlieghere       LLDB_LOGF(log, "PlatformPOSIX::%s created new target", __FUNCTION__);
373b9c1b51eSKate Stone     } else {
374348fb385STodd Fiala       error.Clear();
37563e5fb76SJonas Devlieghere       LLDB_LOGF(log, "PlatformPOSIX::%s target already existed, setting target",
376b9c1b51eSKate Stone                 __FUNCTION__);
377348fb385STodd Fiala     }
378348fb385STodd Fiala 
379b9c1b51eSKate Stone     if (target && error.Success()) {
380b9c1b51eSKate Stone       if (log) {
381348fb385STodd Fiala         ModuleSP exe_module_sp = target->GetExecutableModule();
38263e5fb76SJonas Devlieghere         LLDB_LOGF(log, "PlatformPOSIX::%s set selected target to %p %s",
383b9c1b51eSKate Stone                   __FUNCTION__, (void *)target,
38463e5fb76SJonas Devlieghere                   exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
385b9c1b51eSKate Stone                                 : "<null>");
386348fb385STodd Fiala       }
387348fb385STodd Fiala 
388b9c1b51eSKate Stone       process_sp =
389b9c1b51eSKate Stone           target->CreateProcess(attach_info.GetListenerForProcess(debugger),
3901a1cc0baSMichał Górny                                 "gdb-remote", nullptr, true);
391348fb385STodd Fiala 
392b9c1b51eSKate Stone       if (process_sp) {
393583bbb1dSJim Ingham         ListenerSP listener_sp = attach_info.GetHijackListener();
394b9c1b51eSKate Stone         if (listener_sp == nullptr) {
395b9c1b51eSKate Stone           listener_sp =
396b9c1b51eSKate Stone               Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
397348fb385STodd Fiala           attach_info.SetHijackListener(listener_sp);
398926af0cdSOleksiy Vyalov         }
399583bbb1dSJim Ingham         process_sp->HijackProcessEvents(listener_sp);
400348fb385STodd Fiala         error = process_sp->Attach(attach_info);
401348fb385STodd Fiala       }
402348fb385STodd Fiala     }
403b9c1b51eSKate Stone   } else {
404348fb385STodd Fiala     if (m_remote_platform_sp)
405b9c1b51eSKate Stone       process_sp =
406b9c1b51eSKate Stone           m_remote_platform_sp->Attach(attach_info, debugger, target, error);
407348fb385STodd Fiala     else
408348fb385STodd Fiala       error.SetErrorString("the platform is not currently connected");
409348fb385STodd Fiala   }
410348fb385STodd Fiala   return process_sp;
411348fb385STodd Fiala }
412348fb385STodd Fiala 
413015d818bSTodd Fiala lldb::ProcessSP
414b9c1b51eSKate Stone PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
415b9c1b51eSKate Stone                             Target *target, // Can be NULL, if NULL create a new
416b9c1b51eSKate Stone                                             // target, else use existing one
41797206d57SZachary Turner                             Status &error) {
418a825eaa9SMichał Górny   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
419a825eaa9SMichał Górny   LLDB_LOG(log, "target {0}", target);
420a825eaa9SMichał Górny 
421015d818bSTodd Fiala   ProcessSP process_sp;
422015d818bSTodd Fiala 
423a825eaa9SMichał Górny   if (!IsHost()) {
424015d818bSTodd Fiala     if (m_remote_platform_sp)
425b9c1b51eSKate Stone       process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
426b9c1b51eSKate Stone                                                       target, error);
427015d818bSTodd Fiala     else
428015d818bSTodd Fiala       error.SetErrorString("the platform is not currently connected");
429a825eaa9SMichał Górny     return process_sp;
430015d818bSTodd Fiala   }
431a825eaa9SMichał Górny 
432a825eaa9SMichał Górny   //
433a825eaa9SMichał Górny   // For local debugging, we'll insist on having ProcessGDBRemote create the
434a825eaa9SMichał Górny   // process.
435a825eaa9SMichał Górny   //
436a825eaa9SMichał Górny 
437a825eaa9SMichał Górny   // Make sure we stop at the entry point
438a825eaa9SMichał Górny   launch_info.GetFlags().Set(eLaunchFlagDebug);
439a825eaa9SMichał Górny 
440a825eaa9SMichał Górny   // We always launch the process we are going to debug in a separate process
441a825eaa9SMichał Górny   // group, since then we can handle ^C interrupts ourselves w/o having to
442a825eaa9SMichał Górny   // worry about the target getting them as well.
443a825eaa9SMichał Górny   launch_info.SetLaunchInSeparateProcessGroup(true);
444a825eaa9SMichał Górny 
445a825eaa9SMichał Górny   // Ensure we have a target.
446a825eaa9SMichał Górny   if (target == nullptr) {
447a825eaa9SMichał Górny     LLDB_LOG(log, "creating new target");
448a825eaa9SMichał Górny     TargetSP new_target_sp;
449a825eaa9SMichał Górny     error = debugger.GetTargetList().CreateTarget(
450a825eaa9SMichał Górny         debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
451a825eaa9SMichał Górny     if (error.Fail()) {
452a825eaa9SMichał Górny       LLDB_LOG(log, "failed to create new target: {0}", error);
453a825eaa9SMichał Górny       return process_sp;
454a825eaa9SMichał Górny     }
455a825eaa9SMichał Górny 
456a825eaa9SMichał Górny     target = new_target_sp.get();
457a825eaa9SMichał Górny     if (!target) {
458a825eaa9SMichał Górny       error.SetErrorString("CreateTarget() returned nullptr");
459a825eaa9SMichał Górny       LLDB_LOG(log, "error: {0}", error);
460a825eaa9SMichał Górny       return process_sp;
461a825eaa9SMichał Górny     }
462a825eaa9SMichał Górny   }
463a825eaa9SMichał Górny 
464a825eaa9SMichał Górny   // Now create the gdb-remote process.
465a825eaa9SMichał Górny   LLDB_LOG(log, "having target create process with gdb-remote plugin");
466a825eaa9SMichał Górny   process_sp =
46718e4272aSMichał Górny       target->CreateProcess(launch_info.GetListener(), "gdb-remote", nullptr,
46818e4272aSMichał Górny                             true);
469a825eaa9SMichał Górny 
470a825eaa9SMichał Górny   if (!process_sp) {
471a825eaa9SMichał Górny     error.SetErrorString("CreateProcess() failed for gdb-remote process");
472a825eaa9SMichał Górny     LLDB_LOG(log, "error: {0}", error);
473a825eaa9SMichał Górny     return process_sp;
474a825eaa9SMichał Górny   }
475a825eaa9SMichał Górny 
476a825eaa9SMichał Górny   LLDB_LOG(log, "successfully created process");
477a825eaa9SMichał Górny   // Adjust launch for a hijacker.
478a825eaa9SMichał Górny   ListenerSP listener_sp;
479a825eaa9SMichał Górny   if (!launch_info.GetHijackListener()) {
480a825eaa9SMichał Górny     LLDB_LOG(log, "setting up hijacker");
481a825eaa9SMichał Górny     listener_sp =
482a825eaa9SMichał Górny         Listener::MakeListener("lldb.PlatformLinux.DebugProcess.hijack");
483a825eaa9SMichał Górny     launch_info.SetHijackListener(listener_sp);
484a825eaa9SMichał Górny     process_sp->HijackProcessEvents(listener_sp);
485a825eaa9SMichał Górny   }
486a825eaa9SMichał Górny 
487a825eaa9SMichał Górny   // Log file actions.
488a825eaa9SMichał Górny   if (log) {
489a825eaa9SMichał Górny     LLDB_LOG(log, "launching process with the following file actions:");
490a825eaa9SMichał Górny     StreamString stream;
491a825eaa9SMichał Górny     size_t i = 0;
492a825eaa9SMichał Górny     const FileAction *file_action;
493a825eaa9SMichał Górny     while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) {
494a825eaa9SMichał Górny       file_action->Dump(stream);
495a825eaa9SMichał Górny       LLDB_LOG(log, "{0}", stream.GetData());
496a825eaa9SMichał Górny       stream.Clear();
497a825eaa9SMichał Górny     }
498a825eaa9SMichał Górny   }
499a825eaa9SMichał Górny 
500a825eaa9SMichał Górny   // Do the launch.
501a825eaa9SMichał Górny   error = process_sp->Launch(launch_info);
502a825eaa9SMichał Górny   if (error.Success()) {
503a825eaa9SMichał Górny     // Handle the hijacking of process events.
504a825eaa9SMichał Górny     if (listener_sp) {
505a825eaa9SMichał Górny       const StateType state = process_sp->WaitForProcessToStop(
506a825eaa9SMichał Górny           llvm::None, nullptr, false, listener_sp);
507a825eaa9SMichał Górny 
508a825eaa9SMichał Górny       LLDB_LOG(log, "pid {0} state {0}", process_sp->GetID(), state);
509a825eaa9SMichał Górny     }
510a825eaa9SMichał Górny 
511a825eaa9SMichał Górny     // Hook up process PTY if we have one (which we should for local debugging
512a825eaa9SMichał Górny     // with llgs).
513a825eaa9SMichał Górny     int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
514a825eaa9SMichał Górny     if (pty_fd != PseudoTerminal::invalid_fd) {
515a825eaa9SMichał Górny       process_sp->SetSTDIOFileDescriptor(pty_fd);
516a825eaa9SMichał Górny       LLDB_LOG(log, "hooked up STDIO pty to process");
517a825eaa9SMichał Górny     } else
518a825eaa9SMichał Górny       LLDB_LOG(log, "not using process STDIO pty");
519a825eaa9SMichał Górny   } else {
520a825eaa9SMichał Górny     LLDB_LOG(log, "{0}", error);
521a825eaa9SMichał Górny     // FIXME figure out appropriate cleanup here.  Do we delete the target? Do
522a825eaa9SMichał Górny     // we delete the process?  Does our caller do that?
523a825eaa9SMichał Górny   }
524a825eaa9SMichał Górny 
525015d818bSTodd Fiala   return process_sp;
526015d818bSTodd Fiala }
527015d818bSTodd Fiala 
528b9c1b51eSKate Stone void PlatformPOSIX::CalculateTrapHandlerSymbolNames() {
5292094dbf4SJason Molenda   m_trap_handlers.push_back(ConstString("_sigtramp"));
5302094dbf4SJason Molenda }
5313cb132a0STamas Berghammer 
53297206d57SZachary Turner Status PlatformPOSIX::EvaluateLibdlExpression(
533b9c1b51eSKate Stone     lldb_private::Process *process, const char *expr_cstr,
534d37c9469SPavel Labath     llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
5353cb132a0STamas Berghammer   DynamicLoader *loader = process->GetDynamicLoader();
536b9c1b51eSKate Stone   if (loader) {
53797206d57SZachary Turner     Status error = loader->CanLoadImage();
5383cb132a0STamas Berghammer     if (error.Fail())
5393cb132a0STamas Berghammer       return error;
5403cb132a0STamas Berghammer   }
5413cb132a0STamas Berghammer 
5428d94ba0fSJim Ingham   ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread());
5433cb132a0STamas Berghammer   if (!thread_sp)
54497206d57SZachary Turner     return Status("Selected thread isn't valid");
5453cb132a0STamas Berghammer 
5463cb132a0STamas Berghammer   StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
5473cb132a0STamas Berghammer   if (!frame_sp)
54897206d57SZachary Turner     return Status("Frame 0 isn't valid");
5493cb132a0STamas Berghammer 
5503cb132a0STamas Berghammer   ExecutionContext exe_ctx;
5513cb132a0STamas Berghammer   frame_sp->CalculateExecutionContext(exe_ctx);
5523cb132a0STamas Berghammer   EvaluateExpressionOptions expr_options;
5533cb132a0STamas Berghammer   expr_options.SetUnwindOnError(true);
5543cb132a0STamas Berghammer   expr_options.SetIgnoreBreakpoints(true);
5553cb132a0STamas Berghammer   expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
5563cb132a0STamas Berghammer   expr_options.SetLanguage(eLanguageTypeC_plus_plus);
557b9c1b51eSKate Stone   expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
558b9c1b51eSKate Stone                                          // don't do the work to trap them.
5594c03ea14SAdrian Prantl   expr_options.SetTimeout(process->GetUtilityExpressionTimeout());
5603cb132a0STamas Berghammer 
56197206d57SZachary Turner   Status expr_error;
56202980825SJim Ingham   ExpressionResults result =
563b9c1b51eSKate Stone       UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix,
564b9c1b51eSKate Stone                                result_valobj_sp, expr_error);
56502980825SJim Ingham   if (result != eExpressionCompleted)
56602980825SJim Ingham     return expr_error;
56702980825SJim Ingham 
5683cb132a0STamas Berghammer   if (result_valobj_sp->GetError().Fail())
5693cb132a0STamas Berghammer     return result_valobj_sp->GetError();
57097206d57SZachary Turner   return Status();
5713cb132a0STamas Berghammer }
5723cb132a0STamas Berghammer 
573d10d3795SFrederic Riss std::unique_ptr<UtilityFunction>
5741ecb34f4SJim Ingham PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx,
575d10d3795SFrederic Riss                                             Status &error) {
57605097246SAdrian Prantl   // Remember to prepend this with the prefix from
57705097246SAdrian Prantl   // GetLibdlFunctionDeclarations. The returned values are all in
57805097246SAdrian Prantl   // __lldb_dlopen_result for consistency. The wrapper returns a void * but
57905097246SAdrian Prantl   // doesn't use it because UtilityFunctions don't work with void returns at
58005097246SAdrian Prantl   // present.
5814bd2bfb6SVedant Kumar   //
5824bd2bfb6SVedant Kumar   // Use lazy binding so as to not make dlopen()'s success conditional on
5834bd2bfb6SVedant Kumar   // forcing every symbol in the library.
5844bd2bfb6SVedant Kumar   //
5854bd2bfb6SVedant Kumar   // In general, the debugger should allow programs to load & run with
5864bd2bfb6SVedant Kumar   // libraries as far as they can, instead of defaulting to being super-picky
5874bd2bfb6SVedant Kumar   // about unavailable symbols.
5884bd2bfb6SVedant Kumar   //
5894bd2bfb6SVedant Kumar   // The value "1" appears to imply lazy binding (RTLD_LAZY) on both Darwin
5904bd2bfb6SVedant Kumar   // and other POSIX OSes.
5911ecb34f4SJim Ingham   static const char *dlopen_wrapper_code = R"(
5924bd2bfb6SVedant Kumar   const int RTLD_LAZY = 1;
5934bd2bfb6SVedant Kumar 
5941ecb34f4SJim Ingham   struct __lldb_dlopen_result {
5951ecb34f4SJim Ingham     void *image_ptr;
5961ecb34f4SJim Ingham     const char *error_str;
5971ecb34f4SJim Ingham   };
5981ecb34f4SJim Ingham 
59903856dd9SJim Ingham   extern void *memcpy(void *, const void *, size_t size);
6000d231f71SJim Ingham   extern size_t strlen(const char *);
6010d231f71SJim Ingham 
6020d231f71SJim Ingham 
6030d231f71SJim Ingham   void * __lldb_dlopen_wrapper (const char *name,
6040d231f71SJim Ingham                                 const char *path_strings,
6050d231f71SJim Ingham                                 char *buffer,
6061ecb34f4SJim Ingham                                 __lldb_dlopen_result *result_ptr)
6071ecb34f4SJim Ingham   {
6080d231f71SJim Ingham     // This is the case where the name is the full path:
60903856dd9SJim Ingham     if (!path_strings) {
6104bd2bfb6SVedant Kumar       result_ptr->image_ptr = dlopen(name, RTLD_LAZY);
61103856dd9SJim Ingham       if (result_ptr->image_ptr)
6120d231f71SJim Ingham         result_ptr->error_str = nullptr;
6130d231f71SJim Ingham       return nullptr;
6140d231f71SJim Ingham     }
6150d231f71SJim Ingham 
6160d231f71SJim Ingham     // This is the case where we have a list of paths:
6170d231f71SJim Ingham     size_t name_len = strlen(name);
61803856dd9SJim Ingham     while (path_strings && path_strings[0] != '\0') {
6190d231f71SJim Ingham       size_t path_len = strlen(path_strings);
6200d231f71SJim Ingham       memcpy((void *) buffer, (void *) path_strings, path_len);
6210d231f71SJim Ingham       buffer[path_len] = '/';
6220d231f71SJim Ingham       char *target_ptr = buffer+path_len+1;
6230d231f71SJim Ingham       memcpy((void *) target_ptr, (void *) name, name_len + 1);
6244bd2bfb6SVedant Kumar       result_ptr->image_ptr = dlopen(buffer, RTLD_LAZY);
62503856dd9SJim Ingham       if (result_ptr->image_ptr) {
6260d231f71SJim Ingham         result_ptr->error_str = nullptr;
6270d231f71SJim Ingham         break;
6280d231f71SJim Ingham       }
6291ecb34f4SJim Ingham       result_ptr->error_str = dlerror();
6300d231f71SJim Ingham       path_strings = path_strings + path_len + 1;
6310d231f71SJim Ingham     }
6321ecb34f4SJim Ingham     return nullptr;
6331ecb34f4SJim Ingham   }
6341ecb34f4SJim Ingham   )";
6351ecb34f4SJim Ingham 
6361ecb34f4SJim Ingham   static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
6371ecb34f4SJim Ingham   Process *process = exe_ctx.GetProcessSP().get();
6381ecb34f4SJim Ingham   // Insert the dlopen shim defines into our generic expression:
639adcd0268SBenjamin Kramer   std::string expr(std::string(GetLibdlFunctionDeclarations(process)));
6401ecb34f4SJim Ingham   expr.append(dlopen_wrapper_code);
6411ecb34f4SJim Ingham   Status utility_error;
6421ecb34f4SJim Ingham   DiagnosticManager diagnostics;
6431ecb34f4SJim Ingham 
644de346cf2SJonas Devlieghere   auto utility_fn_or_error = process->GetTarget().CreateUtilityFunction(
645de346cf2SJonas Devlieghere       std::move(expr), dlopen_wrapper_name, eLanguageTypeObjC, exe_ctx);
646de346cf2SJonas Devlieghere   if (!utility_fn_or_error) {
647de346cf2SJonas Devlieghere     std::string error_str = llvm::toString(utility_fn_or_error.takeError());
648de346cf2SJonas Devlieghere     error.SetErrorStringWithFormat("dlopen error: could not create utility"
6491ecb34f4SJim Ingham                                    "function: %s",
650de346cf2SJonas Devlieghere                                    error_str.c_str());
6511ecb34f4SJim Ingham     return nullptr;
6521ecb34f4SJim Ingham   }
653de346cf2SJonas Devlieghere   std::unique_ptr<UtilityFunction> dlopen_utility_func_up =
654de346cf2SJonas Devlieghere       std::move(*utility_fn_or_error);
6551ecb34f4SJim Ingham 
6561ecb34f4SJim Ingham   Value value;
6571ecb34f4SJim Ingham   ValueList arguments;
6581ecb34f4SJim Ingham   FunctionCaller *do_dlopen_function = nullptr;
6591ecb34f4SJim Ingham 
6601ecb34f4SJim Ingham   // Fetch the clang types we will need:
661594308c7SRaphael Isemann   TypeSystemClang *ast =
662594308c7SRaphael Isemann       ScratchTypeSystemClang::GetForTarget(process->GetTarget());
6633031818aSAlex Langford   if (!ast)
6643031818aSAlex Langford     return nullptr;
6651ecb34f4SJim Ingham 
6661ecb34f4SJim Ingham   CompilerType clang_void_pointer_type
6671ecb34f4SJim Ingham       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
6681ecb34f4SJim Ingham   CompilerType clang_char_pointer_type
6691ecb34f4SJim Ingham         = ast->GetBasicType(eBasicTypeChar).GetPointerType();
6701ecb34f4SJim Ingham 
6710d231f71SJim Ingham   // We are passing four arguments, the basename, the list of places to look,
6720d231f71SJim Ingham   // a buffer big enough for all the path + name combos, and
6730d231f71SJim Ingham   // a pointer to the storage we've made for the result:
674057efa99SAdrian Prantl   value.SetValueType(Value::ValueType::Scalar);
6751ecb34f4SJim Ingham   value.SetCompilerType(clang_void_pointer_type);
6761ecb34f4SJim Ingham   arguments.PushValue(value);
6771ecb34f4SJim Ingham   value.SetCompilerType(clang_char_pointer_type);
6781ecb34f4SJim Ingham   arguments.PushValue(value);
6790d231f71SJim Ingham   arguments.PushValue(value);
6800d231f71SJim Ingham   arguments.PushValue(value);
6811ecb34f4SJim Ingham 
6821ecb34f4SJim Ingham   do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
6831ecb34f4SJim Ingham       clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
6841ecb34f4SJim Ingham   if (utility_error.Fail()) {
6851ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not make function"
6861ecb34f4SJim Ingham                                    "caller: %s", utility_error.AsCString());
6871ecb34f4SJim Ingham     return nullptr;
6881ecb34f4SJim Ingham   }
6891ecb34f4SJim Ingham 
6901ecb34f4SJim Ingham   do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
6911ecb34f4SJim Ingham   if (!do_dlopen_function) {
6921ecb34f4SJim Ingham     error.SetErrorString("dlopen error: could not get function caller.");
6931ecb34f4SJim Ingham     return nullptr;
6941ecb34f4SJim Ingham   }
6951ecb34f4SJim Ingham 
6961ecb34f4SJim Ingham   // We made a good utility function, so cache it in the process:
697d10d3795SFrederic Riss   return dlopen_utility_func_up;
6981ecb34f4SJim Ingham }
6991ecb34f4SJim Ingham 
700b9c1b51eSKate Stone uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process,
7014fbd67acSTamas Berghammer                                     const lldb_private::FileSpec &remote_file,
7020d231f71SJim Ingham                                     const std::vector<std::string> *paths,
7030d231f71SJim Ingham                                     lldb_private::Status &error,
7040d231f71SJim Ingham                                     lldb_private::FileSpec *loaded_image) {
7050d231f71SJim Ingham   if (loaded_image)
7060d231f71SJim Ingham     loaded_image->Clear();
7070d231f71SJim Ingham 
7081ecb34f4SJim Ingham   std::string path;
7091ecb34f4SJim Ingham   path = remote_file.GetPath();
7103cb132a0STamas Berghammer 
7111ecb34f4SJim Ingham   ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
7121ecb34f4SJim Ingham   if (!thread_sp) {
7131ecb34f4SJim Ingham     error.SetErrorString("dlopen error: no thread available to call dlopen.");
7143cb132a0STamas Berghammer     return LLDB_INVALID_IMAGE_TOKEN;
7153cb132a0STamas Berghammer   }
7163cb132a0STamas Berghammer 
7171ecb34f4SJim Ingham   DiagnosticManager diagnostics;
7183cb132a0STamas Berghammer 
7191ecb34f4SJim Ingham   ExecutionContext exe_ctx;
7201ecb34f4SJim Ingham   thread_sp->CalculateExecutionContext(exe_ctx);
7211ecb34f4SJim Ingham 
7221ecb34f4SJim Ingham   Status utility_error;
723d10d3795SFrederic Riss   UtilityFunction *dlopen_utility_func;
7241ecb34f4SJim Ingham   ValueList arguments;
7251ecb34f4SJim Ingham   FunctionCaller *do_dlopen_function = nullptr;
7261ecb34f4SJim Ingham 
727d10d3795SFrederic Riss   // The UtilityFunction is held in the Process.  Platforms don't track the
728d10d3795SFrederic Riss   // lifespan of the Targets that use them, we can't put this in the Platform.
729d10d3795SFrederic Riss   dlopen_utility_func = process->GetLoadImageUtilityFunction(
730d10d3795SFrederic Riss       this, [&]() -> std::unique_ptr<UtilityFunction> {
731d10d3795SFrederic Riss         return MakeLoadImageUtilityFunction(exe_ctx, error);
732d10d3795SFrederic Riss       });
7331ecb34f4SJim Ingham   // If we couldn't make it, the error will be in error, so we can exit here.
7341ecb34f4SJim Ingham   if (!dlopen_utility_func)
7351ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7361ecb34f4SJim Ingham 
7371ecb34f4SJim Ingham   do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
7381ecb34f4SJim Ingham   if (!do_dlopen_function) {
7391ecb34f4SJim Ingham     error.SetErrorString("dlopen error: could not get function caller.");
7401ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7411ecb34f4SJim Ingham   }
7421ecb34f4SJim Ingham   arguments = do_dlopen_function->GetArgumentValues();
7431ecb34f4SJim Ingham 
74405097246SAdrian Prantl   // Now insert the path we are searching for and the result structure into the
74505097246SAdrian Prantl   // target.
7461ecb34f4SJim Ingham   uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
7471ecb34f4SJim Ingham   size_t path_len = path.size() + 1;
7481ecb34f4SJim Ingham   lldb::addr_t path_addr = process->AllocateMemory(path_len,
7491ecb34f4SJim Ingham                                                    permissions,
7501ecb34f4SJim Ingham                                                    utility_error);
7511ecb34f4SJim Ingham   if (path_addr == LLDB_INVALID_ADDRESS) {
7521ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
7531ecb34f4SJim Ingham                                     "for path: %s", utility_error.AsCString());
7541ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7551ecb34f4SJim Ingham   }
7561ecb34f4SJim Ingham 
7571ecb34f4SJim Ingham   // Make sure we deallocate the input string memory:
758e0ea8d87SJonas Devlieghere   auto path_cleanup = llvm::make_scope_exit([process, path_addr] {
759e0ea8d87SJonas Devlieghere     // Deallocate the buffer.
7601ecb34f4SJim Ingham     process->DeallocateMemory(path_addr);
7611ecb34f4SJim Ingham   });
7621ecb34f4SJim Ingham 
7631ecb34f4SJim Ingham   process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
7641ecb34f4SJim Ingham   if (utility_error.Fail()) {
7651ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not write path string:"
7661ecb34f4SJim Ingham                                     " %s", utility_error.AsCString());
7671ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7681ecb34f4SJim Ingham   }
7691ecb34f4SJim Ingham 
77005097246SAdrian Prantl   // Make space for our return structure.  It is two pointers big: the token
77105097246SAdrian Prantl   // and the error string.
7721ecb34f4SJim Ingham   const uint32_t addr_size = process->GetAddressByteSize();
7731ecb34f4SJim Ingham   lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
7741ecb34f4SJim Ingham                                                       permissions,
7751ecb34f4SJim Ingham                                                       utility_error);
7761ecb34f4SJim Ingham   if (utility_error.Fail()) {
7771ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
7781ecb34f4SJim Ingham                                     "for path: %s", utility_error.AsCString());
7791ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7801ecb34f4SJim Ingham   }
7811ecb34f4SJim Ingham 
7821ecb34f4SJim Ingham   // Make sure we deallocate the result structure memory
783e0ea8d87SJonas Devlieghere   auto return_cleanup = llvm::make_scope_exit([process, return_addr] {
784e0ea8d87SJonas Devlieghere     // Deallocate the buffer
7851ecb34f4SJim Ingham     process->DeallocateMemory(return_addr);
7861ecb34f4SJim Ingham   });
7871ecb34f4SJim Ingham 
7880d231f71SJim Ingham   // This will be the address of the storage for paths, if we are using them,
7890d231f71SJim Ingham   // or nullptr to signal we aren't.
7900d231f71SJim Ingham   lldb::addr_t path_array_addr = 0x0;
791e0ea8d87SJonas Devlieghere   llvm::Optional<llvm::detail::scope_exit<std::function<void()>>>
792e0ea8d87SJonas Devlieghere       path_array_cleanup;
7930d231f71SJim Ingham 
7940d231f71SJim Ingham   // This is the address to a buffer large enough to hold the largest path
7950d231f71SJim Ingham   // conjoined with the library name we're passing in.  This is a convenience
7960d231f71SJim Ingham   // to avoid having to call malloc in the dlopen function.
7970d231f71SJim Ingham   lldb::addr_t buffer_addr = 0x0;
798e0ea8d87SJonas Devlieghere   llvm::Optional<llvm::detail::scope_exit<std::function<void()>>>
799e0ea8d87SJonas Devlieghere       buffer_cleanup;
8000d231f71SJim Ingham 
8011ecb34f4SJim Ingham   // Set the values into our args and write them to the target:
8020d231f71SJim Ingham   if (paths != nullptr) {
8030d231f71SJim Ingham     // First insert the paths into the target.  This is expected to be a
8040d231f71SJim Ingham     // continuous buffer with the strings laid out null terminated and
8050d231f71SJim Ingham     // end to end with an empty string terminating the buffer.
8060d231f71SJim Ingham     // We also compute the buffer's required size as we go.
8070d231f71SJim Ingham     size_t buffer_size = 0;
8080d231f71SJim Ingham     std::string path_array;
8090d231f71SJim Ingham     for (auto path : *paths) {
81040fa4a1aSJim Ingham       // Don't insert empty paths, they will make us abort the path
81140fa4a1aSJim Ingham       // search prematurely.
81240fa4a1aSJim Ingham       if (path.empty())
81340fa4a1aSJim Ingham         continue;
8140d231f71SJim Ingham       size_t path_size = path.size();
8150d231f71SJim Ingham       path_array.append(path);
8160d231f71SJim Ingham       path_array.push_back('\0');
8170d231f71SJim Ingham       if (path_size > buffer_size)
8180d231f71SJim Ingham         buffer_size = path_size;
8190d231f71SJim Ingham     }
8200d231f71SJim Ingham     path_array.push_back('\0');
8210d231f71SJim Ingham 
8220d231f71SJim Ingham     path_array_addr = process->AllocateMemory(path_array.size(),
8230d231f71SJim Ingham                                               permissions,
8240d231f71SJim Ingham                                               utility_error);
8250d231f71SJim Ingham     if (path_array_addr == LLDB_INVALID_ADDRESS) {
8260d231f71SJim Ingham       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
8270d231f71SJim Ingham                                       "for path array: %s",
8280d231f71SJim Ingham                                       utility_error.AsCString());
8290d231f71SJim Ingham       return LLDB_INVALID_IMAGE_TOKEN;
8300d231f71SJim Ingham     }
8310d231f71SJim Ingham 
8320d231f71SJim Ingham     // Make sure we deallocate the paths array.
833e0ea8d87SJonas Devlieghere     path_array_cleanup.emplace([process, path_array_addr]() {
834e0ea8d87SJonas Devlieghere       // Deallocate the path array.
8350d231f71SJim Ingham       process->DeallocateMemory(path_array_addr);
8360d231f71SJim Ingham     });
8370d231f71SJim Ingham 
8380d231f71SJim Ingham     process->WriteMemory(path_array_addr, path_array.data(),
8390d231f71SJim Ingham                          path_array.size(), utility_error);
8400d231f71SJim Ingham 
8410d231f71SJim Ingham     if (utility_error.Fail()) {
8420d231f71SJim Ingham       error.SetErrorStringWithFormat("dlopen error: could not write path array:"
8430d231f71SJim Ingham                                      " %s", utility_error.AsCString());
8440d231f71SJim Ingham       return LLDB_INVALID_IMAGE_TOKEN;
8450d231f71SJim Ingham     }
8460d231f71SJim Ingham     // Now make spaces in the target for the buffer.  We need to add one for
8470d231f71SJim Ingham     // the '/' that the utility function will insert and one for the '\0':
8480d231f71SJim Ingham     buffer_size += path.size() + 2;
8490d231f71SJim Ingham 
8500d231f71SJim Ingham     buffer_addr = process->AllocateMemory(buffer_size,
8510d231f71SJim Ingham                                           permissions,
8520d231f71SJim Ingham                                           utility_error);
8530d231f71SJim Ingham     if (buffer_addr == LLDB_INVALID_ADDRESS) {
8540d231f71SJim Ingham       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
8550d231f71SJim Ingham                                       "for buffer: %s",
8560d231f71SJim Ingham                                       utility_error.AsCString());
8570d231f71SJim Ingham       return LLDB_INVALID_IMAGE_TOKEN;
8580d231f71SJim Ingham     }
8590d231f71SJim Ingham 
8600d231f71SJim Ingham     // Make sure we deallocate the buffer memory:
861e0ea8d87SJonas Devlieghere     buffer_cleanup.emplace([process, buffer_addr]() {
862e0ea8d87SJonas Devlieghere       // Deallocate the buffer.
8630d231f71SJim Ingham       process->DeallocateMemory(buffer_addr);
8640d231f71SJim Ingham     });
8650d231f71SJim Ingham   }
8660d231f71SJim Ingham 
8671ecb34f4SJim Ingham   arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
8680d231f71SJim Ingham   arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
8690d231f71SJim Ingham   arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
8700d231f71SJim Ingham   arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
8711ecb34f4SJim Ingham 
8721ecb34f4SJim Ingham   lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
8731ecb34f4SJim Ingham 
8741ecb34f4SJim Ingham   diagnostics.Clear();
8751ecb34f4SJim Ingham   if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
8761ecb34f4SJim Ingham                                                  func_args_addr,
8771ecb34f4SJim Ingham                                                  arguments,
8781ecb34f4SJim Ingham                                                  diagnostics)) {
8791ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not write function "
8801ecb34f4SJim Ingham                                    "arguments: %s",
8811ecb34f4SJim Ingham                                    diagnostics.GetString().c_str());
8821ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
8831ecb34f4SJim Ingham   }
8841ecb34f4SJim Ingham 
8851ecb34f4SJim Ingham   // Make sure we clean up the args structure.  We can't reuse it because the
8861ecb34f4SJim Ingham   // Platform lives longer than the process and the Platforms don't get a
8871ecb34f4SJim Ingham   // signal to clean up cached data when a process goes away.
888e0ea8d87SJonas Devlieghere   auto args_cleanup =
889e0ea8d87SJonas Devlieghere       llvm::make_scope_exit([do_dlopen_function, &exe_ctx, func_args_addr] {
8901ecb34f4SJim Ingham         do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
8911ecb34f4SJim Ingham       });
8921ecb34f4SJim Ingham 
8931ecb34f4SJim Ingham   // Now run the caller:
8941ecb34f4SJim Ingham   EvaluateExpressionOptions options;
8951ecb34f4SJim Ingham   options.SetExecutionPolicy(eExecutionPolicyAlways);
8961ecb34f4SJim Ingham   options.SetLanguage(eLanguageTypeC_plus_plus);
8971ecb34f4SJim Ingham   options.SetIgnoreBreakpoints(true);
8981ecb34f4SJim Ingham   options.SetUnwindOnError(true);
8991ecb34f4SJim Ingham   options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
9001ecb34f4SJim Ingham                                     // don't do the work to trap them.
9014c03ea14SAdrian Prantl   options.SetTimeout(process->GetUtilityExpressionTimeout());
902c01783a8SRaphael Isemann   options.SetIsForUtilityExpr(true);
9031ecb34f4SJim Ingham 
9041ecb34f4SJim Ingham   Value return_value;
9051ecb34f4SJim Ingham   // Fetch the clang types we will need:
906594308c7SRaphael Isemann   TypeSystemClang *ast =
907594308c7SRaphael Isemann       ScratchTypeSystemClang::GetForTarget(process->GetTarget());
9083031818aSAlex Langford   if (!ast) {
9096e3b0cc2SRaphael Isemann     error.SetErrorString("dlopen error: Unable to get TypeSystemClang");
9103031818aSAlex Langford     return LLDB_INVALID_IMAGE_TOKEN;
9113031818aSAlex Langford   }
9121ecb34f4SJim Ingham 
9131ecb34f4SJim Ingham   CompilerType clang_void_pointer_type
9141ecb34f4SJim Ingham       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
9151ecb34f4SJim Ingham 
9161ecb34f4SJim Ingham   return_value.SetCompilerType(clang_void_pointer_type);
9171ecb34f4SJim Ingham 
9181ecb34f4SJim Ingham   ExpressionResults results = do_dlopen_function->ExecuteFunction(
9191ecb34f4SJim Ingham       exe_ctx, &func_args_addr, options, diagnostics, return_value);
9201ecb34f4SJim Ingham   if (results != eExpressionCompleted) {
9210d231f71SJim Ingham     error.SetErrorStringWithFormat("dlopen error: failed executing "
9221ecb34f4SJim Ingham                                    "dlopen wrapper function: %s",
9231ecb34f4SJim Ingham                                    diagnostics.GetString().c_str());
9241ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
9251ecb34f4SJim Ingham   }
9261ecb34f4SJim Ingham 
9271ecb34f4SJim Ingham   // Read the dlopen token from the return area:
9281ecb34f4SJim Ingham   lldb::addr_t token = process->ReadPointerFromMemory(return_addr,
9291ecb34f4SJim Ingham                                                       utility_error);
9301ecb34f4SJim Ingham   if (utility_error.Fail()) {
9311ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not read the return "
9321ecb34f4SJim Ingham                                     "struct: %s", utility_error.AsCString());
9331ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
9341ecb34f4SJim Ingham   }
9351ecb34f4SJim Ingham 
9361ecb34f4SJim Ingham   // The dlopen succeeded!
9370d231f71SJim Ingham   if (token != 0x0) {
9380d231f71SJim Ingham     if (loaded_image && buffer_addr != 0x0)
9390d231f71SJim Ingham     {
9400d231f71SJim Ingham       // Capture the image which was loaded.  We leave it in the buffer on
9410d231f71SJim Ingham       // exit from the dlopen function, so we can just read it from there:
9420d231f71SJim Ingham       std::string name_string;
9430d231f71SJim Ingham       process->ReadCStringFromMemory(buffer_addr, name_string, utility_error);
9440d231f71SJim Ingham       if (utility_error.Success())
9458f3be7a3SJonas Devlieghere         loaded_image->SetFile(name_string, llvm::sys::path::Style::posix);
9460d231f71SJim Ingham     }
9471ecb34f4SJim Ingham     return process->AddImageToken(token);
9480d231f71SJim Ingham   }
9491ecb34f4SJim Ingham 
9501ecb34f4SJim Ingham   // We got an error, lets read in the error string:
9511ecb34f4SJim Ingham   std::string dlopen_error_str;
9521ecb34f4SJim Ingham   lldb::addr_t error_addr
9531ecb34f4SJim Ingham     = process->ReadPointerFromMemory(return_addr + addr_size, utility_error);
9541ecb34f4SJim Ingham   if (utility_error.Fail()) {
9551ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not read error string: "
9561ecb34f4SJim Ingham                                     "%s", utility_error.AsCString());
9571ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
9581ecb34f4SJim Ingham   }
9591ecb34f4SJim Ingham 
9601ecb34f4SJim Ingham   size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size,
9611ecb34f4SJim Ingham                                                     dlopen_error_str,
9621ecb34f4SJim Ingham                                                     utility_error);
9631ecb34f4SJim Ingham   if (utility_error.Success() && num_chars > 0)
964b9c1b51eSKate Stone     error.SetErrorStringWithFormat("dlopen error: %s",
9651ecb34f4SJim Ingham                                    dlopen_error_str.c_str());
9663cb132a0STamas Berghammer   else
9673cb132a0STamas Berghammer     error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
9681ecb34f4SJim Ingham 
9693cb132a0STamas Berghammer   return LLDB_INVALID_IMAGE_TOKEN;
9703cb132a0STamas Berghammer }
9713cb132a0STamas Berghammer 
97297206d57SZachary Turner Status PlatformPOSIX::UnloadImage(lldb_private::Process *process,
973b9c1b51eSKate Stone                                   uint32_t image_token) {
9743cb132a0STamas Berghammer   const addr_t image_addr = process->GetImagePtrFromToken(image_token);
9753cb132a0STamas Berghammer   if (image_addr == LLDB_INVALID_ADDRESS)
97697206d57SZachary Turner     return Status("Invalid image token");
9773cb132a0STamas Berghammer 
9783cb132a0STamas Berghammer   StreamString expr;
9793cb132a0STamas Berghammer   expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
980f7a5851dSNitesh Jain   llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
9813cb132a0STamas Berghammer   lldb::ValueObjectSP result_valobj_sp;
98297206d57SZachary Turner   Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
983b9c1b51eSKate Stone                                          result_valobj_sp);
9843cb132a0STamas Berghammer   if (error.Fail())
9853cb132a0STamas Berghammer     return error;
9863cb132a0STamas Berghammer 
9873cb132a0STamas Berghammer   if (result_valobj_sp->GetError().Fail())
9883cb132a0STamas Berghammer     return result_valobj_sp->GetError();
9893cb132a0STamas Berghammer 
9903cb132a0STamas Berghammer   Scalar scalar;
991b9c1b51eSKate Stone   if (result_valobj_sp->ResolveValue(scalar)) {
9923cb132a0STamas Berghammer     if (scalar.UInt(1))
99397206d57SZachary Turner       return Status("expression failed: \"%s\"", expr.GetData());
9943cb132a0STamas Berghammer     process->ResetImageToken(image_token);
9953cb132a0STamas Berghammer   }
99697206d57SZachary Turner   return Status();
9973cb132a0STamas Berghammer }
998fcdde63fSTamas Berghammer 
999f7a5851dSNitesh Jain llvm::StringRef
1000f7a5851dSNitesh Jain PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
1001fcdde63fSTamas Berghammer   return R"(
1002fcdde63fSTamas Berghammer               extern "C" void* dlopen(const char*, int);
1003fcdde63fSTamas Berghammer               extern "C" void* dlsym(void*, const char*);
1004fcdde63fSTamas Berghammer               extern "C" int   dlclose(void*);
1005fcdde63fSTamas Berghammer               extern "C" char* dlerror(void);
1006fcdde63fSTamas Berghammer              )";
1007fcdde63fSTamas Berghammer }
1008ccd6cffbSTamas Berghammer 
1009ec9bc8ccSPavel Labath ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) {
1010ec9bc8ccSPavel Labath   if (basename.IsEmpty())
1011ec9bc8ccSPavel Labath     return basename;
1012ec9bc8ccSPavel Labath 
1013ec9bc8ccSPavel Labath   StreamString stream;
1014ec9bc8ccSPavel Labath   stream.Printf("lib%s.so", basename.GetCString());
1015ec9bc8ccSPavel Labath   return ConstString(stream.GetString());
1016ec9bc8ccSPavel Labath }
1017