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"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleSpec.h"
16 #include "lldb/Core/ValueObject.h"
17 #include "lldb/Expression/DiagnosticManager.h"
18 #include "lldb/Expression/FunctionCaller.h"
19 #include "lldb/Expression/UserExpression.h"
20 #include "lldb/Expression/UtilityFunction.h"
21 #include "lldb/Host/File.h"
22 #include "lldb/Host/FileCache.h"
23 #include "lldb/Host/FileSystem.h"
24 #include "lldb/Host/Host.h"
25 #include "lldb/Host/HostInfo.h"
26 #include "lldb/Symbol/ClangASTContext.h"
27 #include "lldb/Target/DynamicLoader.h"
28 #include "lldb/Target/ExecutionContext.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/ProcessLaunchInfo.h"
31 #include "lldb/Target/Thread.h"
32 #include "lldb/Utility/CleanUp.h"
33 #include "lldb/Utility/DataBufferHeap.h"
34 #include "lldb/Utility/FileSpec.h"
35 #include "lldb/Utility/Log.h"
36 #include "lldb/Utility/StreamString.h"
39 using namespace lldb_private;
41 //------------------------------------------------------------------
42 /// Default Constructor
43 //------------------------------------------------------------------
44 PlatformPOSIX::PlatformPOSIX(bool is_host)
45 : Platform(is_host), // This is the local host platform
46 m_option_group_platform_rsync(new OptionGroupPlatformRSync()),
47 m_option_group_platform_ssh(new OptionGroupPlatformSSH()),
48 m_option_group_platform_caching(new OptionGroupPlatformCaching()),
49 m_remote_platform_sp() {}
51 //------------------------------------------------------------------
54 /// The destructor is virtual since this class is designed to be
55 /// inherited from by the plug-in instance.
56 //------------------------------------------------------------------
57 PlatformPOSIX::~PlatformPOSIX() {}
59 bool PlatformPOSIX::GetModuleSpec(const FileSpec &module_file_spec,
61 ModuleSpec &module_spec) {
62 if (m_remote_platform_sp)
63 return m_remote_platform_sp->GetModuleSpec(module_file_spec, arch,
66 return Platform::GetModuleSpec(module_file_spec, arch, module_spec);
69 lldb_private::OptionGroupOptions *PlatformPOSIX::GetConnectionOptions(
70 lldb_private::CommandInterpreter &interpreter) {
71 auto iter = m_options.find(&interpreter), end = m_options.end();
73 std::unique_ptr<lldb_private::OptionGroupOptions> options(
74 new OptionGroupOptions());
75 options->Append(m_option_group_platform_rsync.get());
76 options->Append(m_option_group_platform_ssh.get());
77 options->Append(m_option_group_platform_caching.get());
78 m_options[&interpreter] = std::move(options);
81 return m_options.at(&interpreter).get();
84 bool PlatformPOSIX::IsConnected() const {
87 else if (m_remote_platform_sp)
88 return m_remote_platform_sp->IsConnected();
92 lldb_private::Status PlatformPOSIX::RunShellCommand(
93 const char *command, // Shouldn't be NULL
95 working_dir, // Pass empty FileSpec to use the current working directory
96 int *status_ptr, // Pass NULL if you don't want the process exit status
97 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
100 *command_output, // Pass NULL if you don't want the command output
101 const Timeout<std::micro> &timeout) {
103 return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr,
104 command_output, timeout);
106 if (m_remote_platform_sp)
107 return m_remote_platform_sp->RunShellCommand(
108 command, working_dir, status_ptr, signo_ptr, command_output, timeout);
110 return Status("unable to run a remote command without a platform");
115 PlatformPOSIX::ResolveExecutable(const ModuleSpec &module_spec,
116 lldb::ModuleSP &exe_module_sp,
117 const FileSpecList *module_search_paths_ptr) {
119 // Nothing special to do here, just use the actual file and architecture
121 char exe_path[PATH_MAX];
122 ModuleSpec resolved_module_spec(module_spec);
125 // If we have "ls" as the exe_file, resolve the executable location based
126 // on the current path variables
127 if (!FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec())) {
128 resolved_module_spec.GetFileSpec().GetPath(exe_path, sizeof(exe_path));
129 resolved_module_spec.GetFileSpec().SetFile(exe_path,
130 FileSpec::Style::native);
131 FileSystem::Instance().Resolve(resolved_module_spec.GetFileSpec());
134 if (!FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()))
135 FileSystem::Instance().ResolveExecutableLocation(
136 resolved_module_spec.GetFileSpec());
138 // Resolve any executable within a bundle on MacOSX
139 Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
141 if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()))
144 const uint32_t permissions = FileSystem::Instance().GetPermissions(
145 resolved_module_spec.GetFileSpec());
146 if (permissions && (permissions & eFilePermissionsEveryoneR) == 0)
147 error.SetErrorStringWithFormat(
148 "executable '%s' is not readable",
149 resolved_module_spec.GetFileSpec().GetPath().c_str());
151 error.SetErrorStringWithFormat(
152 "unable to find executable for '%s'",
153 resolved_module_spec.GetFileSpec().GetPath().c_str());
156 if (m_remote_platform_sp) {
158 GetCachedExecutable(resolved_module_spec, exe_module_sp,
159 module_search_paths_ptr, *m_remote_platform_sp);
161 // We may connect to a process and use the provided executable (Don't use
164 // Resolve any executable within a bundle on MacOSX
165 Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
167 if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()))
170 error.SetErrorStringWithFormat("the platform is not currently "
171 "connected, and '%s' doesn't exist in "
177 if (error.Success()) {
178 if (resolved_module_spec.GetArchitecture().IsValid()) {
179 error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
180 module_search_paths_ptr, nullptr, nullptr);
182 // If we failed, it may be because the vendor and os aren't known. If
183 // that is the case, try setting them to the host architecture and give
185 llvm::Triple &module_triple =
186 resolved_module_spec.GetArchitecture().GetTriple();
187 bool is_vendor_specified =
188 (module_triple.getVendor() != llvm::Triple::UnknownVendor);
189 bool is_os_specified =
190 (module_triple.getOS() != llvm::Triple::UnknownOS);
191 if (!is_vendor_specified || !is_os_specified) {
192 const llvm::Triple &host_triple =
193 HostInfo::GetArchitecture(HostInfo::eArchKindDefault).GetTriple();
195 if (!is_vendor_specified)
196 module_triple.setVendorName(host_triple.getVendorName());
197 if (!is_os_specified)
198 module_triple.setOSName(host_triple.getOSName());
200 error = ModuleList::GetSharedModule(resolved_module_spec,
201 exe_module_sp, module_search_paths_ptr, nullptr, nullptr);
205 // TODO find out why exe_module_sp might be NULL
206 if (error.Fail() || !exe_module_sp || !exe_module_sp->GetObjectFile()) {
207 exe_module_sp.reset();
208 error.SetErrorStringWithFormat(
209 "'%s' doesn't contain the architecture %s",
210 resolved_module_spec.GetFileSpec().GetPath().c_str(),
211 resolved_module_spec.GetArchitecture().GetArchitectureName());
214 // No valid architecture was specified, ask the platform for the
215 // architectures that we should be using (in the correct order) and see
216 // if we can find a match that way
217 StreamString arch_names;
218 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
219 idx, resolved_module_spec.GetArchitecture());
221 error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
222 module_search_paths_ptr, nullptr, nullptr);
223 // Did we find an executable using one of the
224 if (error.Success()) {
225 if (exe_module_sp && exe_module_sp->GetObjectFile())
228 error.SetErrorToGenericError();
232 arch_names.PutCString(", ");
233 arch_names.PutCString(
234 resolved_module_spec.GetArchitecture().GetArchitectureName());
237 if (error.Fail() || !exe_module_sp) {
238 if (FileSystem::Instance().Readable(
239 resolved_module_spec.GetFileSpec())) {
240 error.SetErrorStringWithFormat(
241 "'%s' doesn't contain any '%s' platform architectures: %s",
242 resolved_module_spec.GetFileSpec().GetPath().c_str(),
243 GetPluginName().GetCString(), arch_names.GetData());
245 error.SetErrorStringWithFormat(
246 "'%s' is not readable",
247 resolved_module_spec.GetFileSpec().GetPath().c_str());
256 Status PlatformPOSIX::GetFileWithUUID(const FileSpec &platform_file,
257 const UUID *uuid_ptr,
258 FileSpec &local_file) {
259 if (IsRemote() && m_remote_platform_sp)
260 return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr,
263 // Default to the local case
264 local_file = platform_file;
268 bool PlatformPOSIX::GetProcessInfo(lldb::pid_t pid,
269 ProcessInstanceInfo &process_info) {
271 return Platform::GetProcessInfo(pid, process_info);
272 if (m_remote_platform_sp)
273 return m_remote_platform_sp->GetProcessInfo(pid, process_info);
278 PlatformPOSIX::FindProcesses(const ProcessInstanceInfoMatch &match_info,
279 ProcessInstanceInfoList &process_infos) {
281 return Platform::FindProcesses(match_info, process_infos);
282 if (m_remote_platform_sp)
284 m_remote_platform_sp->FindProcesses(match_info, process_infos);
288 Status PlatformPOSIX::MakeDirectory(const FileSpec &file_spec,
289 uint32_t file_permissions) {
290 if (m_remote_platform_sp)
291 return m_remote_platform_sp->MakeDirectory(file_spec, file_permissions);
293 return Platform::MakeDirectory(file_spec, file_permissions);
296 Status PlatformPOSIX::GetFilePermissions(const FileSpec &file_spec,
297 uint32_t &file_permissions) {
298 if (m_remote_platform_sp)
299 return m_remote_platform_sp->GetFilePermissions(file_spec,
302 return Platform::GetFilePermissions(file_spec, file_permissions);
305 Status PlatformPOSIX::SetFilePermissions(const FileSpec &file_spec,
306 uint32_t file_permissions) {
307 if (m_remote_platform_sp)
308 return m_remote_platform_sp->SetFilePermissions(file_spec,
311 return Platform::SetFilePermissions(file_spec, file_permissions);
314 lldb::user_id_t PlatformPOSIX::OpenFile(const FileSpec &file_spec,
315 uint32_t flags, uint32_t mode,
318 return FileCache::GetInstance().OpenFile(file_spec, flags, mode, error);
319 else if (m_remote_platform_sp)
320 return m_remote_platform_sp->OpenFile(file_spec, flags, mode, error);
322 return Platform::OpenFile(file_spec, flags, mode, error);
325 bool PlatformPOSIX::CloseFile(lldb::user_id_t fd, Status &error) {
327 return FileCache::GetInstance().CloseFile(fd, error);
328 else if (m_remote_platform_sp)
329 return m_remote_platform_sp->CloseFile(fd, error);
331 return Platform::CloseFile(fd, error);
334 uint64_t PlatformPOSIX::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
335 uint64_t dst_len, Status &error) {
337 return FileCache::GetInstance().ReadFile(fd, offset, dst, dst_len, error);
338 else if (m_remote_platform_sp)
339 return m_remote_platform_sp->ReadFile(fd, offset, dst, dst_len, error);
341 return Platform::ReadFile(fd, offset, dst, dst_len, error);
344 uint64_t PlatformPOSIX::WriteFile(lldb::user_id_t fd, uint64_t offset,
345 const void *src, uint64_t src_len,
348 return FileCache::GetInstance().WriteFile(fd, offset, src, src_len, error);
349 else if (m_remote_platform_sp)
350 return m_remote_platform_sp->WriteFile(fd, offset, src, src_len, error);
352 return Platform::WriteFile(fd, offset, src, src_len, error);
355 static uint32_t chown_file(Platform *platform, const char *path,
356 uint32_t uid = UINT32_MAX,
357 uint32_t gid = UINT32_MAX) {
358 if (!platform || !path || *path == 0)
361 if (uid == UINT32_MAX && gid == UINT32_MAX)
362 return 0; // pretend I did chown correctly - actually I just didn't care
364 StreamString command;
365 command.PutCString("chown ");
366 if (uid != UINT32_MAX)
367 command.Printf("%d", uid);
368 if (gid != UINT32_MAX)
369 command.Printf(":%d", gid);
370 command.Printf("%s", path);
372 platform->RunShellCommand(command.GetData(), NULL, &status, NULL, NULL,
373 std::chrono::seconds(10));
378 PlatformPOSIX::PutFile(const lldb_private::FileSpec &source,
379 const lldb_private::FileSpec &destination, uint32_t uid,
381 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
384 if (FileSpec::Equal(source, destination, true))
388 std::string src_path(source.GetPath());
389 if (src_path.empty())
390 return Status("unable to get file path for source");
391 std::string dst_path(destination.GetPath());
392 if (dst_path.empty())
393 return Status("unable to get file path for destination");
394 StreamString command;
395 command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
397 RunShellCommand(command.GetData(), NULL, &status, NULL, NULL,
398 std::chrono::seconds(10));
400 return Status("unable to perform copy");
401 if (uid == UINT32_MAX && gid == UINT32_MAX)
403 if (chown_file(this, dst_path.c_str(), uid, gid) != 0)
404 return Status("unable to perform chown");
406 } else if (m_remote_platform_sp) {
407 if (GetSupportsRSync()) {
408 std::string src_path(source.GetPath());
409 if (src_path.empty())
410 return Status("unable to get file path for source");
411 std::string dst_path(destination.GetPath());
412 if (dst_path.empty())
413 return Status("unable to get file path for destination");
414 StreamString command;
415 if (GetIgnoresRemoteHostname()) {
416 if (!GetRSyncPrefix())
417 command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
420 command.Printf("rsync %s %s %s%s", GetRSyncOpts(), src_path.c_str(),
421 GetRSyncPrefix(), dst_path.c_str());
423 command.Printf("rsync %s %s %s:%s", GetRSyncOpts(), src_path.c_str(),
424 GetHostname(), dst_path.c_str());
426 log->Printf("[PutFile] Running command: %s\n", command.GetData());
428 Host::RunShellCommand(command.GetData(), NULL, &retcode, NULL, NULL,
429 std::chrono::minutes(1));
431 // Don't chown a local file for a remote system
432 // if (chown_file(this,dst_path.c_str(),uid,gid) != 0)
433 // return Status("unable to perform chown");
436 // if we are still here rsync has failed - let's try the slow way before
440 return Platform::PutFile(source, destination, uid, gid);
443 lldb::user_id_t PlatformPOSIX::GetFileSize(const FileSpec &file_spec) {
446 if (llvm::sys::fs::file_size(file_spec.GetPath(), Size))
449 } else if (m_remote_platform_sp)
450 return m_remote_platform_sp->GetFileSize(file_spec);
452 return Platform::GetFileSize(file_spec);
455 Status PlatformPOSIX::CreateSymlink(const FileSpec &src, const FileSpec &dst) {
457 return FileSystem::Instance().Symlink(src, dst);
458 else if (m_remote_platform_sp)
459 return m_remote_platform_sp->CreateSymlink(src, dst);
461 return Platform::CreateSymlink(src, dst);
464 bool PlatformPOSIX::GetFileExists(const FileSpec &file_spec) {
466 return FileSystem::Instance().Exists(file_spec);
467 else if (m_remote_platform_sp)
468 return m_remote_platform_sp->GetFileExists(file_spec);
470 return Platform::GetFileExists(file_spec);
473 Status PlatformPOSIX::Unlink(const FileSpec &file_spec) {
475 return llvm::sys::fs::remove(file_spec.GetPath());
476 else if (m_remote_platform_sp)
477 return m_remote_platform_sp->Unlink(file_spec);
479 return Platform::Unlink(file_spec);
482 lldb_private::Status PlatformPOSIX::GetFile(
483 const lldb_private::FileSpec &source, // remote file path
484 const lldb_private::FileSpec &destination) // local file path
486 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
488 // Check the args, first.
489 std::string src_path(source.GetPath());
490 if (src_path.empty())
491 return Status("unable to get file path for source");
492 std::string dst_path(destination.GetPath());
493 if (dst_path.empty())
494 return Status("unable to get file path for destination");
496 if (FileSpec::Equal(source, destination, true))
497 return Status("local scenario->source and destination are the same file "
498 "path: no operation performed");
500 StreamString cp_command;
501 cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
503 RunShellCommand(cp_command.GetData(), NULL, &status, NULL, NULL,
504 std::chrono::seconds(10));
506 return Status("unable to perform copy");
508 } else if (m_remote_platform_sp) {
509 if (GetSupportsRSync()) {
510 StreamString command;
511 if (GetIgnoresRemoteHostname()) {
512 if (!GetRSyncPrefix())
513 command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
516 command.Printf("rsync %s %s%s %s", GetRSyncOpts(), GetRSyncPrefix(),
517 src_path.c_str(), dst_path.c_str());
519 command.Printf("rsync %s %s:%s %s", GetRSyncOpts(),
520 m_remote_platform_sp->GetHostname(), src_path.c_str(),
523 log->Printf("[GetFile] Running command: %s\n", command.GetData());
525 Host::RunShellCommand(command.GetData(), NULL, &retcode, NULL, NULL,
526 std::chrono::minutes(1));
529 // If we are here, rsync has failed - let's try the slow way before
533 // read/write, read/write, read/write, ...
537 log->Printf("[GetFile] Using block by block transfer....\n");
539 user_id_t fd_src = OpenFile(source, File::eOpenOptionRead,
540 lldb::eFilePermissionsFileDefault, error);
542 if (fd_src == UINT64_MAX)
543 return Status("unable to open source file");
545 uint32_t permissions = 0;
546 error = GetFilePermissions(source, permissions);
548 if (permissions == 0)
549 permissions = lldb::eFilePermissionsFileDefault;
551 user_id_t fd_dst = FileCache::GetInstance().OpenFile(
552 destination, File::eOpenOptionCanCreate | File::eOpenOptionWrite |
553 File::eOpenOptionTruncate,
556 if (fd_dst == UINT64_MAX) {
558 error.SetErrorString("unable to open destination file");
561 if (error.Success()) {
562 lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
565 while (error.Success()) {
566 const uint64_t n_read = ReadFile(fd_src, offset, buffer_sp->GetBytes(),
567 buffer_sp->GetByteSize(), error);
572 if (FileCache::GetInstance().WriteFile(fd_dst, offset,
573 buffer_sp->GetBytes(), n_read,
576 error.SetErrorString("unable to write to destination file");
582 // Ignore the close error of src.
583 if (fd_src != UINT64_MAX)
584 CloseFile(fd_src, error);
585 // And close the dst file descriptot.
586 if (fd_dst != UINT64_MAX &&
587 !FileCache::GetInstance().CloseFile(fd_dst, error)) {
589 error.SetErrorString("unable to close destination file");
593 return Platform::GetFile(source, destination);
596 std::string PlatformPOSIX::GetPlatformSpecificConnectionInformation() {
598 if (GetSupportsRSync()) {
599 stream.PutCString("rsync");
600 if ((GetRSyncOpts() && *GetRSyncOpts()) ||
601 (GetRSyncPrefix() && *GetRSyncPrefix()) || GetIgnoresRemoteHostname()) {
602 stream.Printf(", options: ");
603 if (GetRSyncOpts() && *GetRSyncOpts())
604 stream.Printf("'%s' ", GetRSyncOpts());
605 stream.Printf(", prefix: ");
606 if (GetRSyncPrefix() && *GetRSyncPrefix())
607 stream.Printf("'%s' ", GetRSyncPrefix());
608 if (GetIgnoresRemoteHostname())
609 stream.Printf("ignore remote-hostname ");
612 if (GetSupportsSSH()) {
613 stream.PutCString("ssh");
614 if (GetSSHOpts() && *GetSSHOpts())
615 stream.Printf(", options: '%s' ", GetSSHOpts());
617 if (GetLocalCacheDirectory() && *GetLocalCacheDirectory())
618 stream.Printf("cache dir: %s", GetLocalCacheDirectory());
619 if (stream.GetSize())
620 return stream.GetString();
625 bool PlatformPOSIX::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
628 return Platform::CalculateMD5(file_spec, low, high);
629 if (m_remote_platform_sp)
630 return m_remote_platform_sp->CalculateMD5(file_spec, low, high);
634 const lldb::UnixSignalsSP &PlatformPOSIX::GetRemoteUnixSignals() {
635 if (IsRemote() && m_remote_platform_sp)
636 return m_remote_platform_sp->GetRemoteUnixSignals();
637 return Platform::GetRemoteUnixSignals();
640 FileSpec PlatformPOSIX::GetRemoteWorkingDirectory() {
641 if (IsRemote() && m_remote_platform_sp)
642 return m_remote_platform_sp->GetRemoteWorkingDirectory();
644 return Platform::GetRemoteWorkingDirectory();
647 bool PlatformPOSIX::SetRemoteWorkingDirectory(const FileSpec &working_dir) {
648 if (IsRemote() && m_remote_platform_sp)
649 return m_remote_platform_sp->SetRemoteWorkingDirectory(working_dir);
651 return Platform::SetRemoteWorkingDirectory(working_dir);
654 bool PlatformPOSIX::GetRemoteOSVersion() {
655 if (m_remote_platform_sp) {
656 m_os_version = m_remote_platform_sp->GetOSVersion();
657 return !m_os_version.empty();
662 bool PlatformPOSIX::GetRemoteOSBuildString(std::string &s) {
663 if (m_remote_platform_sp)
664 return m_remote_platform_sp->GetRemoteOSBuildString(s);
669 Environment PlatformPOSIX::GetEnvironment() {
671 if (m_remote_platform_sp)
672 return m_remote_platform_sp->GetEnvironment();
673 return Environment();
675 return Host::GetEnvironment();
678 bool PlatformPOSIX::GetRemoteOSKernelDescription(std::string &s) {
679 if (m_remote_platform_sp)
680 return m_remote_platform_sp->GetRemoteOSKernelDescription(s);
685 // Remote Platform subclasses need to override this function
686 ArchSpec PlatformPOSIX::GetRemoteSystemArchitecture() {
687 if (m_remote_platform_sp)
688 return m_remote_platform_sp->GetRemoteSystemArchitecture();
692 const char *PlatformPOSIX::GetHostname() {
694 return Platform::GetHostname();
696 if (m_remote_platform_sp)
697 return m_remote_platform_sp->GetHostname();
701 const char *PlatformPOSIX::GetUserName(uint32_t uid) {
702 // Check the cache in Platform in case we have already looked this uid up
703 const char *user_name = Platform::GetUserName(uid);
707 if (IsRemote() && m_remote_platform_sp)
708 return m_remote_platform_sp->GetUserName(uid);
712 const char *PlatformPOSIX::GetGroupName(uint32_t gid) {
713 const char *group_name = Platform::GetGroupName(gid);
717 if (IsRemote() && m_remote_platform_sp)
718 return m_remote_platform_sp->GetGroupName(gid);
722 Status PlatformPOSIX::ConnectRemote(Args &args) {
725 error.SetErrorStringWithFormat(
726 "can't connect to the host platform '%s', always connected",
727 GetPluginName().GetCString());
729 if (!m_remote_platform_sp)
730 m_remote_platform_sp =
731 Platform::Create(ConstString("remote-gdb-server"), error);
733 if (m_remote_platform_sp && error.Success())
734 error = m_remote_platform_sp->ConnectRemote(args);
736 error.SetErrorString("failed to create a 'remote-gdb-server' platform");
739 m_remote_platform_sp.reset();
742 if (error.Success() && m_remote_platform_sp) {
743 if (m_option_group_platform_rsync.get() &&
744 m_option_group_platform_ssh.get() &&
745 m_option_group_platform_caching.get()) {
746 if (m_option_group_platform_rsync->m_rsync) {
747 SetSupportsRSync(true);
748 SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str());
749 SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str());
750 SetIgnoresRemoteHostname(
751 m_option_group_platform_rsync->m_ignores_remote_hostname);
753 if (m_option_group_platform_ssh->m_ssh) {
754 SetSupportsSSH(true);
755 SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str());
757 SetLocalCacheDirectory(
758 m_option_group_platform_caching->m_cache_dir.c_str());
765 Status PlatformPOSIX::DisconnectRemote() {
769 error.SetErrorStringWithFormat(
770 "can't disconnect from the host platform '%s', always connected",
771 GetPluginName().GetCString());
773 if (m_remote_platform_sp)
774 error = m_remote_platform_sp->DisconnectRemote();
776 error.SetErrorString("the platform is not currently connected");
781 Status PlatformPOSIX::LaunchProcess(ProcessLaunchInfo &launch_info) {
785 error = Platform::LaunchProcess(launch_info);
787 if (m_remote_platform_sp)
788 error = m_remote_platform_sp->LaunchProcess(launch_info);
790 error.SetErrorString("the platform is not currently connected");
795 lldb_private::Status PlatformPOSIX::KillProcess(const lldb::pid_t pid) {
797 return Platform::KillProcess(pid);
799 if (m_remote_platform_sp)
800 return m_remote_platform_sp->KillProcess(pid);
802 return Status("the platform is not currently connected");
805 lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info,
806 Debugger &debugger, Target *target,
808 lldb::ProcessSP process_sp;
809 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
812 if (target == NULL) {
813 TargetSP new_target_sp;
815 error = debugger.GetTargetList().CreateTarget(
816 debugger, "", "", eLoadDependentsNo, NULL, new_target_sp);
817 target = new_target_sp.get();
819 log->Printf("PlatformPOSIX::%s created new target", __FUNCTION__);
823 log->Printf("PlatformPOSIX::%s target already existed, setting target",
827 if (target && error.Success()) {
828 debugger.GetTargetList().SetSelectedTarget(target);
830 ModuleSP exe_module_sp = target->GetExecutableModule();
831 log->Printf("PlatformPOSIX::%s set selected target to %p %s",
832 __FUNCTION__, (void *)target,
834 ? exe_module_sp->GetFileSpec().GetPath().c_str()
839 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
840 attach_info.GetProcessPluginName(), NULL);
843 ListenerSP listener_sp = attach_info.GetHijackListener();
844 if (listener_sp == nullptr) {
846 Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
847 attach_info.SetHijackListener(listener_sp);
849 process_sp->HijackProcessEvents(listener_sp);
850 error = process_sp->Attach(attach_info);
854 if (m_remote_platform_sp)
856 m_remote_platform_sp->Attach(attach_info, debugger, target, error);
858 error.SetErrorString("the platform is not currently connected");
864 PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
865 Target *target, // Can be NULL, if NULL create a new
866 // target, else use existing one
868 ProcessSP process_sp;
871 // We are going to hand this process off to debugserver which will be in
872 // charge of setting the exit status. However, we still need to reap it
873 // from lldb. So, make sure we use a exit callback which does not set exit
875 const bool monitor_signals = false;
876 launch_info.SetMonitorProcessCallback(
877 &ProcessLaunchInfo::NoOpMonitorCallback, monitor_signals);
878 process_sp = Platform::DebugProcess(launch_info, debugger, target, error);
880 if (m_remote_platform_sp)
881 process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
884 error.SetErrorString("the platform is not currently connected");
889 void PlatformPOSIX::CalculateTrapHandlerSymbolNames() {
890 m_trap_handlers.push_back(ConstString("_sigtramp"));
893 Status PlatformPOSIX::EvaluateLibdlExpression(
894 lldb_private::Process *process, const char *expr_cstr,
895 llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
896 DynamicLoader *loader = process->GetDynamicLoader();
898 Status error = loader->CanLoadImage();
903 ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread());
905 return Status("Selected thread isn't valid");
907 StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
909 return Status("Frame 0 isn't valid");
911 ExecutionContext exe_ctx;
912 frame_sp->CalculateExecutionContext(exe_ctx);
913 EvaluateExpressionOptions expr_options;
914 expr_options.SetUnwindOnError(true);
915 expr_options.SetIgnoreBreakpoints(true);
916 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
917 expr_options.SetLanguage(eLanguageTypeC_plus_plus);
918 expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
919 // don't do the work to trap them.
920 expr_options.SetTimeout(std::chrono::seconds(2));
923 ExpressionResults result =
924 UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix,
925 result_valobj_sp, expr_error);
926 if (result != eExpressionCompleted)
929 if (result_valobj_sp->GetError().Fail())
930 return result_valobj_sp->GetError();
934 std::unique_ptr<UtilityFunction>
935 PlatformPOSIX::MakeLoadImageUtilityFunction(ExecutionContext &exe_ctx,
937 // Remember to prepend this with the prefix from
938 // GetLibdlFunctionDeclarations. The returned values are all in
939 // __lldb_dlopen_result for consistency. The wrapper returns a void * but
940 // doesn't use it because UtilityFunctions don't work with void returns at
942 static const char *dlopen_wrapper_code = R"(
943 struct __lldb_dlopen_result {
945 const char *error_str;
948 extern void *memcpy(void *, const void *, size_t size);
949 extern size_t strlen(const char *);
952 void * __lldb_dlopen_wrapper (const char *name,
953 const char *path_strings,
955 __lldb_dlopen_result *result_ptr)
957 // This is the case where the name is the full path:
959 result_ptr->image_ptr = dlopen(name, 2);
960 if (result_ptr->image_ptr)
961 result_ptr->error_str = nullptr;
965 // This is the case where we have a list of paths:
966 size_t name_len = strlen(name);
967 while (path_strings && path_strings[0] != '\0') {
968 size_t path_len = strlen(path_strings);
969 memcpy((void *) buffer, (void *) path_strings, path_len);
970 buffer[path_len] = '/';
971 char *target_ptr = buffer+path_len+1;
972 memcpy((void *) target_ptr, (void *) name, name_len + 1);
973 result_ptr->image_ptr = dlopen(buffer, 2);
974 if (result_ptr->image_ptr) {
975 result_ptr->error_str = nullptr;
978 result_ptr->error_str = dlerror();
979 path_strings = path_strings + path_len + 1;
985 static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
986 Process *process = exe_ctx.GetProcessSP().get();
987 // Insert the dlopen shim defines into our generic expression:
988 std::string expr(GetLibdlFunctionDeclarations(process));
989 expr.append(dlopen_wrapper_code);
990 Status utility_error;
991 DiagnosticManager diagnostics;
993 std::unique_ptr<UtilityFunction> dlopen_utility_func_up(process
994 ->GetTarget().GetUtilityFunctionForLanguage(expr.c_str(),
998 if (utility_error.Fail()) {
999 error.SetErrorStringWithFormat("dlopen error: could not make utility"
1000 "function: %s", utility_error.AsCString());
1003 if (!dlopen_utility_func_up->Install(diagnostics, exe_ctx)) {
1004 error.SetErrorStringWithFormat("dlopen error: could not install utility"
1006 diagnostics.GetString().c_str());
1011 ValueList arguments;
1012 FunctionCaller *do_dlopen_function = nullptr;
1014 // Fetch the clang types we will need:
1015 ClangASTContext *ast = process->GetTarget().GetScratchClangASTContext();
1017 CompilerType clang_void_pointer_type
1018 = ast->GetBasicType(eBasicTypeVoid).GetPointerType();
1019 CompilerType clang_char_pointer_type
1020 = ast->GetBasicType(eBasicTypeChar).GetPointerType();
1022 // We are passing four arguments, the basename, the list of places to look,
1023 // a buffer big enough for all the path + name combos, and
1024 // a pointer to the storage we've made for the result:
1025 value.SetValueType(Value::eValueTypeScalar);
1026 value.SetCompilerType(clang_void_pointer_type);
1027 arguments.PushValue(value);
1028 value.SetCompilerType(clang_char_pointer_type);
1029 arguments.PushValue(value);
1030 arguments.PushValue(value);
1031 arguments.PushValue(value);
1033 do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
1034 clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
1035 if (utility_error.Fail()) {
1036 error.SetErrorStringWithFormat("dlopen error: could not make function"
1037 "caller: %s", utility_error.AsCString());
1041 do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
1042 if (!do_dlopen_function) {
1043 error.SetErrorString("dlopen error: could not get function caller.");
1047 // We made a good utility function, so cache it in the process:
1048 return dlopen_utility_func_up;
1051 uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process,
1052 const lldb_private::FileSpec &remote_file,
1053 const std::vector<std::string> *paths,
1054 lldb_private::Status &error,
1055 lldb_private::FileSpec *loaded_image) {
1057 loaded_image->Clear();
1060 path = remote_file.GetPath();
1062 ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
1064 error.SetErrorString("dlopen error: no thread available to call dlopen.");
1065 return LLDB_INVALID_IMAGE_TOKEN;
1068 DiagnosticManager diagnostics;
1070 ExecutionContext exe_ctx;
1071 thread_sp->CalculateExecutionContext(exe_ctx);
1073 Status utility_error;
1074 UtilityFunction *dlopen_utility_func;
1075 ValueList arguments;
1076 FunctionCaller *do_dlopen_function = nullptr;
1078 // The UtilityFunction is held in the Process. Platforms don't track the
1079 // lifespan of the Targets that use them, we can't put this in the Platform.
1080 dlopen_utility_func = process->GetLoadImageUtilityFunction(
1081 this, [&]() -> std::unique_ptr<UtilityFunction> {
1082 return MakeLoadImageUtilityFunction(exe_ctx, error);
1084 // If we couldn't make it, the error will be in error, so we can exit here.
1085 if (!dlopen_utility_func)
1086 return LLDB_INVALID_IMAGE_TOKEN;
1088 do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
1089 if (!do_dlopen_function) {
1090 error.SetErrorString("dlopen error: could not get function caller.");
1091 return LLDB_INVALID_IMAGE_TOKEN;
1093 arguments = do_dlopen_function->GetArgumentValues();
1095 // Now insert the path we are searching for and the result structure into the
1097 uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
1098 size_t path_len = path.size() + 1;
1099 lldb::addr_t path_addr = process->AllocateMemory(path_len,
1102 if (path_addr == LLDB_INVALID_ADDRESS) {
1103 error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1104 "for path: %s", utility_error.AsCString());
1105 return LLDB_INVALID_IMAGE_TOKEN;
1108 // Make sure we deallocate the input string memory:
1109 CleanUp path_cleanup([process, path_addr] {
1110 process->DeallocateMemory(path_addr);
1113 process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
1114 if (utility_error.Fail()) {
1115 error.SetErrorStringWithFormat("dlopen error: could not write path string:"
1116 " %s", utility_error.AsCString());
1117 return LLDB_INVALID_IMAGE_TOKEN;
1120 // Make space for our return structure. It is two pointers big: the token
1121 // and the error string.
1122 const uint32_t addr_size = process->GetAddressByteSize();
1123 lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
1126 if (utility_error.Fail()) {
1127 error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1128 "for path: %s", utility_error.AsCString());
1129 return LLDB_INVALID_IMAGE_TOKEN;
1132 // Make sure we deallocate the result structure memory
1133 CleanUp return_cleanup([process, return_addr] {
1134 process->DeallocateMemory(return_addr);
1137 // This will be the address of the storage for paths, if we are using them,
1138 // or nullptr to signal we aren't.
1139 lldb::addr_t path_array_addr = 0x0;
1140 llvm::Optional<CleanUp> path_array_cleanup;
1142 // This is the address to a buffer large enough to hold the largest path
1143 // conjoined with the library name we're passing in. This is a convenience
1144 // to avoid having to call malloc in the dlopen function.
1145 lldb::addr_t buffer_addr = 0x0;
1146 llvm::Optional<CleanUp> buffer_cleanup;
1148 // Set the values into our args and write them to the target:
1149 if (paths != nullptr) {
1150 // First insert the paths into the target. This is expected to be a
1151 // continuous buffer with the strings laid out null terminated and
1152 // end to end with an empty string terminating the buffer.
1153 // We also compute the buffer's required size as we go.
1154 size_t buffer_size = 0;
1155 std::string path_array;
1156 for (auto path : *paths) {
1157 // Don't insert empty paths, they will make us abort the path
1158 // search prematurely.
1161 size_t path_size = path.size();
1162 path_array.append(path);
1163 path_array.push_back('\0');
1164 if (path_size > buffer_size)
1165 buffer_size = path_size;
1167 path_array.push_back('\0');
1169 path_array_addr = process->AllocateMemory(path_array.size(),
1172 if (path_array_addr == LLDB_INVALID_ADDRESS) {
1173 error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1174 "for path array: %s",
1175 utility_error.AsCString());
1176 return LLDB_INVALID_IMAGE_TOKEN;
1179 // Make sure we deallocate the paths array.
1180 path_array_cleanup.emplace([process, path_array_addr] {
1181 process->DeallocateMemory(path_array_addr);
1184 process->WriteMemory(path_array_addr, path_array.data(),
1185 path_array.size(), utility_error);
1187 if (utility_error.Fail()) {
1188 error.SetErrorStringWithFormat("dlopen error: could not write path array:"
1189 " %s", utility_error.AsCString());
1190 return LLDB_INVALID_IMAGE_TOKEN;
1192 // Now make spaces in the target for the buffer. We need to add one for
1193 // the '/' that the utility function will insert and one for the '\0':
1194 buffer_size += path.size() + 2;
1196 buffer_addr = process->AllocateMemory(buffer_size,
1199 if (buffer_addr == LLDB_INVALID_ADDRESS) {
1200 error.SetErrorStringWithFormat("dlopen error: could not allocate memory"
1202 utility_error.AsCString());
1203 return LLDB_INVALID_IMAGE_TOKEN;
1206 // Make sure we deallocate the buffer memory:
1207 buffer_cleanup.emplace([process, buffer_addr] {
1208 process->DeallocateMemory(buffer_addr);
1212 arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
1213 arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
1214 arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
1215 arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
1217 lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
1219 diagnostics.Clear();
1220 if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
1224 error.SetErrorStringWithFormat("dlopen error: could not write function "
1226 diagnostics.GetString().c_str());
1227 return LLDB_INVALID_IMAGE_TOKEN;
1230 // Make sure we clean up the args structure. We can't reuse it because the
1231 // Platform lives longer than the process and the Platforms don't get a
1232 // signal to clean up cached data when a process goes away.
1233 CleanUp args_cleanup([do_dlopen_function, &exe_ctx, func_args_addr] {
1234 do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
1237 // Now run the caller:
1238 EvaluateExpressionOptions options;
1239 options.SetExecutionPolicy(eExecutionPolicyAlways);
1240 options.SetLanguage(eLanguageTypeC_plus_plus);
1241 options.SetIgnoreBreakpoints(true);
1242 options.SetUnwindOnError(true);
1243 options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
1244 // don't do the work to trap them.
1245 options.SetTimeout(std::chrono::seconds(2));
1246 options.SetIsForUtilityExpr(true);
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, llvm::sys::path::Style::posix);
1286 return process->AddImageToken(token);
1289 // We got an error, lets read in the error string:
1290 std::string dlopen_error_str;
1291 lldb::addr_t error_addr
1292 = process->ReadPointerFromMemory(return_addr + addr_size, utility_error);
1293 if (utility_error.Fail()) {
1294 error.SetErrorStringWithFormat("dlopen error: could not read error string: "
1295 "%s", utility_error.AsCString());
1296 return LLDB_INVALID_IMAGE_TOKEN;
1299 size_t num_chars = process->ReadCStringFromMemory(error_addr + addr_size,
1302 if (utility_error.Success() && num_chars > 0)
1303 error.SetErrorStringWithFormat("dlopen error: %s",
1304 dlopen_error_str.c_str());
1306 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
1308 return LLDB_INVALID_IMAGE_TOKEN;
1311 Status PlatformPOSIX::UnloadImage(lldb_private::Process *process,
1312 uint32_t image_token) {
1313 const addr_t image_addr = process->GetImagePtrFromToken(image_token);
1314 if (image_addr == LLDB_INVALID_ADDRESS)
1315 return Status("Invalid image token");
1318 expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
1319 llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
1320 lldb::ValueObjectSP result_valobj_sp;
1321 Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
1326 if (result_valobj_sp->GetError().Fail())
1327 return result_valobj_sp->GetError();
1330 if (result_valobj_sp->ResolveValue(scalar)) {
1332 return Status("expression failed: \"%s\"", expr.GetData());
1333 process->ResetImageToken(image_token);
1338 lldb::ProcessSP PlatformPOSIX::ConnectProcess(llvm::StringRef connect_url,
1339 llvm::StringRef plugin_name,
1340 lldb_private::Debugger &debugger,
1341 lldb_private::Target *target,
1342 lldb_private::Status &error) {
1343 if (m_remote_platform_sp)
1344 return m_remote_platform_sp->ConnectProcess(connect_url, plugin_name,
1345 debugger, target, error);
1347 return Platform::ConnectProcess(connect_url, plugin_name, debugger, target,
1352 PlatformPOSIX::GetLibdlFunctionDeclarations(lldb_private::Process *process) {
1354 extern "C" void* dlopen(const char*, int);
1355 extern "C" void* dlsym(void*, const char*);
1356 extern "C" int dlclose(void*);
1357 extern "C" char* dlerror(void);
1361 size_t PlatformPOSIX::ConnectToWaitingProcesses(Debugger &debugger,
1363 if (m_remote_platform_sp)
1364 return m_remote_platform_sp->ConnectToWaitingProcesses(debugger, error);
1365 return Platform::ConnectToWaitingProcesses(debugger, error);
1368 ConstString PlatformPOSIX::GetFullNameForDylib(ConstString basename) {
1369 if (basename.IsEmpty())
1372 StreamString stream;
1373 stream.Printf("lib%s.so", basename.GetCString());
1374 return ConstString(stream.GetString());