1 //===-- GDBRemoteCommunicationServerPlatform.cpp ----------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "GDBRemoteCommunicationServerPlatform.h" 10 11 #include <errno.h> 12 13 #include <chrono> 14 #include <csignal> 15 #include <cstring> 16 #include <mutex> 17 #include <sstream> 18 19 #include "llvm/Support/FileSystem.h" 20 #include "llvm/Support/Threading.h" 21 22 #include "lldb/Host/Config.h" 23 #include "lldb/Host/ConnectionFileDescriptor.h" 24 #include "lldb/Host/FileAction.h" 25 #include "lldb/Host/Host.h" 26 #include "lldb/Host/HostInfo.h" 27 #include "lldb/Target/Platform.h" 28 #include "lldb/Target/UnixSignals.h" 29 #include "lldb/Utility/JSON.h" 30 #include "lldb/Utility/Log.h" 31 #include "lldb/Utility/StreamGDBRemote.h" 32 #include "lldb/Utility/StreamString.h" 33 #include "lldb/Utility/StructuredData.h" 34 #include "lldb/Utility/UriParser.h" 35 36 #include "lldb/Utility/StringExtractorGDBRemote.h" 37 38 using namespace lldb; 39 using namespace lldb_private; 40 using namespace lldb_private::process_gdb_remote; 41 42 // GDBRemoteCommunicationServerPlatform constructor 43 GDBRemoteCommunicationServerPlatform::GDBRemoteCommunicationServerPlatform( 44 const Socket::SocketProtocol socket_protocol, const char *socket_scheme) 45 : GDBRemoteCommunicationServerCommon("gdb-remote.server", 46 "gdb-remote.server.rx_packet"), 47 m_socket_protocol(socket_protocol), m_socket_scheme(socket_scheme), 48 m_spawned_pids_mutex(), m_port_map(), m_port_offset(0) { 49 m_pending_gdb_server.pid = LLDB_INVALID_PROCESS_ID; 50 m_pending_gdb_server.port = 0; 51 52 RegisterMemberFunctionHandler( 53 StringExtractorGDBRemote::eServerPacketType_qC, 54 &GDBRemoteCommunicationServerPlatform::Handle_qC); 55 RegisterMemberFunctionHandler( 56 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir, 57 &GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir); 58 RegisterMemberFunctionHandler( 59 StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer, 60 &GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer); 61 RegisterMemberFunctionHandler( 62 StringExtractorGDBRemote::eServerPacketType_qQueryGDBServer, 63 &GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer); 64 RegisterMemberFunctionHandler( 65 StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess, 66 &GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess); 67 RegisterMemberFunctionHandler( 68 StringExtractorGDBRemote::eServerPacketType_qProcessInfo, 69 &GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo); 70 RegisterMemberFunctionHandler( 71 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir, 72 &GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir); 73 RegisterMemberFunctionHandler( 74 StringExtractorGDBRemote::eServerPacketType_jSignalsInfo, 75 &GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo); 76 77 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_interrupt, 78 [](StringExtractorGDBRemote packet, Status &error, 79 bool &interrupt, bool &quit) { 80 error.SetErrorString("interrupt received"); 81 interrupt = true; 82 return PacketResult::Success; 83 }); 84 } 85 86 // Destructor 87 GDBRemoteCommunicationServerPlatform::~GDBRemoteCommunicationServerPlatform() {} 88 89 Status GDBRemoteCommunicationServerPlatform::LaunchGDBServer( 90 const lldb_private::Args &args, std::string hostname, lldb::pid_t &pid, 91 uint16_t &port, std::string &socket_name) { 92 if (port == UINT16_MAX) 93 port = GetNextAvailablePort(); 94 95 // Spawn a new thread to accept the port that gets bound after binding to 96 // port 0 (zero). 97 98 // ignore the hostname send from the remote end, just use the ip address that 99 // we're currently communicating with as the hostname 100 101 // Spawn a debugserver and try to get the port it listens to. 102 ProcessLaunchInfo debugserver_launch_info; 103 if (hostname.empty()) 104 hostname = "127.0.0.1"; 105 106 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); 107 if (log) 108 log->Printf("Launching debugserver with: %s:%u...", hostname.c_str(), port); 109 110 // Do not run in a new session so that it can not linger after the platform 111 // closes. 112 debugserver_launch_info.SetLaunchInSeparateProcessGroup(false); 113 debugserver_launch_info.SetMonitorProcessCallback( 114 std::bind(&GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped, 115 this, std::placeholders::_1), 116 false); 117 118 std::ostringstream url; 119 // debugserver does not accept the URL scheme prefix. 120 #if !defined(__APPLE__) 121 url << m_socket_scheme << "://"; 122 #endif 123 uint16_t *port_ptr = &port; 124 if (m_socket_protocol == Socket::ProtocolTcp) { 125 llvm::StringRef platform_scheme; 126 llvm::StringRef platform_ip; 127 int platform_port; 128 llvm::StringRef platform_path; 129 std::string platform_uri = GetConnection()->GetURI(); 130 bool ok = UriParser::Parse(platform_uri, platform_scheme, platform_ip, 131 platform_port, platform_path); 132 UNUSED_IF_ASSERT_DISABLED(ok); 133 assert(ok); 134 url << platform_ip.str() << ":" << port; 135 } else { 136 socket_name = GetDomainSocketPath("gdbserver").GetPath(); 137 url << socket_name; 138 port_ptr = nullptr; 139 } 140 141 Status error = StartDebugserverProcess( 142 url.str().c_str(), nullptr, debugserver_launch_info, port_ptr, &args, -1); 143 144 pid = debugserver_launch_info.GetProcessID(); 145 if (pid != LLDB_INVALID_PROCESS_ID) { 146 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex); 147 m_spawned_pids.insert(pid); 148 if (port > 0) 149 AssociatePortWithProcess(port, pid); 150 } else { 151 if (port > 0) 152 FreePort(port); 153 } 154 return error; 155 } 156 157 GDBRemoteCommunication::PacketResult 158 GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer( 159 StringExtractorGDBRemote &packet) { 160 // Spawn a local debugserver as a platform so we can then attach or launch a 161 // process... 162 163 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); 164 if (log) 165 log->Printf("GDBRemoteCommunicationServerPlatform::%s() called", 166 __FUNCTION__); 167 168 ConnectionFileDescriptor file_conn; 169 std::string hostname; 170 packet.SetFilePos(::strlen("qLaunchGDBServer;")); 171 llvm::StringRef name; 172 llvm::StringRef value; 173 uint16_t port = UINT16_MAX; 174 while (packet.GetNameColonValue(name, value)) { 175 if (name.equals("host")) 176 hostname = value; 177 else if (name.equals("port")) 178 value.getAsInteger(0, port); 179 } 180 181 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID; 182 std::string socket_name; 183 Status error = 184 LaunchGDBServer(Args(), hostname, debugserver_pid, port, socket_name); 185 if (error.Fail()) { 186 if (log) 187 log->Printf("GDBRemoteCommunicationServerPlatform::%s() debugserver " 188 "launch failed: %s", 189 __FUNCTION__, error.AsCString()); 190 return SendErrorResponse(9); 191 } 192 193 if (log) 194 log->Printf("GDBRemoteCommunicationServerPlatform::%s() debugserver " 195 "launched successfully as pid %" PRIu64, 196 __FUNCTION__, debugserver_pid); 197 198 StreamGDBRemote response; 199 response.Printf("pid:%" PRIu64 ";port:%u;", debugserver_pid, 200 port + m_port_offset); 201 if (!socket_name.empty()) { 202 response.PutCString("socket_name:"); 203 response.PutStringAsRawHex8(socket_name); 204 response.PutChar(';'); 205 } 206 207 PacketResult packet_result = SendPacketNoLock(response.GetString()); 208 if (packet_result != PacketResult::Success) { 209 if (debugserver_pid != LLDB_INVALID_PROCESS_ID) 210 Host::Kill(debugserver_pid, SIGINT); 211 } 212 return packet_result; 213 } 214 215 GDBRemoteCommunication::PacketResult 216 GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer( 217 StringExtractorGDBRemote &packet) { 218 if (m_pending_gdb_server.pid == LLDB_INVALID_PROCESS_ID) 219 return SendErrorResponse(4); 220 221 JSONObject::SP server_sp = std::make_shared<JSONObject>(); 222 server_sp->SetObject("port", 223 std::make_shared<JSONNumber>(m_pending_gdb_server.port)); 224 if (!m_pending_gdb_server.socket_name.empty()) 225 server_sp->SetObject( 226 "socket_name", 227 std::make_shared<JSONString>(m_pending_gdb_server.socket_name.c_str())); 228 229 JSONArray server_list; 230 server_list.AppendObject(server_sp); 231 232 StreamGDBRemote response; 233 server_list.Write(response); 234 235 StreamGDBRemote escaped_response; 236 escaped_response.PutEscapedBytes(response.GetString().data(), 237 response.GetSize()); 238 return SendPacketNoLock(escaped_response.GetString()); 239 } 240 241 GDBRemoteCommunication::PacketResult 242 GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess( 243 StringExtractorGDBRemote &packet) { 244 packet.SetFilePos(::strlen("qKillSpawnedProcess:")); 245 246 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID); 247 248 // verify that we know anything about this pid. Scope for locker 249 { 250 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex); 251 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) { 252 // not a pid we know about 253 return SendErrorResponse(10); 254 } 255 } 256 257 // go ahead and attempt to kill the spawned process 258 if (KillSpawnedProcess(pid)) 259 return SendOKResponse(); 260 else 261 return SendErrorResponse(11); 262 } 263 264 bool GDBRemoteCommunicationServerPlatform::KillSpawnedProcess(lldb::pid_t pid) { 265 // make sure we know about this process 266 { 267 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex); 268 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 269 return false; 270 } 271 272 // first try a SIGTERM (standard kill) 273 Host::Kill(pid, SIGTERM); 274 275 // check if that worked 276 for (size_t i = 0; i < 10; ++i) { 277 { 278 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex); 279 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) { 280 // it is now killed 281 return true; 282 } 283 } 284 usleep(10000); 285 } 286 287 // check one more time after the final usleep 288 { 289 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex); 290 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 291 return true; 292 } 293 294 // the launched process still lives. Now try killing it again, this time 295 // with an unblockable signal. 296 Host::Kill(pid, SIGKILL); 297 298 for (size_t i = 0; i < 10; ++i) { 299 { 300 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex); 301 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) { 302 // it is now killed 303 return true; 304 } 305 } 306 usleep(10000); 307 } 308 309 // check one more time after the final usleep Scope for locker 310 { 311 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex); 312 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) 313 return true; 314 } 315 316 // no luck - the process still lives 317 return false; 318 } 319 320 GDBRemoteCommunication::PacketResult 321 GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo( 322 StringExtractorGDBRemote &packet) { 323 lldb::pid_t pid = m_process_launch_info.GetProcessID(); 324 m_process_launch_info.Clear(); 325 326 if (pid == LLDB_INVALID_PROCESS_ID) 327 return SendErrorResponse(1); 328 329 ProcessInstanceInfo proc_info; 330 if (!Host::GetProcessInfo(pid, proc_info)) 331 return SendErrorResponse(1); 332 333 StreamString response; 334 CreateProcessInfoResponse_DebugServerStyle(proc_info, response); 335 return SendPacketNoLock(response.GetString()); 336 } 337 338 GDBRemoteCommunication::PacketResult 339 GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir( 340 StringExtractorGDBRemote &packet) { 341 342 llvm::SmallString<64> cwd; 343 if (std::error_code ec = llvm::sys::fs::current_path(cwd)) 344 return SendErrorResponse(ec.value()); 345 346 StreamString response; 347 response.PutBytesAsRawHex8(cwd.data(), cwd.size()); 348 return SendPacketNoLock(response.GetString()); 349 } 350 351 GDBRemoteCommunication::PacketResult 352 GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir( 353 StringExtractorGDBRemote &packet) { 354 packet.SetFilePos(::strlen("QSetWorkingDir:")); 355 std::string path; 356 packet.GetHexByteString(path); 357 358 if (std::error_code ec = llvm::sys::fs::set_current_path(path)) 359 return SendErrorResponse(ec.value()); 360 return SendOKResponse(); 361 } 362 363 GDBRemoteCommunication::PacketResult 364 GDBRemoteCommunicationServerPlatform::Handle_qC( 365 StringExtractorGDBRemote &packet) { 366 // NOTE: lldb should now be using qProcessInfo for process IDs. This path 367 // here 368 // should not be used. It is reporting process id instead of thread id. The 369 // correct answer doesn't seem to make much sense for lldb-platform. 370 // CONSIDER: flip to "unsupported". 371 lldb::pid_t pid = m_process_launch_info.GetProcessID(); 372 373 StreamString response; 374 response.Printf("QC%" PRIx64, pid); 375 376 // If we launch a process and this GDB server is acting as a platform, then 377 // we need to clear the process launch state so we can start launching 378 // another process. In order to launch a process a bunch or packets need to 379 // be sent: environment packets, working directory, disable ASLR, and many 380 // more settings. When we launch a process we then need to know when to clear 381 // this information. Currently we are selecting the 'qC' packet as that 382 // packet which seems to make the most sense. 383 if (pid != LLDB_INVALID_PROCESS_ID) { 384 m_process_launch_info.Clear(); 385 } 386 387 return SendPacketNoLock(response.GetString()); 388 } 389 390 GDBRemoteCommunication::PacketResult 391 GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo( 392 StringExtractorGDBRemote &packet) { 393 StructuredData::Array signal_array; 394 395 lldb::UnixSignalsSP signals = UnixSignals::CreateForHost(); 396 for (auto signo = signals->GetFirstSignalNumber(); 397 signo != LLDB_INVALID_SIGNAL_NUMBER; 398 signo = signals->GetNextSignalNumber(signo)) { 399 auto dictionary = std::make_shared<StructuredData::Dictionary>(); 400 401 dictionary->AddIntegerItem("signo", signo); 402 dictionary->AddStringItem("name", signals->GetSignalAsCString(signo)); 403 404 bool suppress, stop, notify; 405 signals->GetSignalInfo(signo, suppress, stop, notify); 406 dictionary->AddBooleanItem("suppress", suppress); 407 dictionary->AddBooleanItem("stop", stop); 408 dictionary->AddBooleanItem("notify", notify); 409 410 signal_array.Push(dictionary); 411 } 412 413 StreamString response; 414 signal_array.Dump(response); 415 return SendPacketNoLock(response.GetString()); 416 } 417 418 bool GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped( 419 lldb::pid_t pid) { 420 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex); 421 FreePortForProcess(pid); 422 m_spawned_pids.erase(pid); 423 return true; 424 } 425 426 Status GDBRemoteCommunicationServerPlatform::LaunchProcess() { 427 if (!m_process_launch_info.GetArguments().GetArgumentCount()) 428 return Status("%s: no process command line specified to launch", 429 __FUNCTION__); 430 431 // specify the process monitor if not already set. This should generally be 432 // what happens since we need to reap started processes. 433 if (!m_process_launch_info.GetMonitorProcessCallback()) 434 m_process_launch_info.SetMonitorProcessCallback( 435 std::bind( 436 &GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped, 437 this, std::placeholders::_1), 438 false); 439 440 Status error = Host::LaunchProcess(m_process_launch_info); 441 if (!error.Success()) { 442 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__, 443 m_process_launch_info.GetArguments().GetArgumentAtIndex(0)); 444 return error; 445 } 446 447 printf("Launched '%s' as process %" PRIu64 "...\n", 448 m_process_launch_info.GetArguments().GetArgumentAtIndex(0), 449 m_process_launch_info.GetProcessID()); 450 451 // add to list of spawned processes. On an lldb-gdbserver, we would expect 452 // there to be only one. 453 const auto pid = m_process_launch_info.GetProcessID(); 454 if (pid != LLDB_INVALID_PROCESS_ID) { 455 // add to spawned pids 456 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex); 457 m_spawned_pids.insert(pid); 458 } 459 460 return error; 461 } 462 463 void GDBRemoteCommunicationServerPlatform::SetPortMap(PortMap &&port_map) { 464 m_port_map = port_map; 465 } 466 467 uint16_t GDBRemoteCommunicationServerPlatform::GetNextAvailablePort() { 468 if (m_port_map.empty()) 469 return 0; // Bind to port zero and get a port, we didn't have any 470 // limitations 471 472 for (auto &pair : m_port_map) { 473 if (pair.second == LLDB_INVALID_PROCESS_ID) { 474 pair.second = ~(lldb::pid_t)LLDB_INVALID_PROCESS_ID; 475 return pair.first; 476 } 477 } 478 return UINT16_MAX; 479 } 480 481 bool GDBRemoteCommunicationServerPlatform::AssociatePortWithProcess( 482 uint16_t port, lldb::pid_t pid) { 483 PortMap::iterator pos = m_port_map.find(port); 484 if (pos != m_port_map.end()) { 485 pos->second = pid; 486 return true; 487 } 488 return false; 489 } 490 491 bool GDBRemoteCommunicationServerPlatform::FreePort(uint16_t port) { 492 PortMap::iterator pos = m_port_map.find(port); 493 if (pos != m_port_map.end()) { 494 pos->second = LLDB_INVALID_PROCESS_ID; 495 return true; 496 } 497 return false; 498 } 499 500 bool GDBRemoteCommunicationServerPlatform::FreePortForProcess(lldb::pid_t pid) { 501 if (!m_port_map.empty()) { 502 for (auto &pair : m_port_map) { 503 if (pair.second == pid) { 504 pair.second = LLDB_INVALID_PROCESS_ID; 505 return true; 506 } 507 } 508 } 509 return false; 510 } 511 512 const FileSpec &GDBRemoteCommunicationServerPlatform::GetDomainSocketDir() { 513 static FileSpec g_domainsocket_dir; 514 static llvm::once_flag g_once_flag; 515 516 llvm::call_once(g_once_flag, []() { 517 const char *domainsocket_dir_env = 518 ::getenv("LLDB_DEBUGSERVER_DOMAINSOCKET_DIR"); 519 if (domainsocket_dir_env != nullptr) 520 g_domainsocket_dir = FileSpec(domainsocket_dir_env); 521 else 522 g_domainsocket_dir = HostInfo::GetProcessTempDir(); 523 }); 524 525 return g_domainsocket_dir; 526 } 527 528 FileSpec 529 GDBRemoteCommunicationServerPlatform::GetDomainSocketPath(const char *prefix) { 530 llvm::SmallString<128> socket_path; 531 llvm::SmallString<128> socket_name( 532 (llvm::StringRef(prefix) + ".%%%%%%").str()); 533 534 FileSpec socket_path_spec(GetDomainSocketDir()); 535 socket_path_spec.AppendPathComponent(socket_name.c_str()); 536 537 llvm::sys::fs::createUniqueFile(socket_path_spec.GetCString(), socket_path); 538 return FileSpec(socket_path.c_str()); 539 } 540 541 void GDBRemoteCommunicationServerPlatform::SetPortOffset(uint16_t port_offset) { 542 m_port_offset = port_offset; 543 } 544 545 void GDBRemoteCommunicationServerPlatform::SetPendingGdbServer( 546 lldb::pid_t pid, uint16_t port, const std::string &socket_name) { 547 m_pending_gdb_server.pid = pid; 548 m_pending_gdb_server.port = port; 549 m_pending_gdb_server.socket_name = socket_name; 550 } 551