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"
31*c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
326f9e6901SZachary Turner #include "lldb/Utility/Log.h"
33bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
34e0ea8d87SJonas Devlieghere #include "llvm/ADT/ScopeExit.h"
35e0f8f574SDaniel Malea 
36e0f8f574SDaniel Malea using namespace lldb;
37e0f8f574SDaniel Malea using namespace lldb_private;
38e0f8f574SDaniel Malea 
39e0f8f574SDaniel Malea /// Default Constructor
40b9c1b51eSKate Stone PlatformPOSIX::PlatformPOSIX(bool is_host)
4152d9c62aSPavel Labath     : RemoteAwarePlatform(is_host), // This is the local host platform
420a66e2f1SEnrico Granata       m_option_group_platform_rsync(new OptionGroupPlatformRSync()),
430a66e2f1SEnrico Granata       m_option_group_platform_ssh(new OptionGroupPlatformSSH()),
4452d9c62aSPavel Labath       m_option_group_platform_caching(new OptionGroupPlatformCaching()) {}
45e0f8f574SDaniel Malea 
46e0f8f574SDaniel Malea /// Destructor.
47e0f8f574SDaniel Malea ///
48e0f8f574SDaniel Malea /// The destructor is virtual since this class is designed to be
49e0f8f574SDaniel Malea /// inherited from by the plug-in instance.
50fd2433e1SJonas Devlieghere PlatformPOSIX::~PlatformPOSIX() = default;
51e0f8f574SDaniel Malea 
52b9c1b51eSKate Stone lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions(
53b9c1b51eSKate Stone     lldb_private::CommandInterpreter &interpreter) {
540a66e2f1SEnrico Granata   auto iter = m_options.find(&interpreter), end = m_options.end();
55b9c1b51eSKate Stone   if (iter == end) {
56b9c1b51eSKate Stone     std::unique_ptr<lldb_private::OptionGroupOptions> options(
57b9c1b51eSKate Stone         new OptionGroupOptions());
580a66e2f1SEnrico Granata     options->Append(m_option_group_platform_rsync.get());
590a66e2f1SEnrico Granata     options->Append(m_option_group_platform_ssh.get());
600a66e2f1SEnrico Granata     options->Append(m_option_group_platform_caching.get());
610a66e2f1SEnrico Granata     m_options[&interpreter] = std::move(options);
62e0f8f574SDaniel Malea   }
630a66e2f1SEnrico Granata 
640a66e2f1SEnrico Granata   return m_options.at(&interpreter).get();
65e0f8f574SDaniel Malea }
66e0f8f574SDaniel Malea 
67b9c1b51eSKate Stone static uint32_t chown_file(Platform *platform, const char *path,
68e0f8f574SDaniel Malea                            uint32_t uid = UINT32_MAX,
69b9c1b51eSKate Stone                            uint32_t gid = UINT32_MAX) {
70e0f8f574SDaniel Malea   if (!platform || !path || *path == 0)
71e0f8f574SDaniel Malea     return UINT32_MAX;
72e0f8f574SDaniel Malea 
73e0f8f574SDaniel Malea   if (uid == UINT32_MAX && gid == UINT32_MAX)
74e0f8f574SDaniel Malea     return 0; // pretend I did chown correctly - actually I just didn't care
75e0f8f574SDaniel Malea 
76e0f8f574SDaniel Malea   StreamString command;
77e0f8f574SDaniel Malea   command.PutCString("chown ");
78e0f8f574SDaniel Malea   if (uid != UINT32_MAX)
79e0f8f574SDaniel Malea     command.Printf("%d", uid);
80e0f8f574SDaniel Malea   if (gid != UINT32_MAX)
81e0f8f574SDaniel Malea     command.Printf(":%d", gid);
82e0f8f574SDaniel Malea   command.Printf("%s", path);
83e0f8f574SDaniel Malea   int status;
8428e4942bSPavel Labath   platform->RunShellCommand(command.GetData(), FileSpec(), &status, nullptr,
85248a1305SKonrad Kleine                             nullptr, std::chrono::seconds(10));
86e0f8f574SDaniel Malea   return status;
87e0f8f574SDaniel Malea }
88e0f8f574SDaniel Malea 
8997206d57SZachary Turner lldb_private::Status
90e0f8f574SDaniel Malea PlatformPOSIX::PutFile(const lldb_private::FileSpec &source,
91b9c1b51eSKate Stone                        const lldb_private::FileSpec &destination, uint32_t uid,
92b9c1b51eSKate Stone                        uint32_t gid) {
93a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
94fbb76349SGreg Clayton 
95b9c1b51eSKate Stone   if (IsHost()) {
96532290e6SPavel Labath     if (source == destination)
9797206d57SZachary Turner       return Status();
98e0f8f574SDaniel Malea     // cp src dst
99e0f8f574SDaniel Malea     // chown uid:gid dst
100e0f8f574SDaniel Malea     std::string src_path(source.GetPath());
101e0f8f574SDaniel Malea     if (src_path.empty())
10297206d57SZachary Turner       return Status("unable to get file path for source");
103e0f8f574SDaniel Malea     std::string dst_path(destination.GetPath());
104e0f8f574SDaniel Malea     if (dst_path.empty())
10597206d57SZachary Turner       return Status("unable to get file path for destination");
106e0f8f574SDaniel Malea     StreamString command;
107e0f8f574SDaniel Malea     command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
108e0f8f574SDaniel Malea     int status;
10928e4942bSPavel Labath     RunShellCommand(command.GetData(), FileSpec(), &status, nullptr, nullptr,
11019dd1a0eSPavel Labath                     std::chrono::seconds(10));
111e0f8f574SDaniel Malea     if (status != 0)
11297206d57SZachary Turner       return Status("unable to perform copy");
113e0f8f574SDaniel Malea     if (uid == UINT32_MAX && gid == UINT32_MAX)
11497206d57SZachary Turner       return Status();
115e0f8f574SDaniel Malea     if (chown_file(this, dst_path.c_str(), uid, gid) != 0)
11697206d57SZachary Turner       return Status("unable to perform chown");
11797206d57SZachary Turner     return Status();
118b9c1b51eSKate Stone   } else if (m_remote_platform_sp) {
119b9c1b51eSKate Stone     if (GetSupportsRSync()) {
120e0f8f574SDaniel Malea       std::string src_path(source.GetPath());
121e0f8f574SDaniel Malea       if (src_path.empty())
12297206d57SZachary Turner         return Status("unable to get file path for source");
123e0f8f574SDaniel Malea       std::string dst_path(destination.GetPath());
124e0f8f574SDaniel Malea       if (dst_path.empty())
12597206d57SZachary Turner         return Status("unable to get file path for destination");
126e0f8f574SDaniel Malea       StreamString command;
127b9c1b51eSKate Stone       if (GetIgnoresRemoteHostname()) {
128e0f8f574SDaniel Malea         if (!GetRSyncPrefix())
129b9c1b51eSKate Stone           command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
130e0f8f574SDaniel Malea                          dst_path.c_str());
131e0f8f574SDaniel Malea         else
132b9c1b51eSKate Stone           command.Printf("rsync %s %s %s%s", GetRSyncOpts(), src_path.c_str(),
133b9c1b51eSKate Stone                          GetRSyncPrefix(), dst_path.c_str());
134b9c1b51eSKate Stone       } else
135b9c1b51eSKate Stone         command.Printf("rsync %s %s %s:%s", GetRSyncOpts(), src_path.c_str(),
136b9c1b51eSKate Stone                        GetHostname(), dst_path.c_str());
13763e5fb76SJonas Devlieghere       LLDB_LOGF(log, "[PutFile] Running command: %s\n", command.GetData());
138e0f8f574SDaniel Malea       int retcode;
13928e4942bSPavel Labath       Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
140248a1305SKonrad Kleine                             nullptr, std::chrono::minutes(1));
141b9c1b51eSKate Stone       if (retcode == 0) {
142e0f8f574SDaniel Malea         // Don't chown a local file for a remote system
143e0f8f574SDaniel Malea         //                if (chown_file(this,dst_path.c_str(),uid,gid) != 0)
14497206d57SZachary Turner         //                    return Status("unable to perform chown");
14597206d57SZachary Turner         return Status();
146e0f8f574SDaniel Malea       }
147b9c1b51eSKate Stone       // if we are still here rsync has failed - let's try the slow way before
148b9c1b51eSKate Stone       // giving up
149e0f8f574SDaniel Malea     }
150e0f8f574SDaniel Malea   }
151e0f8f574SDaniel Malea   return Platform::PutFile(source, destination, uid, gid);
152e0f8f574SDaniel Malea }
153e0f8f574SDaniel Malea 
15497206d57SZachary Turner lldb_private::Status PlatformPOSIX::GetFile(
155b9c1b51eSKate Stone     const lldb_private::FileSpec &source,      // remote file path
156d3173f34SChaoren Lin     const lldb_private::FileSpec &destination) // local file path
157e0f8f574SDaniel Malea {
158a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
159fbb76349SGreg Clayton 
160e0f8f574SDaniel Malea   // Check the args, first.
161e0f8f574SDaniel Malea   std::string src_path(source.GetPath());
162e0f8f574SDaniel Malea   if (src_path.empty())
16397206d57SZachary Turner     return Status("unable to get file path for source");
164e0f8f574SDaniel Malea   std::string dst_path(destination.GetPath());
165e0f8f574SDaniel Malea   if (dst_path.empty())
16697206d57SZachary Turner     return Status("unable to get file path for destination");
167b9c1b51eSKate Stone   if (IsHost()) {
168532290e6SPavel Labath     if (source == destination)
16997206d57SZachary Turner       return Status("local scenario->source and destination are the same file "
170b9c1b51eSKate Stone                     "path: no operation performed");
171e0f8f574SDaniel Malea     // cp src dst
172e0f8f574SDaniel Malea     StreamString cp_command;
173e0f8f574SDaniel Malea     cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
174e0f8f574SDaniel Malea     int status;
17528e4942bSPavel Labath     RunShellCommand(cp_command.GetData(), FileSpec(), &status, nullptr, nullptr,
17619dd1a0eSPavel Labath                     std::chrono::seconds(10));
177e0f8f574SDaniel Malea     if (status != 0)
17897206d57SZachary Turner       return Status("unable to perform copy");
17997206d57SZachary Turner     return Status();
180b9c1b51eSKate Stone   } else if (m_remote_platform_sp) {
181b9c1b51eSKate Stone     if (GetSupportsRSync()) {
182e0f8f574SDaniel Malea       StreamString command;
183b9c1b51eSKate Stone       if (GetIgnoresRemoteHostname()) {
184e0f8f574SDaniel Malea         if (!GetRSyncPrefix())
185b9c1b51eSKate Stone           command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
186e0f8f574SDaniel Malea                          dst_path.c_str());
187e0f8f574SDaniel Malea         else
188b9c1b51eSKate Stone           command.Printf("rsync %s %s%s %s", GetRSyncOpts(), GetRSyncPrefix(),
189b9c1b51eSKate Stone                          src_path.c_str(), dst_path.c_str());
190b9c1b51eSKate Stone       } else
191b9c1b51eSKate Stone         command.Printf("rsync %s %s:%s %s", GetRSyncOpts(),
192b9c1b51eSKate Stone                        m_remote_platform_sp->GetHostname(), src_path.c_str(),
193e0f8f574SDaniel Malea                        dst_path.c_str());
19463e5fb76SJonas Devlieghere       LLDB_LOGF(log, "[GetFile] Running command: %s\n", command.GetData());
195e0f8f574SDaniel Malea       int retcode;
19628e4942bSPavel Labath       Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
197248a1305SKonrad Kleine                             nullptr, std::chrono::minutes(1));
198e0f8f574SDaniel Malea       if (retcode == 0)
19997206d57SZachary Turner         return Status();
20005097246SAdrian Prantl       // If we are here, rsync has failed - let's try the slow way before
20105097246SAdrian Prantl       // giving up
202e0f8f574SDaniel Malea     }
203e0f8f574SDaniel Malea     // open src and dst
204e0f8f574SDaniel Malea     // read/write, read/write, read/write, ...
205e0f8f574SDaniel Malea     // close src
206e0f8f574SDaniel Malea     // close dst
20763e5fb76SJonas Devlieghere     LLDB_LOGF(log, "[GetFile] Using block by block transfer....\n");
20897206d57SZachary Turner     Status error;
20914735cabSMichał Górny     user_id_t fd_src = OpenFile(source, File::eOpenOptionReadOnly,
210b9c1b51eSKate Stone                                 lldb::eFilePermissionsFileDefault, error);
211e0f8f574SDaniel Malea 
212e0f8f574SDaniel Malea     if (fd_src == UINT64_MAX)
21397206d57SZachary Turner       return Status("unable to open source file");
214e0f8f574SDaniel Malea 
215fbb76349SGreg Clayton     uint32_t permissions = 0;
216d3173f34SChaoren Lin     error = GetFilePermissions(source, permissions);
217e0f8f574SDaniel Malea 
218e0f8f574SDaniel Malea     if (permissions == 0)
219fbb76349SGreg Clayton       permissions = lldb::eFilePermissionsFileDefault;
220e0f8f574SDaniel Malea 
221c00cf4a0SZachary Turner     user_id_t fd_dst = FileCache::GetInstance().OpenFile(
22214735cabSMichał Górny         destination, File::eOpenOptionCanCreate | File::eOpenOptionWriteOnly |
223b9c1b51eSKate Stone                          File::eOpenOptionTruncate,
224b9c1b51eSKate Stone         permissions, error);
225e0f8f574SDaniel Malea 
226b9c1b51eSKate Stone     if (fd_dst == UINT64_MAX) {
227e0f8f574SDaniel Malea       if (error.Success())
228e0f8f574SDaniel Malea         error.SetErrorString("unable to open destination file");
229e0f8f574SDaniel Malea     }
230e0f8f574SDaniel Malea 
231b9c1b51eSKate Stone     if (error.Success()) {
232e0f8f574SDaniel Malea       lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
233e0f8f574SDaniel Malea       uint64_t offset = 0;
234e0f8f574SDaniel Malea       error.Clear();
235b9c1b51eSKate Stone       while (error.Success()) {
236b9c1b51eSKate Stone         const uint64_t n_read = ReadFile(fd_src, offset, buffer_sp->GetBytes(),
237b9c1b51eSKate Stone                                          buffer_sp->GetByteSize(), error);
238e0f8f574SDaniel Malea         if (error.Fail())
239e0f8f574SDaniel Malea           break;
240e0f8f574SDaniel Malea         if (n_read == 0)
241e0f8f574SDaniel Malea           break;
242b9c1b51eSKate Stone         if (FileCache::GetInstance().WriteFile(fd_dst, offset,
243b9c1b51eSKate Stone                                                buffer_sp->GetBytes(), n_read,
244b9c1b51eSKate Stone                                                error) != n_read) {
245e0f8f574SDaniel Malea           if (!error.Fail())
246e0f8f574SDaniel Malea             error.SetErrorString("unable to write to destination file");
247e0f8f574SDaniel Malea           break;
248e0f8f574SDaniel Malea         }
249e0f8f574SDaniel Malea         offset += n_read;
250e0f8f574SDaniel Malea       }
251e0f8f574SDaniel Malea     }
252e0f8f574SDaniel Malea     // Ignore the close error of src.
253e0f8f574SDaniel Malea     if (fd_src != UINT64_MAX)
254e0f8f574SDaniel Malea       CloseFile(fd_src, error);
255e0f8f574SDaniel Malea     // And close the dst file descriptot.
256b9c1b51eSKate Stone     if (fd_dst != UINT64_MAX &&
257b9c1b51eSKate Stone         !FileCache::GetInstance().CloseFile(fd_dst, error)) {
258e0f8f574SDaniel Malea       if (!error.Fail())
259e0f8f574SDaniel Malea         error.SetErrorString("unable to close destination file");
260e0f8f574SDaniel Malea     }
261e0f8f574SDaniel Malea     return error;
262e0f8f574SDaniel Malea   }
263e0f8f574SDaniel Malea   return Platform::GetFile(source, destination);
264e0f8f574SDaniel Malea }
265e0f8f574SDaniel Malea 
266b9c1b51eSKate Stone std::string PlatformPOSIX::GetPlatformSpecificConnectionInformation() {
267e0f8f574SDaniel Malea   StreamString stream;
268b9c1b51eSKate Stone   if (GetSupportsRSync()) {
269e0f8f574SDaniel Malea     stream.PutCString("rsync");
270e0f8f574SDaniel Malea     if ((GetRSyncOpts() && *GetRSyncOpts()) ||
271b9c1b51eSKate Stone         (GetRSyncPrefix() && *GetRSyncPrefix()) || GetIgnoresRemoteHostname()) {
272e0f8f574SDaniel Malea       stream.Printf(", options: ");
273e0f8f574SDaniel Malea       if (GetRSyncOpts() && *GetRSyncOpts())
274e0f8f574SDaniel Malea         stream.Printf("'%s' ", GetRSyncOpts());
275e0f8f574SDaniel Malea       stream.Printf(", prefix: ");
276e0f8f574SDaniel Malea       if (GetRSyncPrefix() && *GetRSyncPrefix())
277e0f8f574SDaniel Malea         stream.Printf("'%s' ", GetRSyncPrefix());
278e0f8f574SDaniel Malea       if (GetIgnoresRemoteHostname())
279e0f8f574SDaniel Malea         stream.Printf("ignore remote-hostname ");
280e0f8f574SDaniel Malea     }
281e0f8f574SDaniel Malea   }
282b9c1b51eSKate Stone   if (GetSupportsSSH()) {
283e0f8f574SDaniel Malea     stream.PutCString("ssh");
284e0f8f574SDaniel Malea     if (GetSSHOpts() && *GetSSHOpts())
285e0f8f574SDaniel Malea       stream.Printf(", options: '%s' ", GetSSHOpts());
286e0f8f574SDaniel Malea   }
287e0f8f574SDaniel Malea   if (GetLocalCacheDirectory() && *GetLocalCacheDirectory())
288e0f8f574SDaniel Malea     stream.Printf("cache dir: %s", GetLocalCacheDirectory());
289e0f8f574SDaniel Malea   if (stream.GetSize())
290adcd0268SBenjamin Kramer     return std::string(stream.GetString());
291e0f8f574SDaniel Malea   else
292e0f8f574SDaniel Malea     return "";
293e0f8f574SDaniel Malea }
294e0f8f574SDaniel Malea 
295b9c1b51eSKate Stone const lldb::UnixSignalsSP &PlatformPOSIX::GetRemoteUnixSignals() {
29698d0a4b3SChaoren Lin   if (IsRemote() && m_remote_platform_sp)
29798d0a4b3SChaoren Lin     return m_remote_platform_sp->GetRemoteUnixSignals();
29898d0a4b3SChaoren Lin   return Platform::GetRemoteUnixSignals();
29998d0a4b3SChaoren Lin }
30098d0a4b3SChaoren Lin 
30197206d57SZachary Turner Status PlatformPOSIX::ConnectRemote(Args &args) {
30297206d57SZachary Turner   Status error;
303b9c1b51eSKate Stone   if (IsHost()) {
304a3939e15SPavel Labath     error.SetErrorStringWithFormatv(
305a3939e15SPavel Labath         "can't connect to the host platform '{0}', always connected",
306a3939e15SPavel Labath         GetPluginName());
307b9c1b51eSKate Stone   } else {
308015d818bSTodd Fiala     if (!m_remote_platform_sp)
309b9c1b51eSKate Stone       m_remote_platform_sp =
310b9c1b51eSKate Stone           Platform::Create(ConstString("remote-gdb-server"), error);
311015d818bSTodd Fiala 
312015d818bSTodd Fiala     if (m_remote_platform_sp && error.Success())
313015d818bSTodd Fiala       error = m_remote_platform_sp->ConnectRemote(args);
314015d818bSTodd Fiala     else
315015d818bSTodd Fiala       error.SetErrorString("failed to create a 'remote-gdb-server' platform");
316015d818bSTodd Fiala 
317015d818bSTodd Fiala     if (error.Fail())
318015d818bSTodd Fiala       m_remote_platform_sp.reset();
319015d818bSTodd Fiala   }
320015d818bSTodd Fiala 
321b9c1b51eSKate Stone   if (error.Success() && m_remote_platform_sp) {
322b9c1b51eSKate Stone     if (m_option_group_platform_rsync.get() &&
323b9c1b51eSKate Stone         m_option_group_platform_ssh.get() &&
324b9c1b51eSKate Stone         m_option_group_platform_caching.get()) {
325b9c1b51eSKate Stone       if (m_option_group_platform_rsync->m_rsync) {
326015d818bSTodd Fiala         SetSupportsRSync(true);
3270a66e2f1SEnrico Granata         SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str());
3280a66e2f1SEnrico Granata         SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str());
329b9c1b51eSKate Stone         SetIgnoresRemoteHostname(
330b9c1b51eSKate Stone             m_option_group_platform_rsync->m_ignores_remote_hostname);
331015d818bSTodd Fiala       }
332b9c1b51eSKate Stone       if (m_option_group_platform_ssh->m_ssh) {
333015d818bSTodd Fiala         SetSupportsSSH(true);
3340a66e2f1SEnrico Granata         SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str());
335015d818bSTodd Fiala       }
336b9c1b51eSKate Stone       SetLocalCacheDirectory(
337b9c1b51eSKate Stone           m_option_group_platform_caching->m_cache_dir.c_str());
338015d818bSTodd Fiala     }
339015d818bSTodd Fiala   }
340015d818bSTodd Fiala 
341015d818bSTodd Fiala   return error;
342015d818bSTodd Fiala }
343015d818bSTodd Fiala 
34497206d57SZachary Turner Status PlatformPOSIX::DisconnectRemote() {
34597206d57SZachary Turner   Status error;
346015d818bSTodd Fiala 
347b9c1b51eSKate Stone   if (IsHost()) {
348a3939e15SPavel Labath     error.SetErrorStringWithFormatv(
349a3939e15SPavel Labath         "can't disconnect from the host platform '{0}', always connected",
350a3939e15SPavel Labath         GetPluginName());
351b9c1b51eSKate Stone   } else {
352015d818bSTodd Fiala     if (m_remote_platform_sp)
353015d818bSTodd Fiala       error = m_remote_platform_sp->DisconnectRemote();
354015d818bSTodd Fiala     else
355015d818bSTodd Fiala       error.SetErrorString("the platform is not currently connected");
356015d818bSTodd Fiala   }
357015d818bSTodd Fiala   return error;
358015d818bSTodd Fiala }
359015d818bSTodd Fiala 
360b9c1b51eSKate Stone lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info,
361b9c1b51eSKate Stone                                       Debugger &debugger, Target *target,
36297206d57SZachary Turner                                       Status &error) {
363348fb385STodd Fiala   lldb::ProcessSP process_sp;
364a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
365348fb385STodd Fiala 
366b9c1b51eSKate Stone   if (IsHost()) {
367248a1305SKonrad Kleine     if (target == nullptr) {
368348fb385STodd Fiala       TargetSP new_target_sp;
369348fb385STodd Fiala 
370f9a07e9fSJonas Devlieghere       error = debugger.GetTargetList().CreateTarget(
371248a1305SKonrad Kleine           debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
372348fb385STodd Fiala       target = new_target_sp.get();
37363e5fb76SJonas Devlieghere       LLDB_LOGF(log, "PlatformPOSIX::%s created new target", __FUNCTION__);
374b9c1b51eSKate Stone     } else {
375348fb385STodd Fiala       error.Clear();
37663e5fb76SJonas Devlieghere       LLDB_LOGF(log, "PlatformPOSIX::%s target already existed, setting target",
377b9c1b51eSKate Stone                 __FUNCTION__);
378348fb385STodd Fiala     }
379348fb385STodd Fiala 
380b9c1b51eSKate Stone     if (target && error.Success()) {
381b9c1b51eSKate Stone       if (log) {
382348fb385STodd Fiala         ModuleSP exe_module_sp = target->GetExecutableModule();
38363e5fb76SJonas Devlieghere         LLDB_LOGF(log, "PlatformPOSIX::%s set selected target to %p %s",
384b9c1b51eSKate Stone                   __FUNCTION__, (void *)target,
38563e5fb76SJonas Devlieghere                   exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
386b9c1b51eSKate Stone                                 : "<null>");
387348fb385STodd Fiala       }
388348fb385STodd Fiala 
389b9c1b51eSKate Stone       process_sp =
390b9c1b51eSKate Stone           target->CreateProcess(attach_info.GetListenerForProcess(debugger),
3911a1cc0baSMichał Górny                                 "gdb-remote", nullptr, true);
392348fb385STodd Fiala 
393b9c1b51eSKate Stone       if (process_sp) {
394583bbb1dSJim Ingham         ListenerSP listener_sp = attach_info.GetHijackListener();
395b9c1b51eSKate Stone         if (listener_sp == nullptr) {
396b9c1b51eSKate Stone           listener_sp =
397b9c1b51eSKate Stone               Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
398348fb385STodd Fiala           attach_info.SetHijackListener(listener_sp);
399926af0cdSOleksiy Vyalov         }
400583bbb1dSJim Ingham         process_sp->HijackProcessEvents(listener_sp);
401348fb385STodd Fiala         error = process_sp->Attach(attach_info);
402348fb385STodd Fiala       }
403348fb385STodd Fiala     }
404b9c1b51eSKate Stone   } else {
405348fb385STodd Fiala     if (m_remote_platform_sp)
406b9c1b51eSKate Stone       process_sp =
407b9c1b51eSKate Stone           m_remote_platform_sp->Attach(attach_info, debugger, target, error);
408348fb385STodd Fiala     else
409348fb385STodd Fiala       error.SetErrorString("the platform is not currently connected");
410348fb385STodd Fiala   }
411348fb385STodd Fiala   return process_sp;
412348fb385STodd Fiala }
413348fb385STodd Fiala 
414bd590a5fSPavel Labath lldb::ProcessSP PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info,
415bd590a5fSPavel Labath                                             Debugger &debugger, Target &target,
41697206d57SZachary Turner                                             Status &error) {
417a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
418bd590a5fSPavel Labath   LLDB_LOG(log, "target {0}", &target);
419a825eaa9SMichał Górny 
420015d818bSTodd Fiala   ProcessSP process_sp;
421015d818bSTodd Fiala 
422a825eaa9SMichał Górny   if (!IsHost()) {
423015d818bSTodd Fiala     if (m_remote_platform_sp)
424b9c1b51eSKate Stone       process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
425b9c1b51eSKate Stone                                                       target, error);
426015d818bSTodd Fiala     else
427015d818bSTodd Fiala       error.SetErrorString("the platform is not currently connected");
428a825eaa9SMichał Górny     return process_sp;
429015d818bSTodd Fiala   }
430a825eaa9SMichał Górny 
431a825eaa9SMichał Górny   //
432a825eaa9SMichał Górny   // For local debugging, we'll insist on having ProcessGDBRemote create the
433a825eaa9SMichał Górny   // process.
434a825eaa9SMichał Górny   //
435a825eaa9SMichał Górny 
436a825eaa9SMichał Górny   // Make sure we stop at the entry point
437a825eaa9SMichał Górny   launch_info.GetFlags().Set(eLaunchFlagDebug);
438a825eaa9SMichał Górny 
439a825eaa9SMichał Górny   // We always launch the process we are going to debug in a separate process
440a825eaa9SMichał Górny   // group, since then we can handle ^C interrupts ourselves w/o having to
441a825eaa9SMichał Górny   // worry about the target getting them as well.
442a825eaa9SMichał Górny   launch_info.SetLaunchInSeparateProcessGroup(true);
443a825eaa9SMichał Górny 
444a825eaa9SMichał Górny   // Now create the gdb-remote process.
445a825eaa9SMichał Górny   LLDB_LOG(log, "having target create process with gdb-remote plugin");
446a825eaa9SMichał Górny   process_sp =
447bd590a5fSPavel Labath       target.CreateProcess(launch_info.GetListener(), "gdb-remote", nullptr,
44818e4272aSMichał Górny                             true);
449a825eaa9SMichał Górny 
450a825eaa9SMichał Górny   if (!process_sp) {
451a825eaa9SMichał Górny     error.SetErrorString("CreateProcess() failed for gdb-remote process");
452a825eaa9SMichał Górny     LLDB_LOG(log, "error: {0}", error);
453a825eaa9SMichał Górny     return process_sp;
454a825eaa9SMichał Górny   }
455a825eaa9SMichał Górny 
456a825eaa9SMichał Górny   LLDB_LOG(log, "successfully created process");
457a825eaa9SMichał Górny   // Adjust launch for a hijacker.
458a825eaa9SMichał Górny   ListenerSP listener_sp;
459a825eaa9SMichał Górny   if (!launch_info.GetHijackListener()) {
460a825eaa9SMichał Górny     LLDB_LOG(log, "setting up hijacker");
461a825eaa9SMichał Górny     listener_sp =
462a825eaa9SMichał Górny         Listener::MakeListener("lldb.PlatformLinux.DebugProcess.hijack");
463a825eaa9SMichał Górny     launch_info.SetHijackListener(listener_sp);
464a825eaa9SMichał Górny     process_sp->HijackProcessEvents(listener_sp);
465a825eaa9SMichał Górny   }
466a825eaa9SMichał Górny 
467a825eaa9SMichał Górny   // Log file actions.
468a825eaa9SMichał Górny   if (log) {
469a825eaa9SMichał Górny     LLDB_LOG(log, "launching process with the following file actions:");
470a825eaa9SMichał Górny     StreamString stream;
471a825eaa9SMichał Górny     size_t i = 0;
472a825eaa9SMichał Górny     const FileAction *file_action;
473a825eaa9SMichał Górny     while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) {
474a825eaa9SMichał Górny       file_action->Dump(stream);
475a825eaa9SMichał Górny       LLDB_LOG(log, "{0}", stream.GetData());
476a825eaa9SMichał Górny       stream.Clear();
477a825eaa9SMichał Górny     }
478a825eaa9SMichał Górny   }
479a825eaa9SMichał Górny 
480a825eaa9SMichał Górny   // Do the launch.
481a825eaa9SMichał Górny   error = process_sp->Launch(launch_info);
482a825eaa9SMichał Górny   if (error.Success()) {
483a825eaa9SMichał Górny     // Handle the hijacking of process events.
484a825eaa9SMichał Górny     if (listener_sp) {
485a825eaa9SMichał Górny       const StateType state = process_sp->WaitForProcessToStop(
486a825eaa9SMichał Górny           llvm::None, nullptr, false, listener_sp);
487a825eaa9SMichał Górny 
488a825eaa9SMichał Górny       LLDB_LOG(log, "pid {0} state {0}", process_sp->GetID(), state);
489a825eaa9SMichał Górny     }
490a825eaa9SMichał Górny 
491a825eaa9SMichał Górny     // Hook up process PTY if we have one (which we should for local debugging
492a825eaa9SMichał Górny     // with llgs).
493a825eaa9SMichał Górny     int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
494a825eaa9SMichał Górny     if (pty_fd != PseudoTerminal::invalid_fd) {
495a825eaa9SMichał Górny       process_sp->SetSTDIOFileDescriptor(pty_fd);
496a825eaa9SMichał Górny       LLDB_LOG(log, "hooked up STDIO pty to process");
497a825eaa9SMichał Górny     } else
498a825eaa9SMichał Górny       LLDB_LOG(log, "not using process STDIO pty");
499a825eaa9SMichał Górny   } else {
500a825eaa9SMichał Górny     LLDB_LOG(log, "{0}", error);
501bd590a5fSPavel Labath     // FIXME figure out appropriate cleanup here. Do we delete the process?
502bd590a5fSPavel Labath     // Does our caller do that?
503a825eaa9SMichał Górny   }
504a825eaa9SMichał Górny 
505015d818bSTodd Fiala   return process_sp;
506015d818bSTodd Fiala }
507015d818bSTodd Fiala 
508b9c1b51eSKate Stone void PlatformPOSIX::CalculateTrapHandlerSymbolNames() {
5092094dbf4SJason Molenda   m_trap_handlers.push_back(ConstString("_sigtramp"));
5102094dbf4SJason Molenda }
5113cb132a0STamas Berghammer 
51297206d57SZachary Turner Status PlatformPOSIX::EvaluateLibdlExpression(
513b9c1b51eSKate Stone     lldb_private::Process *process, const char *expr_cstr,
514d37c9469SPavel Labath     llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
5153cb132a0STamas Berghammer   DynamicLoader *loader = process->GetDynamicLoader();
516b9c1b51eSKate Stone   if (loader) {
51797206d57SZachary Turner     Status error = loader->CanLoadImage();
5183cb132a0STamas Berghammer     if (error.Fail())
5193cb132a0STamas Berghammer       return error;
5203cb132a0STamas Berghammer   }
5213cb132a0STamas Berghammer 
5228d94ba0fSJim Ingham   ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread());
5233cb132a0STamas Berghammer   if (!thread_sp)
52497206d57SZachary Turner     return Status("Selected thread isn't valid");
5253cb132a0STamas Berghammer 
5263cb132a0STamas Berghammer   StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
5273cb132a0STamas Berghammer   if (!frame_sp)
52897206d57SZachary Turner     return Status("Frame 0 isn't valid");
5293cb132a0STamas Berghammer 
5303cb132a0STamas Berghammer   ExecutionContext exe_ctx;
5313cb132a0STamas Berghammer   frame_sp->CalculateExecutionContext(exe_ctx);
5323cb132a0STamas Berghammer   EvaluateExpressionOptions expr_options;
5333cb132a0STamas Berghammer   expr_options.SetUnwindOnError(true);
5343cb132a0STamas Berghammer   expr_options.SetIgnoreBreakpoints(true);
5353cb132a0STamas Berghammer   expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
5363cb132a0STamas Berghammer   expr_options.SetLanguage(eLanguageTypeC_plus_plus);
537b9c1b51eSKate Stone   expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
538b9c1b51eSKate Stone                                          // don't do the work to trap them.
5394c03ea14SAdrian Prantl   expr_options.SetTimeout(process->GetUtilityExpressionTimeout());
5403cb132a0STamas Berghammer 
54197206d57SZachary Turner   Status expr_error;
54202980825SJim Ingham   ExpressionResults result =
543b9c1b51eSKate Stone       UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix,
544b9c1b51eSKate Stone                                result_valobj_sp, expr_error);
54502980825SJim Ingham   if (result != eExpressionCompleted)
54602980825SJim Ingham     return expr_error;
54702980825SJim Ingham 
5483cb132a0STamas Berghammer   if (result_valobj_sp->GetError().Fail())
5493cb132a0STamas Berghammer     return result_valobj_sp->GetError();
55097206d57SZachary Turner   return Status();
5513cb132a0STamas Berghammer }
5523cb132a0STamas Berghammer 
553d10d3795SFrederic Riss std::unique_ptr<UtilityFunction>
5541ecb34f4SJim Ingham PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx,
555d10d3795SFrederic Riss                                             Status &error) {
55605097246SAdrian Prantl   // Remember to prepend this with the prefix from
55705097246SAdrian Prantl   // GetLibdlFunctionDeclarations. The returned values are all in
55805097246SAdrian Prantl   // __lldb_dlopen_result for consistency. The wrapper returns a void * but
55905097246SAdrian Prantl   // doesn't use it because UtilityFunctions don't work with void returns at
56005097246SAdrian Prantl   // present.
5614bd2bfb6SVedant Kumar   //
5624bd2bfb6SVedant Kumar   // Use lazy binding so as to not make dlopen()'s success conditional on
5634bd2bfb6SVedant Kumar   // forcing every symbol in the library.
5644bd2bfb6SVedant Kumar   //
5654bd2bfb6SVedant Kumar   // In general, the debugger should allow programs to load & run with
5664bd2bfb6SVedant Kumar   // libraries as far as they can, instead of defaulting to being super-picky
5674bd2bfb6SVedant Kumar   // about unavailable symbols.
5684bd2bfb6SVedant Kumar   //
5694bd2bfb6SVedant Kumar   // The value "1" appears to imply lazy binding (RTLD_LAZY) on both Darwin
5704bd2bfb6SVedant Kumar   // and other POSIX OSes.
5711ecb34f4SJim Ingham   static const char *dlopen_wrapper_code = R"(
5724bd2bfb6SVedant Kumar   const int RTLD_LAZY = 1;
5734bd2bfb6SVedant Kumar 
5741ecb34f4SJim Ingham   struct __lldb_dlopen_result {
5751ecb34f4SJim Ingham     void *image_ptr;
5761ecb34f4SJim Ingham     const char *error_str;
5771ecb34f4SJim Ingham   };
5781ecb34f4SJim Ingham 
57903856dd9SJim Ingham   extern void *memcpy(void *, const void *, size_t size);
5800d231f71SJim Ingham   extern size_t strlen(const char *);
5810d231f71SJim Ingham 
5820d231f71SJim Ingham 
5830d231f71SJim Ingham   void * __lldb_dlopen_wrapper (const char *name,
5840d231f71SJim Ingham                                 const char *path_strings,
5850d231f71SJim Ingham                                 char *buffer,
5861ecb34f4SJim Ingham                                 __lldb_dlopen_result *result_ptr)
5871ecb34f4SJim Ingham   {
5880d231f71SJim Ingham     // This is the case where the name is the full path:
58903856dd9SJim Ingham     if (!path_strings) {
5904bd2bfb6SVedant Kumar       result_ptr->image_ptr = dlopen(name, RTLD_LAZY);
59103856dd9SJim Ingham       if (result_ptr->image_ptr)
5920d231f71SJim Ingham         result_ptr->error_str = nullptr;
593f7588597SJim Ingham       else
594f7588597SJim Ingham         result_ptr->error_str = dlerror();
5950d231f71SJim Ingham       return nullptr;
5960d231f71SJim Ingham     }
5970d231f71SJim Ingham 
5980d231f71SJim Ingham     // This is the case where we have a list of paths:
5990d231f71SJim Ingham     size_t name_len = strlen(name);
60003856dd9SJim Ingham     while (path_strings && path_strings[0] != '\0') {
6010d231f71SJim Ingham       size_t path_len = strlen(path_strings);
6020d231f71SJim Ingham       memcpy((void *) buffer, (void *) path_strings, path_len);
6030d231f71SJim Ingham       buffer[path_len] = '/';
6040d231f71SJim Ingham       char *target_ptr = buffer+path_len+1;
6050d231f71SJim Ingham       memcpy((void *) target_ptr, (void *) name, name_len + 1);
6064bd2bfb6SVedant Kumar       result_ptr->image_ptr = dlopen(buffer, RTLD_LAZY);
60703856dd9SJim Ingham       if (result_ptr->image_ptr) {
6080d231f71SJim Ingham         result_ptr->error_str = nullptr;
6090d231f71SJim Ingham         break;
6100d231f71SJim Ingham       }
6111ecb34f4SJim Ingham       result_ptr->error_str = dlerror();
6120d231f71SJim Ingham       path_strings = path_strings + path_len + 1;
6130d231f71SJim Ingham     }
6141ecb34f4SJim Ingham     return nullptr;
6151ecb34f4SJim Ingham   }
6161ecb34f4SJim Ingham   )";
6171ecb34f4SJim Ingham 
6181ecb34f4SJim Ingham   static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
6191ecb34f4SJim Ingham   Process *process = exe_ctx.GetProcessSP().get();
6201ecb34f4SJim Ingham   // Insert the dlopen shim defines into our generic expression:
621adcd0268SBenjamin Kramer   std::string expr(std::string(GetLibdlFunctionDeclarations(process)));
6221ecb34f4SJim Ingham   expr.append(dlopen_wrapper_code);
6231ecb34f4SJim Ingham   Status utility_error;
6241ecb34f4SJim Ingham   DiagnosticManager diagnostics;
6251ecb34f4SJim Ingham 
626de346cf2SJonas Devlieghere   auto utility_fn_or_error = process->GetTarget().CreateUtilityFunction(
627de346cf2SJonas Devlieghere       std::move(expr), dlopen_wrapper_name, eLanguageTypeObjC, exe_ctx);
628de346cf2SJonas Devlieghere   if (!utility_fn_or_error) {
629de346cf2SJonas Devlieghere     std::string error_str = llvm::toString(utility_fn_or_error.takeError());
630de346cf2SJonas Devlieghere     error.SetErrorStringWithFormat("dlopen error: could not create utility"
6311ecb34f4SJim Ingham                                    "function: %s",
632de346cf2SJonas Devlieghere                                    error_str.c_str());
6331ecb34f4SJim Ingham     return nullptr;
6341ecb34f4SJim Ingham   }
635de346cf2SJonas Devlieghere   std::unique_ptr<UtilityFunction> dlopen_utility_func_up =
636de346cf2SJonas Devlieghere       std::move(*utility_fn_or_error);
6371ecb34f4SJim Ingham 
6381ecb34f4SJim Ingham   Value value;
6391ecb34f4SJim Ingham   ValueList arguments;
6401ecb34f4SJim Ingham   FunctionCaller *do_dlopen_function = nullptr;
6411ecb34f4SJim Ingham 
6421ecb34f4SJim Ingham   // Fetch the clang types we will need:
643594308c7SRaphael Isemann   TypeSystemClang *ast =
644594308c7SRaphael Isemann       ScratchTypeSystemClang::GetForTarget(process->GetTarget());
6453031818aSAlex Langford   if (!ast)
6463031818aSAlex Langford     return nullptr;
6471ecb34f4SJim Ingham 
6481ecb34f4SJim Ingham   CompilerType clang_void_pointer_type
6491ecb34f4SJim Ingham       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
6501ecb34f4SJim Ingham   CompilerType clang_char_pointer_type
6511ecb34f4SJim Ingham         = ast->GetBasicType(eBasicTypeChar).GetPointerType();
6521ecb34f4SJim Ingham 
6530d231f71SJim Ingham   // We are passing four arguments, the basename, the list of places to look,
6540d231f71SJim Ingham   // a buffer big enough for all the path + name combos, and
6550d231f71SJim Ingham   // a pointer to the storage we've made for the result:
656057efa99SAdrian Prantl   value.SetValueType(Value::ValueType::Scalar);
6571ecb34f4SJim Ingham   value.SetCompilerType(clang_void_pointer_type);
6581ecb34f4SJim Ingham   arguments.PushValue(value);
6591ecb34f4SJim Ingham   value.SetCompilerType(clang_char_pointer_type);
6601ecb34f4SJim Ingham   arguments.PushValue(value);
6610d231f71SJim Ingham   arguments.PushValue(value);
6620d231f71SJim Ingham   arguments.PushValue(value);
6631ecb34f4SJim Ingham 
6641ecb34f4SJim Ingham   do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
6651ecb34f4SJim Ingham       clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
6661ecb34f4SJim Ingham   if (utility_error.Fail()) {
6671ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not make function"
6681ecb34f4SJim Ingham                                    "caller: %s", utility_error.AsCString());
6691ecb34f4SJim Ingham     return nullptr;
6701ecb34f4SJim Ingham   }
6711ecb34f4SJim Ingham 
6721ecb34f4SJim Ingham   do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
6731ecb34f4SJim Ingham   if (!do_dlopen_function) {
6741ecb34f4SJim Ingham     error.SetErrorString("dlopen error: could not get function caller.");
6751ecb34f4SJim Ingham     return nullptr;
6761ecb34f4SJim Ingham   }
6771ecb34f4SJim Ingham 
6781ecb34f4SJim Ingham   // We made a good utility function, so cache it in the process:
679d10d3795SFrederic Riss   return dlopen_utility_func_up;
6801ecb34f4SJim Ingham }
6811ecb34f4SJim Ingham 
682b9c1b51eSKate Stone uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process,
6834fbd67acSTamas Berghammer                                     const lldb_private::FileSpec &remote_file,
6840d231f71SJim Ingham                                     const std::vector<std::string> *paths,
6850d231f71SJim Ingham                                     lldb_private::Status &error,
6860d231f71SJim Ingham                                     lldb_private::FileSpec *loaded_image) {
6870d231f71SJim Ingham   if (loaded_image)
6880d231f71SJim Ingham     loaded_image->Clear();
6890d231f71SJim Ingham 
6901ecb34f4SJim Ingham   std::string path;
6911ecb34f4SJim Ingham   path = remote_file.GetPath();
6923cb132a0STamas Berghammer 
6931ecb34f4SJim Ingham   ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
6941ecb34f4SJim Ingham   if (!thread_sp) {
6951ecb34f4SJim Ingham     error.SetErrorString("dlopen error: no thread available to call dlopen.");
6963cb132a0STamas Berghammer     return LLDB_INVALID_IMAGE_TOKEN;
6973cb132a0STamas Berghammer   }
6983cb132a0STamas Berghammer 
6991ecb34f4SJim Ingham   DiagnosticManager diagnostics;
7003cb132a0STamas Berghammer 
7011ecb34f4SJim Ingham   ExecutionContext exe_ctx;
7021ecb34f4SJim Ingham   thread_sp->CalculateExecutionContext(exe_ctx);
7031ecb34f4SJim Ingham 
7041ecb34f4SJim Ingham   Status utility_error;
705d10d3795SFrederic Riss   UtilityFunction *dlopen_utility_func;
7061ecb34f4SJim Ingham   ValueList arguments;
7071ecb34f4SJim Ingham   FunctionCaller *do_dlopen_function = nullptr;
7081ecb34f4SJim Ingham 
709d10d3795SFrederic Riss   // The UtilityFunction is held in the Process.  Platforms don't track the
710d10d3795SFrederic Riss   // lifespan of the Targets that use them, we can't put this in the Platform.
711d10d3795SFrederic Riss   dlopen_utility_func = process->GetLoadImageUtilityFunction(
712d10d3795SFrederic Riss       this, [&]() -> std::unique_ptr<UtilityFunction> {
713d10d3795SFrederic Riss         return MakeLoadImageUtilityFunction(exe_ctx, error);
714d10d3795SFrederic Riss       });
7151ecb34f4SJim Ingham   // If we couldn't make it, the error will be in error, so we can exit here.
7161ecb34f4SJim Ingham   if (!dlopen_utility_func)
7171ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7181ecb34f4SJim Ingham 
7191ecb34f4SJim Ingham   do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
7201ecb34f4SJim Ingham   if (!do_dlopen_function) {
7211ecb34f4SJim Ingham     error.SetErrorString("dlopen error: could not get function caller.");
7221ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7231ecb34f4SJim Ingham   }
7241ecb34f4SJim Ingham   arguments = do_dlopen_function->GetArgumentValues();
7251ecb34f4SJim Ingham 
72605097246SAdrian Prantl   // Now insert the path we are searching for and the result structure into the
72705097246SAdrian Prantl   // target.
7281ecb34f4SJim Ingham   uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
7291ecb34f4SJim Ingham   size_t path_len = path.size() + 1;
7301ecb34f4SJim Ingham   lldb::addr_t path_addr = process->AllocateMemory(path_len,
7311ecb34f4SJim Ingham                                                    permissions,
7321ecb34f4SJim Ingham                                                    utility_error);
7331ecb34f4SJim Ingham   if (path_addr == LLDB_INVALID_ADDRESS) {
7341ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
7351ecb34f4SJim Ingham                                     "for path: %s", utility_error.AsCString());
7361ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7371ecb34f4SJim Ingham   }
7381ecb34f4SJim Ingham 
7391ecb34f4SJim Ingham   // Make sure we deallocate the input string memory:
740e0ea8d87SJonas Devlieghere   auto path_cleanup = llvm::make_scope_exit([process, path_addr] {
741e0ea8d87SJonas Devlieghere     // Deallocate the buffer.
7421ecb34f4SJim Ingham     process->DeallocateMemory(path_addr);
7431ecb34f4SJim Ingham   });
7441ecb34f4SJim Ingham 
7451ecb34f4SJim Ingham   process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
7461ecb34f4SJim Ingham   if (utility_error.Fail()) {
7471ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not write path string:"
7481ecb34f4SJim Ingham                                     " %s", utility_error.AsCString());
7491ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7501ecb34f4SJim Ingham   }
7511ecb34f4SJim Ingham 
75205097246SAdrian Prantl   // Make space for our return structure.  It is two pointers big: the token
75305097246SAdrian Prantl   // and the error string.
7541ecb34f4SJim Ingham   const uint32_t addr_size = process->GetAddressByteSize();
7551ecb34f4SJim Ingham   lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
7561ecb34f4SJim Ingham                                                       permissions,
7571ecb34f4SJim Ingham                                                       utility_error);
7581ecb34f4SJim Ingham   if (utility_error.Fail()) {
7591ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
7601ecb34f4SJim Ingham                                     "for path: %s", utility_error.AsCString());
7611ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
7621ecb34f4SJim Ingham   }
7631ecb34f4SJim Ingham 
7641ecb34f4SJim Ingham   // Make sure we deallocate the result structure memory
765e0ea8d87SJonas Devlieghere   auto return_cleanup = llvm::make_scope_exit([process, return_addr] {
766e0ea8d87SJonas Devlieghere     // Deallocate the buffer
7671ecb34f4SJim Ingham     process->DeallocateMemory(return_addr);
7681ecb34f4SJim Ingham   });
7691ecb34f4SJim Ingham 
7700d231f71SJim Ingham   // This will be the address of the storage for paths, if we are using them,
7710d231f71SJim Ingham   // or nullptr to signal we aren't.
7720d231f71SJim Ingham   lldb::addr_t path_array_addr = 0x0;
773e0ea8d87SJonas Devlieghere   llvm::Optional<llvm::detail::scope_exit<std::function<void()>>>
774e0ea8d87SJonas Devlieghere       path_array_cleanup;
7750d231f71SJim Ingham 
7760d231f71SJim Ingham   // This is the address to a buffer large enough to hold the largest path
7770d231f71SJim Ingham   // conjoined with the library name we're passing in.  This is a convenience
7780d231f71SJim Ingham   // to avoid having to call malloc in the dlopen function.
7790d231f71SJim Ingham   lldb::addr_t buffer_addr = 0x0;
780e0ea8d87SJonas Devlieghere   llvm::Optional<llvm::detail::scope_exit<std::function<void()>>>
781e0ea8d87SJonas Devlieghere       buffer_cleanup;
7820d231f71SJim Ingham 
7831ecb34f4SJim Ingham   // Set the values into our args and write them to the target:
7840d231f71SJim Ingham   if (paths != nullptr) {
7850d231f71SJim Ingham     // First insert the paths into the target.  This is expected to be a
7860d231f71SJim Ingham     // continuous buffer with the strings laid out null terminated and
7870d231f71SJim Ingham     // end to end with an empty string terminating the buffer.
7880d231f71SJim Ingham     // We also compute the buffer's required size as we go.
7890d231f71SJim Ingham     size_t buffer_size = 0;
7900d231f71SJim Ingham     std::string path_array;
7910d231f71SJim Ingham     for (auto path : *paths) {
79240fa4a1aSJim Ingham       // Don't insert empty paths, they will make us abort the path
79340fa4a1aSJim Ingham       // search prematurely.
79440fa4a1aSJim Ingham       if (path.empty())
79540fa4a1aSJim Ingham         continue;
7960d231f71SJim Ingham       size_t path_size = path.size();
7970d231f71SJim Ingham       path_array.append(path);
7980d231f71SJim Ingham       path_array.push_back('\0');
7990d231f71SJim Ingham       if (path_size > buffer_size)
8000d231f71SJim Ingham         buffer_size = path_size;
8010d231f71SJim Ingham     }
8020d231f71SJim Ingham     path_array.push_back('\0');
8030d231f71SJim Ingham 
8040d231f71SJim Ingham     path_array_addr = process->AllocateMemory(path_array.size(),
8050d231f71SJim Ingham                                               permissions,
8060d231f71SJim Ingham                                               utility_error);
8070d231f71SJim Ingham     if (path_array_addr == LLDB_INVALID_ADDRESS) {
8080d231f71SJim Ingham       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
8090d231f71SJim Ingham                                       "for path array: %s",
8100d231f71SJim Ingham                                       utility_error.AsCString());
8110d231f71SJim Ingham       return LLDB_INVALID_IMAGE_TOKEN;
8120d231f71SJim Ingham     }
8130d231f71SJim Ingham 
8140d231f71SJim Ingham     // Make sure we deallocate the paths array.
815e0ea8d87SJonas Devlieghere     path_array_cleanup.emplace([process, path_array_addr]() {
816e0ea8d87SJonas Devlieghere       // Deallocate the path array.
8170d231f71SJim Ingham       process->DeallocateMemory(path_array_addr);
8180d231f71SJim Ingham     });
8190d231f71SJim Ingham 
8200d231f71SJim Ingham     process->WriteMemory(path_array_addr, path_array.data(),
8210d231f71SJim Ingham                          path_array.size(), utility_error);
8220d231f71SJim Ingham 
8230d231f71SJim Ingham     if (utility_error.Fail()) {
8240d231f71SJim Ingham       error.SetErrorStringWithFormat("dlopen error: could not write path array:"
8250d231f71SJim Ingham                                      " %s", utility_error.AsCString());
8260d231f71SJim Ingham       return LLDB_INVALID_IMAGE_TOKEN;
8270d231f71SJim Ingham     }
8280d231f71SJim Ingham     // Now make spaces in the target for the buffer.  We need to add one for
8290d231f71SJim Ingham     // the '/' that the utility function will insert and one for the '\0':
8300d231f71SJim Ingham     buffer_size += path.size() + 2;
8310d231f71SJim Ingham 
8320d231f71SJim Ingham     buffer_addr = process->AllocateMemory(buffer_size,
8330d231f71SJim Ingham                                           permissions,
8340d231f71SJim Ingham                                           utility_error);
8350d231f71SJim Ingham     if (buffer_addr == LLDB_INVALID_ADDRESS) {
8360d231f71SJim Ingham       error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
8370d231f71SJim Ingham                                       "for buffer: %s",
8380d231f71SJim Ingham                                       utility_error.AsCString());
8390d231f71SJim Ingham       return LLDB_INVALID_IMAGE_TOKEN;
8400d231f71SJim Ingham     }
8410d231f71SJim Ingham 
8420d231f71SJim Ingham     // Make sure we deallocate the buffer memory:
843e0ea8d87SJonas Devlieghere     buffer_cleanup.emplace([process, buffer_addr]() {
844e0ea8d87SJonas Devlieghere       // Deallocate the buffer.
8450d231f71SJim Ingham       process->DeallocateMemory(buffer_addr);
8460d231f71SJim Ingham     });
8470d231f71SJim Ingham   }
8480d231f71SJim Ingham 
8491ecb34f4SJim Ingham   arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
8500d231f71SJim Ingham   arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
8510d231f71SJim Ingham   arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
8520d231f71SJim Ingham   arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
8531ecb34f4SJim Ingham 
8541ecb34f4SJim Ingham   lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
8551ecb34f4SJim Ingham 
8561ecb34f4SJim Ingham   diagnostics.Clear();
8571ecb34f4SJim Ingham   if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
8581ecb34f4SJim Ingham                                                  func_args_addr,
8591ecb34f4SJim Ingham                                                  arguments,
8601ecb34f4SJim Ingham                                                  diagnostics)) {
8611ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not write function "
8621ecb34f4SJim Ingham                                    "arguments: %s",
8631ecb34f4SJim Ingham                                    diagnostics.GetString().c_str());
8641ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
8651ecb34f4SJim Ingham   }
8661ecb34f4SJim Ingham 
8671ecb34f4SJim Ingham   // Make sure we clean up the args structure.  We can't reuse it because the
8681ecb34f4SJim Ingham   // Platform lives longer than the process and the Platforms don't get a
8691ecb34f4SJim Ingham   // signal to clean up cached data when a process goes away.
870e0ea8d87SJonas Devlieghere   auto args_cleanup =
871e0ea8d87SJonas Devlieghere       llvm::make_scope_exit([do_dlopen_function, &exe_ctx, func_args_addr] {
8721ecb34f4SJim Ingham         do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
8731ecb34f4SJim Ingham       });
8741ecb34f4SJim Ingham 
8751ecb34f4SJim Ingham   // Now run the caller:
8761ecb34f4SJim Ingham   EvaluateExpressionOptions options;
8771ecb34f4SJim Ingham   options.SetExecutionPolicy(eExecutionPolicyAlways);
8781ecb34f4SJim Ingham   options.SetLanguage(eLanguageTypeC_plus_plus);
8791ecb34f4SJim Ingham   options.SetIgnoreBreakpoints(true);
8801ecb34f4SJim Ingham   options.SetUnwindOnError(true);
8811ecb34f4SJim Ingham   options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
8821ecb34f4SJim Ingham                                     // don't do the work to trap them.
8834c03ea14SAdrian Prantl   options.SetTimeout(process->GetUtilityExpressionTimeout());
884c01783a8SRaphael Isemann   options.SetIsForUtilityExpr(true);
8851ecb34f4SJim Ingham 
8861ecb34f4SJim Ingham   Value return_value;
8871ecb34f4SJim Ingham   // Fetch the clang types we will need:
888594308c7SRaphael Isemann   TypeSystemClang *ast =
889594308c7SRaphael Isemann       ScratchTypeSystemClang::GetForTarget(process->GetTarget());
8903031818aSAlex Langford   if (!ast) {
8916e3b0cc2SRaphael Isemann     error.SetErrorString("dlopen error: Unable to get TypeSystemClang");
8923031818aSAlex Langford     return LLDB_INVALID_IMAGE_TOKEN;
8933031818aSAlex Langford   }
8941ecb34f4SJim Ingham 
8951ecb34f4SJim Ingham   CompilerType clang_void_pointer_type
8961ecb34f4SJim Ingham       = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
8971ecb34f4SJim Ingham 
8981ecb34f4SJim Ingham   return_value.SetCompilerType(clang_void_pointer_type);
8991ecb34f4SJim Ingham 
9001ecb34f4SJim Ingham   ExpressionResults results = do_dlopen_function->ExecuteFunction(
9011ecb34f4SJim Ingham       exe_ctx, &func_args_addr, options, diagnostics, return_value);
9021ecb34f4SJim Ingham   if (results != eExpressionCompleted) {
9030d231f71SJim Ingham     error.SetErrorStringWithFormat("dlopen error: failed executing "
9041ecb34f4SJim Ingham                                    "dlopen wrapper function: %s",
9051ecb34f4SJim Ingham                                    diagnostics.GetString().c_str());
9061ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
9071ecb34f4SJim Ingham   }
9081ecb34f4SJim Ingham 
9091ecb34f4SJim Ingham   // Read the dlopen token from the return area:
9101ecb34f4SJim Ingham   lldb::addr_t token = process->ReadPointerFromMemory(return_addr,
9111ecb34f4SJim Ingham                                                       utility_error);
9121ecb34f4SJim Ingham   if (utility_error.Fail()) {
9131ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not read the return "
9141ecb34f4SJim Ingham                                     "struct: %s", utility_error.AsCString());
9151ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
9161ecb34f4SJim Ingham   }
9171ecb34f4SJim Ingham 
9181ecb34f4SJim Ingham   // The dlopen succeeded!
9190d231f71SJim Ingham   if (token != 0x0) {
9200d231f71SJim Ingham     if (loaded_image && buffer_addr != 0x0)
9210d231f71SJim Ingham     {
9220d231f71SJim Ingham       // Capture the image which was loaded.  We leave it in the buffer on
9230d231f71SJim Ingham       // exit from the dlopen function, so we can just read it from there:
9240d231f71SJim Ingham       std::string name_string;
9250d231f71SJim Ingham       process->ReadCStringFromMemory(buffer_addr, name_string, utility_error);
9260d231f71SJim Ingham       if (utility_error.Success())
9278f3be7a3SJonas Devlieghere         loaded_image->SetFile(name_string, llvm::sys::path::Style::posix);
9280d231f71SJim Ingham     }
9291ecb34f4SJim Ingham     return process->AddImageToken(token);
9300d231f71SJim Ingham   }
9311ecb34f4SJim Ingham 
9321ecb34f4SJim Ingham   // We got an error, lets read in the error string:
9331ecb34f4SJim Ingham   std::string dlopen_error_str;
9341ecb34f4SJim Ingham   lldb::addr_t error_addr
9351ecb34f4SJim Ingham     = process->ReadPointerFromMemory(return_addr + addr_size, utility_error);
9361ecb34f4SJim Ingham   if (utility_error.Fail()) {
9371ecb34f4SJim Ingham     error.SetErrorStringWithFormat("dlopen error: could not read error string: "
9381ecb34f4SJim Ingham                                     "%s", utility_error.AsCString());
9391ecb34f4SJim Ingham     return LLDB_INVALID_IMAGE_TOKEN;
9401ecb34f4SJim Ingham   }
9411ecb34f4SJim Ingham 
9421ecb34f4SJim Ingham   size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size,
9431ecb34f4SJim Ingham                                                     dlopen_error_str,
9441ecb34f4SJim Ingham                                                     utility_error);
9451ecb34f4SJim Ingham   if (utility_error.Success() && num_chars > 0)
946b9c1b51eSKate Stone     error.SetErrorStringWithFormat("dlopen error: %s",
9471ecb34f4SJim Ingham                                    dlopen_error_str.c_str());
9483cb132a0STamas Berghammer   else
9493cb132a0STamas Berghammer     error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
9501ecb34f4SJim Ingham 
9513cb132a0STamas Berghammer   return LLDB_INVALID_IMAGE_TOKEN;
9523cb132a0STamas Berghammer }
9533cb132a0STamas Berghammer 
95497206d57SZachary Turner Status PlatformPOSIX::UnloadImage(lldb_private::Process *process,
955b9c1b51eSKate Stone                                   uint32_t image_token) {
9563cb132a0STamas Berghammer   const addr_t image_addr = process->GetImagePtrFromToken(image_token);
9573cb132a0STamas Berghammer   if (image_addr == LLDB_INVALID_ADDRESS)
95897206d57SZachary Turner     return Status("Invalid image token");
9593cb132a0STamas Berghammer 
9603cb132a0STamas Berghammer   StreamString expr;
9613cb132a0STamas Berghammer   expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
962f7a5851dSNitesh Jain   llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
9633cb132a0STamas Berghammer   lldb::ValueObjectSP result_valobj_sp;
96497206d57SZachary Turner   Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
965b9c1b51eSKate Stone                                          result_valobj_sp);
9663cb132a0STamas Berghammer   if (error.Fail())
9673cb132a0STamas Berghammer     return error;
9683cb132a0STamas Berghammer 
9693cb132a0STamas Berghammer   if (result_valobj_sp->GetError().Fail())
9703cb132a0STamas Berghammer     return result_valobj_sp->GetError();
9713cb132a0STamas Berghammer 
9723cb132a0STamas Berghammer   Scalar scalar;
973b9c1b51eSKate Stone   if (result_valobj_sp->ResolveValue(scalar)) {
9743cb132a0STamas Berghammer     if (scalar.UInt(1))
97597206d57SZachary Turner       return Status("expression failed: \"%s\"", expr.GetData());
9763cb132a0STamas Berghammer     process->ResetImageToken(image_token);
9773cb132a0STamas Berghammer   }
97897206d57SZachary Turner   return Status();
9793cb132a0STamas Berghammer }
980fcdde63fSTamas Berghammer 
981f7a5851dSNitesh Jain llvm::StringRef
982f7a5851dSNitesh Jain PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
983fcdde63fSTamas Berghammer   return R"(
984fcdde63fSTamas Berghammer               extern "C" void* dlopen(const char*, int);
985fcdde63fSTamas Berghammer               extern "C" void* dlsym(void*, const char*);
986fcdde63fSTamas Berghammer               extern "C" int   dlclose(void*);
987fcdde63fSTamas Berghammer               extern "C" char* dlerror(void);
988fcdde63fSTamas Berghammer              )";
989fcdde63fSTamas Berghammer }
990ccd6cffbSTamas Berghammer 
991ec9bc8ccSPavel Labath ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) {
992ec9bc8ccSPavel Labath   if (basename.IsEmpty())
993ec9bc8ccSPavel Labath     return basename;
994ec9bc8ccSPavel Labath 
995ec9bc8ccSPavel Labath   StreamString stream;
996ec9bc8ccSPavel Labath   stream.Printf("lib%s.so", basename.GetCString());
997ec9bc8ccSPavel Labath   return ConstString(stream.GetString());
998ec9bc8ccSPavel Labath }
999