blob: 3521ddafbb1663b68b3c8458bb49236f49f502af [file] [log] [blame]
Tamas Berghammere13c2732015-02-11 10:29:30 +00001//===-- GDBRemoteCommunicationServerPlatform.cpp ----------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "GDBRemoteCommunicationServerPlatform.h"
11
12#include <errno.h>
13
Tamas Berghammere13c2732015-02-11 10:29:30 +000014#include <chrono>
Pavel Labath6b3c8bb2018-04-05 16:23:54 +000015#include <csignal>
Kate Stoneb9c1b512016-09-06 20:57:50 +000016#include <cstring>
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +000017#include <mutex>
18#include <sstream>
Tamas Berghammere13c2732015-02-11 10:29:30 +000019
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +000020#include "llvm/Support/FileSystem.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000021#include "llvm/Support/Threading.h"
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +000022
Tamas Berghammere13c2732015-02-11 10:29:30 +000023#include "lldb/Host/Config.h"
24#include "lldb/Host/ConnectionFileDescriptor.h"
25#include "lldb/Host/Host.h"
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +000026#include "lldb/Host/HostInfo.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000027#include "lldb/Target/FileAction.h"
28#include "lldb/Target/Platform.h"
29#include "lldb/Target/Process.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000030#include "lldb/Target/UnixSignals.h"
Tamas Berghammerccd6cff2015-12-08 14:08:19 +000031#include "lldb/Utility/JSON.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000032#include "lldb/Utility/Log.h"
Zachary Turnerfb1a0a02017-03-06 18:34:25 +000033#include "lldb/Utility/StreamGDBRemote.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000034#include "lldb/Utility/StreamString.h"
Pavel Labathf2a8bcc2017-06-27 10:45:31 +000035#include "lldb/Utility/StructuredData.h"
Pavel Labath5f7e5832017-02-10 12:21:22 +000036#include "lldb/Utility/UriParser.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000037
Pavel Labath9af71b32018-03-20 16:14:00 +000038#include "lldb/Utility/StringExtractorGDBRemote.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000039
40using namespace lldb;
41using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000042using namespace lldb_private::process_gdb_remote;
Tamas Berghammere13c2732015-02-11 10:29:30 +000043
44//----------------------------------------------------------------------
45// GDBRemoteCommunicationServerPlatform constructor
46//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000047GDBRemoteCommunicationServerPlatform::GDBRemoteCommunicationServerPlatform(
48 const Socket::SocketProtocol socket_protocol, const char *socket_scheme)
49 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
50 "gdb-remote.server.rx_packet"),
51 m_socket_protocol(socket_protocol), m_socket_scheme(socket_scheme),
52 m_spawned_pids_mutex(), m_port_map(), m_port_offset(0) {
53 m_pending_gdb_server.pid = LLDB_INVALID_PROCESS_ID;
54 m_pending_gdb_server.port = 0;
Tamas Berghammer372810f2015-12-08 14:27:40 +000055
Kate Stoneb9c1b512016-09-06 20:57:50 +000056 RegisterMemberFunctionHandler(
57 StringExtractorGDBRemote::eServerPacketType_qC,
58 &GDBRemoteCommunicationServerPlatform::Handle_qC);
59 RegisterMemberFunctionHandler(
60 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
61 &GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir);
62 RegisterMemberFunctionHandler(
63 StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer,
64 &GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer);
65 RegisterMemberFunctionHandler(
66 StringExtractorGDBRemote::eServerPacketType_qQueryGDBServer,
67 &GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer);
68 RegisterMemberFunctionHandler(
69 StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess,
70 &GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess);
71 RegisterMemberFunctionHandler(
72 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
73 &GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo);
74 RegisterMemberFunctionHandler(
75 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
76 &GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir);
77 RegisterMemberFunctionHandler(
78 StringExtractorGDBRemote::eServerPacketType_jSignalsInfo,
79 &GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo);
Tamas Berghammere13c2732015-02-11 10:29:30 +000080
Kate Stoneb9c1b512016-09-06 20:57:50 +000081 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
Zachary Turner97206d52017-05-12 04:51:55 +000082 [](StringExtractorGDBRemote packet, Status &error,
Zachary Turner3bc714b2017-03-02 00:05:25 +000083 bool &interrupt, bool &quit) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000084 error.SetErrorString("interrupt received");
85 interrupt = true;
86 return PacketResult::Success;
87 });
Tamas Berghammere13c2732015-02-11 10:29:30 +000088}
89
90//----------------------------------------------------------------------
91// Destructor
92//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000093GDBRemoteCommunicationServerPlatform::~GDBRemoteCommunicationServerPlatform() {}
Tamas Berghammere13c2732015-02-11 10:29:30 +000094
Zachary Turner97206d52017-05-12 04:51:55 +000095Status GDBRemoteCommunicationServerPlatform::LaunchGDBServer(
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 const lldb_private::Args &args, std::string hostname, lldb::pid_t &pid,
97 uint16_t &port, std::string &socket_name) {
98 if (port == UINT16_MAX)
99 port = GetNextAvailablePort();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000100
Adrian Prantl05097242018-04-30 16:49:04 +0000101 // Spawn a new thread to accept the port that gets bound after binding to
102 // port 0 (zero).
Tamas Berghammere13c2732015-02-11 10:29:30 +0000103
Adrian Prantl05097242018-04-30 16:49:04 +0000104 // ignore the hostname send from the remote end, just use the ip address that
105 // we're currently communicating with as the hostname
Tamas Berghammerccd6cff2015-12-08 14:08:19 +0000106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 // Spawn a debugserver and try to get the port it listens to.
108 ProcessLaunchInfo debugserver_launch_info;
109 if (hostname.empty())
110 hostname = "127.0.0.1";
Tamas Berghammere13c2732015-02-11 10:29:30 +0000111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
113 if (log)
114 log->Printf("Launching debugserver with: %s:%u...", hostname.c_str(), port);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000115
Adrian Prantl05097242018-04-30 16:49:04 +0000116 // Do not run in a new session so that it can not linger after the platform
117 // closes.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 debugserver_launch_info.SetLaunchInSeparateProcessGroup(false);
119 debugserver_launch_info.SetMonitorProcessCallback(
120 std::bind(&GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped,
121 this, std::placeholders::_1),
122 false);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +0000123
Zachary Turner245f7fd2016-11-17 01:38:02 +0000124 llvm::StringRef platform_scheme;
125 llvm::StringRef platform_ip;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 int platform_port;
Zachary Turner245f7fd2016-11-17 01:38:02 +0000127 llvm::StringRef platform_path;
Pavel Labathae7dd122017-10-27 04:53:24 +0000128 std::string platform_uri = GetConnection()->GetURI();
129 bool ok = UriParser::Parse(platform_uri, platform_scheme, platform_ip,
130 platform_port, platform_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 UNUSED_IF_ASSERT_DISABLED(ok);
132 assert(ok);
133
134 std::ostringstream url;
135// debugserver does not accept the URL scheme prefix.
Todd Fiala873a2ab2016-05-27 04:04:52 +0000136#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137 url << m_socket_scheme << "://";
Todd Fiala873a2ab2016-05-27 04:04:52 +0000138#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 uint16_t *port_ptr = &port;
140 if (m_socket_protocol == Socket::ProtocolTcp)
Zachary Turner245f7fd2016-11-17 01:38:02 +0000141 url << platform_ip.str() << ":" << port;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 else {
143 socket_name = GetDomainSocketPath("gdbserver").GetPath();
144 url << socket_name;
145 port_ptr = nullptr;
146 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +0000147
Zachary Turner97206d52017-05-12 04:51:55 +0000148 Status error = StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 url.str().c_str(), nullptr, debugserver_launch_info, port_ptr, &args, -1);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 pid = debugserver_launch_info.GetProcessID();
152 if (pid != LLDB_INVALID_PROCESS_ID) {
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000153 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 m_spawned_pids.insert(pid);
155 if (port > 0)
156 AssociatePortWithProcess(port, pid);
157 } else {
158 if (port > 0)
159 FreePort(port);
160 }
161 return error;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000162}
163
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164GDBRemoteCommunication::PacketResult
165GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer(
166 StringExtractorGDBRemote &packet) {
Adrian Prantl05097242018-04-30 16:49:04 +0000167 // Spawn a local debugserver as a platform so we can then attach or launch a
168 // process...
Tamas Berghammere13c2732015-02-11 10:29:30 +0000169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
171 if (log)
172 log->Printf("GDBRemoteCommunicationServerPlatform::%s() called",
173 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175 ConnectionFileDescriptor file_conn;
176 std::string hostname;
177 packet.SetFilePos(::strlen("qLaunchGDBServer;"));
178 llvm::StringRef name;
179 llvm::StringRef value;
180 uint16_t port = UINT16_MAX;
181 while (packet.GetNameColonValue(name, value)) {
182 if (name.equals("host"))
183 hostname = value;
184 else if (name.equals("port"))
185 value.getAsInteger(0, port);
186 }
187
188 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
189 std::string socket_name;
Zachary Turner97206d52017-05-12 04:51:55 +0000190 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191 LaunchGDBServer(Args(), hostname, debugserver_pid, port, socket_name);
192 if (error.Fail()) {
193 if (log)
194 log->Printf("GDBRemoteCommunicationServerPlatform::%s() debugserver "
195 "launch failed: %s",
196 __FUNCTION__, error.AsCString());
197 return SendErrorResponse(9);
198 }
199
200 if (log)
201 log->Printf("GDBRemoteCommunicationServerPlatform::%s() debugserver "
202 "launched successfully as pid %" PRIu64,
203 __FUNCTION__, debugserver_pid);
204
205 StreamGDBRemote response;
206 response.Printf("pid:%" PRIu64 ";port:%u;", debugserver_pid,
207 port + m_port_offset);
208 if (!socket_name.empty()) {
209 response.PutCString("socket_name:");
210 response.PutCStringAsRawHex8(socket_name.c_str());
211 response.PutChar(';');
212 }
213
214 PacketResult packet_result = SendPacketNoLock(response.GetString());
215 if (packet_result != PacketResult::Success) {
216 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
Aaron Smithe55850b2019-01-10 00:46:09 +0000217 Host::Kill(debugserver_pid, SIGINT);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000218 }
219 return packet_result;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220}
221
222GDBRemoteCommunication::PacketResult
223GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer(
224 StringExtractorGDBRemote &packet) {
225 if (m_pending_gdb_server.pid == LLDB_INVALID_PROCESS_ID)
226 return SendErrorResponse(4);
227
228 JSONObject::SP server_sp = std::make_shared<JSONObject>();
229 server_sp->SetObject("port",
230 std::make_shared<JSONNumber>(m_pending_gdb_server.port));
231 if (!m_pending_gdb_server.socket_name.empty())
232 server_sp->SetObject(
233 "socket_name",
234 std::make_shared<JSONString>(m_pending_gdb_server.socket_name.c_str()));
235
236 JSONArray server_list;
237 server_list.AppendObject(server_sp);
238
239 StreamGDBRemote response;
240 server_list.Write(response);
241
242 StreamGDBRemote escaped_response;
Zachary Turnerc1564272016-11-16 21:15:24 +0000243 escaped_response.PutEscapedBytes(response.GetString().data(),
244 response.GetSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 return SendPacketNoLock(escaped_response.GetString());
246}
247
248GDBRemoteCommunication::PacketResult
249GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess(
250 StringExtractorGDBRemote &packet) {
251 packet.SetFilePos(::strlen("qKillSpawnedProcess:"));
252
253 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
254
Adrian Prantl05097242018-04-30 16:49:04 +0000255 // verify that we know anything about this pid. Scope for locker
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 {
257 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
258 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
259 // not a pid we know about
260 return SendErrorResponse(10);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000261 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000263
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 // go ahead and attempt to kill the spawned process
265 if (KillSpawnedProcess(pid))
266 return SendOKResponse();
267 else
268 return SendErrorResponse(11);
269}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271bool GDBRemoteCommunicationServerPlatform::KillSpawnedProcess(lldb::pid_t pid) {
272 // make sure we know about this process
273 {
274 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
275 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
276 return false;
277 }
278
279 // first try a SIGTERM (standard kill)
280 Host::Kill(pid, SIGTERM);
281
282 // check if that worked
283 for (size_t i = 0; i < 10; ++i) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000284 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
286 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
287 // it is now killed
288 return true;
289 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000290 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291 usleep(10000);
292 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 // check one more time after the final usleep
295 {
296 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
297 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
298 return true;
299 }
300
Adrian Prantl05097242018-04-30 16:49:04 +0000301 // the launched process still lives. Now try killing it again, this time
302 // with an unblockable signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 Host::Kill(pid, SIGKILL);
304
305 for (size_t i = 0; i < 10; ++i) {
306 {
307 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
308 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
309 // it is now killed
310 return true;
311 }
312 }
313 usleep(10000);
314 }
315
Adrian Prantl05097242018-04-30 16:49:04 +0000316 // check one more time after the final usleep Scope for locker
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317 {
318 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
319 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
320 return true;
321 }
322
323 // no luck - the process still lives
324 return false;
325}
326
327GDBRemoteCommunication::PacketResult
328GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo(
329 StringExtractorGDBRemote &packet) {
330 lldb::pid_t pid = m_process_launch_info.GetProcessID();
331 m_process_launch_info.Clear();
332
333 if (pid == LLDB_INVALID_PROCESS_ID)
334 return SendErrorResponse(1);
335
336 ProcessInstanceInfo proc_info;
337 if (!Host::GetProcessInfo(pid, proc_info))
338 return SendErrorResponse(1);
339
340 StreamString response;
341 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
342 return SendPacketNoLock(response.GetString());
343}
344
345GDBRemoteCommunication::PacketResult
346GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir(
347 StringExtractorGDBRemote &packet) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348
Pavel Labath1d5855b2017-01-23 15:56:45 +0000349 llvm::SmallString<64> cwd;
350 if (std::error_code ec = llvm::sys::fs::current_path(cwd))
351 return SendErrorResponse(ec.value());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352
353 StreamString response;
Pavel Labath1d5855b2017-01-23 15:56:45 +0000354 response.PutBytesAsRawHex8(cwd.data(), cwd.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 return SendPacketNoLock(response.GetString());
356}
357
358GDBRemoteCommunication::PacketResult
359GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir(
360 StringExtractorGDBRemote &packet) {
361 packet.SetFilePos(::strlen("QSetWorkingDir:"));
362 std::string path;
363 packet.GetHexByteString(path);
364
Pavel Labath2d0c5b02017-01-25 11:10:52 +0000365 if (std::error_code ec = llvm::sys::fs::set_current_path(path))
366 return SendErrorResponse(ec.value());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 return SendOKResponse();
368}
369
370GDBRemoteCommunication::PacketResult
371GDBRemoteCommunicationServerPlatform::Handle_qC(
372 StringExtractorGDBRemote &packet) {
373 // NOTE: lldb should now be using qProcessInfo for process IDs. This path
374 // here
375 // should not be used. It is reporting process id instead of thread id. The
376 // correct answer doesn't seem to make much sense for lldb-platform.
377 // CONSIDER: flip to "unsupported".
378 lldb::pid_t pid = m_process_launch_info.GetProcessID();
379
380 StreamString response;
381 response.Printf("QC%" PRIx64, pid);
382
Adrian Prantl05097242018-04-30 16:49:04 +0000383 // If we launch a process and this GDB server is acting as a platform, then
384 // we need to clear the process launch state so we can start launching
385 // another process. In order to launch a process a bunch or packets need to
386 // be sent: environment packets, working directory, disable ASLR, and many
387 // more settings. When we launch a process we then need to know when to clear
388 // this information. Currently we are selecting the 'qC' packet as that
389 // packet which seems to make the most sense.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390 if (pid != LLDB_INVALID_PROCESS_ID) {
391 m_process_launch_info.Clear();
392 }
393
394 return SendPacketNoLock(response.GetString());
395}
396
397GDBRemoteCommunication::PacketResult
398GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo(
399 StringExtractorGDBRemote &packet) {
400 StructuredData::Array signal_array;
401
402 const auto &signals = Host::GetUnixSignals();
403 for (auto signo = signals->GetFirstSignalNumber();
404 signo != LLDB_INVALID_SIGNAL_NUMBER;
405 signo = signals->GetNextSignalNumber(signo)) {
406 auto dictionary = std::make_shared<StructuredData::Dictionary>();
407
408 dictionary->AddIntegerItem("signo", signo);
409 dictionary->AddStringItem("name", signals->GetSignalAsCString(signo));
410
411 bool suppress, stop, notify;
412 signals->GetSignalInfo(signo, suppress, stop, notify);
413 dictionary->AddBooleanItem("suppress", suppress);
414 dictionary->AddBooleanItem("stop", stop);
415 dictionary->AddBooleanItem("notify", notify);
416
417 signal_array.Push(dictionary);
418 }
419
420 StreamString response;
421 signal_array.Dump(response);
422 return SendPacketNoLock(response.GetString());
423}
424
425bool GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped(
426 lldb::pid_t pid) {
427 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
428 FreePortForProcess(pid);
429 m_spawned_pids.erase(pid);
430 return true;
431}
432
Zachary Turner97206d52017-05-12 04:51:55 +0000433Status GDBRemoteCommunicationServerPlatform::LaunchProcess() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 if (!m_process_launch_info.GetArguments().GetArgumentCount())
Zachary Turner97206d52017-05-12 04:51:55 +0000435 return Status("%s: no process command line specified to launch",
436 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437
Adrian Prantl05097242018-04-30 16:49:04 +0000438 // specify the process monitor if not already set. This should generally be
439 // what happens since we need to reap started processes.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440 if (!m_process_launch_info.GetMonitorProcessCallback())
441 m_process_launch_info.SetMonitorProcessCallback(
442 std::bind(
443 &GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped,
444 this, std::placeholders::_1),
445 false);
446
Zachary Turner97206d52017-05-12 04:51:55 +0000447 Status error = Host::LaunchProcess(m_process_launch_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 if (!error.Success()) {
449 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
450 m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000451 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 }
453
454 printf("Launched '%s' as process %" PRIu64 "...\n",
455 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
456 m_process_launch_info.GetProcessID());
457
Adrian Prantl05097242018-04-30 16:49:04 +0000458 // add to list of spawned processes. On an lldb-gdbserver, we would expect
459 // there to be only one.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 const auto pid = m_process_launch_info.GetProcessID();
461 if (pid != LLDB_INVALID_PROCESS_ID) {
462 // add to spawned pids
463 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
464 m_spawned_pids.insert(pid);
465 }
466
467 return error;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000468}
469
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470void GDBRemoteCommunicationServerPlatform::SetPortMap(PortMap &&port_map) {
471 m_port_map = port_map;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000472}
473
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474uint16_t GDBRemoteCommunicationServerPlatform::GetNextAvailablePort() {
475 if (m_port_map.empty())
476 return 0; // Bind to port zero and get a port, we didn't have any
477 // limitations
Tamas Berghammere13c2732015-02-11 10:29:30 +0000478
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479 for (auto &pair : m_port_map) {
480 if (pair.second == LLDB_INVALID_PROCESS_ID) {
481 pair.second = ~(lldb::pid_t)LLDB_INVALID_PROCESS_ID;
482 return pair.first;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000483 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 }
485 return UINT16_MAX;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000486}
487
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488bool GDBRemoteCommunicationServerPlatform::AssociatePortWithProcess(
489 uint16_t port, lldb::pid_t pid) {
490 PortMap::iterator pos = m_port_map.find(port);
491 if (pos != m_port_map.end()) {
492 pos->second = pid;
493 return true;
494 }
495 return false;
496}
497
498bool GDBRemoteCommunicationServerPlatform::FreePort(uint16_t port) {
499 PortMap::iterator pos = m_port_map.find(port);
500 if (pos != m_port_map.end()) {
501 pos->second = LLDB_INVALID_PROCESS_ID;
502 return true;
503 }
504 return false;
505}
506
507bool GDBRemoteCommunicationServerPlatform::FreePortForProcess(lldb::pid_t pid) {
508 if (!m_port_map.empty()) {
509 for (auto &pair : m_port_map) {
510 if (pair.second == pid) {
511 pair.second = LLDB_INVALID_PROCESS_ID;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000512 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000514 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 }
516 return false;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000517}
518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519const FileSpec &GDBRemoteCommunicationServerPlatform::GetDomainSocketDir() {
520 static FileSpec g_domainsocket_dir;
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000521 static llvm::once_flag g_once_flag;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000522
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000523 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 const char *domainsocket_dir_env =
525 ::getenv("LLDB_DEBUGSERVER_DOMAINSOCKET_DIR");
526 if (domainsocket_dir_env != nullptr)
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000527 g_domainsocket_dir = FileSpec(domainsocket_dir_env);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 else
Pavel Labath60f028f2018-06-19 15:09:07 +0000529 g_domainsocket_dir = HostInfo::GetProcessTempDir();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 });
Tamas Berghammere13c2732015-02-11 10:29:30 +0000531
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532 return g_domainsocket_dir;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +0000533}
534
535FileSpec
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536GDBRemoteCommunicationServerPlatform::GetDomainSocketPath(const char *prefix) {
Stella Stamenovab3f44ad2018-12-10 17:23:28 +0000537 llvm::SmallString<128> socket_path;
538 llvm::SmallString<128> socket_name(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 (llvm::StringRef(prefix) + ".%%%%%%").str());
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +0000540
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 FileSpec socket_path_spec(GetDomainSocketDir());
542 socket_path_spec.AppendPathComponent(socket_name.c_str());
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +0000543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 llvm::sys::fs::createUniqueFile(socket_path_spec.GetCString(), socket_path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000545 return FileSpec(socket_path.c_str());
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +0000546}
547
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548void GDBRemoteCommunicationServerPlatform::SetPortOffset(uint16_t port_offset) {
549 m_port_offset = port_offset;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000550}
Tamas Berghammerccd6cff2015-12-08 14:08:19 +0000551
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552void GDBRemoteCommunicationServerPlatform::SetPendingGdbServer(
553 lldb::pid_t pid, uint16_t port, const std::string &socket_name) {
554 m_pending_gdb_server.pid = pid;
555 m_pending_gdb_server.port = port;
556 m_pending_gdb_server.socket_name = socket_name;
Tamas Berghammerccd6cff2015-12-08 14:08:19 +0000557}