1dda28197Spatrick //===-- PlatformPOSIX.cpp -------------------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick
9061da546Spatrick #include "PlatformPOSIX.h"
10061da546Spatrick
11*f6aab3d8Srobert #include "Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h"
12dda28197Spatrick #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
13061da546Spatrick #include "lldb/Core/Debugger.h"
14061da546Spatrick #include "lldb/Core/Module.h"
15061da546Spatrick #include "lldb/Core/ValueObject.h"
16061da546Spatrick #include "lldb/Expression/DiagnosticManager.h"
17061da546Spatrick #include "lldb/Expression/FunctionCaller.h"
18061da546Spatrick #include "lldb/Expression/UserExpression.h"
19061da546Spatrick #include "lldb/Expression/UtilityFunction.h"
20061da546Spatrick #include "lldb/Host/File.h"
21061da546Spatrick #include "lldb/Host/FileCache.h"
22061da546Spatrick #include "lldb/Host/FileSystem.h"
23061da546Spatrick #include "lldb/Host/Host.h"
24061da546Spatrick #include "lldb/Host/HostInfo.h"
25061da546Spatrick #include "lldb/Host/ProcessLaunchInfo.h"
26061da546Spatrick #include "lldb/Target/DynamicLoader.h"
27061da546Spatrick #include "lldb/Target/ExecutionContext.h"
28061da546Spatrick #include "lldb/Target/Process.h"
29061da546Spatrick #include "lldb/Target/Thread.h"
30061da546Spatrick #include "lldb/Utility/DataBufferHeap.h"
31061da546Spatrick #include "lldb/Utility/FileSpec.h"
32*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
33061da546Spatrick #include "lldb/Utility/Log.h"
34061da546Spatrick #include "lldb/Utility/StreamString.h"
35061da546Spatrick #include "llvm/ADT/ScopeExit.h"
36*f6aab3d8Srobert #include <optional>
37061da546Spatrick
38061da546Spatrick using namespace lldb;
39061da546Spatrick using namespace lldb_private;
40061da546Spatrick
41061da546Spatrick /// Default Constructor
PlatformPOSIX(bool is_host)42061da546Spatrick PlatformPOSIX::PlatformPOSIX(bool is_host)
43061da546Spatrick : RemoteAwarePlatform(is_host), // This is the local host platform
44061da546Spatrick m_option_group_platform_rsync(new OptionGroupPlatformRSync()),
45061da546Spatrick m_option_group_platform_ssh(new OptionGroupPlatformSSH()),
46061da546Spatrick m_option_group_platform_caching(new OptionGroupPlatformCaching()) {}
47061da546Spatrick
48061da546Spatrick /// Destructor.
49061da546Spatrick ///
50061da546Spatrick /// The destructor is virtual since this class is designed to be
51061da546Spatrick /// inherited from by the plug-in instance.
52be691f3bSpatrick PlatformPOSIX::~PlatformPOSIX() = default;
53061da546Spatrick
GetConnectionOptions(lldb_private::CommandInterpreter & interpreter)54061da546Spatrick lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions(
55061da546Spatrick lldb_private::CommandInterpreter &interpreter) {
56061da546Spatrick auto iter = m_options.find(&interpreter), end = m_options.end();
57061da546Spatrick if (iter == end) {
58061da546Spatrick std::unique_ptr<lldb_private::OptionGroupOptions> options(
59061da546Spatrick new OptionGroupOptions());
60061da546Spatrick options->Append(m_option_group_platform_rsync.get());
61061da546Spatrick options->Append(m_option_group_platform_ssh.get());
62061da546Spatrick options->Append(m_option_group_platform_caching.get());
63061da546Spatrick m_options[&interpreter] = std::move(options);
64061da546Spatrick }
65061da546Spatrick
66061da546Spatrick return m_options.at(&interpreter).get();
67061da546Spatrick }
68061da546Spatrick
chown_file(Platform * platform,const char * path,uint32_t uid=UINT32_MAX,uint32_t gid=UINT32_MAX)69061da546Spatrick static uint32_t chown_file(Platform *platform, const char *path,
70061da546Spatrick uint32_t uid = UINT32_MAX,
71061da546Spatrick uint32_t gid = UINT32_MAX) {
72061da546Spatrick if (!platform || !path || *path == 0)
73061da546Spatrick return UINT32_MAX;
74061da546Spatrick
75061da546Spatrick if (uid == UINT32_MAX && gid == UINT32_MAX)
76061da546Spatrick return 0; // pretend I did chown correctly - actually I just didn't care
77061da546Spatrick
78061da546Spatrick StreamString command;
79061da546Spatrick command.PutCString("chown ");
80061da546Spatrick if (uid != UINT32_MAX)
81061da546Spatrick command.Printf("%d", uid);
82061da546Spatrick if (gid != UINT32_MAX)
83061da546Spatrick command.Printf(":%d", gid);
84061da546Spatrick command.Printf("%s", path);
85061da546Spatrick int status;
86061da546Spatrick platform->RunShellCommand(command.GetData(), FileSpec(), &status, nullptr,
87061da546Spatrick nullptr, std::chrono::seconds(10));
88061da546Spatrick return status;
89061da546Spatrick }
90061da546Spatrick
91061da546Spatrick lldb_private::Status
PutFile(const lldb_private::FileSpec & source,const lldb_private::FileSpec & destination,uint32_t uid,uint32_t gid)92061da546Spatrick PlatformPOSIX::PutFile(const lldb_private::FileSpec &source,
93061da546Spatrick const lldb_private::FileSpec &destination, uint32_t uid,
94061da546Spatrick uint32_t gid) {
95*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Platform);
96061da546Spatrick
97061da546Spatrick if (IsHost()) {
98061da546Spatrick if (source == destination)
99061da546Spatrick return Status();
100061da546Spatrick // cp src dst
101061da546Spatrick // chown uid:gid dst
102061da546Spatrick std::string src_path(source.GetPath());
103061da546Spatrick if (src_path.empty())
104061da546Spatrick return Status("unable to get file path for source");
105061da546Spatrick std::string dst_path(destination.GetPath());
106061da546Spatrick if (dst_path.empty())
107061da546Spatrick return Status("unable to get file path for destination");
108061da546Spatrick StreamString command;
109061da546Spatrick command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
110061da546Spatrick int status;
111061da546Spatrick RunShellCommand(command.GetData(), FileSpec(), &status, nullptr, nullptr,
112061da546Spatrick std::chrono::seconds(10));
113061da546Spatrick if (status != 0)
114061da546Spatrick return Status("unable to perform copy");
115061da546Spatrick if (uid == UINT32_MAX && gid == UINT32_MAX)
116061da546Spatrick return Status();
117061da546Spatrick if (chown_file(this, dst_path.c_str(), uid, gid) != 0)
118061da546Spatrick return Status("unable to perform chown");
119061da546Spatrick return Status();
120061da546Spatrick } else if (m_remote_platform_sp) {
121061da546Spatrick if (GetSupportsRSync()) {
122061da546Spatrick std::string src_path(source.GetPath());
123061da546Spatrick if (src_path.empty())
124061da546Spatrick return Status("unable to get file path for source");
125061da546Spatrick std::string dst_path(destination.GetPath());
126061da546Spatrick if (dst_path.empty())
127061da546Spatrick return Status("unable to get file path for destination");
128061da546Spatrick StreamString command;
129061da546Spatrick if (GetIgnoresRemoteHostname()) {
130061da546Spatrick if (!GetRSyncPrefix())
131061da546Spatrick command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
132061da546Spatrick dst_path.c_str());
133061da546Spatrick else
134061da546Spatrick command.Printf("rsync %s %s %s%s", GetRSyncOpts(), src_path.c_str(),
135061da546Spatrick GetRSyncPrefix(), dst_path.c_str());
136061da546Spatrick } else
137061da546Spatrick command.Printf("rsync %s %s %s:%s", GetRSyncOpts(), src_path.c_str(),
138061da546Spatrick GetHostname(), dst_path.c_str());
139061da546Spatrick LLDB_LOGF(log, "[PutFile] Running command: %s\n", command.GetData());
140061da546Spatrick int retcode;
141061da546Spatrick Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
142061da546Spatrick nullptr, std::chrono::minutes(1));
143061da546Spatrick if (retcode == 0) {
144061da546Spatrick // Don't chown a local file for a remote system
145061da546Spatrick // if (chown_file(this,dst_path.c_str(),uid,gid) != 0)
146061da546Spatrick // return Status("unable to perform chown");
147061da546Spatrick return Status();
148061da546Spatrick }
149061da546Spatrick // if we are still here rsync has failed - let's try the slow way before
150061da546Spatrick // giving up
151061da546Spatrick }
152061da546Spatrick }
153061da546Spatrick return Platform::PutFile(source, destination, uid, gid);
154061da546Spatrick }
155061da546Spatrick
GetFile(const lldb_private::FileSpec & source,const lldb_private::FileSpec & destination)156061da546Spatrick lldb_private::Status PlatformPOSIX::GetFile(
157061da546Spatrick const lldb_private::FileSpec &source, // remote file path
158061da546Spatrick const lldb_private::FileSpec &destination) // local file path
159061da546Spatrick {
160*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Platform);
161061da546Spatrick
162061da546Spatrick // Check the args, first.
163061da546Spatrick std::string src_path(source.GetPath());
164061da546Spatrick if (src_path.empty())
165061da546Spatrick return Status("unable to get file path for source");
166061da546Spatrick std::string dst_path(destination.GetPath());
167061da546Spatrick if (dst_path.empty())
168061da546Spatrick return Status("unable to get file path for destination");
169061da546Spatrick if (IsHost()) {
170061da546Spatrick if (source == destination)
171061da546Spatrick return Status("local scenario->source and destination are the same file "
172061da546Spatrick "path: no operation performed");
173061da546Spatrick // cp src dst
174061da546Spatrick StreamString cp_command;
175061da546Spatrick cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
176061da546Spatrick int status;
177061da546Spatrick RunShellCommand(cp_command.GetData(), FileSpec(), &status, nullptr, nullptr,
178061da546Spatrick std::chrono::seconds(10));
179061da546Spatrick if (status != 0)
180061da546Spatrick return Status("unable to perform copy");
181061da546Spatrick return Status();
182061da546Spatrick } else if (m_remote_platform_sp) {
183061da546Spatrick if (GetSupportsRSync()) {
184061da546Spatrick StreamString command;
185061da546Spatrick if (GetIgnoresRemoteHostname()) {
186061da546Spatrick if (!GetRSyncPrefix())
187061da546Spatrick command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
188061da546Spatrick dst_path.c_str());
189061da546Spatrick else
190061da546Spatrick command.Printf("rsync %s %s%s %s", GetRSyncOpts(), GetRSyncPrefix(),
191061da546Spatrick src_path.c_str(), dst_path.c_str());
192061da546Spatrick } else
193061da546Spatrick command.Printf("rsync %s %s:%s %s", GetRSyncOpts(),
194061da546Spatrick m_remote_platform_sp->GetHostname(), src_path.c_str(),
195061da546Spatrick dst_path.c_str());
196061da546Spatrick LLDB_LOGF(log, "[GetFile] Running command: %s\n", command.GetData());
197061da546Spatrick int retcode;
198061da546Spatrick Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
199061da546Spatrick nullptr, std::chrono::minutes(1));
200061da546Spatrick if (retcode == 0)
201061da546Spatrick return Status();
202061da546Spatrick // If we are here, rsync has failed - let's try the slow way before
203061da546Spatrick // giving up
204061da546Spatrick }
205061da546Spatrick // open src and dst
206061da546Spatrick // read/write, read/write, read/write, ...
207061da546Spatrick // close src
208061da546Spatrick // close dst
209061da546Spatrick LLDB_LOGF(log, "[GetFile] Using block by block transfer....\n");
210061da546Spatrick Status error;
211*f6aab3d8Srobert user_id_t fd_src = OpenFile(source, File::eOpenOptionReadOnly,
212061da546Spatrick lldb::eFilePermissionsFileDefault, error);
213061da546Spatrick
214061da546Spatrick if (fd_src == UINT64_MAX)
215061da546Spatrick return Status("unable to open source file");
216061da546Spatrick
217061da546Spatrick uint32_t permissions = 0;
218061da546Spatrick error = GetFilePermissions(source, permissions);
219061da546Spatrick
220061da546Spatrick if (permissions == 0)
221061da546Spatrick permissions = lldb::eFilePermissionsFileDefault;
222061da546Spatrick
223061da546Spatrick user_id_t fd_dst = FileCache::GetInstance().OpenFile(
224*f6aab3d8Srobert destination, File::eOpenOptionCanCreate | File::eOpenOptionWriteOnly |
225061da546Spatrick File::eOpenOptionTruncate,
226061da546Spatrick permissions, error);
227061da546Spatrick
228061da546Spatrick if (fd_dst == UINT64_MAX) {
229061da546Spatrick if (error.Success())
230061da546Spatrick error.SetErrorString("unable to open destination file");
231061da546Spatrick }
232061da546Spatrick
233061da546Spatrick if (error.Success()) {
234*f6aab3d8Srobert lldb::WritableDataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
235061da546Spatrick uint64_t offset = 0;
236061da546Spatrick error.Clear();
237061da546Spatrick while (error.Success()) {
238061da546Spatrick const uint64_t n_read = ReadFile(fd_src, offset, buffer_sp->GetBytes(),
239061da546Spatrick buffer_sp->GetByteSize(), error);
240061da546Spatrick if (error.Fail())
241061da546Spatrick break;
242061da546Spatrick if (n_read == 0)
243061da546Spatrick break;
244061da546Spatrick if (FileCache::GetInstance().WriteFile(fd_dst, offset,
245061da546Spatrick buffer_sp->GetBytes(), n_read,
246061da546Spatrick error) != n_read) {
247061da546Spatrick if (!error.Fail())
248061da546Spatrick error.SetErrorString("unable to write to destination file");
249061da546Spatrick break;
250061da546Spatrick }
251061da546Spatrick offset += n_read;
252061da546Spatrick }
253061da546Spatrick }
254061da546Spatrick // Ignore the close error of src.
255061da546Spatrick if (fd_src != UINT64_MAX)
256061da546Spatrick CloseFile(fd_src, error);
257061da546Spatrick // And close the dst file descriptot.
258061da546Spatrick if (fd_dst != UINT64_MAX &&
259061da546Spatrick !FileCache::GetInstance().CloseFile(fd_dst, error)) {
260061da546Spatrick if (!error.Fail())
261061da546Spatrick error.SetErrorString("unable to close destination file");
262061da546Spatrick }
263061da546Spatrick return error;
264061da546Spatrick }
265061da546Spatrick return Platform::GetFile(source, destination);
266061da546Spatrick }
267061da546Spatrick
GetPlatformSpecificConnectionInformation()268061da546Spatrick std::string PlatformPOSIX::GetPlatformSpecificConnectionInformation() {
269061da546Spatrick StreamString stream;
270061da546Spatrick if (GetSupportsRSync()) {
271061da546Spatrick stream.PutCString("rsync");
272061da546Spatrick if ((GetRSyncOpts() && *GetRSyncOpts()) ||
273061da546Spatrick (GetRSyncPrefix() && *GetRSyncPrefix()) || GetIgnoresRemoteHostname()) {
274061da546Spatrick stream.Printf(", options: ");
275061da546Spatrick if (GetRSyncOpts() && *GetRSyncOpts())
276061da546Spatrick stream.Printf("'%s' ", GetRSyncOpts());
277061da546Spatrick stream.Printf(", prefix: ");
278061da546Spatrick if (GetRSyncPrefix() && *GetRSyncPrefix())
279061da546Spatrick stream.Printf("'%s' ", GetRSyncPrefix());
280061da546Spatrick if (GetIgnoresRemoteHostname())
281061da546Spatrick stream.Printf("ignore remote-hostname ");
282061da546Spatrick }
283061da546Spatrick }
284061da546Spatrick if (GetSupportsSSH()) {
285061da546Spatrick stream.PutCString("ssh");
286061da546Spatrick if (GetSSHOpts() && *GetSSHOpts())
287061da546Spatrick stream.Printf(", options: '%s' ", GetSSHOpts());
288061da546Spatrick }
289061da546Spatrick if (GetLocalCacheDirectory() && *GetLocalCacheDirectory())
290061da546Spatrick stream.Printf("cache dir: %s", GetLocalCacheDirectory());
291061da546Spatrick if (stream.GetSize())
292dda28197Spatrick return std::string(stream.GetString());
293061da546Spatrick else
294061da546Spatrick return "";
295061da546Spatrick }
296061da546Spatrick
GetRemoteUnixSignals()297061da546Spatrick const lldb::UnixSignalsSP &PlatformPOSIX::GetRemoteUnixSignals() {
298061da546Spatrick if (IsRemote() && m_remote_platform_sp)
299061da546Spatrick return m_remote_platform_sp->GetRemoteUnixSignals();
300061da546Spatrick return Platform::GetRemoteUnixSignals();
301061da546Spatrick }
302061da546Spatrick
ConnectRemote(Args & args)303061da546Spatrick Status PlatformPOSIX::ConnectRemote(Args &args) {
304061da546Spatrick Status error;
305061da546Spatrick if (IsHost()) {
306*f6aab3d8Srobert error.SetErrorStringWithFormatv(
307*f6aab3d8Srobert "can't connect to the host platform '{0}', always connected",
308*f6aab3d8Srobert GetPluginName());
309061da546Spatrick } else {
310061da546Spatrick if (!m_remote_platform_sp)
311061da546Spatrick m_remote_platform_sp =
312*f6aab3d8Srobert platform_gdb_server::PlatformRemoteGDBServer::CreateInstance(
313*f6aab3d8Srobert /*force=*/true, nullptr);
314061da546Spatrick
315061da546Spatrick if (m_remote_platform_sp && error.Success())
316061da546Spatrick error = m_remote_platform_sp->ConnectRemote(args);
317061da546Spatrick else
318061da546Spatrick error.SetErrorString("failed to create a 'remote-gdb-server' platform");
319061da546Spatrick
320061da546Spatrick if (error.Fail())
321061da546Spatrick m_remote_platform_sp.reset();
322061da546Spatrick }
323061da546Spatrick
324061da546Spatrick if (error.Success() && m_remote_platform_sp) {
325061da546Spatrick if (m_option_group_platform_rsync.get() &&
326061da546Spatrick m_option_group_platform_ssh.get() &&
327061da546Spatrick m_option_group_platform_caching.get()) {
328061da546Spatrick if (m_option_group_platform_rsync->m_rsync) {
329061da546Spatrick SetSupportsRSync(true);
330061da546Spatrick SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str());
331061da546Spatrick SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str());
332061da546Spatrick SetIgnoresRemoteHostname(
333061da546Spatrick m_option_group_platform_rsync->m_ignores_remote_hostname);
334061da546Spatrick }
335061da546Spatrick if (m_option_group_platform_ssh->m_ssh) {
336061da546Spatrick SetSupportsSSH(true);
337061da546Spatrick SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str());
338061da546Spatrick }
339061da546Spatrick SetLocalCacheDirectory(
340061da546Spatrick m_option_group_platform_caching->m_cache_dir.c_str());
341061da546Spatrick }
342061da546Spatrick }
343061da546Spatrick
344061da546Spatrick return error;
345061da546Spatrick }
346061da546Spatrick
DisconnectRemote()347061da546Spatrick Status PlatformPOSIX::DisconnectRemote() {
348061da546Spatrick Status error;
349061da546Spatrick
350061da546Spatrick if (IsHost()) {
351*f6aab3d8Srobert error.SetErrorStringWithFormatv(
352*f6aab3d8Srobert "can't disconnect from the host platform '{0}', always connected",
353*f6aab3d8Srobert GetPluginName());
354061da546Spatrick } else {
355061da546Spatrick if (m_remote_platform_sp)
356061da546Spatrick error = m_remote_platform_sp->DisconnectRemote();
357061da546Spatrick else
358061da546Spatrick error.SetErrorString("the platform is not currently connected");
359061da546Spatrick }
360061da546Spatrick return error;
361061da546Spatrick }
362061da546Spatrick
Attach(ProcessAttachInfo & attach_info,Debugger & debugger,Target * target,Status & error)363061da546Spatrick lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info,
364061da546Spatrick Debugger &debugger, Target *target,
365061da546Spatrick Status &error) {
366061da546Spatrick lldb::ProcessSP process_sp;
367*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Platform);
368061da546Spatrick
369061da546Spatrick if (IsHost()) {
370061da546Spatrick if (target == nullptr) {
371061da546Spatrick TargetSP new_target_sp;
372061da546Spatrick
373061da546Spatrick error = debugger.GetTargetList().CreateTarget(
374061da546Spatrick debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
375061da546Spatrick target = new_target_sp.get();
376061da546Spatrick LLDB_LOGF(log, "PlatformPOSIX::%s created new target", __FUNCTION__);
377061da546Spatrick } else {
378061da546Spatrick error.Clear();
379061da546Spatrick LLDB_LOGF(log, "PlatformPOSIX::%s target already existed, setting target",
380061da546Spatrick __FUNCTION__);
381061da546Spatrick }
382061da546Spatrick
383061da546Spatrick if (target && error.Success()) {
384061da546Spatrick if (log) {
385061da546Spatrick ModuleSP exe_module_sp = target->GetExecutableModule();
386061da546Spatrick LLDB_LOGF(log, "PlatformPOSIX::%s set selected target to %p %s",
387061da546Spatrick __FUNCTION__, (void *)target,
388061da546Spatrick exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
389061da546Spatrick : "<null>");
390061da546Spatrick }
391061da546Spatrick
392061da546Spatrick process_sp =
393061da546Spatrick target->CreateProcess(attach_info.GetListenerForProcess(debugger),
394be691f3bSpatrick "gdb-remote", nullptr, true);
395061da546Spatrick
396061da546Spatrick if (process_sp) {
397061da546Spatrick ListenerSP listener_sp = attach_info.GetHijackListener();
398061da546Spatrick if (listener_sp == nullptr) {
399061da546Spatrick listener_sp =
400061da546Spatrick Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
401061da546Spatrick attach_info.SetHijackListener(listener_sp);
402061da546Spatrick }
403061da546Spatrick process_sp->HijackProcessEvents(listener_sp);
404061da546Spatrick error = process_sp->Attach(attach_info);
405061da546Spatrick }
406061da546Spatrick }
407061da546Spatrick } else {
408061da546Spatrick if (m_remote_platform_sp)
409061da546Spatrick process_sp =
410061da546Spatrick m_remote_platform_sp->Attach(attach_info, debugger, target, error);
411061da546Spatrick else
412061da546Spatrick error.SetErrorString("the platform is not currently connected");
413061da546Spatrick }
414061da546Spatrick return process_sp;
415061da546Spatrick }
416061da546Spatrick
DebugProcess(ProcessLaunchInfo & launch_info,Debugger & debugger,Target & target,Status & error)417*f6aab3d8Srobert lldb::ProcessSP PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info,
418*f6aab3d8Srobert Debugger &debugger, Target &target,
419061da546Spatrick Status &error) {
420*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Platform);
421*f6aab3d8Srobert LLDB_LOG(log, "target {0}", &target);
422be691f3bSpatrick
423061da546Spatrick ProcessSP process_sp;
424061da546Spatrick
425be691f3bSpatrick if (!IsHost()) {
426061da546Spatrick if (m_remote_platform_sp)
427061da546Spatrick process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
428061da546Spatrick target, error);
429061da546Spatrick else
430061da546Spatrick error.SetErrorString("the platform is not currently connected");
431be691f3bSpatrick return process_sp;
432061da546Spatrick }
433be691f3bSpatrick
434be691f3bSpatrick //
435be691f3bSpatrick // For local debugging, we'll insist on having ProcessGDBRemote create the
436be691f3bSpatrick // process.
437be691f3bSpatrick //
438be691f3bSpatrick
439be691f3bSpatrick // Make sure we stop at the entry point
440be691f3bSpatrick launch_info.GetFlags().Set(eLaunchFlagDebug);
441be691f3bSpatrick
442be691f3bSpatrick // We always launch the process we are going to debug in a separate process
443be691f3bSpatrick // group, since then we can handle ^C interrupts ourselves w/o having to
444be691f3bSpatrick // worry about the target getting them as well.
445be691f3bSpatrick launch_info.SetLaunchInSeparateProcessGroup(true);
446be691f3bSpatrick
447be691f3bSpatrick // Now create the gdb-remote process.
448be691f3bSpatrick LLDB_LOG(log, "having target create process with gdb-remote plugin");
449*f6aab3d8Srobert process_sp = target.CreateProcess(launch_info.GetListener(), "gdb-remote",
450*f6aab3d8Srobert nullptr, true);
451be691f3bSpatrick
452be691f3bSpatrick if (!process_sp) {
453be691f3bSpatrick error.SetErrorString("CreateProcess() failed for gdb-remote process");
454be691f3bSpatrick LLDB_LOG(log, "error: {0}", error);
455be691f3bSpatrick return process_sp;
456be691f3bSpatrick }
457be691f3bSpatrick
458be691f3bSpatrick LLDB_LOG(log, "successfully created process");
459*f6aab3d8Srobert
460*f6aab3d8Srobert process_sp->HijackProcessEvents(launch_info.GetHijackListener());
461be691f3bSpatrick
462be691f3bSpatrick // Log file actions.
463be691f3bSpatrick if (log) {
464be691f3bSpatrick LLDB_LOG(log, "launching process with the following file actions:");
465be691f3bSpatrick StreamString stream;
466be691f3bSpatrick size_t i = 0;
467be691f3bSpatrick const FileAction *file_action;
468be691f3bSpatrick while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) {
469be691f3bSpatrick file_action->Dump(stream);
470be691f3bSpatrick LLDB_LOG(log, "{0}", stream.GetData());
471be691f3bSpatrick stream.Clear();
472be691f3bSpatrick }
473be691f3bSpatrick }
474be691f3bSpatrick
475be691f3bSpatrick // Do the launch.
476be691f3bSpatrick error = process_sp->Launch(launch_info);
477be691f3bSpatrick if (error.Success()) {
478be691f3bSpatrick // Hook up process PTY if we have one (which we should for local debugging
479be691f3bSpatrick // with llgs).
480be691f3bSpatrick int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
481be691f3bSpatrick if (pty_fd != PseudoTerminal::invalid_fd) {
482be691f3bSpatrick process_sp->SetSTDIOFileDescriptor(pty_fd);
483be691f3bSpatrick LLDB_LOG(log, "hooked up STDIO pty to process");
484be691f3bSpatrick } else
485be691f3bSpatrick LLDB_LOG(log, "not using process STDIO pty");
486be691f3bSpatrick } else {
487be691f3bSpatrick LLDB_LOG(log, "{0}", error);
488*f6aab3d8Srobert // FIXME figure out appropriate cleanup here. Do we delete the process?
489*f6aab3d8Srobert // Does our caller do that?
490be691f3bSpatrick }
491be691f3bSpatrick
492061da546Spatrick return process_sp;
493061da546Spatrick }
494061da546Spatrick
CalculateTrapHandlerSymbolNames()495061da546Spatrick void PlatformPOSIX::CalculateTrapHandlerSymbolNames() {
496061da546Spatrick m_trap_handlers.push_back(ConstString("_sigtramp"));
497061da546Spatrick }
498061da546Spatrick
EvaluateLibdlExpression(lldb_private::Process * process,const char * expr_cstr,llvm::StringRef expr_prefix,lldb::ValueObjectSP & result_valobj_sp)499061da546Spatrick Status PlatformPOSIX::EvaluateLibdlExpression(
500061da546Spatrick lldb_private::Process *process, const char *expr_cstr,
501061da546Spatrick llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
502061da546Spatrick DynamicLoader *loader = process->GetDynamicLoader();
503061da546Spatrick if (loader) {
504061da546Spatrick Status error = loader->CanLoadImage();
505061da546Spatrick if (error.Fail())
506061da546Spatrick return error;
507061da546Spatrick }
508061da546Spatrick
509061da546Spatrick ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread());
510061da546Spatrick if (!thread_sp)
511061da546Spatrick return Status("Selected thread isn't valid");
512061da546Spatrick
513061da546Spatrick StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
514061da546Spatrick if (!frame_sp)
515061da546Spatrick return Status("Frame 0 isn't valid");
516061da546Spatrick
517061da546Spatrick ExecutionContext exe_ctx;
518061da546Spatrick frame_sp->CalculateExecutionContext(exe_ctx);
519061da546Spatrick EvaluateExpressionOptions expr_options;
520061da546Spatrick expr_options.SetUnwindOnError(true);
521061da546Spatrick expr_options.SetIgnoreBreakpoints(true);
522061da546Spatrick expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
523061da546Spatrick expr_options.SetLanguage(eLanguageTypeC_plus_plus);
524061da546Spatrick expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
525061da546Spatrick // don't do the work to trap them.
526061da546Spatrick expr_options.SetTimeout(process->GetUtilityExpressionTimeout());
527061da546Spatrick
528061da546Spatrick Status expr_error;
529061da546Spatrick ExpressionResults result =
530061da546Spatrick UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix,
531061da546Spatrick result_valobj_sp, expr_error);
532061da546Spatrick if (result != eExpressionCompleted)
533061da546Spatrick return expr_error;
534061da546Spatrick
535061da546Spatrick if (result_valobj_sp->GetError().Fail())
536061da546Spatrick return result_valobj_sp->GetError();
537061da546Spatrick return Status();
538061da546Spatrick }
539061da546Spatrick
540061da546Spatrick std::unique_ptr<UtilityFunction>
MakeLoadImageUtilityFunction(ExecutionContext & exe_ctx,Status & error)541061da546Spatrick PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx,
542061da546Spatrick Status &error) {
543061da546Spatrick // Remember to prepend this with the prefix from
544061da546Spatrick // GetLibdlFunctionDeclarations. The returned values are all in
545061da546Spatrick // __lldb_dlopen_result for consistency. The wrapper returns a void * but
546061da546Spatrick // doesn't use it because UtilityFunctions don't work with void returns at
547061da546Spatrick // present.
548be691f3bSpatrick //
549be691f3bSpatrick // Use lazy binding so as to not make dlopen()'s success conditional on
550be691f3bSpatrick // forcing every symbol in the library.
551be691f3bSpatrick //
552be691f3bSpatrick // In general, the debugger should allow programs to load & run with
553be691f3bSpatrick // libraries as far as they can, instead of defaulting to being super-picky
554be691f3bSpatrick // about unavailable symbols.
555be691f3bSpatrick //
556be691f3bSpatrick // The value "1" appears to imply lazy binding (RTLD_LAZY) on both Darwin
557be691f3bSpatrick // and other POSIX OSes.
558061da546Spatrick static const char *dlopen_wrapper_code = R"(
559be691f3bSpatrick const int RTLD_LAZY = 1;
560be691f3bSpatrick
561061da546Spatrick struct __lldb_dlopen_result {
562061da546Spatrick void *image_ptr;
563061da546Spatrick const char *error_str;
564061da546Spatrick };
565061da546Spatrick
566*f6aab3d8Srobert extern "C" void *memcpy(void *, const void *, size_t size);
567*f6aab3d8Srobert extern "C" size_t strlen(const char *);
568061da546Spatrick
569061da546Spatrick
570061da546Spatrick void * __lldb_dlopen_wrapper (const char *name,
571061da546Spatrick const char *path_strings,
572061da546Spatrick char *buffer,
573061da546Spatrick __lldb_dlopen_result *result_ptr)
574061da546Spatrick {
575061da546Spatrick // This is the case where the name is the full path:
576061da546Spatrick if (!path_strings) {
577be691f3bSpatrick result_ptr->image_ptr = dlopen(name, RTLD_LAZY);
578061da546Spatrick if (result_ptr->image_ptr)
579061da546Spatrick result_ptr->error_str = nullptr;
580*f6aab3d8Srobert else
581*f6aab3d8Srobert result_ptr->error_str = dlerror();
582061da546Spatrick return nullptr;
583061da546Spatrick }
584061da546Spatrick
585061da546Spatrick // This is the case where we have a list of paths:
586061da546Spatrick size_t name_len = strlen(name);
587061da546Spatrick while (path_strings && path_strings[0] != '\0') {
588061da546Spatrick size_t path_len = strlen(path_strings);
589061da546Spatrick memcpy((void *) buffer, (void *) path_strings, path_len);
590061da546Spatrick buffer[path_len] = '/';
591061da546Spatrick char *target_ptr = buffer+path_len+1;
592061da546Spatrick memcpy((void *) target_ptr, (void *) name, name_len + 1);
593be691f3bSpatrick result_ptr->image_ptr = dlopen(buffer, RTLD_LAZY);
594061da546Spatrick if (result_ptr->image_ptr) {
595061da546Spatrick result_ptr->error_str = nullptr;
596061da546Spatrick break;
597061da546Spatrick }
598061da546Spatrick result_ptr->error_str = dlerror();
599061da546Spatrick path_strings = path_strings + path_len + 1;
600061da546Spatrick }
601061da546Spatrick return nullptr;
602061da546Spatrick }
603061da546Spatrick )";
604061da546Spatrick
605061da546Spatrick static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
606061da546Spatrick Process *process = exe_ctx.GetProcessSP().get();
607061da546Spatrick // Insert the dlopen shim defines into our generic expression:
608dda28197Spatrick std::string expr(std::string(GetLibdlFunctionDeclarations(process)));
609061da546Spatrick expr.append(dlopen_wrapper_code);
610061da546Spatrick Status utility_error;
611061da546Spatrick DiagnosticManager diagnostics;
612061da546Spatrick
613be691f3bSpatrick auto utility_fn_or_error = process->GetTarget().CreateUtilityFunction(
614*f6aab3d8Srobert std::move(expr), dlopen_wrapper_name, eLanguageTypeC_plus_plus, exe_ctx);
615be691f3bSpatrick if (!utility_fn_or_error) {
616be691f3bSpatrick std::string error_str = llvm::toString(utility_fn_or_error.takeError());
617*f6aab3d8Srobert error.SetErrorStringWithFormat(
618*f6aab3d8Srobert "dlopen error: could not create utility function: %s",
619be691f3bSpatrick error_str.c_str());
620061da546Spatrick return nullptr;
621061da546Spatrick }
622be691f3bSpatrick std::unique_ptr<UtilityFunction> dlopen_utility_func_up =
623be691f3bSpatrick std::move(*utility_fn_or_error);
624061da546Spatrick
625061da546Spatrick Value value;
626061da546Spatrick ValueList arguments;
627061da546Spatrick FunctionCaller *do_dlopen_function = nullptr;
628061da546Spatrick
629061da546Spatrick // Fetch the clang types we will need:
630*f6aab3d8Srobert TypeSystemClangSP scratch_ts_sp =
631be691f3bSpatrick ScratchTypeSystemClang::GetForTarget(process->GetTarget());
632*f6aab3d8Srobert if (!scratch_ts_sp)
633061da546Spatrick return nullptr;
634061da546Spatrick
635*f6aab3d8Srobert CompilerType clang_void_pointer_type =
636*f6aab3d8Srobert scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
637*f6aab3d8Srobert CompilerType clang_char_pointer_type =
638*f6aab3d8Srobert scratch_ts_sp->GetBasicType(eBasicTypeChar).GetPointerType();
639061da546Spatrick
640061da546Spatrick // We are passing four arguments, the basename, the list of places to look,
641061da546Spatrick // a buffer big enough for all the path + name combos, and
642061da546Spatrick // a pointer to the storage we've made for the result:
643be691f3bSpatrick value.SetValueType(Value::ValueType::Scalar);
644061da546Spatrick value.SetCompilerType(clang_void_pointer_type);
645061da546Spatrick arguments.PushValue(value);
646061da546Spatrick value.SetCompilerType(clang_char_pointer_type);
647061da546Spatrick arguments.PushValue(value);
648061da546Spatrick arguments.PushValue(value);
649061da546Spatrick arguments.PushValue(value);
650061da546Spatrick
651061da546Spatrick do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
652061da546Spatrick clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
653061da546Spatrick if (utility_error.Fail()) {
654*f6aab3d8Srobert error.SetErrorStringWithFormat(
655*f6aab3d8Srobert "dlopen error: could not make function caller: %s",
656*f6aab3d8Srobert utility_error.AsCString());
657061da546Spatrick return nullptr;
658061da546Spatrick }
659061da546Spatrick
660061da546Spatrick do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
661061da546Spatrick if (!do_dlopen_function) {
662061da546Spatrick error.SetErrorString("dlopen error: could not get function caller.");
663061da546Spatrick return nullptr;
664061da546Spatrick }
665061da546Spatrick
666061da546Spatrick // We made a good utility function, so cache it in the process:
667061da546Spatrick return dlopen_utility_func_up;
668061da546Spatrick }
669061da546Spatrick
DoLoadImage(lldb_private::Process * process,const lldb_private::FileSpec & remote_file,const std::vector<std::string> * paths,lldb_private::Status & error,lldb_private::FileSpec * loaded_image)670061da546Spatrick uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process,
671061da546Spatrick const lldb_private::FileSpec &remote_file,
672061da546Spatrick const std::vector<std::string> *paths,
673061da546Spatrick lldb_private::Status &error,
674061da546Spatrick lldb_private::FileSpec *loaded_image) {
675061da546Spatrick if (loaded_image)
676061da546Spatrick loaded_image->Clear();
677061da546Spatrick
678061da546Spatrick std::string path;
679061da546Spatrick path = remote_file.GetPath();
680061da546Spatrick
681061da546Spatrick ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
682061da546Spatrick if (!thread_sp) {
683061da546Spatrick error.SetErrorString("dlopen error: no thread available to call dlopen.");
684061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
685061da546Spatrick }
686061da546Spatrick
687061da546Spatrick DiagnosticManager diagnostics;
688061da546Spatrick
689061da546Spatrick ExecutionContext exe_ctx;
690061da546Spatrick thread_sp->CalculateExecutionContext(exe_ctx);
691061da546Spatrick
692061da546Spatrick Status utility_error;
693061da546Spatrick UtilityFunction *dlopen_utility_func;
694061da546Spatrick ValueList arguments;
695061da546Spatrick FunctionCaller *do_dlopen_function = nullptr;
696061da546Spatrick
697061da546Spatrick // The UtilityFunction is held in the Process. Platforms don't track the
698061da546Spatrick // lifespan of the Targets that use them, we can't put this in the Platform.
699061da546Spatrick dlopen_utility_func = process->GetLoadImageUtilityFunction(
700061da546Spatrick this, [&]() -> std::unique_ptr<UtilityFunction> {
701061da546Spatrick return MakeLoadImageUtilityFunction(exe_ctx, error);
702061da546Spatrick });
703061da546Spatrick // If we couldn't make it, the error will be in error, so we can exit here.
704061da546Spatrick if (!dlopen_utility_func)
705061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
706061da546Spatrick
707061da546Spatrick do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
708061da546Spatrick if (!do_dlopen_function) {
709061da546Spatrick error.SetErrorString("dlopen error: could not get function caller.");
710061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
711061da546Spatrick }
712061da546Spatrick arguments = do_dlopen_function->GetArgumentValues();
713061da546Spatrick
714061da546Spatrick // Now insert the path we are searching for and the result structure into the
715061da546Spatrick // target.
716061da546Spatrick uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
717061da546Spatrick size_t path_len = path.size() + 1;
718061da546Spatrick lldb::addr_t path_addr = process->AllocateMemory(path_len,
719061da546Spatrick permissions,
720061da546Spatrick utility_error);
721061da546Spatrick if (path_addr == LLDB_INVALID_ADDRESS) {
722*f6aab3d8Srobert error.SetErrorStringWithFormat(
723*f6aab3d8Srobert "dlopen error: could not allocate memory for path: %s",
724*f6aab3d8Srobert utility_error.AsCString());
725061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
726061da546Spatrick }
727061da546Spatrick
728061da546Spatrick // Make sure we deallocate the input string memory:
729061da546Spatrick auto path_cleanup = llvm::make_scope_exit([process, path_addr] {
730061da546Spatrick // Deallocate the buffer.
731061da546Spatrick process->DeallocateMemory(path_addr);
732061da546Spatrick });
733061da546Spatrick
734061da546Spatrick process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
735061da546Spatrick if (utility_error.Fail()) {
736*f6aab3d8Srobert error.SetErrorStringWithFormat(
737*f6aab3d8Srobert "dlopen error: could not write path string: %s",
738*f6aab3d8Srobert utility_error.AsCString());
739061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
740061da546Spatrick }
741061da546Spatrick
742061da546Spatrick // Make space for our return structure. It is two pointers big: the token
743061da546Spatrick // and the error string.
744061da546Spatrick const uint32_t addr_size = process->GetAddressByteSize();
745061da546Spatrick lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
746061da546Spatrick permissions,
747061da546Spatrick utility_error);
748061da546Spatrick if (utility_error.Fail()) {
749*f6aab3d8Srobert error.SetErrorStringWithFormat(
750*f6aab3d8Srobert "dlopen error: could not allocate memory for path: %s",
751*f6aab3d8Srobert utility_error.AsCString());
752061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
753061da546Spatrick }
754061da546Spatrick
755061da546Spatrick // Make sure we deallocate the result structure memory
756061da546Spatrick auto return_cleanup = llvm::make_scope_exit([process, return_addr] {
757061da546Spatrick // Deallocate the buffer
758061da546Spatrick process->DeallocateMemory(return_addr);
759061da546Spatrick });
760061da546Spatrick
761061da546Spatrick // This will be the address of the storage for paths, if we are using them,
762061da546Spatrick // or nullptr to signal we aren't.
763061da546Spatrick lldb::addr_t path_array_addr = 0x0;
764*f6aab3d8Srobert std::optional<llvm::detail::scope_exit<std::function<void()>>>
765061da546Spatrick path_array_cleanup;
766061da546Spatrick
767061da546Spatrick // This is the address to a buffer large enough to hold the largest path
768061da546Spatrick // conjoined with the library name we're passing in. This is a convenience
769061da546Spatrick // to avoid having to call malloc in the dlopen function.
770061da546Spatrick lldb::addr_t buffer_addr = 0x0;
771*f6aab3d8Srobert std::optional<llvm::detail::scope_exit<std::function<void()>>> buffer_cleanup;
772061da546Spatrick
773061da546Spatrick // Set the values into our args and write them to the target:
774061da546Spatrick if (paths != nullptr) {
775061da546Spatrick // First insert the paths into the target. This is expected to be a
776061da546Spatrick // continuous buffer with the strings laid out null terminated and
777061da546Spatrick // end to end with an empty string terminating the buffer.
778061da546Spatrick // We also compute the buffer's required size as we go.
779061da546Spatrick size_t buffer_size = 0;
780061da546Spatrick std::string path_array;
781061da546Spatrick for (auto path : *paths) {
782061da546Spatrick // Don't insert empty paths, they will make us abort the path
783061da546Spatrick // search prematurely.
784061da546Spatrick if (path.empty())
785061da546Spatrick continue;
786061da546Spatrick size_t path_size = path.size();
787061da546Spatrick path_array.append(path);
788061da546Spatrick path_array.push_back('\0');
789061da546Spatrick if (path_size > buffer_size)
790061da546Spatrick buffer_size = path_size;
791061da546Spatrick }
792061da546Spatrick path_array.push_back('\0');
793061da546Spatrick
794061da546Spatrick path_array_addr = process->AllocateMemory(path_array.size(),
795061da546Spatrick permissions,
796061da546Spatrick utility_error);
797061da546Spatrick if (path_array_addr == LLDB_INVALID_ADDRESS) {
798*f6aab3d8Srobert error.SetErrorStringWithFormat(
799*f6aab3d8Srobert "dlopen error: could not allocate memory for path array: %s",
800061da546Spatrick utility_error.AsCString());
801061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
802061da546Spatrick }
803061da546Spatrick
804061da546Spatrick // Make sure we deallocate the paths array.
805061da546Spatrick path_array_cleanup.emplace([process, path_array_addr]() {
806061da546Spatrick // Deallocate the path array.
807061da546Spatrick process->DeallocateMemory(path_array_addr);
808061da546Spatrick });
809061da546Spatrick
810061da546Spatrick process->WriteMemory(path_array_addr, path_array.data(),
811061da546Spatrick path_array.size(), utility_error);
812061da546Spatrick
813061da546Spatrick if (utility_error.Fail()) {
814*f6aab3d8Srobert error.SetErrorStringWithFormat(
815*f6aab3d8Srobert "dlopen error: could not write path array: %s",
816*f6aab3d8Srobert utility_error.AsCString());
817061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
818061da546Spatrick }
819061da546Spatrick // Now make spaces in the target for the buffer. We need to add one for
820061da546Spatrick // the '/' that the utility function will insert and one for the '\0':
821061da546Spatrick buffer_size += path.size() + 2;
822061da546Spatrick
823061da546Spatrick buffer_addr = process->AllocateMemory(buffer_size,
824061da546Spatrick permissions,
825061da546Spatrick utility_error);
826061da546Spatrick if (buffer_addr == LLDB_INVALID_ADDRESS) {
827*f6aab3d8Srobert error.SetErrorStringWithFormat(
828*f6aab3d8Srobert "dlopen error: could not allocate memory for buffer: %s",
829061da546Spatrick utility_error.AsCString());
830061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
831061da546Spatrick }
832061da546Spatrick
833061da546Spatrick // Make sure we deallocate the buffer memory:
834061da546Spatrick buffer_cleanup.emplace([process, buffer_addr]() {
835061da546Spatrick // Deallocate the buffer.
836061da546Spatrick process->DeallocateMemory(buffer_addr);
837061da546Spatrick });
838061da546Spatrick }
839061da546Spatrick
840061da546Spatrick arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
841061da546Spatrick arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
842061da546Spatrick arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
843061da546Spatrick arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
844061da546Spatrick
845061da546Spatrick lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
846061da546Spatrick
847061da546Spatrick diagnostics.Clear();
848061da546Spatrick if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
849061da546Spatrick func_args_addr,
850061da546Spatrick arguments,
851061da546Spatrick diagnostics)) {
852*f6aab3d8Srobert error.SetErrorStringWithFormat(
853*f6aab3d8Srobert "dlopen error: could not write function arguments: %s",
854061da546Spatrick diagnostics.GetString().c_str());
855061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
856061da546Spatrick }
857061da546Spatrick
858061da546Spatrick // Make sure we clean up the args structure. We can't reuse it because the
859061da546Spatrick // Platform lives longer than the process and the Platforms don't get a
860061da546Spatrick // signal to clean up cached data when a process goes away.
861061da546Spatrick auto args_cleanup =
862061da546Spatrick llvm::make_scope_exit([do_dlopen_function, &exe_ctx, func_args_addr] {
863061da546Spatrick do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
864061da546Spatrick });
865061da546Spatrick
866061da546Spatrick // Now run the caller:
867061da546Spatrick EvaluateExpressionOptions options;
868061da546Spatrick options.SetExecutionPolicy(eExecutionPolicyAlways);
869061da546Spatrick options.SetLanguage(eLanguageTypeC_plus_plus);
870061da546Spatrick options.SetIgnoreBreakpoints(true);
871061da546Spatrick options.SetUnwindOnError(true);
872061da546Spatrick options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
873061da546Spatrick // don't do the work to trap them.
874061da546Spatrick options.SetTimeout(process->GetUtilityExpressionTimeout());
875061da546Spatrick options.SetIsForUtilityExpr(true);
876061da546Spatrick
877061da546Spatrick Value return_value;
878061da546Spatrick // Fetch the clang types we will need:
879*f6aab3d8Srobert TypeSystemClangSP scratch_ts_sp =
880be691f3bSpatrick ScratchTypeSystemClang::GetForTarget(process->GetTarget());
881*f6aab3d8Srobert if (!scratch_ts_sp) {
882dda28197Spatrick error.SetErrorString("dlopen error: Unable to get TypeSystemClang");
883061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
884061da546Spatrick }
885061da546Spatrick
886*f6aab3d8Srobert CompilerType clang_void_pointer_type =
887*f6aab3d8Srobert scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
888061da546Spatrick
889061da546Spatrick return_value.SetCompilerType(clang_void_pointer_type);
890061da546Spatrick
891061da546Spatrick ExpressionResults results = do_dlopen_function->ExecuteFunction(
892061da546Spatrick exe_ctx, &func_args_addr, options, diagnostics, return_value);
893061da546Spatrick if (results != eExpressionCompleted) {
894*f6aab3d8Srobert error.SetErrorStringWithFormat(
895*f6aab3d8Srobert "dlopen error: failed executing dlopen wrapper function: %s",
896061da546Spatrick diagnostics.GetString().c_str());
897061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
898061da546Spatrick }
899061da546Spatrick
900061da546Spatrick // Read the dlopen token from the return area:
901061da546Spatrick lldb::addr_t token = process->ReadPointerFromMemory(return_addr,
902061da546Spatrick utility_error);
903061da546Spatrick if (utility_error.Fail()) {
904*f6aab3d8Srobert error.SetErrorStringWithFormat(
905*f6aab3d8Srobert "dlopen error: could not read the return struct: %s",
906*f6aab3d8Srobert utility_error.AsCString());
907061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
908061da546Spatrick }
909061da546Spatrick
910061da546Spatrick // The dlopen succeeded!
911061da546Spatrick if (token != 0x0) {
912061da546Spatrick if (loaded_image && buffer_addr != 0x0)
913061da546Spatrick {
914061da546Spatrick // Capture the image which was loaded. We leave it in the buffer on
915061da546Spatrick // exit from the dlopen function, so we can just read it from there:
916061da546Spatrick std::string name_string;
917061da546Spatrick process->ReadCStringFromMemory(buffer_addr, name_string, utility_error);
918061da546Spatrick if (utility_error.Success())
919061da546Spatrick loaded_image->SetFile(name_string, llvm::sys::path::Style::posix);
920061da546Spatrick }
921061da546Spatrick return process->AddImageToken(token);
922061da546Spatrick }
923061da546Spatrick
924061da546Spatrick // We got an error, lets read in the error string:
925061da546Spatrick std::string dlopen_error_str;
926061da546Spatrick lldb::addr_t error_addr
927061da546Spatrick = process->ReadPointerFromMemory(return_addr + addr_size, utility_error);
928061da546Spatrick if (utility_error.Fail()) {
929*f6aab3d8Srobert error.SetErrorStringWithFormat(
930*f6aab3d8Srobert "dlopen error: could not read error string: %s",
931*f6aab3d8Srobert utility_error.AsCString());
932061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
933061da546Spatrick }
934061da546Spatrick
935061da546Spatrick size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size,
936061da546Spatrick dlopen_error_str,
937061da546Spatrick utility_error);
938061da546Spatrick if (utility_error.Success() && num_chars > 0)
939061da546Spatrick error.SetErrorStringWithFormat("dlopen error: %s",
940061da546Spatrick dlopen_error_str.c_str());
941061da546Spatrick else
942061da546Spatrick error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
943061da546Spatrick
944061da546Spatrick return LLDB_INVALID_IMAGE_TOKEN;
945061da546Spatrick }
946061da546Spatrick
UnloadImage(lldb_private::Process * process,uint32_t image_token)947061da546Spatrick Status PlatformPOSIX::UnloadImage(lldb_private::Process *process,
948061da546Spatrick uint32_t image_token) {
949061da546Spatrick const addr_t image_addr = process->GetImagePtrFromToken(image_token);
950061da546Spatrick if (image_addr == LLDB_INVALID_ADDRESS)
951061da546Spatrick return Status("Invalid image token");
952061da546Spatrick
953061da546Spatrick StreamString expr;
954061da546Spatrick expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
955061da546Spatrick llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
956061da546Spatrick lldb::ValueObjectSP result_valobj_sp;
957061da546Spatrick Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
958061da546Spatrick result_valobj_sp);
959061da546Spatrick if (error.Fail())
960061da546Spatrick return error;
961061da546Spatrick
962061da546Spatrick if (result_valobj_sp->GetError().Fail())
963061da546Spatrick return result_valobj_sp->GetError();
964061da546Spatrick
965061da546Spatrick Scalar scalar;
966061da546Spatrick if (result_valobj_sp->ResolveValue(scalar)) {
967061da546Spatrick if (scalar.UInt(1))
968061da546Spatrick return Status("expression failed: \"%s\"", expr.GetData());
969061da546Spatrick process->ResetImageToken(image_token);
970061da546Spatrick }
971061da546Spatrick return Status();
972061da546Spatrick }
973061da546Spatrick
974061da546Spatrick llvm::StringRef
GetLibdlFunctionDeclarations(lldb_private::Process * process)975061da546Spatrick PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
976061da546Spatrick return R"(
977061da546Spatrick extern "C" void* dlopen(const char*, int);
978061da546Spatrick extern "C" void* dlsym(void*, const char*);
979061da546Spatrick extern "C" int dlclose(void*);
980061da546Spatrick extern "C" char* dlerror(void);
981061da546Spatrick )";
982061da546Spatrick }
983061da546Spatrick
GetFullNameForDylib(ConstString basename)984061da546Spatrick ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) {
985061da546Spatrick if (basename.IsEmpty())
986061da546Spatrick return basename;
987061da546Spatrick
988061da546Spatrick StreamString stream;
989061da546Spatrick stream.Printf("lib%s.so", basename.GetCString());
990061da546Spatrick return ConstString(stream.GetString());
991061da546Spatrick }
992