180814287SRaphael Isemann //===-- PlatformRemoteGDBServer.cpp ---------------------------------------===//
2d314e810SGreg Clayton //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d314e810SGreg Clayton //
7d314e810SGreg Clayton //===----------------------------------------------------------------------===//
8d314e810SGreg Clayton 
9d314e810SGreg Clayton #include "PlatformRemoteGDBServer.h"
10b2f1fb29SVirgile Bello #include "lldb/Host/Config.h"
11d314e810SGreg Clayton 
12d314e810SGreg Clayton #include "lldb/Breakpoint/BreakpointLocation.h"
138b82f087SGreg Clayton #include "lldb/Core/Debugger.h"
14d314e810SGreg Clayton #include "lldb/Core/Module.h"
15d314e810SGreg Clayton #include "lldb/Core/ModuleList.h"
168012cadbSGreg Clayton #include "lldb/Core/ModuleSpec.h"
17d314e810SGreg Clayton #include "lldb/Core/PluginManager.h"
18ccd6cffbSTamas Berghammer #include "lldb/Core/StreamFile.h"
1993a66fc1SZachary Turner #include "lldb/Host/ConnectionFileDescriptor.h"
20d314e810SGreg Clayton #include "lldb/Host/Host.h"
2163acdfdeSOleksiy Vyalov #include "lldb/Host/HostInfo.h"
22b6dbe9a9SPavel Labath #include "lldb/Host/PosixApi.h"
23d314e810SGreg Clayton #include "lldb/Target/Process.h"
24d314e810SGreg Clayton #include "lldb/Target/Target.h"
255713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
26c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
276f9e6901SZachary Turner #include "lldb/Utility/Log.h"
28805e7106SZachary Turner #include "lldb/Utility/ProcessInfo.h"
2997206d57SZachary Turner #include "lldb/Utility/Status.h"
30bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
315f7e583bSPavel Labath #include "lldb/Utility/UriParser.h"
321b5a74eeSVince Harron 
3398d0a4b3SChaoren Lin #include "Plugins/Process/Utility/GDBRemoteSignals.h"
34bf3ac994SPavel Labath #include "Plugins/Process/gdb-remote/ProcessGDBRemote.h"
3598d0a4b3SChaoren Lin 
36d314e810SGreg Clayton using namespace lldb;
37d314e810SGreg Clayton using namespace lldb_private;
38db264a6dSTamas Berghammer using namespace lldb_private::platform_gdb_server;
39d314e810SGreg Clayton 
40ccad1948SJonas Devlieghere LLDB_PLUGIN_DEFINE_ADV(PlatformRemoteGDBServer, PlatformGDB)
41fbb4d1e4SJonas Devlieghere 
42d314e810SGreg Clayton static bool g_initialized = false;
43d314e810SGreg Clayton 
Initialize()44b9c1b51eSKate Stone void PlatformRemoteGDBServer::Initialize() {
453c4f89d7STamas Berghammer   Platform::Initialize();
463c4f89d7STamas Berghammer 
47a6682a41SJonas Devlieghere   if (!g_initialized) {
48d314e810SGreg Clayton     g_initialized = true;
49b9c1b51eSKate Stone     PluginManager::RegisterPlugin(
50b9c1b51eSKate Stone         PlatformRemoteGDBServer::GetPluginNameStatic(),
51d314e810SGreg Clayton         PlatformRemoteGDBServer::GetDescriptionStatic(),
52d314e810SGreg Clayton         PlatformRemoteGDBServer::CreateInstance);
53d314e810SGreg Clayton   }
54d314e810SGreg Clayton }
55d314e810SGreg Clayton 
Terminate()56b9c1b51eSKate Stone void PlatformRemoteGDBServer::Terminate() {
57b9c1b51eSKate Stone   if (g_initialized) {
58d314e810SGreg Clayton     g_initialized = false;
59d314e810SGreg Clayton     PluginManager::UnregisterPlugin(PlatformRemoteGDBServer::CreateInstance);
60d314e810SGreg Clayton   }
613c4f89d7STamas Berghammer 
623c4f89d7STamas Berghammer   Platform::Terminate();
63d314e810SGreg Clayton }
64d314e810SGreg Clayton 
CreateInstance(bool force,const ArchSpec * arch)65b9c1b51eSKate Stone PlatformSP PlatformRemoteGDBServer::CreateInstance(bool force,
66b9c1b51eSKate Stone                                                    const ArchSpec *arch) {
6770512317SGreg Clayton   bool create = force;
68b9c1b51eSKate Stone   if (!create) {
6970512317SGreg Clayton     create = !arch->TripleVendorWasSpecified() && !arch->TripleOSWasSpecified();
70d314e810SGreg Clayton   }
7170512317SGreg Clayton   if (create)
72615eb7e6SGreg Clayton     return PlatformSP(new PlatformRemoteGDBServer());
73615eb7e6SGreg Clayton   return PlatformSP();
7470512317SGreg Clayton }
7570512317SGreg Clayton 
GetDescriptionStatic()76a458ef4fSPavel Labath llvm::StringRef PlatformRemoteGDBServer::GetDescriptionStatic() {
77b9c1b51eSKate Stone   return "A platform that uses the GDB remote protocol as the communication "
78b9c1b51eSKate Stone          "transport.";
79d314e810SGreg Clayton }
80d314e810SGreg Clayton 
GetDescription()81a458ef4fSPavel Labath llvm::StringRef PlatformRemoteGDBServer::GetDescription() {
82b9c1b51eSKate Stone   if (m_platform_description.empty()) {
83b9c1b51eSKate Stone     if (IsConnected()) {
84d314e810SGreg Clayton       // Send the get description packet
85d314e810SGreg Clayton     }
86d314e810SGreg Clayton   }
87d314e810SGreg Clayton 
88d314e810SGreg Clayton   if (!m_platform_description.empty())
89d314e810SGreg Clayton     return m_platform_description.c_str();
90d314e810SGreg Clayton   return GetDescriptionStatic();
91d314e810SGreg Clayton }
92d314e810SGreg Clayton 
GetModuleSpec(const FileSpec & module_file_spec,const ArchSpec & arch,ModuleSpec & module_spec)93b9c1b51eSKate Stone bool PlatformRemoteGDBServer::GetModuleSpec(const FileSpec &module_file_spec,
9463acdfdeSOleksiy Vyalov                                             const ArchSpec &arch,
95b9c1b51eSKate Stone                                             ModuleSpec &module_spec) {
96a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
9763acdfdeSOleksiy Vyalov 
987d9d941bSOleksiy Vyalov   const auto module_path = module_file_spec.GetPath(false);
9963acdfdeSOleksiy Vyalov 
1008ccfcab3SPavel Labath   if (!m_gdb_client_up ||
1018ccfcab3SPavel Labath       !m_gdb_client_up->GetModuleInfo(module_file_spec, arch, module_spec)) {
10263e5fb76SJonas Devlieghere     LLDB_LOGF(
10363e5fb76SJonas Devlieghere         log,
104b9c1b51eSKate Stone         "PlatformRemoteGDBServer::%s - failed to get module info for %s:%s",
105b9c1b51eSKate Stone         __FUNCTION__, module_path.c_str(),
106b9c1b51eSKate Stone         arch.GetTriple().getTriple().c_str());
10763acdfdeSOleksiy Vyalov     return false;
10863acdfdeSOleksiy Vyalov   }
10963acdfdeSOleksiy Vyalov 
110b9c1b51eSKate Stone   if (log) {
11163acdfdeSOleksiy Vyalov     StreamString stream;
11263acdfdeSOleksiy Vyalov     module_spec.Dump(stream);
11363e5fb76SJonas Devlieghere     LLDB_LOGF(log,
114b9c1b51eSKate Stone               "PlatformRemoteGDBServer::%s - got module info for (%s:%s) : %s",
11563e5fb76SJonas Devlieghere               __FUNCTION__, module_path.c_str(),
11663e5fb76SJonas Devlieghere               arch.GetTriple().getTriple().c_str(), stream.GetData());
11763acdfdeSOleksiy Vyalov   }
11863acdfdeSOleksiy Vyalov 
11963acdfdeSOleksiy Vyalov   return true;
12063acdfdeSOleksiy Vyalov }
12163acdfdeSOleksiy Vyalov 
GetFileWithUUID(const FileSpec & platform_file,const UUID * uuid_ptr,FileSpec & local_file)12297206d57SZachary Turner Status PlatformRemoteGDBServer::GetFileWithUUID(const FileSpec &platform_file,
123d314e810SGreg Clayton                                                 const UUID *uuid_ptr,
124b9c1b51eSKate Stone                                                 FileSpec &local_file) {
125d314e810SGreg Clayton   // Default to the local case
126d314e810SGreg Clayton   local_file = platform_file;
12797206d57SZachary Turner   return Status();
128d314e810SGreg Clayton }
129d314e810SGreg Clayton 
130d314e810SGreg Clayton /// Default Constructor
PlatformRemoteGDBServer()131b9c1b51eSKate Stone PlatformRemoteGDBServer::PlatformRemoteGDBServer()
1328ccfcab3SPavel Labath     : Platform(/*is_host=*/false) {}
133d314e810SGreg Clayton 
134d314e810SGreg Clayton /// Destructor.
135d314e810SGreg Clayton ///
136d314e810SGreg Clayton /// The destructor is virtual since this class is designed to be
137d314e810SGreg Clayton /// inherited from by the plug-in instance.
138fd2433e1SJonas Devlieghere PlatformRemoteGDBServer::~PlatformRemoteGDBServer() = default;
139d314e810SGreg Clayton 
GetSoftwareBreakpointTrapOpcode(Target & target,BreakpointSite * bp_site)140b9c1b51eSKate Stone size_t PlatformRemoteGDBServer::GetSoftwareBreakpointTrapOpcode(
141b9c1b51eSKate Stone     Target &target, BreakpointSite *bp_site) {
142d314e810SGreg Clayton   // This isn't needed if the z/Z packets are supported in the GDB remote
143d314e810SGreg Clayton   // server. But we might need a packet to detect this.
144d314e810SGreg Clayton   return 0;
145d314e810SGreg Clayton }
146d314e810SGreg Clayton 
GetRemoteOSVersion()147b9c1b51eSKate Stone bool PlatformRemoteGDBServer::GetRemoteOSVersion() {
1488ccfcab3SPavel Labath   if (m_gdb_client_up)
1498ccfcab3SPavel Labath     m_os_version = m_gdb_client_up->GetOSVersion();
1502272c481SPavel Labath   return !m_os_version.empty();
151d314e810SGreg Clayton }
152d314e810SGreg Clayton 
GetRemoteOSBuildString()15340e4ac3eSPavel Labath llvm::Optional<std::string> PlatformRemoteGDBServer::GetRemoteOSBuildString() {
1548ccfcab3SPavel Labath   if (!m_gdb_client_up)
1558ccfcab3SPavel Labath     return llvm::None;
1568ccfcab3SPavel Labath   return m_gdb_client_up->GetOSBuildString();
1571cb6496eSGreg Clayton }
1581cb6496eSGreg Clayton 
159f5158ca4SPavel Labath llvm::Optional<std::string>
GetRemoteOSKernelDescription()160f5158ca4SPavel Labath PlatformRemoteGDBServer::GetRemoteOSKernelDescription() {
1618ccfcab3SPavel Labath   if (!m_gdb_client_up)
1628ccfcab3SPavel Labath     return llvm::None;
1638ccfcab3SPavel Labath   return m_gdb_client_up->GetOSKernelDescription();
1641cb6496eSGreg Clayton }
1651cb6496eSGreg Clayton 
1661cb6496eSGreg Clayton // Remote Platform subclasses need to override this function
GetRemoteSystemArchitecture()167b9c1b51eSKate Stone ArchSpec PlatformRemoteGDBServer::GetRemoteSystemArchitecture() {
1688ccfcab3SPavel Labath   if (!m_gdb_client_up)
1698ccfcab3SPavel Labath     return ArchSpec();
1708ccfcab3SPavel Labath   return m_gdb_client_up->GetSystemArchitecture();
1711cb6496eSGreg Clayton }
1721cb6496eSGreg Clayton 
GetRemoteWorkingDirectory()173b9c1b51eSKate Stone FileSpec PlatformRemoteGDBServer::GetRemoteWorkingDirectory() {
174b9c1b51eSKate Stone   if (IsConnected()) {
175a007a6d8SPavel Labath     Log *log = GetLog(LLDBLog::Platform);
176d3173f34SChaoren Lin     FileSpec working_dir;
1778ccfcab3SPavel Labath     if (m_gdb_client_up->GetWorkingDir(working_dir) && log)
17863e5fb76SJonas Devlieghere       LLDB_LOGF(log,
179b9c1b51eSKate Stone                 "PlatformRemoteGDBServer::GetRemoteWorkingDirectory() -> '%s'",
180*1b4b12a3SNico Weber                 working_dir.GetCString());
1815fb8f797SGreg Clayton     return working_dir;
182b9c1b51eSKate Stone   } else {
183fbb76349SGreg Clayton     return Platform::GetRemoteWorkingDirectory();
184fbb76349SGreg Clayton   }
185fbb76349SGreg Clayton }
186fbb76349SGreg Clayton 
SetRemoteWorkingDirectory(const FileSpec & working_dir)187b9c1b51eSKate Stone bool PlatformRemoteGDBServer::SetRemoteWorkingDirectory(
188b9c1b51eSKate Stone     const FileSpec &working_dir) {
189b9c1b51eSKate Stone   if (IsConnected()) {
190b9c1b51eSKate Stone     // Clear the working directory it case it doesn't get set correctly. This
19105097246SAdrian Prantl     // will for use to re-read it
192a007a6d8SPavel Labath     Log *log = GetLog(LLDBLog::Platform);
19363e5fb76SJonas Devlieghere     LLDB_LOGF(log, "PlatformRemoteGDBServer::SetRemoteWorkingDirectory('%s')",
194*1b4b12a3SNico Weber               working_dir.GetCString());
1958ccfcab3SPavel Labath     return m_gdb_client_up->SetWorkingDir(working_dir) == 0;
196b9c1b51eSKate Stone   } else
197d3173f34SChaoren Lin     return Platform::SetRemoteWorkingDirectory(working_dir);
198fbb76349SGreg Clayton }
199fbb76349SGreg Clayton 
IsConnected() const200b9c1b51eSKate Stone bool PlatformRemoteGDBServer::IsConnected() const {
2018ccfcab3SPavel Labath   if (m_gdb_client_up) {
2028ccfcab3SPavel Labath     assert(m_gdb_client_up->IsConnected());
2038ccfcab3SPavel Labath     return true;
2048ccfcab3SPavel Labath   }
2058ccfcab3SPavel Labath   return false;
2061cb6496eSGreg Clayton }
2071cb6496eSGreg Clayton 
ConnectRemote(Args & args)20897206d57SZachary Turner Status PlatformRemoteGDBServer::ConnectRemote(Args &args) {
20997206d57SZachary Turner   Status error;
210b9c1b51eSKate Stone   if (IsConnected()) {
211b9c1b51eSKate Stone     error.SetErrorStringWithFormat("the platform is already connected to '%s', "
212b9c1b51eSKate Stone                                    "execute 'platform disconnect' to close the "
213b9c1b51eSKate Stone                                    "current connection",
2141cb6496eSGreg Clayton                                    GetHostname());
215d57b80e1SJonas Devlieghere     return error;
216d57b80e1SJonas Devlieghere   }
217d57b80e1SJonas Devlieghere 
218d57b80e1SJonas Devlieghere   if (args.GetArgumentCount() != 1) {
219d57b80e1SJonas Devlieghere     error.SetErrorString(
220d57b80e1SJonas Devlieghere         "\"platform connect\" takes a single argument: <connect-url>");
221d57b80e1SJonas Devlieghere     return error;
222d57b80e1SJonas Devlieghere   }
223d57b80e1SJonas Devlieghere 
2243ea689b3SChaoren Lin   const char *url = args.GetArgumentAtIndex(0);
2253ea689b3SChaoren Lin   if (!url)
22697206d57SZachary Turner     return Status("URL is null.");
227d57b80e1SJonas Devlieghere 
2280e5a4147SMichał Górny   llvm::Optional<URI> parsed_url = URI::Parse(url);
2290e5a4147SMichał Górny   if (!parsed_url)
23097206d57SZachary Turner     return Status("Invalid URL: %s", url);
231d57b80e1SJonas Devlieghere 
232d57b80e1SJonas Devlieghere   // We're going to reuse the hostname when we connect to the debugserver.
2330e5a4147SMichał Górny   m_platform_scheme = parsed_url->scheme.str();
2340e5a4147SMichał Górny   m_platform_hostname = parsed_url->hostname.str();
2351b5a74eeSVince Harron 
2368ccfcab3SPavel Labath   auto client_up =
2378ccfcab3SPavel Labath       std::make_unique<process_gdb_remote::GDBRemoteCommunicationClient>();
2388ccfcab3SPavel Labath   client_up->SetPacketTimeout(
2398ccfcab3SPavel Labath       process_gdb_remote::ProcessGDBRemote::GetPacketTimeout());
2408ccfcab3SPavel Labath   client_up->SetConnection(std::make_unique<ConnectionFileDescriptor>());
241d57b80e1SJonas Devlieghere   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
242d57b80e1SJonas Devlieghere     repro::GDBRemoteProvider &provider =
243d57b80e1SJonas Devlieghere         g->GetOrCreate<repro::GDBRemoteProvider>();
2448ccfcab3SPavel Labath     client_up->SetPacketRecorder(provider.GetNewPacketRecorder());
245d57b80e1SJonas Devlieghere   }
2468ccfcab3SPavel Labath   client_up->Connect(url, &error);
247d57b80e1SJonas Devlieghere 
248d57b80e1SJonas Devlieghere   if (error.Fail())
249d57b80e1SJonas Devlieghere     return error;
250d57b80e1SJonas Devlieghere 
2518ccfcab3SPavel Labath   if (client_up->HandshakeWithServer(&error)) {
2528ccfcab3SPavel Labath     m_gdb_client_up = std::move(client_up);
2538ccfcab3SPavel Labath     m_gdb_client_up->GetHostInfo();
254b9c1b51eSKate Stone     // If a working directory was set prior to connecting, send it down
255d57b80e1SJonas Devlieghere     // now.
256fbb76349SGreg Clayton     if (m_working_dir)
2578ccfcab3SPavel Labath       m_gdb_client_up->SetWorkingDir(m_working_dir);
2581b468f1cSPavel Labath 
2591b468f1cSPavel Labath     m_supported_architectures.clear();
2608ccfcab3SPavel Labath     ArchSpec remote_arch = m_gdb_client_up->GetSystemArchitecture();
2611b468f1cSPavel Labath     if (remote_arch) {
2621b468f1cSPavel Labath       m_supported_architectures.push_back(remote_arch);
2631b468f1cSPavel Labath       if (remote_arch.GetTriple().isArch64Bit())
2641b468f1cSPavel Labath         m_supported_architectures.push_back(
2651b468f1cSPavel Labath             ArchSpec(remote_arch.GetTriple().get32BitArchVariant()));
2661b468f1cSPavel Labath     }
267b9c1b51eSKate Stone   } else {
2688ccfcab3SPavel Labath     client_up->Disconnect();
269fb90931bSGreg Clayton     if (error.Success())
270fb90931bSGreg Clayton       error.SetErrorString("handshake failed");
2711cb6496eSGreg Clayton   }
272d314e810SGreg Clayton   return error;
273d314e810SGreg Clayton }
274d314e810SGreg Clayton 
DisconnectRemote()27597206d57SZachary Turner Status PlatformRemoteGDBServer::DisconnectRemote() {
27697206d57SZachary Turner   Status error;
2778ccfcab3SPavel Labath   m_gdb_client_up.reset();
27898d0a4b3SChaoren Lin   m_remote_signals_sp.reset();
279d314e810SGreg Clayton   return error;
280d314e810SGreg Clayton }
281d314e810SGreg Clayton 
GetHostname()282b9c1b51eSKate Stone const char *PlatformRemoteGDBServer::GetHostname() {
2838ccfcab3SPavel Labath   if (m_gdb_client_up)
284a53c5c66SPavel Labath     m_gdb_client_up->GetHostname(m_hostname);
285a53c5c66SPavel Labath   if (m_hostname.empty())
286248a1305SKonrad Kleine     return nullptr;
287a53c5c66SPavel Labath   return m_hostname.c_str();
288d314e810SGreg Clayton }
289d314e810SGreg Clayton 
290aa51e6a6SPavel Labath llvm::Optional<std::string>
DoGetUserName(UserIDResolver::id_t uid)291aa51e6a6SPavel Labath PlatformRemoteGDBServer::DoGetUserName(UserIDResolver::id_t uid) {
29232e0a750SGreg Clayton   std::string name;
2938ccfcab3SPavel Labath   if (m_gdb_client_up && m_gdb_client_up->GetUserName(uid, name))
294aa51e6a6SPavel Labath     return std::move(name);
295aa51e6a6SPavel Labath   return llvm::None;
29632e0a750SGreg Clayton }
29732e0a750SGreg Clayton 
298aa51e6a6SPavel Labath llvm::Optional<std::string>
DoGetGroupName(UserIDResolver::id_t gid)299aa51e6a6SPavel Labath PlatformRemoteGDBServer::DoGetGroupName(UserIDResolver::id_t gid) {
30032e0a750SGreg Clayton   std::string name;
3018ccfcab3SPavel Labath   if (m_gdb_client_up && m_gdb_client_up->GetGroupName(gid, name))
302aa51e6a6SPavel Labath     return std::move(name);
303aa51e6a6SPavel Labath   return llvm::None;
30432e0a750SGreg Clayton }
30532e0a750SGreg Clayton 
FindProcesses(const ProcessInstanceInfoMatch & match_info,ProcessInstanceInfoList & process_infos)306b9c1b51eSKate Stone uint32_t PlatformRemoteGDBServer::FindProcesses(
307b9c1b51eSKate Stone     const ProcessInstanceInfoMatch &match_info,
308b9c1b51eSKate Stone     ProcessInstanceInfoList &process_infos) {
3098ccfcab3SPavel Labath   if (m_gdb_client_up)
3108ccfcab3SPavel Labath     return m_gdb_client_up->FindProcesses(match_info, process_infos);
3118ccfcab3SPavel Labath   return 0;
31232e0a750SGreg Clayton }
31332e0a750SGreg Clayton 
GetProcessInfo(lldb::pid_t pid,ProcessInstanceInfo & process_info)314b9c1b51eSKate Stone bool PlatformRemoteGDBServer::GetProcessInfo(
315b9c1b51eSKate Stone     lldb::pid_t pid, ProcessInstanceInfo &process_info) {
3168ccfcab3SPavel Labath   if (m_gdb_client_up)
3178ccfcab3SPavel Labath     return m_gdb_client_up->GetProcessInfo(pid, process_info);
3188ccfcab3SPavel Labath   return false;
31932e0a750SGreg Clayton }
32032e0a750SGreg Clayton 
LaunchProcess(ProcessLaunchInfo & launch_info)32197206d57SZachary Turner Status PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) {
322a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
32397206d57SZachary Turner   Status error;
3248b82f087SGreg Clayton 
32563e5fb76SJonas Devlieghere   LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() called", __FUNCTION__);
326015d818bSTodd Fiala 
3278ccfcab3SPavel Labath   if (!IsConnected())
3288ccfcab3SPavel Labath     return Status("Not connected.");
3291ef7b2c8SOleksiy Vyalov   auto num_file_actions = launch_info.GetNumFileActions();
330b9c1b51eSKate Stone   for (decltype(num_file_actions) i = 0; i < num_file_actions; ++i) {
3311ef7b2c8SOleksiy Vyalov     const auto file_action = launch_info.GetFileActionAtIndex(i);
3321ef7b2c8SOleksiy Vyalov     if (file_action->GetAction() != FileAction::eFileActionOpen)
3331ef7b2c8SOleksiy Vyalov       continue;
334b9c1b51eSKate Stone     switch (file_action->GetFD()) {
3351ef7b2c8SOleksiy Vyalov     case STDIN_FILENO:
3368ccfcab3SPavel Labath       m_gdb_client_up->SetSTDIN(file_action->GetFileSpec());
3371ef7b2c8SOleksiy Vyalov       break;
3381ef7b2c8SOleksiy Vyalov     case STDOUT_FILENO:
3398ccfcab3SPavel Labath       m_gdb_client_up->SetSTDOUT(file_action->GetFileSpec());
3401ef7b2c8SOleksiy Vyalov       break;
3411ef7b2c8SOleksiy Vyalov     case STDERR_FILENO:
3428ccfcab3SPavel Labath       m_gdb_client_up->SetSTDERR(file_action->GetFileSpec());
3431ef7b2c8SOleksiy Vyalov       break;
3441ef7b2c8SOleksiy Vyalov     }
3451ef7b2c8SOleksiy Vyalov   }
3461ef7b2c8SOleksiy Vyalov 
3478ccfcab3SPavel Labath   m_gdb_client_up->SetDisableASLR(
348b9c1b51eSKate Stone       launch_info.GetFlags().Test(eLaunchFlagDisableASLR));
3498ccfcab3SPavel Labath   m_gdb_client_up->SetDetachOnError(
350b9c1b51eSKate Stone       launch_info.GetFlags().Test(eLaunchFlagDetachOnError));
3518b82f087SGreg Clayton 
352d3173f34SChaoren Lin   FileSpec working_dir = launch_info.GetWorkingDirectory();
353b9c1b51eSKate Stone   if (working_dir) {
3548ccfcab3SPavel Labath     m_gdb_client_up->SetWorkingDir(working_dir);
3558b82f087SGreg Clayton   }
3568b82f087SGreg Clayton 
3578b82f087SGreg Clayton   // Send the environment and the program + arguments after we connect
3588ccfcab3SPavel Labath   m_gdb_client_up->SendEnvironment(launch_info.GetEnvironment());
359e0f8f574SDaniel Malea 
360e0f8f574SDaniel Malea   ArchSpec arch_spec = launch_info.GetArchitecture();
361e0f8f574SDaniel Malea   const char *arch_triple = arch_spec.GetTriple().str().c_str();
362e0f8f574SDaniel Malea 
3638ccfcab3SPavel Labath   m_gdb_client_up->SendLaunchArchPacket(arch_triple);
36463e5fb76SJonas Devlieghere   LLDB_LOGF(
36563e5fb76SJonas Devlieghere       log,
366b9c1b51eSKate Stone       "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'",
367b9c1b51eSKate Stone       __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
368e0f8f574SDaniel Malea 
369912800c4STamas Berghammer   int arg_packet_err;
370912800c4STamas Berghammer   {
371912800c4STamas Berghammer     // Scope for the scoped timeout object
372b9c1b51eSKate Stone     process_gdb_remote::GDBRemoteCommunication::ScopedTimeout timeout(
3738ccfcab3SPavel Labath         *m_gdb_client_up, std::chrono::seconds(5));
3748ccfcab3SPavel Labath     arg_packet_err = m_gdb_client_up->SendArgumentsPacket(launch_info);
375912800c4STamas Berghammer   }
376912800c4STamas Berghammer 
377b9c1b51eSKate Stone   if (arg_packet_err == 0) {
3788b82f087SGreg Clayton     std::string error_str;
3798ccfcab3SPavel Labath     if (m_gdb_client_up->GetLaunchSuccess(error_str)) {
3808ccfcab3SPavel Labath       const auto pid = m_gdb_client_up->GetCurrentProcessID(false);
381b9c1b51eSKate Stone       if (pid != LLDB_INVALID_PROCESS_ID) {
3828b82f087SGreg Clayton         launch_info.SetProcessID(pid);
38363e5fb76SJonas Devlieghere         LLDB_LOGF(log,
38463e5fb76SJonas Devlieghere                   "PlatformRemoteGDBServer::%s() pid %" PRIu64
385b9c1b51eSKate Stone                   " launched successfully",
386b9c1b51eSKate Stone                   __FUNCTION__, pid);
387b9c1b51eSKate Stone       } else {
38863e5fb76SJonas Devlieghere         LLDB_LOGF(log,
38963e5fb76SJonas Devlieghere                   "PlatformRemoteGDBServer::%s() launch succeeded but we "
390b9c1b51eSKate Stone                   "didn't get a valid process id back!",
391b9c1b51eSKate Stone                   __FUNCTION__);
3921ef7b2c8SOleksiy Vyalov         error.SetErrorString("failed to get PID");
393015d818bSTodd Fiala       }
394b9c1b51eSKate Stone     } else {
3958b82f087SGreg Clayton       error.SetErrorString(error_str.c_str());
39663e5fb76SJonas Devlieghere       LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() launch failed: %s",
397b9c1b51eSKate Stone                 __FUNCTION__, error.AsCString());
3988b82f087SGreg Clayton     }
399b9c1b51eSKate Stone   } else {
400b9c1b51eSKate Stone     error.SetErrorStringWithFormat("'A' packet returned an error: %i",
401b9c1b51eSKate Stone                                    arg_packet_err);
4028b82f087SGreg Clayton   }
4038b82f087SGreg Clayton   return error;
4048b82f087SGreg Clayton }
4058b82f087SGreg Clayton 
KillProcess(const lldb::pid_t pid)40697206d57SZachary Turner Status PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) {
40700e305d2STamas Berghammer   if (!KillSpawnedProcess(pid))
40897206d57SZachary Turner     return Status("failed to kill remote spawned process");
40997206d57SZachary Turner   return Status();
4101ef7b2c8SOleksiy Vyalov }
4111ef7b2c8SOleksiy Vyalov 
412bd590a5fSPavel Labath lldb::ProcessSP
DebugProcess(ProcessLaunchInfo & launch_info,Debugger & debugger,Target & target,Status & error)413bd590a5fSPavel Labath PlatformRemoteGDBServer::DebugProcess(ProcessLaunchInfo &launch_info,
414bd590a5fSPavel Labath                                       Debugger &debugger, Target &target,
41597206d57SZachary Turner                                       Status &error) {
416fbb76349SGreg Clayton   lldb::ProcessSP process_sp;
417b9c1b51eSKate Stone   if (IsRemote()) {
418b9c1b51eSKate Stone     if (IsConnected()) {
419fbb76349SGreg Clayton       lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
4209fe526c2SOleksiy Vyalov       std::string connect_url;
421b9c1b51eSKate Stone       if (!LaunchGDBServer(debugserver_pid, connect_url)) {
422b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
423b9c1b51eSKate Stone                                        GetHostname());
424b9c1b51eSKate Stone       } else {
425fbb76349SGreg Clayton         // The darwin always currently uses the GDB remote debugger plug-in
426fbb76349SGreg Clayton         // so even when debugging locally we are debugging remotely!
427bd590a5fSPavel Labath         process_sp = target.CreateProcess(launch_info.GetListener(),
42818e4272aSMichał Górny                                           "gdb-remote", nullptr, true);
429fbb76349SGreg Clayton 
430b9c1b51eSKate Stone         if (process_sp) {
431a2c267e0SIlya Nozhkin           process_sp->HijackProcessEvents(launch_info.GetHijackListener());
432a2c267e0SIlya Nozhkin 
43332d35fb7SJonas Devlieghere           error = process_sp->ConnectRemote(connect_url.c_str());
43456bf5592SGreg Clayton           // Retry the connect remote one time...
43556bf5592SGreg Clayton           if (error.Fail())
43632d35fb7SJonas Devlieghere             error = process_sp->ConnectRemote(connect_url.c_str());
437fbb76349SGreg Clayton           if (error.Success())
438fbb76349SGreg Clayton             error = process_sp->Launch(launch_info);
439b9c1b51eSKate Stone           else if (debugserver_pid != LLDB_INVALID_PROCESS_ID) {
44056bf5592SGreg Clayton             printf("error: connect remote failed (%s)\n", error.AsCString());
44100e305d2STamas Berghammer             KillSpawnedProcess(debugserver_pid);
442fbb76349SGreg Clayton           }
443fbb76349SGreg Clayton         }
444fbb76349SGreg Clayton       }
445b9c1b51eSKate Stone     } else {
446fbb76349SGreg Clayton       error.SetErrorString("not connected to remote gdb server");
447fbb76349SGreg Clayton     }
448fbb76349SGreg Clayton   }
449fbb76349SGreg Clayton   return process_sp;
450fbb76349SGreg Clayton }
451fbb76349SGreg Clayton 
LaunchGDBServer(lldb::pid_t & pid,std::string & connect_url)452b9c1b51eSKate Stone bool PlatformRemoteGDBServer::LaunchGDBServer(lldb::pid_t &pid,
453b9c1b51eSKate Stone                                               std::string &connect_url) {
4548ccfcab3SPavel Labath   assert(IsConnected());
4558ccfcab3SPavel Labath 
45600e305d2STamas Berghammer   ArchSpec remote_arch = GetRemoteSystemArchitecture();
45700e305d2STamas Berghammer   llvm::Triple &remote_triple = remote_arch.GetTriple();
4589fe526c2SOleksiy Vyalov 
4599fe526c2SOleksiy Vyalov   uint16_t port = 0;
4609fe526c2SOleksiy Vyalov   std::string socket_name;
4619fe526c2SOleksiy Vyalov   bool launch_result = false;
462b9c1b51eSKate Stone   if (remote_triple.getVendor() == llvm::Triple::Apple &&
463b9c1b51eSKate Stone       remote_triple.getOS() == llvm::Triple::IOS) {
46405097246SAdrian Prantl     // When remote debugging to iOS, we use a USB mux that always talks to
46505097246SAdrian Prantl     // localhost, so we will need the remote debugserver to accept connections
46600e305d2STamas Berghammer     // only from localhost, no matter what our current hostname is
467b9c1b51eSKate Stone     launch_result =
4688ccfcab3SPavel Labath         m_gdb_client_up->LaunchGDBServer("127.0.0.1", pid, port, socket_name);
469b9c1b51eSKate Stone   } else {
47000e305d2STamas Berghammer     // All other hosts should use their actual hostname
471b9c1b51eSKate Stone     launch_result =
4728ccfcab3SPavel Labath         m_gdb_client_up->LaunchGDBServer(nullptr, pid, port, socket_name);
47300e305d2STamas Berghammer   }
4749fe526c2SOleksiy Vyalov 
4759fe526c2SOleksiy Vyalov   if (!launch_result)
4769fe526c2SOleksiy Vyalov     return false;
4779fe526c2SOleksiy Vyalov 
478b9c1b51eSKate Stone   connect_url =
479b9c1b51eSKate Stone       MakeGdbServerUrl(m_platform_scheme, m_platform_hostname, port,
4809fe526c2SOleksiy Vyalov                        (socket_name.empty()) ? nullptr : socket_name.c_str());
4819fe526c2SOleksiy Vyalov   return true;
48200e305d2STamas Berghammer }
48300e305d2STamas Berghammer 
KillSpawnedProcess(lldb::pid_t pid)484b9c1b51eSKate Stone bool PlatformRemoteGDBServer::KillSpawnedProcess(lldb::pid_t pid) {
4858ccfcab3SPavel Labath   assert(IsConnected());
4868ccfcab3SPavel Labath   return m_gdb_client_up->KillSpawnedProcess(pid);
48700e305d2STamas Berghammer }
48800e305d2STamas Berghammer 
Attach(ProcessAttachInfo & attach_info,Debugger & debugger,Target * target,Status & error)489b9c1b51eSKate Stone lldb::ProcessSP PlatformRemoteGDBServer::Attach(
490b9c1b51eSKate Stone     ProcessAttachInfo &attach_info, Debugger &debugger,
491b9c1b51eSKate Stone     Target *target, // Can be NULL, if NULL create a new target, else use
492b9c1b51eSKate Stone                     // existing one
49397206d57SZachary Turner     Status &error) {
4948b82f087SGreg Clayton   lldb::ProcessSP process_sp;
495b9c1b51eSKate Stone   if (IsRemote()) {
496b9c1b51eSKate Stone     if (IsConnected()) {
497e0f8f574SDaniel Malea       lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
4989fe526c2SOleksiy Vyalov       std::string connect_url;
499b9c1b51eSKate Stone       if (!LaunchGDBServer(debugserver_pid, connect_url)) {
500b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
501b9c1b51eSKate Stone                                        GetHostname());
502b9c1b51eSKate Stone       } else {
503248a1305SKonrad Kleine         if (target == nullptr) {
5048b82f087SGreg Clayton           TargetSP new_target_sp;
5058b82f087SGreg Clayton 
506f9a07e9fSJonas Devlieghere           error = debugger.GetTargetList().CreateTarget(
507248a1305SKonrad Kleine               debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
5088b82f087SGreg Clayton           target = new_target_sp.get();
509b9c1b51eSKate Stone         } else
5108b82f087SGreg Clayton           error.Clear();
5118b82f087SGreg Clayton 
512b9c1b51eSKate Stone         if (target && error.Success()) {
5138b82f087SGreg Clayton           // The darwin always currently uses the GDB remote debugger plug-in
5148b82f087SGreg Clayton           // so even when debugging locally we are debugging remotely!
515248a1305SKonrad Kleine           process_sp =
516248a1305SKonrad Kleine               target->CreateProcess(attach_info.GetListenerForProcess(debugger),
51718e4272aSMichał Górny                                     "gdb-remote", nullptr, true);
518b9c1b51eSKate Stone           if (process_sp) {
51932d35fb7SJonas Devlieghere             error = process_sp->ConnectRemote(connect_url.c_str());
520b9c1b51eSKate Stone             if (error.Success()) {
521583bbb1dSJim Ingham               ListenerSP listener_sp = attach_info.GetHijackListener();
522583bbb1dSJim Ingham               if (listener_sp)
523583bbb1dSJim Ingham                 process_sp->HijackProcessEvents(listener_sp);
524144f3a9cSGreg Clayton               error = process_sp->Attach(attach_info);
525926af0cdSOleksiy Vyalov             }
526926af0cdSOleksiy Vyalov 
527b9c1b51eSKate Stone             if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) {
52800e305d2STamas Berghammer               KillSpawnedProcess(debugserver_pid);
529e0f8f574SDaniel Malea             }
5308b82f087SGreg Clayton           }
5318b82f087SGreg Clayton         }
5328b82f087SGreg Clayton       }
533b9c1b51eSKate Stone     } else {
5348b82f087SGreg Clayton       error.SetErrorString("not connected to remote gdb server");
5358b82f087SGreg Clayton     }
5368b82f087SGreg Clayton   }
5378b82f087SGreg Clayton   return process_sp;
5388b82f087SGreg Clayton }
5398b82f087SGreg Clayton 
MakeDirectory(const FileSpec & file_spec,uint32_t mode)54097206d57SZachary Turner Status PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec,
541b9c1b51eSKate Stone                                               uint32_t mode) {
5428ccfcab3SPavel Labath   if (!IsConnected())
5438ccfcab3SPavel Labath     return Status("Not connected.");
5448ccfcab3SPavel Labath   Status error = m_gdb_client_up->MakeDirectory(file_spec, mode);
545a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
54663e5fb76SJonas Devlieghere   LLDB_LOGF(log,
54763e5fb76SJonas Devlieghere             "PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) "
548b9c1b51eSKate Stone             "error = %u (%s)",
549*1b4b12a3SNico Weber             file_spec.GetCString(), mode, error.GetError(), error.AsCString());
550fbb76349SGreg Clayton   return error;
551e0f8f574SDaniel Malea }
55232e0a750SGreg Clayton 
GetFilePermissions(const FileSpec & file_spec,uint32_t & file_permissions)55397206d57SZachary Turner Status PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec,
554b9c1b51eSKate Stone                                                    uint32_t &file_permissions) {
5558ccfcab3SPavel Labath   if (!IsConnected())
5568ccfcab3SPavel Labath     return Status("Not connected.");
5578ccfcab3SPavel Labath   Status error =
5588ccfcab3SPavel Labath       m_gdb_client_up->GetFilePermissions(file_spec, file_permissions);
559a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
56063e5fb76SJonas Devlieghere   LLDB_LOGF(log,
56163e5fb76SJonas Devlieghere             "PlatformRemoteGDBServer::GetFilePermissions(path='%s', "
562b9c1b51eSKate Stone             "file_permissions=%o) error = %u (%s)",
563*1b4b12a3SNico Weber             file_spec.GetCString(), file_permissions, error.GetError(),
564b9c1b51eSKate Stone             error.AsCString());
565fbb76349SGreg Clayton   return error;
566fbb76349SGreg Clayton }
567fbb76349SGreg Clayton 
SetFilePermissions(const FileSpec & file_spec,uint32_t file_permissions)56897206d57SZachary Turner Status PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec,
569b9c1b51eSKate Stone                                                    uint32_t file_permissions) {
5708ccfcab3SPavel Labath   if (!IsConnected())
5718ccfcab3SPavel Labath     return Status("Not connected.");
5728ccfcab3SPavel Labath   Status error =
5738ccfcab3SPavel Labath       m_gdb_client_up->SetFilePermissions(file_spec, file_permissions);
574a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
57563e5fb76SJonas Devlieghere   LLDB_LOGF(log,
57663e5fb76SJonas Devlieghere             "PlatformRemoteGDBServer::SetFilePermissions(path='%s', "
577b9c1b51eSKate Stone             "file_permissions=%o) error = %u (%s)",
578*1b4b12a3SNico Weber             file_spec.GetCString(), file_permissions, error.GetError(),
579b9c1b51eSKate Stone             error.AsCString());
580fbb76349SGreg Clayton   return error;
581fbb76349SGreg Clayton }
582fbb76349SGreg Clayton 
OpenFile(const FileSpec & file_spec,File::OpenOptions flags,uint32_t mode,Status & error)583b9c1b51eSKate Stone lldb::user_id_t PlatformRemoteGDBServer::OpenFile(const FileSpec &file_spec,
58462c9fe42SLawrence D'Anna                                                   File::OpenOptions flags,
58562c9fe42SLawrence D'Anna                                                   uint32_t mode,
58697206d57SZachary Turner                                                   Status &error) {
5878ccfcab3SPavel Labath   if (IsConnected())
5888ccfcab3SPavel Labath     return m_gdb_client_up->OpenFile(file_spec, flags, mode, error);
5898ccfcab3SPavel Labath   return LLDB_INVALID_UID;
590e0f8f574SDaniel Malea }
591e0f8f574SDaniel Malea 
CloseFile(lldb::user_id_t fd,Status & error)59297206d57SZachary Turner bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Status &error) {
5938ccfcab3SPavel Labath   if (IsConnected())
5948ccfcab3SPavel Labath     return m_gdb_client_up->CloseFile(fd, error);
5958ccfcab3SPavel Labath   error = Status("Not connected.");
5968ccfcab3SPavel Labath   return false;
597e0f8f574SDaniel Malea }
598e0f8f574SDaniel Malea 
599e0f8f574SDaniel Malea lldb::user_id_t
GetFileSize(const FileSpec & file_spec)600b9c1b51eSKate Stone PlatformRemoteGDBServer::GetFileSize(const FileSpec &file_spec) {
6018ccfcab3SPavel Labath   if (IsConnected())
6028ccfcab3SPavel Labath     return m_gdb_client_up->GetFileSize(file_spec);
6038ccfcab3SPavel Labath   return LLDB_INVALID_UID;
604e0f8f574SDaniel Malea }
605e0f8f574SDaniel Malea 
AutoCompleteDiskFileOrDirectory(CompletionRequest & request,bool only_dir)6063cd8d7b1SGongyu Deng void PlatformRemoteGDBServer::AutoCompleteDiskFileOrDirectory(
6073cd8d7b1SGongyu Deng     CompletionRequest &request, bool only_dir) {
6088ccfcab3SPavel Labath   if (IsConnected())
6098ccfcab3SPavel Labath     m_gdb_client_up->AutoCompleteDiskFileOrDirectory(request, only_dir);
6103cd8d7b1SGongyu Deng }
6113cd8d7b1SGongyu Deng 
ReadFile(lldb::user_id_t fd,uint64_t offset,void * dst,uint64_t dst_len,Status & error)612b9c1b51eSKate Stone uint64_t PlatformRemoteGDBServer::ReadFile(lldb::user_id_t fd, uint64_t offset,
613b9c1b51eSKate Stone                                            void *dst, uint64_t dst_len,
61497206d57SZachary Turner                                            Status &error) {
6158ccfcab3SPavel Labath   if (IsConnected())
6168ccfcab3SPavel Labath     return m_gdb_client_up->ReadFile(fd, offset, dst, dst_len, error);
6178ccfcab3SPavel Labath   error = Status("Not connected.");
6188ccfcab3SPavel Labath   return 0;
619e0f8f574SDaniel Malea }
620e0f8f574SDaniel Malea 
WriteFile(lldb::user_id_t fd,uint64_t offset,const void * src,uint64_t src_len,Status & error)621b9c1b51eSKate Stone uint64_t PlatformRemoteGDBServer::WriteFile(lldb::user_id_t fd, uint64_t offset,
622b9c1b51eSKate Stone                                             const void *src, uint64_t src_len,
62397206d57SZachary Turner                                             Status &error) {
6248ccfcab3SPavel Labath   if (IsConnected())
6258ccfcab3SPavel Labath     return m_gdb_client_up->WriteFile(fd, offset, src, src_len, error);
6268ccfcab3SPavel Labath   error = Status("Not connected.");
6278ccfcab3SPavel Labath   return 0;
628e0f8f574SDaniel Malea }
629e0f8f574SDaniel Malea 
PutFile(const FileSpec & source,const FileSpec & destination,uint32_t uid,uint32_t gid)63097206d57SZachary Turner Status PlatformRemoteGDBServer::PutFile(const FileSpec &source,
631db264a6dSTamas Berghammer                                         const FileSpec &destination,
632b9c1b51eSKate Stone                                         uint32_t uid, uint32_t gid) {
633e0f8f574SDaniel Malea   return Platform::PutFile(source, destination, uid, gid);
634e0f8f574SDaniel Malea }
635e0f8f574SDaniel Malea 
CreateSymlink(const FileSpec & src,const FileSpec & dst)63697206d57SZachary Turner Status PlatformRemoteGDBServer::CreateSymlink(
637b9c1b51eSKate Stone     const FileSpec &src, // The name of the link is in src
638d3173f34SChaoren Lin     const FileSpec &dst) // The symlink points to dst
639fbb76349SGreg Clayton {
6408ccfcab3SPavel Labath   if (!IsConnected())
6418ccfcab3SPavel Labath     return Status("Not connected.");
6428ccfcab3SPavel Labath   Status error = m_gdb_client_up->CreateSymlink(src, dst);
643a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
64463e5fb76SJonas Devlieghere   LLDB_LOGF(log,
64563e5fb76SJonas Devlieghere             "PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') "
646b9c1b51eSKate Stone             "error = %u (%s)",
647*1b4b12a3SNico Weber             src.GetCString(), dst.GetCString(), error.GetError(),
648b9c1b51eSKate Stone             error.AsCString());
649fbb76349SGreg Clayton   return error;
650fbb76349SGreg Clayton }
651fbb76349SGreg Clayton 
Unlink(const FileSpec & file_spec)65297206d57SZachary Turner Status PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) {
6538ccfcab3SPavel Labath   if (!IsConnected())
6548ccfcab3SPavel Labath     return Status("Not connected.");
6558ccfcab3SPavel Labath   Status error = m_gdb_client_up->Unlink(file_spec);
656a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
65763e5fb76SJonas Devlieghere   LLDB_LOGF(log, "PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)",
658*1b4b12a3SNico Weber             file_spec.GetCString(), error.GetError(), error.AsCString());
659fbb76349SGreg Clayton   return error;
660fbb76349SGreg Clayton }
661fbb76349SGreg Clayton 
GetFileExists(const FileSpec & file_spec)662b9c1b51eSKate Stone bool PlatformRemoteGDBServer::GetFileExists(const FileSpec &file_spec) {
6638ccfcab3SPavel Labath   if (IsConnected())
6648ccfcab3SPavel Labath     return m_gdb_client_up->GetFileExists(file_spec);
6658ccfcab3SPavel Labath   return false;
666e0f8f574SDaniel Malea }
667e0f8f574SDaniel Malea 
RunShellCommand(llvm::StringRef shell,llvm::StringRef command,const FileSpec & working_dir,int * status_ptr,int * signo_ptr,std::string * command_output,const Timeout<std::micro> & timeout)66897206d57SZachary Turner Status PlatformRemoteGDBServer::RunShellCommand(
669addb5148SMed Ismail Bennani     llvm::StringRef shell, llvm::StringRef command,
670b9c1b51eSKate Stone     const FileSpec &
671b9c1b51eSKate Stone         working_dir, // Pass empty FileSpec to use the current working directory
672e0f8f574SDaniel Malea     int *status_ptr, // Pass NULL if you don't want the process exit status
673b9c1b51eSKate Stone     int *signo_ptr,  // Pass NULL if you don't want the signal that caused the
674b9c1b51eSKate Stone                      // process to exit
675b9c1b51eSKate Stone     std::string
676b9c1b51eSKate Stone         *command_output, // Pass NULL if you don't want the command output
67719dd1a0eSPavel Labath     const Timeout<std::micro> &timeout) {
6788ccfcab3SPavel Labath   if (!IsConnected())
6798ccfcab3SPavel Labath     return Status("Not connected.");
6808ccfcab3SPavel Labath   return m_gdb_client_up->RunShellCommand(command, working_dir, status_ptr,
68119dd1a0eSPavel Labath                                           signo_ptr, command_output, timeout);
682e0f8f574SDaniel Malea }
6832094dbf4SJason Molenda 
CalculateTrapHandlerSymbolNames()684b9c1b51eSKate Stone void PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames() {
6852094dbf4SJason Molenda   m_trap_handlers.push_back(ConstString("_sigtramp"));
6862094dbf4SJason Molenda }
68798d0a4b3SChaoren Lin 
GetRemoteUnixSignals()688b9c1b51eSKate Stone const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() {
68998d0a4b3SChaoren Lin   if (!IsConnected())
69098d0a4b3SChaoren Lin     return Platform::GetRemoteUnixSignals();
69198d0a4b3SChaoren Lin 
69298d0a4b3SChaoren Lin   if (m_remote_signals_sp)
69398d0a4b3SChaoren Lin     return m_remote_signals_sp;
69498d0a4b3SChaoren Lin 
69505097246SAdrian Prantl   // If packet not implemented or JSON failed to parse, we'll guess the signal
69605097246SAdrian Prantl   // set based on the remote architecture.
69798d0a4b3SChaoren Lin   m_remote_signals_sp = UnixSignals::Create(GetRemoteSystemArchitecture());
69898d0a4b3SChaoren Lin 
69998d0a4b3SChaoren Lin   StringExtractorGDBRemote response;
700379f24ffSJim Ingham   auto result =
7018ccfcab3SPavel Labath       m_gdb_client_up->SendPacketAndWaitForResponse("jSignalsInfo", response);
70298d0a4b3SChaoren Lin 
70398d0a4b3SChaoren Lin   if (result != decltype(result)::Success ||
70498d0a4b3SChaoren Lin       response.GetResponseType() != response.eResponse)
70598d0a4b3SChaoren Lin     return m_remote_signals_sp;
70698d0a4b3SChaoren Lin 
707adcd0268SBenjamin Kramer   auto object_sp =
708adcd0268SBenjamin Kramer       StructuredData::ParseJSON(std::string(response.GetStringRef()));
70998d0a4b3SChaoren Lin   if (!object_sp || !object_sp->IsValid())
71098d0a4b3SChaoren Lin     return m_remote_signals_sp;
71198d0a4b3SChaoren Lin 
71298d0a4b3SChaoren Lin   auto array_sp = object_sp->GetAsArray();
71398d0a4b3SChaoren Lin   if (!array_sp || !array_sp->IsValid())
71498d0a4b3SChaoren Lin     return m_remote_signals_sp;
71598d0a4b3SChaoren Lin 
71698d0a4b3SChaoren Lin   auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>();
71798d0a4b3SChaoren Lin 
71898d0a4b3SChaoren Lin   bool done = array_sp->ForEach(
719b9c1b51eSKate Stone       [&remote_signals_sp](StructuredData::Object *object) -> bool {
72098d0a4b3SChaoren Lin         if (!object || !object->IsValid())
72198d0a4b3SChaoren Lin           return false;
72298d0a4b3SChaoren Lin 
72398d0a4b3SChaoren Lin         auto dict = object->GetAsDictionary();
72498d0a4b3SChaoren Lin         if (!dict || !dict->IsValid())
72598d0a4b3SChaoren Lin           return false;
72698d0a4b3SChaoren Lin 
72798d0a4b3SChaoren Lin         // Signal number and signal name are required.
72898d0a4b3SChaoren Lin         int signo;
72998d0a4b3SChaoren Lin         if (!dict->GetValueForKeyAsInteger("signo", signo))
73098d0a4b3SChaoren Lin           return false;
73198d0a4b3SChaoren Lin 
7322833321fSZachary Turner         llvm::StringRef name;
73398d0a4b3SChaoren Lin         if (!dict->GetValueForKeyAsString("name", name))
73498d0a4b3SChaoren Lin           return false;
73598d0a4b3SChaoren Lin 
73698d0a4b3SChaoren Lin         // We can live without short_name, description, etc.
73798d0a4b3SChaoren Lin         bool suppress{false};
73879be9e8cSMohit K. Bhakkad         auto object_sp = dict->GetValueForKey("suppress");
73998d0a4b3SChaoren Lin         if (object_sp && object_sp->IsValid())
74098d0a4b3SChaoren Lin           suppress = object_sp->GetBooleanValue();
74198d0a4b3SChaoren Lin 
74298d0a4b3SChaoren Lin         bool stop{false};
74398d0a4b3SChaoren Lin         object_sp = dict->GetValueForKey("stop");
74498d0a4b3SChaoren Lin         if (object_sp && object_sp->IsValid())
74598d0a4b3SChaoren Lin           stop = object_sp->GetBooleanValue();
74698d0a4b3SChaoren Lin 
74798d0a4b3SChaoren Lin         bool notify{false};
74898d0a4b3SChaoren Lin         object_sp = dict->GetValueForKey("notify");
74998d0a4b3SChaoren Lin         if (object_sp && object_sp->IsValid())
75098d0a4b3SChaoren Lin           notify = object_sp->GetBooleanValue();
75198d0a4b3SChaoren Lin 
7520542d152SKazu Hirata         std::string description;
75398d0a4b3SChaoren Lin         object_sp = dict->GetValueForKey("description");
75498d0a4b3SChaoren Lin         if (object_sp && object_sp->IsValid())
755adcd0268SBenjamin Kramer           description = std::string(object_sp->GetStringValue());
75698d0a4b3SChaoren Lin 
7572833321fSZachary Turner         remote_signals_sp->AddSignal(signo, name.str().c_str(), suppress, stop,
758b9c1b51eSKate Stone                                      notify, description.c_str());
75998d0a4b3SChaoren Lin         return true;
76098d0a4b3SChaoren Lin       });
76198d0a4b3SChaoren Lin 
76298d0a4b3SChaoren Lin   if (done)
76398d0a4b3SChaoren Lin     m_remote_signals_sp = std::move(remote_signals_sp);
76498d0a4b3SChaoren Lin 
76598d0a4b3SChaoren Lin   return m_remote_signals_sp;
76698d0a4b3SChaoren Lin }
76754971856SOleksiy Vyalov 
MakeGdbServerUrl(const std::string & platform_scheme,const std::string & platform_hostname,uint16_t port,const char * socket_name)768b9c1b51eSKate Stone std::string PlatformRemoteGDBServer::MakeGdbServerUrl(
769b9c1b51eSKate Stone     const std::string &platform_scheme, const std::string &platform_hostname,
770b9c1b51eSKate Stone     uint16_t port, const char *socket_name) {
771b9c1b51eSKate Stone   const char *override_scheme =
772b9c1b51eSKate Stone       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_SCHEME");
773b9c1b51eSKate Stone   const char *override_hostname =
774b9c1b51eSKate Stone       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
775b9c1b51eSKate Stone   const char *port_offset_c_str =
776b9c1b51eSKate Stone       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
77754971856SOleksiy Vyalov   int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
77854971856SOleksiy Vyalov 
779e7eabbb5SOleksiy Vyalov   return MakeUrl(override_scheme ? override_scheme : platform_scheme.c_str(),
780b9c1b51eSKate Stone                  override_hostname ? override_hostname
781b9c1b51eSKate Stone                                    : platform_hostname.c_str(),
782b9c1b51eSKate Stone                  port + port_offset, socket_name);
78354971856SOleksiy Vyalov }
78454971856SOleksiy Vyalov 
MakeUrl(const char * scheme,const char * hostname,uint16_t port,const char * path)785b9c1b51eSKate Stone std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme,
78654971856SOleksiy Vyalov                                              const char *hostname,
787b9c1b51eSKate Stone                                              uint16_t port, const char *path) {
78854971856SOleksiy Vyalov   StreamString result;
7894b284b9cSPavel Labath   result.Printf("%s://[%s]", scheme, hostname);
7909fe526c2SOleksiy Vyalov   if (port != 0)
7919fe526c2SOleksiy Vyalov     result.Printf(":%u", port);
792e7eabbb5SOleksiy Vyalov   if (path)
793e7eabbb5SOleksiy Vyalov     result.Write(path, strlen(path));
794adcd0268SBenjamin Kramer   return std::string(result.GetString());
79554971856SOleksiy Vyalov }
796ccd6cffbSTamas Berghammer 
ConnectToWaitingProcesses(Debugger & debugger,Status & error)797b9c1b51eSKate Stone size_t PlatformRemoteGDBServer::ConnectToWaitingProcesses(Debugger &debugger,
79897206d57SZachary Turner                                                           Status &error) {
79919d80679SMohit K. Bhakkad   std::vector<std::string> connection_urls;
80019d80679SMohit K. Bhakkad   GetPendingGdbServerList(connection_urls);
80119d80679SMohit K. Bhakkad 
802b9c1b51eSKate Stone   for (size_t i = 0; i < connection_urls.size(); ++i) {
803463863ffSPavel Labath     ConnectProcess(connection_urls[i].c_str(), "gdb-remote", debugger, nullptr, error);
80419d80679SMohit K. Bhakkad     if (error.Fail())
80519d80679SMohit K. Bhakkad       return i; // We already connected to i process succsessfully
80619d80679SMohit K. Bhakkad   }
80719d80679SMohit K. Bhakkad   return connection_urls.size();
80819d80679SMohit K. Bhakkad }
80919d80679SMohit K. Bhakkad 
GetPendingGdbServerList(std::vector<std::string> & connection_urls)810b9c1b51eSKate Stone size_t PlatformRemoteGDBServer::GetPendingGdbServerList(
811b9c1b51eSKate Stone     std::vector<std::string> &connection_urls) {
812ccd6cffbSTamas Berghammer   std::vector<std::pair<uint16_t, std::string>> remote_servers;
8138ccfcab3SPavel Labath   if (!IsConnected())
8148ccfcab3SPavel Labath     return 0;
8158ccfcab3SPavel Labath   m_gdb_client_up->QueryGDBServer(remote_servers);
816b9c1b51eSKate Stone   for (const auto &gdbserver : remote_servers) {
817b9c1b51eSKate Stone     const char *socket_name_cstr =
818b9c1b51eSKate Stone         gdbserver.second.empty() ? nullptr : gdbserver.second.c_str();
819b9c1b51eSKate Stone     connection_urls.emplace_back(
820b9c1b51eSKate Stone         MakeGdbServerUrl(m_platform_scheme, m_platform_hostname,
821b9c1b51eSKate Stone                          gdbserver.first, socket_name_cstr));
822ccd6cffbSTamas Berghammer   }
823ccd6cffbSTamas Berghammer   return connection_urls.size();
824ccd6cffbSTamas Berghammer }
825