1 //===-- PlatformPOSIX.cpp ---------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "PlatformPOSIX.h"
14 // Other libraries and framework includes
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/ModuleSpec.h"
20 #include "lldb/Core/ValueObject.h"
21 #include "lldb/Expression/DiagnosticManager.h"
22 #include "lldb/Expression/FunctionCaller.h"
23 #include "lldb/Expression/UserExpression.h"
24 #include "lldb/Expression/UtilityFunction.h"
25 #include "lldb/Host/File.h"
26 #include "lldb/Host/FileCache.h"
27 #include "lldb/Host/FileSystem.h"
28 #include "lldb/Host/Host.h"
29 #include "lldb/Host/HostInfo.h"
30 #include "lldb/Symbol/ClangASTContext.h"
31 #include "lldb/Target/DynamicLoader.h"
32 #include "lldb/Target/ExecutionContext.h"
33 #include "lldb/Target/Process.h"
34 #include "lldb/Target/ProcessLaunchInfo.h"
35 #include "lldb/Target/Thread.h"
36 #include "lldb/Utility/CleanUp.h"
37 #include "lldb/Utility/DataBufferHeap.h"
38 #include "lldb/Utility/FileSpec.h"
39 #include "lldb/Utility/Log.h"
40 #include "lldb/Utility/StreamString.h"
43 using namespace lldb_private;
45 //------------------------------------------------------------------
46 /// Default Constructor
47 //------------------------------------------------------------------
48 PlatformPOSIX::PlatformPOSIX(bool is_host)
49 : Platform(is_host), // This is the local host platform
50 m_option_group_platform_rsync(new OptionGroupPlatformRSync()),
51 m_option_group_platform_ssh(new OptionGroupPlatformSSH()),
52 m_option_group_platform_caching(new OptionGroupPlatformCaching()),
53 m_remote_platform_sp() {}
55 //------------------------------------------------------------------
58 /// The destructor is virtual since this class is designed to be
59 /// inherited from by the plug-in instance.
60 //------------------------------------------------------------------
61 PlatformPOSIX::~PlatformPOSIX() {}
63 bool PlatformPOSIX::GetModuleSpec(const FileSpec &module_file_spec,
65 ModuleSpec &module_spec) {
66 if (m_remote_platform_sp)
67 return m_remote_platform_sp->GetModuleSpec(module_file_spec, arch,
70 return Platform::GetModuleSpec(module_file_spec, arch, module_spec);
73 lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions(
74 lldb_private::CommandInterpreter &interpreter) {
75 auto iter = m_options.find(&interpreter), end = m_options.end();
77 std::unique_ptr<lldb_private::OptionGroupOptions> options(
78 new OptionGroupOptions());
79 options->Append(m_option_group_platform_rsync.get());
80 options->Append(m_option_group_platform_ssh.get());
81 options->Append(m_option_group_platform_caching.get());
82 m_options[&interpreter] = std::move(options);
85 return m_options.at(&interpreter).get();
88 bool PlatformPOSIX::IsConnected() const {
91 else if (m_remote_platform_sp)
92 return m_remote_platform_sp->IsConnected();
96 lldb_private::Status PlatformPOSIX::RunShellCommand(
97 const char *command, // Shouldn't be NULL
99 working_dir, // Pass empty FileSpec to use the current working directory
100 int *status_ptr, // Pass NULL if you don't want the process exit status
101 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
104 *command_output, // Pass NULL if you don't want the command output
105 const Timeout<std::micro> &timeout) {
107 return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr,
108 command_output, timeout);
110 if (m_remote_platform_sp)
111 return m_remote_platform_sp->RunShellCommand(
112 command, working_dir, status_ptr, signo_ptr, command_output, timeout);
114 return Status("unable to run a remote command without a platform");
119 PlatformPOSIX::ResolveExecutable(const ModuleSpec &module_spec,
120 lldb::ModuleSP &exe_module_sp,
121 const FileSpecList *module_search_paths_ptr) {
123 // Nothing special to do here, just use the actual file and architecture
125 char exe_path[PATH_MAX];
126 ModuleSpec resolved_module_spec(module_spec);
129 // If we have "ls" as the exe_file, resolve the executable location based
130 // on the current path variables
131 if (!resolved_module_spec.GetFileSpec().Exists()) {
132 resolved_module_spec.GetFileSpec().GetPath(exe_path, sizeof(exe_path));
133 resolved_module_spec.GetFileSpec().SetFile(exe_path, true,
134 FileSpec::Style::native);
137 if (!resolved_module_spec.GetFileSpec().Exists())
138 resolved_module_spec.GetFileSpec().ResolveExecutableLocation();
140 // Resolve any executable within a bundle on MacOSX
141 Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
143 if (resolved_module_spec.GetFileSpec().Exists())
146 const uint32_t permissions =
147 resolved_module_spec.GetFileSpec().GetPermissions();
148 if (permissions && (permissions & eFilePermissionsEveryoneR) == 0)
149 error.SetErrorStringWithFormat(
150 "executable '%s' is not readable",
151 resolved_module_spec.GetFileSpec().GetPath().c_str());
153 error.SetErrorStringWithFormat(
154 "unable to find executable for '%s'",
155 resolved_module_spec.GetFileSpec().GetPath().c_str());
158 if (m_remote_platform_sp) {
160 GetCachedExecutable(resolved_module_spec, exe_module_sp,
161 module_search_paths_ptr, *m_remote_platform_sp);
163 // We may connect to a process and use the provided executable (Don't use
166 // Resolve any executable within a bundle on MacOSX
167 Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
169 if (resolved_module_spec.GetFileSpec().Exists())
172 error.SetErrorStringWithFormat("the platform is not currently "
173 "connected, and '%s' doesn't exist in "
179 if (error.Success()) {
180 if (resolved_module_spec.GetArchitecture().IsValid()) {
181 error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
182 module_search_paths_ptr, nullptr, nullptr);
184 // If we failed, it may be because the vendor and os aren't known. If
185 // that is the case, try setting them to the host architecture and give
187 llvm::Triple &module_triple =
188 resolved_module_spec.GetArchitecture().GetTriple();
189 bool is_vendor_specified =
190 (module_triple.getVendor() != llvm::Triple::UnknownVendor);
191 bool is_os_specified =
192 (module_triple.getOS() != llvm::Triple::UnknownOS);
193 if (!is_vendor_specified || !is_os_specified) {
194 const llvm::Triple &host_triple =
195 HostInfo::GetArchitecture(HostInfo::eArchKindDefault).GetTriple();
197 if (!is_vendor_specified)
198 module_triple.setVendorName(host_triple.getVendorName());
199 if (!is_os_specified)
200 module_triple.setOSName(host_triple.getOSName());
202 error = ModuleList::GetSharedModule(resolved_module_spec,
203 exe_module_sp, module_search_paths_ptr, nullptr, nullptr);
207 // TODO find out why exe_module_sp might be NULL
208 if (error.Fail() || !exe_module_sp || !exe_module_sp->GetObjectFile()) {
209 exe_module_sp.reset();
210 error.SetErrorStringWithFormat(
211 "'%s' doesn't contain the architecture %s",
212 resolved_module_spec.GetFileSpec().GetPath().c_str(),
213 resolved_module_spec.GetArchitecture().GetArchitectureName());
216 // No valid architecture was specified, ask the platform for the
217 // architectures that we should be using (in the correct order) and see
218 // if we can find a match that way
219 StreamString arch_names;
220 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
221 idx, resolved_module_spec.GetArchitecture());
223 error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
224 module_search_paths_ptr, nullptr, nullptr);
225 // Did we find an executable using one of the
226 if (error.Success()) {
227 if (exe_module_sp && exe_module_sp->GetObjectFile())
230 error.SetErrorToGenericError();
234 arch_names.PutCString(", ");
235 arch_names.PutCString(
236 resolved_module_spec.GetArchitecture().GetArchitectureName());
239 if (error.Fail() || !exe_module_sp) {
240 if (resolved_module_spec.GetFileSpec().Readable()) {
241 error.SetErrorStringWithFormat(
242 "'%s' doesn't contain any '%s' platform architectures: %s",
243 resolved_module_spec.GetFileSpec().GetPath().c_str(),
244 GetPluginName().GetCString(), arch_names.GetData());
246 error.SetErrorStringWithFormat(
247 "'%s' is not readable",
248 resolved_module_spec.GetFileSpec().GetPath().c_str());
257 Status PlatformPOSIX::GetFileWithUUID(const FileSpec &platform_file,
258 const UUID *uuid_ptr,
259 FileSpec &local_file) {
260 if (IsRemote() && m_remote_platform_sp)
261 return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr,
264 // Default to the local case
265 local_file = platform_file;
269 bool PlatformPOSIX::GetProcessInfo(lldb::pid_t pid,
270 ProcessInstanceInfo &process_info) {
272 return Platform::GetProcessInfo(pid, process_info);
273 if (m_remote_platform_sp)
274 return m_remote_platform_sp->GetProcessInfo(pid, process_info);
279 PlatformPOSIX::FindProcesses(const ProcessInstanceInfoMatch &match_info,
280 ProcessInstanceInfoList &process_infos) {
282 return Platform::FindProcesses(match_info, process_infos);
283 if (m_remote_platform_sp)
285 m_remote_platform_sp->FindProcesses(match_info, process_infos);
289 Status PlatformPOSIX::MakeDirectory(const FileSpec &file_spec,
290 uint32_t file_permissions) {
291 if (m_remote_platform_sp)
292 return m_remote_platform_sp->MakeDirectory(file_spec, file_permissions);
294 return Platform::MakeDirectory(file_spec, file_permissions);
297 Status PlatformPOSIX::GetFilePermissions(const FileSpec &file_spec,
298 uint32_t &file_permissions) {
299 if (m_remote_platform_sp)
300 return m_remote_platform_sp->GetFilePermissions(file_spec,
303 return Platform::GetFilePermissions(file_spec, file_permissions);
306 Status PlatformPOSIX::SetFilePermissions(const FileSpec &file_spec,
307 uint32_t file_permissions) {
308 if (m_remote_platform_sp)
309 return m_remote_platform_sp->SetFilePermissions(file_spec,
312 return Platform::SetFilePermissions(file_spec, file_permissions);
315 lldb::user_id_t PlatformPOSIX::OpenFile(const FileSpec &file_spec,
316 uint32_t flags, uint32_t mode,
319 return FileCache::GetInstance().OpenFile(file_spec, flags, mode, error);
320 else if (m_remote_platform_sp)
321 return m_remote_platform_sp->OpenFile(file_spec, flags, mode, error);
323 return Platform::OpenFile(file_spec, flags, mode, error);
326 bool PlatformPOSIX::CloseFile(lldb::user_id_t fd, Status &error) {
328 return FileCache::GetInstance().CloseFile(fd, error);
329 else if (m_remote_platform_sp)
330 return m_remote_platform_sp->CloseFile(fd, error);
332 return Platform::CloseFile(fd, error);
335 uint64_t PlatformPOSIX::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
336 uint64_t dst_len, Status &error) {
338 return FileCache::GetInstance().ReadFile(fd, offset, dst, dst_len, error);
339 else if (m_remote_platform_sp)
340 return m_remote_platform_sp->ReadFile(fd, offset, dst, dst_len, error);
342 return Platform::ReadFile(fd, offset, dst, dst_len, error);
345 uint64_t PlatformPOSIX::WriteFile(lldb::user_id_t fd, uint64_t offset,
346 const void *src, uint64_t src_len,
349 return FileCache::GetInstance().WriteFile(fd, offset, src, src_len, error);
350 else if (m_remote_platform_sp)
351 return m_remote_platform_sp->WriteFile(fd, offset, src, src_len, error);
353 return Platform::WriteFile(fd, offset, src, src_len, error);
356 static uint32_t chown_file(Platform *platform, const char *path,
357 uint32_t uid = UINT32_MAX,
358 uint32_t gid = UINT32_MAX) {
359 if (!platform || !path || *path == 0)
362 if (uid == UINT32_MAX && gid == UINT32_MAX)
363 return 0; // pretend I did chown correctly - actually I just didn't care
365 StreamString command;
366 command.PutCString("chown ");
367 if (uid != UINT32_MAX)
368 command.Printf("%d", uid);
369 if (gid != UINT32_MAX)
370 command.Printf(":%d", gid);
371 command.Printf("%s", path);
373 platform->RunShellCommand(command.GetData(), NULL, &status, NULL, NULL,
374 std::chrono::seconds(10));
379 PlatformPOSIX::PutFile(const lldb_private::FileSpec &source,
380 const lldb_private::FileSpec &destination, uint32_t uid,
382 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
385 if (FileSpec::Equal(source, destination, true))
389 std::string src_path(source.GetPath());
390 if (src_path.empty())
391 return Status("unable to get file path for source");
392 std::string dst_path(destination.GetPath());
393 if (dst_path.empty())
394 return Status("unable to get file path for destination");
395 StreamString command;
396 command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
398 RunShellCommand(command.GetData(), NULL, &status, NULL, NULL,
399 std::chrono::seconds(10));
401 return Status("unable to perform copy");
402 if (uid == UINT32_MAX && gid == UINT32_MAX)
404 if (chown_file(this, dst_path.c_str(), uid, gid) != 0)
405 return Status("unable to perform chown");
407 } else if (m_remote_platform_sp) {
408 if (GetSupportsRSync()) {
409 std::string src_path(source.GetPath());
410 if (src_path.empty())
411 return Status("unable to get file path for source");
412 std::string dst_path(destination.GetPath());
413 if (dst_path.empty())
414 return Status("unable to get file path for destination");
415 StreamString command;
416 if (GetIgnoresRemoteHostname()) {
417 if (!GetRSyncPrefix())
418 command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
421 command.Printf("rsync %s %s %s%s", GetRSyncOpts(), src_path.c_str(),
422 GetRSyncPrefix(), dst_path.c_str());
424 command.Printf("rsync %s %s %s:%s", GetRSyncOpts(), src_path.c_str(),
425 GetHostname(), dst_path.c_str());
427 log->Printf("[PutFile] Running command: %s\n", command.GetData());
429 Host::RunShellCommand(command.GetData(), NULL, &retcode, NULL, NULL,
430 std::chrono::minutes(1));
432 // Don't chown a local file for a remote system
433 // if (chown_file(this,dst_path.c_str(),uid,gid) != 0)
434 // return Status("unable to perform chown");
437 // if we are still here rsync has failed - let's try the slow way before
441 return Platform::PutFile(source, destination, uid, gid);
444 lldb::user_id_t PlatformPOSIX::GetFileSize(const FileSpec &file_spec) {
447 if (llvm::sys::fs::file_size(file_spec.GetPath(), Size))
450 } else if (m_remote_platform_sp)
451 return m_remote_platform_sp->GetFileSize(file_spec);
453 return Platform::GetFileSize(file_spec);
456 Status PlatformPOSIX::CreateSymlink(const FileSpec &src, const FileSpec &dst) {
458 return FileSystem::Symlink(src, dst);
459 else if (m_remote_platform_sp)
460 return m_remote_platform_sp->CreateSymlink(src, dst);
462 return Platform::CreateSymlink(src, dst);
465 bool PlatformPOSIX::GetFileExists(const FileSpec &file_spec) {
467 return file_spec.Exists();
468 else if (m_remote_platform_sp)
469 return m_remote_platform_sp->GetFileExists(file_spec);
471 return Platform::GetFileExists(file_spec);
474 Status PlatformPOSIX::Unlink(const FileSpec &file_spec) {
476 return llvm::sys::fs::remove(file_spec.GetPath());
477 else if (m_remote_platform_sp)
478 return m_remote_platform_sp->Unlink(file_spec);
480 return Platform::Unlink(file_spec);
483 lldb_private::Status PlatformPOSIX::GetFile(
484 const lldb_private::FileSpec &source, // remote file path
485 const lldb_private::FileSpec &destination) // local file path
487 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
489 // Check the args, first.
490 std::string src_path(source.GetPath());
491 if (src_path.empty())
492 return Status("unable to get file path for source");
493 std::string dst_path(destination.GetPath());
494 if (dst_path.empty())
495 return Status("unable to get file path for destination");
497 if (FileSpec::Equal(source, destination, true))
498 return Status("local scenario->source and destination are the same file "
499 "path: no operation performed");
501 StreamString cp_command;
502 cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
504 RunShellCommand(cp_command.GetData(), NULL, &status, NULL, NULL,
505 std::chrono::seconds(10));
507 return Status("unable to perform copy");
509 } else if (m_remote_platform_sp) {
510 if (GetSupportsRSync()) {
511 StreamString command;
512 if (GetIgnoresRemoteHostname()) {
513 if (!GetRSyncPrefix())
514 command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
517 command.Printf("rsync %s %s%s %s", GetRSyncOpts(), GetRSyncPrefix(),
518 src_path.c_str(), dst_path.c_str());
520 command.Printf("rsync %s %s:%s %s", GetRSyncOpts(),
521 m_remote_platform_sp->GetHostname(), src_path.c_str(),
524 log->Printf("[GetFile] Running command: %s\n", command.GetData());
526 Host::RunShellCommand(command.GetData(), NULL, &retcode, NULL, NULL,
527 std::chrono::minutes(1));
530 // If we are here, rsync has failed - let's try the slow way before
534 // read/write, read/write, read/write, ...
538 log->Printf("[GetFile] Using block by block transfer....\n");
540 user_id_t fd_src = OpenFile(source, File::eOpenOptionRead,
541 lldb::eFilePermissionsFileDefault, error);
543 if (fd_src == UINT64_MAX)
544 return Status("unable to open source file");
546 uint32_t permissions = 0;
547 error = GetFilePermissions(source, permissions);
549 if (permissions == 0)
550 permissions = lldb::eFilePermissionsFileDefault;
552 user_id_t fd_dst = FileCache::GetInstance().OpenFile(
553 destination, File::eOpenOptionCanCreate | File::eOpenOptionWrite |
554 File::eOpenOptionTruncate,
557 if (fd_dst == UINT64_MAX) {
559 error.SetErrorString("unable to open destination file");
562 if (error.Success()) {
563 lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
566 while (error.Success()) {
567 const uint64_t n_read = ReadFile(fd_src, offset, buffer_sp->GetBytes(),
568 buffer_sp->GetByteSize(), error);
573 if (FileCache::GetInstance().WriteFile(fd_dst, offset,
574 buffer_sp->GetBytes(), n_read,
577 error.SetErrorString("unable to write to destination file");
583 // Ignore the close error of src.
584 if (fd_src != UINT64_MAX)
585 CloseFile(fd_src, error);
586 // And close the dst file descriptot.
587 if (fd_dst != UINT64_MAX &&
588 !FileCache::GetInstance().CloseFile(fd_dst, error)) {
590 error.SetErrorString("unable to close destination file");
594 return Platform::GetFile(source, destination);
597 std::string PlatformPOSIX::GetPlatformSpecificConnectionInformation() {
599 if (GetSupportsRSync()) {
600 stream.PutCString("rsync");
601 if ((GetRSyncOpts() && *GetRSyncOpts()) ||
602 (GetRSyncPrefix() && *GetRSyncPrefix()) || GetIgnoresRemoteHostname()) {
603 stream.Printf(", options: ");
604 if (GetRSyncOpts() && *GetRSyncOpts())
605 stream.Printf("'%s' ", GetRSyncOpts());
606 stream.Printf(", prefix: ");
607 if (GetRSyncPrefix() && *GetRSyncPrefix())
608 stream.Printf("'%s' ", GetRSyncPrefix());
609 if (GetIgnoresRemoteHostname())
610 stream.Printf("ignore remote-hostname ");
613 if (GetSupportsSSH()) {
614 stream.PutCString("ssh");
615 if (GetSSHOpts() && *GetSSHOpts())
616 stream.Printf(", options: '%s' ", GetSSHOpts());
618 if (GetLocalCacheDirectory() && *GetLocalCacheDirectory())
619 stream.Printf("cache dir: %s", GetLocalCacheDirectory());
620 if (stream.GetSize())
621 return stream.GetString();
626 bool PlatformPOSIX::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
629 return Platform::CalculateMD5(file_spec, low, high);
630 if (m_remote_platform_sp)
631 return m_remote_platform_sp->CalculateMD5(file_spec, low, high);
635 const lldb::UnixSignalsSP &PlatformPOSIX::GetRemoteUnixSignals() {
636 if (IsRemote() && m_remote_platform_sp)
637 return m_remote_platform_sp->GetRemoteUnixSignals();
638 return Platform::GetRemoteUnixSignals();
641 FileSpec PlatformPOSIX::GetRemoteWorkingDirectory() {
642 if (IsRemote() && m_remote_platform_sp)
643 return m_remote_platform_sp->GetRemoteWorkingDirectory();
645 return Platform::GetRemoteWorkingDirectory();
648 bool PlatformPOSIX::SetRemoteWorkingDirectory(const FileSpec &working_dir) {
649 if (IsRemote() && m_remote_platform_sp)
650 return m_remote_platform_sp->SetRemoteWorkingDirectory(working_dir);
652 return Platform::SetRemoteWorkingDirectory(working_dir);
655 bool PlatformPOSIX::GetRemoteOSVersion() {
656 if (m_remote_platform_sp) {
657 m_os_version = m_remote_platform_sp->GetOSVersion();
658 return !m_os_version.empty();
663 bool PlatformPOSIX::GetRemoteOSBuildString(std::string &s) {
664 if (m_remote_platform_sp)
665 return m_remote_platform_sp->GetRemoteOSBuildString(s);
670 Environment PlatformPOSIX::GetEnvironment() {
672 if (m_remote_platform_sp)
673 return m_remote_platform_sp->GetEnvironment();
674 return Environment();
676 return Host::GetEnvironment();
679 bool PlatformPOSIX::GetRemoteOSKernelDescription(std::string &s) {
680 if (m_remote_platform_sp)
681 return m_remote_platform_sp->GetRemoteOSKernelDescription(s);
686 // Remote Platform subclasses need to override this function
687 ArchSpec PlatformPOSIX::GetRemoteSystemArchitecture() {
688 if (m_remote_platform_sp)
689 return m_remote_platform_sp->GetRemoteSystemArchitecture();
693 const char *PlatformPOSIX::GetHostname() {
695 return Platform::GetHostname();
697 if (m_remote_platform_sp)
698 return m_remote_platform_sp->GetHostname();
702 const char *PlatformPOSIX::GetUserName(uint32_t uid) {
703 // Check the cache in Platform in case we have already looked this uid up
704 const char *user_name = Platform::GetUserName(uid);
708 if (IsRemote() && m_remote_platform_sp)
709 return m_remote_platform_sp->GetUserName(uid);
713 const char *PlatformPOSIX::GetGroupName(uint32_t gid) {
714 const char *group_name = Platform::GetGroupName(gid);
718 if (IsRemote() && m_remote_platform_sp)
719 return m_remote_platform_sp->GetGroupName(gid);
723 Status PlatformPOSIX::ConnectRemote(Args &args) {
726 error.SetErrorStringWithFormat(
727 "can't connect to the host platform '%s', always connected",
728 GetPluginName().GetCString());
730 if (!m_remote_platform_sp)
731 m_remote_platform_sp =
732 Platform::Create(ConstString("remote-gdb-server"), error);
734 if (m_remote_platform_sp && error.Success())
735 error = m_remote_platform_sp->ConnectRemote(args);
737 error.SetErrorString("failed to create a 'remote-gdb-server' platform");
740 m_remote_platform_sp.reset();
743 if (error.Success() && m_remote_platform_sp) {
744 if (m_option_group_platform_rsync.get() &&
745 m_option_group_platform_ssh.get() &&
746 m_option_group_platform_caching.get()) {
747 if (m_option_group_platform_rsync->m_rsync) {
748 SetSupportsRSync(true);
749 SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str());
750 SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str());
751 SetIgnoresRemoteHostname(
752 m_option_group_platform_rsync->m_ignores_remote_hostname);
754 if (m_option_group_platform_ssh->m_ssh) {
755 SetSupportsSSH(true);
756 SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str());
758 SetLocalCacheDirectory(
759 m_option_group_platform_caching->m_cache_dir.c_str());
766 Status PlatformPOSIX::DisconnectRemote() {
770 error.SetErrorStringWithFormat(
771 "can't disconnect from the host platform '%s', always connected",
772 GetPluginName().GetCString());
774 if (m_remote_platform_sp)
775 error = m_remote_platform_sp->DisconnectRemote();
777 error.SetErrorString("the platform is not currently connected");
782 Status PlatformPOSIX::LaunchProcess(ProcessLaunchInfo &launch_info) {
786 error = Platform::LaunchProcess(launch_info);
788 if (m_remote_platform_sp)
789 error = m_remote_platform_sp->LaunchProcess(launch_info);
791 error.SetErrorString("the platform is not currently connected");
796 lldb_private::Status PlatformPOSIX::KillProcess(const lldb::pid_t pid) {
798 return Platform::KillProcess(pid);
800 if (m_remote_platform_sp)
801 return m_remote_platform_sp->KillProcess(pid);
803 return Status("the platform is not currently connected");
806 lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info,
807 Debugger &debugger, Target *target,
809 lldb::ProcessSP process_sp;
810 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
813 if (target == NULL) {
814 TargetSP new_target_sp;
816 error = debugger.GetTargetList().CreateTarget(debugger, "", "", false,
817 NULL, new_target_sp);
818 target = new_target_sp.get();
820 log->Printf("PlatformPOSIX::%s created new target", __FUNCTION__);
824 log->Printf("PlatformPOSIX::%s target already existed, setting target",
828 if (target && error.Success()) {
829 debugger.GetTargetList().SetSelectedTarget(target);
831 ModuleSP exe_module_sp = target->GetExecutableModule();
832 log->Printf("PlatformPOSIX::%s set selected target to %p %s",
833 __FUNCTION__, (void *)target,
835 ? exe_module_sp->GetFileSpec().GetPath().c_str()
840 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
841 attach_info.GetProcessPluginName(), NULL);
844 ListenerSP listener_sp = attach_info.GetHijackListener();
845 if (listener_sp == nullptr) {
847 Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
848 attach_info.SetHijackListener(listener_sp);
850 process_sp->HijackProcessEvents(listener_sp);
851 error = process_sp->Attach(attach_info);
855 if (m_remote_platform_sp)
857 m_remote_platform_sp->Attach(attach_info, debugger, target, error);
859 error.SetErrorString("the platform is not currently connected");
865 PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
866 Target *target, // Can be NULL, if NULL create a new
867 // target, else use existing one
869 ProcessSP process_sp;
872 // We are going to hand this process off to debugserver which will be in
873 // charge of setting the exit status. However, we still need to reap it
874 // from lldb. So, make sure we use a exit callback which does not set exit
876 const bool monitor_signals = false;
877 launch_info.SetMonitorProcessCallback(
878 &ProcessLaunchInfo::NoOpMonitorCallback, monitor_signals);
879 process_sp = Platform::DebugProcess(launch_info, debugger, target, error);
881 if (m_remote_platform_sp)
882 process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
885 error.SetErrorString("the platform is not currently connected");
890 void PlatformPOSIX::CalculateTrapHandlerSymbolNames() {
891 m_trap_handlers.push_back(ConstString("_sigtramp"));
894 Status PlatformPOSIX::EvaluateLibdlExpression(
895 lldb_private::Process *process, const char *expr_cstr,
896 llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
897 DynamicLoader *loader = process->GetDynamicLoader();
899 Status error = loader->CanLoadImage();
904 ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread());
906 return Status("Selected thread isn't valid");
908 StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
910 return Status("Frame 0 isn't valid");
912 ExecutionContext exe_ctx;
913 frame_sp->CalculateExecutionContext(exe_ctx);
914 EvaluateExpressionOptions expr_options;
915 expr_options.SetUnwindOnError(true);
916 expr_options.SetIgnoreBreakpoints(true);
917 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
918 expr_options.SetLanguage(eLanguageTypeC_plus_plus);
919 expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
920 // don't do the work to trap them.
921 expr_options.SetTimeout(std::chrono::seconds(2));
924 ExpressionResults result =
925 UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix,
926 result_valobj_sp, expr_error);
927 if (result != eExpressionCompleted)
930 if (result_valobj_sp->GetError().Fail())
931 return result_valobj_sp->GetError();
935 std::unique_ptr<UtilityFunction>
936 PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx,
938 // Remember to prepend this with the prefix from
939 // GetLibdlFunctionDeclarations. The returned values are all in
940 // __lldb_dlopen_result for consistency. The wrapper returns a void * but
941 // doesn't use it because UtilityFunctions don't work with void returns at
943 static const char *dlopen_wrapper_code = R"(
944 struct __lldb_dlopen_result {
946 const char *error_str;
949 extern void *memcpy(void *, const void *, size_t size);
950 extern size_t strlen(const char *);
953 void * __lldb_dlopen_wrapper (const char *name,
954 const char *path_strings,
956 __lldb_dlopen_result *result_ptr)
958 // This is the case where the name is the full path:
960 result_ptr->image_ptr = dlopen(name, 2);
961 if (result_ptr->image_ptr)
962 result_ptr->error_str = nullptr;
966 // This is the case where we have a list of paths:
967 size_t name_len = strlen(name);
968 while (path_strings && path_strings[0] != '\0') {
969 size_t path_len = strlen(path_strings);
970 memcpy((void *) buffer, (void *) path_strings, path_len);
971 buffer[path_len] = '/';
972 char *target_ptr = buffer+path_len+1;
973 memcpy((void *) target_ptr, (void *) name, name_len + 1);
974 result_ptr->image_ptr = dlopen(buffer, 2);
975 if (result_ptr->image_ptr) {
976 result_ptr->error_str = nullptr;
979 result_ptr->error_str = dlerror();
980 path_strings = path_strings + path_len + 1;
986 static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
987 Process *process = exe_ctx.GetProcessSP().get();
988 // Insert the dlopen shim defines into our generic expression:
989 std::string expr(GetLibdlFunctionDeclarations(process));
990 expr.append(dlopen_wrapper_code);
991 Status utility_error;
992 DiagnosticManager diagnostics;
994 std::unique_ptr<UtilityFunction> dlopen_utility_func_up(process
995 ->GetTarget().GetUtilityFunctionForLanguage(expr.c_str(),
999 if (utility_error.Fail()) {
1000 error.SetErrorStringWithFormat("dlopen error: could not make utility"
1001 "function: %s", utility_error.AsCString());
1004 if (!dlopen_utility_func_up->Install(diagnostics, exe_ctx)) {
1005 error.SetErrorStringWithFormat("dlopen error: could not install utility"
1007 diagnostics.GetString().c_str());
1012 ValueList arguments;
1013 FunctionCaller *do_dlopen_function = nullptr;
1015 // Fetch the clang types we will need:
1016 ClangASTContext *ast = process->GetTarget().GetScratchClangASTContext();
1018 CompilerType clang_void_pointer_type
1019 = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
1020 CompilerType clang_char_pointer_type
1021 = ast->GetBasicType(eBasicTypeChar).GetPointerType();
1023 // We are passing four arguments, the basename, the list of places to look,
1024 // a buffer big enough for all the path + name combos, and
1025 // a pointer to the storage we've made for the result:
1026 value.SetValueType(Value::eValueTypeScalar);
1027 value.SetCompilerType(clang_void_pointer_type);
1028 arguments.PushValue(value);
1029 value.SetCompilerType(clang_char_pointer_type);
1030 arguments.PushValue(value);
1031 arguments.PushValue(value);
1032 arguments.PushValue(value);
1034 do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
1035 clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
1036 if (utility_error.Fail()) {
1037 error.SetErrorStringWithFormat("dlopen error: could not make function"
1038 "caller: %s", utility_error.AsCString());
1042 do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
1043 if (!do_dlopen_function) {
1044 error.SetErrorString("dlopen error: could not get function caller.");
1048 // We made a good utility function, so cache it in the process:
1049 return dlopen_utility_func_up;
1052 uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process,
1053 const lldb_private::FileSpec &remote_file,
1054 const std::vector<std::string> *paths,
1055 lldb_private::Status &error,
1056 lldb_private::FileSpec *loaded_image) {
1058 loaded_image->Clear();
1061 path = remote_file.GetPath();
1063 ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
1065 error.SetErrorString("dlopen error: no thread available to call dlopen.");
1066 return LLDB_INVALID_IMAGE_TOKEN;
1069 DiagnosticManager diagnostics;
1071 ExecutionContext exe_ctx;
1072 thread_sp->CalculateExecutionContext(exe_ctx);
1074 Status utility_error;
1075 UtilityFunction *dlopen_utility_func;
1076 ValueList arguments;
1077 FunctionCaller *do_dlopen_function = nullptr;
1079 // The UtilityFunction is held in the Process. Platforms don't track the
1080 // lifespan of the Targets that use them, we can't put this in the Platform.
1081 dlopen_utility_func = process->GetLoadImageUtilityFunction(
1082 this, [&]() -> std::unique_ptr<UtilityFunction> {
1083 return MakeLoadImageUtilityFunction(exe_ctx, error);
1085 // If we couldn't make it, the error will be in error, so we can exit here.
1086 if (!dlopen_utility_func)
1087 return LLDB_INVALID_IMAGE_TOKEN;
1089 do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
1090 if (!do_dlopen_function) {
1091 error.SetErrorString("dlopen error: could not get function caller.");
1092 return LLDB_INVALID_IMAGE_TOKEN;
1094 arguments = do_dlopen_function->GetArgumentValues();
1096 // Now insert the path we are searching for and the result structure into the
1098 uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
1099 size_t path_len = path.size() + 1;
1100 lldb::addr_t path_addr = process->AllocateMemory(path_len,
1103 if (path_addr == LLDB_INVALID_ADDRESS) {
1104 error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1105 "for path: %s", utility_error.AsCString());
1106 return LLDB_INVALID_IMAGE_TOKEN;
1109 // Make sure we deallocate the input string memory:
1110 CleanUp path_cleanup([process, path_addr] {
1111 process->DeallocateMemory(path_addr);
1114 process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
1115 if (utility_error.Fail()) {
1116 error.SetErrorStringWithFormat("dlopen error: could not write path string:"
1117 " %s", utility_error.AsCString());
1118 return LLDB_INVALID_IMAGE_TOKEN;
1121 // Make space for our return structure. It is two pointers big: the token
1122 // and the error string.
1123 const uint32_t addr_size = process->GetAddressByteSize();
1124 lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
1127 if (utility_error.Fail()) {
1128 error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1129 "for path: %s", utility_error.AsCString());
1130 return LLDB_INVALID_IMAGE_TOKEN;
1133 // Make sure we deallocate the result structure memory
1134 CleanUp return_cleanup([process, return_addr] {
1135 process->DeallocateMemory(return_addr);
1138 // This will be the address of the storage for paths, if we are using them,
1139 // or nullptr to signal we aren't.
1140 lldb::addr_t path_array_addr = 0x0;
1141 llvm::Optional<CleanUp> path_array_cleanup;
1143 // This is the address to a buffer large enough to hold the largest path
1144 // conjoined with the library name we're passing in. This is a convenience
1145 // to avoid having to call malloc in the dlopen function.
1146 lldb::addr_t buffer_addr = 0x0;
1147 llvm::Optional<CleanUp> buffer_cleanup;
1149 // Set the values into our args and write them to the target:
1150 if (paths != nullptr) {
1151 // First insert the paths into the target. This is expected to be a
1152 // continuous buffer with the strings laid out null terminated and
1153 // end to end with an empty string terminating the buffer.
1154 // We also compute the buffer's required size as we go.
1155 size_t buffer_size = 0;
1156 std::string path_array;
1157 for (auto path : *paths) {
1158 // Don't insert empty paths, they will make us abort the path
1159 // search prematurely.
1162 size_t path_size = path.size();
1163 path_array.append(path);
1164 path_array.push_back('\0');
1165 if (path_size > buffer_size)
1166 buffer_size = path_size;
1168 path_array.push_back('\0');
1170 path_array_addr = process->AllocateMemory(path_array.size(),
1173 if (path_array_addr == LLDB_INVALID_ADDRESS) {
1174 error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1175 "for path array: %s",
1176 utility_error.AsCString());
1177 return LLDB_INVALID_IMAGE_TOKEN;
1180 // Make sure we deallocate the paths array.
1181 path_array_cleanup.emplace([process, path_array_addr] {
1182 process->DeallocateMemory(path_array_addr);
1185 process->WriteMemory(path_array_addr, path_array.data(),
1186 path_array.size(), utility_error);
1188 if (utility_error.Fail()) {
1189 error.SetErrorStringWithFormat("dlopen error: could not write path array:"
1190 " %s", utility_error.AsCString());
1191 return LLDB_INVALID_IMAGE_TOKEN;
1193 // Now make spaces in the target for the buffer. We need to add one for
1194 // the '/' that the utility function will insert and one for the '\0':
1195 buffer_size += path.size() + 2;
1197 buffer_addr = process->AllocateMemory(buffer_size,
1200 if (buffer_addr == LLDB_INVALID_ADDRESS) {
1201 error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1203 utility_error.AsCString());
1204 return LLDB_INVALID_IMAGE_TOKEN;
1207 // Make sure we deallocate the buffer memory:
1208 buffer_cleanup.emplace([process, buffer_addr] {
1209 process->DeallocateMemory(buffer_addr);
1213 arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
1214 arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
1215 arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
1216 arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
1218 lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
1220 diagnostics.Clear();
1221 if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
1225 error.SetErrorStringWithFormat("dlopen error: could not write function "
1227 diagnostics.GetString().c_str());
1228 return LLDB_INVALID_IMAGE_TOKEN;
1231 // Make sure we clean up the args structure. We can't reuse it because the
1232 // Platform lives longer than the process and the Platforms don't get a
1233 // signal to clean up cached data when a process goes away.
1234 CleanUp args_cleanup([do_dlopen_function, &exe_ctx, func_args_addr] {
1235 do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
1238 // Now run the caller:
1239 EvaluateExpressionOptions options;
1240 options.SetExecutionPolicy(eExecutionPolicyAlways);
1241 options.SetLanguage(eLanguageTypeC_plus_plus);
1242 options.SetIgnoreBreakpoints(true);
1243 options.SetUnwindOnError(true);
1244 options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
1245 // don't do the work to trap them.
1246 options.SetTimeout(std::chrono::seconds(2));
1249 // Fetch the clang types we will need:
1250 ClangASTContext *ast = process->GetTarget().GetScratchClangASTContext();
1252 CompilerType clang_void_pointer_type
1253 = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
1255 return_value.SetCompilerType(clang_void_pointer_type);
1257 ExpressionResults results = do_dlopen_function->ExecuteFunction(
1258 exe_ctx, &func_args_addr, options, diagnostics, return_value);
1259 if (results != eExpressionCompleted) {
1260 error.SetErrorStringWithFormat("dlopen error: failed executing "
1261 "dlopen wrapper function: %s",
1262 diagnostics.GetString().c_str());
1263 return LLDB_INVALID_IMAGE_TOKEN;
1266 // Read the dlopen token from the return area:
1267 lldb::addr_t token = process->ReadPointerFromMemory(return_addr,
1269 if (utility_error.Fail()) {
1270 error.SetErrorStringWithFormat("dlopen error: could not read the return "
1271 "struct: %s", utility_error.AsCString());
1272 return LLDB_INVALID_IMAGE_TOKEN;
1275 // The dlopen succeeded!
1277 if (loaded_image && buffer_addr != 0x0)
1279 // Capture the image which was loaded. We leave it in the buffer on
1280 // exit from the dlopen function, so we can just read it from there:
1281 std::string name_string;
1282 process->ReadCStringFromMemory(buffer_addr, name_string, utility_error);
1283 if (utility_error.Success())
1284 loaded_image->SetFile(name_string, false,
1285 llvm::sys::path::Style::posix);
1287 return process->AddImageToken(token);
1290 // We got an error, lets read in the error string:
1291 std::string dlopen_error_str;
1292 lldb::addr_t error_addr
1293 = process->ReadPointerFromMemory(return_addr + addr_size, utility_error);
1294 if (utility_error.Fail()) {
1295 error.SetErrorStringWithFormat("dlopen error: could not read error string: "
1296 "%s", utility_error.AsCString());
1297 return LLDB_INVALID_IMAGE_TOKEN;
1300 size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size,
1303 if (utility_error.Success() && num_chars > 0)
1304 error.SetErrorStringWithFormat("dlopen error: %s",
1305 dlopen_error_str.c_str());
1307 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
1309 return LLDB_INVALID_IMAGE_TOKEN;
1312 Status PlatformPOSIX::UnloadImage(lldb_private::Process *process,
1313 uint32_t image_token) {
1314 const addr_t image_addr = process->GetImagePtrFromToken(image_token);
1315 if (image_addr == LLDB_INVALID_ADDRESS)
1316 return Status("Invalid image token");
1319 expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
1320 llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
1321 lldb::ValueObjectSP result_valobj_sp;
1322 Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
1327 if (result_valobj_sp->GetError().Fail())
1328 return result_valobj_sp->GetError();
1331 if (result_valobj_sp->ResolveValue(scalar)) {
1333 return Status("expression failed: \"%s\"", expr.GetData());
1334 process->ResetImageToken(image_token);
1339 lldb::ProcessSP PlatformPOSIX::ConnectProcess(llvm::StringRef connect_url,
1340 llvm::StringRef plugin_name,
1341 lldb_private::Debugger &debugger,
1342 lldb_private::Target *target,
1343 lldb_private::Status &error) {
1344 if (m_remote_platform_sp)
1345 return m_remote_platform_sp->ConnectProcess(connect_url, plugin_name,
1346 debugger, target, error);
1348 return Platform::ConnectProcess(connect_url, plugin_name, debugger, target,
1353 PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
1355 extern "C" void* dlopen(const char*, int);
1356 extern "C" void* dlsym(void*, const char*);
1357 extern "C" int dlclose(void*);
1358 extern "C" char* dlerror(void);
1362 size_t PlatformPOSIX::ConnectToWaitingProcesses(Debugger &debugger,
1364 if (m_remote_platform_sp)
1365 return m_remote_platform_sp->ConnectToWaitingProcesses(debugger, error);
1366 return Platform::ConnectToWaitingProcesses(debugger, error);
1369 ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) {
1370 if (basename.IsEmpty())
1373 StreamString stream;
1374 stream.Printf("lib%s.so", basename.GetCString());
1375 return ConstString(stream.GetString());