1 //===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===// 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 <cerrno> 10 11 #include "lldb/Host/Config.h" 12 13 14 #include <chrono> 15 #include <cstring> 16 #include <limits> 17 #include <thread> 18 19 #include "GDBRemoteCommunicationServerLLGS.h" 20 #include "lldb/Host/ConnectionFileDescriptor.h" 21 #include "lldb/Host/Debug.h" 22 #include "lldb/Host/File.h" 23 #include "lldb/Host/FileAction.h" 24 #include "lldb/Host/FileSystem.h" 25 #include "lldb/Host/Host.h" 26 #include "lldb/Host/HostInfo.h" 27 #include "lldb/Host/PosixApi.h" 28 #include "lldb/Host/Socket.h" 29 #include "lldb/Host/common/NativeProcessProtocol.h" 30 #include "lldb/Host/common/NativeRegisterContext.h" 31 #include "lldb/Host/common/NativeThreadProtocol.h" 32 #include "lldb/Target/MemoryRegionInfo.h" 33 #include "lldb/Utility/Args.h" 34 #include "lldb/Utility/DataBuffer.h" 35 #include "lldb/Utility/Endian.h" 36 #include "lldb/Utility/GDBRemote.h" 37 #include "lldb/Utility/LLDBAssert.h" 38 #include "lldb/Utility/LLDBLog.h" 39 #include "lldb/Utility/Log.h" 40 #include "lldb/Utility/RegisterValue.h" 41 #include "lldb/Utility/State.h" 42 #include "lldb/Utility/StreamString.h" 43 #include "lldb/Utility/UnimplementedError.h" 44 #include "lldb/Utility/UriParser.h" 45 #include "llvm/ADT/Triple.h" 46 #include "llvm/Support/JSON.h" 47 #include "llvm/Support/ScopedPrinter.h" 48 49 #include "ProcessGDBRemote.h" 50 #include "ProcessGDBRemoteLog.h" 51 #include "lldb/Utility/StringExtractorGDBRemote.h" 52 53 using namespace lldb; 54 using namespace lldb_private; 55 using namespace lldb_private::process_gdb_remote; 56 using namespace llvm; 57 58 // GDBRemote Errors 59 60 namespace { 61 enum GDBRemoteServerError { 62 // Set to the first unused error number in literal form below 63 eErrorFirst = 29, 64 eErrorNoProcess = eErrorFirst, 65 eErrorResume, 66 eErrorExitStatus 67 }; 68 } 69 70 // GDBRemoteCommunicationServerLLGS constructor 71 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS( 72 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory) 73 : GDBRemoteCommunicationServerCommon("gdb-remote.server", 74 "gdb-remote.server.rx_packet"), 75 m_mainloop(mainloop), m_process_factory(process_factory), 76 m_current_process(nullptr), m_continue_process(nullptr), 77 m_stdio_communication("process.stdio") { 78 RegisterPacketHandlers(); 79 } 80 81 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() { 82 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C, 83 &GDBRemoteCommunicationServerLLGS::Handle_C); 84 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c, 85 &GDBRemoteCommunicationServerLLGS::Handle_c); 86 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D, 87 &GDBRemoteCommunicationServerLLGS::Handle_D); 88 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H, 89 &GDBRemoteCommunicationServerLLGS::Handle_H); 90 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I, 91 &GDBRemoteCommunicationServerLLGS::Handle_I); 92 RegisterMemberFunctionHandler( 93 StringExtractorGDBRemote::eServerPacketType_interrupt, 94 &GDBRemoteCommunicationServerLLGS::Handle_interrupt); 95 RegisterMemberFunctionHandler( 96 StringExtractorGDBRemote::eServerPacketType_m, 97 &GDBRemoteCommunicationServerLLGS::Handle_memory_read); 98 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M, 99 &GDBRemoteCommunicationServerLLGS::Handle_M); 100 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M, 101 &GDBRemoteCommunicationServerLLGS::Handle__M); 102 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m, 103 &GDBRemoteCommunicationServerLLGS::Handle__m); 104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p, 105 &GDBRemoteCommunicationServerLLGS::Handle_p); 106 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P, 107 &GDBRemoteCommunicationServerLLGS::Handle_P); 108 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC, 109 &GDBRemoteCommunicationServerLLGS::Handle_qC); 110 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_T, 111 &GDBRemoteCommunicationServerLLGS::Handle_T); 112 RegisterMemberFunctionHandler( 113 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo, 114 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo); 115 RegisterMemberFunctionHandler( 116 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress, 117 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress); 118 RegisterMemberFunctionHandler( 119 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir, 120 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir); 121 RegisterMemberFunctionHandler( 122 StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported, 123 &GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported); 124 RegisterMemberFunctionHandler( 125 StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply, 126 &GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply); 127 RegisterMemberFunctionHandler( 128 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo, 129 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo); 130 RegisterMemberFunctionHandler( 131 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported, 132 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported); 133 RegisterMemberFunctionHandler( 134 StringExtractorGDBRemote::eServerPacketType_qProcessInfo, 135 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo); 136 RegisterMemberFunctionHandler( 137 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo, 138 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo); 139 RegisterMemberFunctionHandler( 140 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState, 141 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState); 142 RegisterMemberFunctionHandler( 143 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState, 144 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState); 145 RegisterMemberFunctionHandler( 146 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR, 147 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR); 148 RegisterMemberFunctionHandler( 149 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir, 150 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir); 151 RegisterMemberFunctionHandler( 152 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo, 153 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo); 154 RegisterMemberFunctionHandler( 155 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo, 156 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo); 157 RegisterMemberFunctionHandler( 158 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo, 159 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo); 160 RegisterMemberFunctionHandler( 161 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo, 162 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo); 163 RegisterMemberFunctionHandler( 164 StringExtractorGDBRemote::eServerPacketType_qXfer, 165 &GDBRemoteCommunicationServerLLGS::Handle_qXfer); 166 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s, 167 &GDBRemoteCommunicationServerLLGS::Handle_s); 168 RegisterMemberFunctionHandler( 169 StringExtractorGDBRemote::eServerPacketType_stop_reason, 170 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ? 171 RegisterMemberFunctionHandler( 172 StringExtractorGDBRemote::eServerPacketType_vAttach, 173 &GDBRemoteCommunicationServerLLGS::Handle_vAttach); 174 RegisterMemberFunctionHandler( 175 StringExtractorGDBRemote::eServerPacketType_vAttachWait, 176 &GDBRemoteCommunicationServerLLGS::Handle_vAttachWait); 177 RegisterMemberFunctionHandler( 178 StringExtractorGDBRemote::eServerPacketType_qVAttachOrWaitSupported, 179 &GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported); 180 RegisterMemberFunctionHandler( 181 StringExtractorGDBRemote::eServerPacketType_vAttachOrWait, 182 &GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait); 183 RegisterMemberFunctionHandler( 184 StringExtractorGDBRemote::eServerPacketType_vCont, 185 &GDBRemoteCommunicationServerLLGS::Handle_vCont); 186 RegisterMemberFunctionHandler( 187 StringExtractorGDBRemote::eServerPacketType_vCont_actions, 188 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions); 189 RegisterMemberFunctionHandler( 190 StringExtractorGDBRemote::eServerPacketType_vRun, 191 &GDBRemoteCommunicationServerLLGS::Handle_vRun); 192 RegisterMemberFunctionHandler( 193 StringExtractorGDBRemote::eServerPacketType_x, 194 &GDBRemoteCommunicationServerLLGS::Handle_memory_read); 195 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z, 196 &GDBRemoteCommunicationServerLLGS::Handle_Z); 197 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z, 198 &GDBRemoteCommunicationServerLLGS::Handle_z); 199 RegisterMemberFunctionHandler( 200 StringExtractorGDBRemote::eServerPacketType_QPassSignals, 201 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals); 202 203 RegisterMemberFunctionHandler( 204 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupported, 205 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported); 206 RegisterMemberFunctionHandler( 207 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStart, 208 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart); 209 RegisterMemberFunctionHandler( 210 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStop, 211 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop); 212 RegisterMemberFunctionHandler( 213 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetState, 214 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState); 215 RegisterMemberFunctionHandler( 216 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetBinaryData, 217 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData); 218 219 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g, 220 &GDBRemoteCommunicationServerLLGS::Handle_g); 221 222 RegisterMemberFunctionHandler( 223 StringExtractorGDBRemote::eServerPacketType_qMemTags, 224 &GDBRemoteCommunicationServerLLGS::Handle_qMemTags); 225 226 RegisterMemberFunctionHandler( 227 StringExtractorGDBRemote::eServerPacketType_QMemTags, 228 &GDBRemoteCommunicationServerLLGS::Handle_QMemTags); 229 230 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k, 231 [this](StringExtractorGDBRemote packet, Status &error, 232 bool &interrupt, bool &quit) { 233 quit = true; 234 return this->Handle_k(packet); 235 }); 236 237 RegisterMemberFunctionHandler( 238 StringExtractorGDBRemote::eServerPacketType_vKill, 239 &GDBRemoteCommunicationServerLLGS::Handle_vKill); 240 241 RegisterMemberFunctionHandler( 242 StringExtractorGDBRemote::eServerPacketType_qLLDBSaveCore, 243 &GDBRemoteCommunicationServerLLGS::Handle_qSaveCore); 244 245 RegisterMemberFunctionHandler( 246 StringExtractorGDBRemote::eServerPacketType_QNonStop, 247 &GDBRemoteCommunicationServerLLGS::Handle_QNonStop); 248 RegisterMemberFunctionHandler( 249 StringExtractorGDBRemote::eServerPacketType_vStopped, 250 &GDBRemoteCommunicationServerLLGS::Handle_vStopped); 251 RegisterMemberFunctionHandler( 252 StringExtractorGDBRemote::eServerPacketType_vCtrlC, 253 &GDBRemoteCommunicationServerLLGS::Handle_vCtrlC); 254 } 255 256 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) { 257 m_process_launch_info = info; 258 } 259 260 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() { 261 Log *log = GetLog(LLDBLog::Process); 262 263 if (!m_process_launch_info.GetArguments().GetArgumentCount()) 264 return Status("%s: no process command line specified to launch", 265 __FUNCTION__); 266 267 const bool should_forward_stdio = 268 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr || 269 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr || 270 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr; 271 m_process_launch_info.SetLaunchInSeparateProcessGroup(true); 272 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug); 273 274 if (should_forward_stdio) { 275 // Temporarily relax the following for Windows until we can take advantage 276 // of the recently added pty support. This doesn't really affect the use of 277 // lldb-server on Windows. 278 #if !defined(_WIN32) 279 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection()) 280 return Status(std::move(Err)); 281 #endif 282 } 283 284 { 285 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex); 286 assert(m_debugged_processes.empty() && "lldb-server creating debugged " 287 "process but one already exists"); 288 auto process_or = 289 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop); 290 if (!process_or) 291 return Status(process_or.takeError()); 292 m_continue_process = m_current_process = process_or->get(); 293 m_debugged_processes.emplace( 294 m_current_process->GetID(), 295 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}}); 296 } 297 298 SetEnabledExtensions(*m_current_process); 299 300 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as 301 // needed. llgs local-process debugging may specify PTY paths, which will 302 // make these file actions non-null process launch -i/e/o will also make 303 // these file actions non-null nullptr means that the traffic is expected to 304 // flow over gdb-remote protocol 305 if (should_forward_stdio) { 306 // nullptr means it's not redirected to file or pty (in case of LLGS local) 307 // at least one of stdio will be transferred pty<->gdb-remote we need to 308 // give the pty primary handle to this object to read and/or write 309 LLDB_LOG(log, 310 "pid = {0}: setting up stdout/stderr redirection via $O " 311 "gdb-remote commands", 312 m_current_process->GetID()); 313 314 // Setup stdout/stderr mapping from inferior to $O 315 auto terminal_fd = m_current_process->GetTerminalFileDescriptor(); 316 if (terminal_fd >= 0) { 317 LLDB_LOGF(log, 318 "ProcessGDBRemoteCommunicationServerLLGS::%s setting " 319 "inferior STDIO fd to %d", 320 __FUNCTION__, terminal_fd); 321 Status status = SetSTDIOFileDescriptor(terminal_fd); 322 if (status.Fail()) 323 return status; 324 } else { 325 LLDB_LOGF(log, 326 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring " 327 "inferior STDIO since terminal fd reported as %d", 328 __FUNCTION__, terminal_fd); 329 } 330 } else { 331 LLDB_LOG(log, 332 "pid = {0} skipping stdout/stderr redirection via $O: inferior " 333 "will communicate over client-provided file descriptors", 334 m_current_process->GetID()); 335 } 336 337 printf("Launched '%s' as process %" PRIu64 "...\n", 338 m_process_launch_info.GetArguments().GetArgumentAtIndex(0), 339 m_current_process->GetID()); 340 341 return Status(); 342 } 343 344 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) { 345 Log *log = GetLog(LLDBLog::Process); 346 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, 347 __FUNCTION__, pid); 348 349 // Before we try to attach, make sure we aren't already monitoring something 350 // else. 351 if (!m_debugged_processes.empty()) 352 return Status("cannot attach to process %" PRIu64 353 " when another process with pid %" PRIu64 354 " is being debugged.", 355 pid, m_current_process->GetID()); 356 357 // Try to attach. 358 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop); 359 if (!process_or) { 360 Status status(process_or.takeError()); 361 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid, 362 status); 363 return status; 364 } 365 m_continue_process = m_current_process = process_or->get(); 366 m_debugged_processes.emplace( 367 m_current_process->GetID(), 368 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}}); 369 SetEnabledExtensions(*m_current_process); 370 371 // Setup stdout/stderr mapping from inferior. 372 auto terminal_fd = m_current_process->GetTerminalFileDescriptor(); 373 if (terminal_fd >= 0) { 374 LLDB_LOGF(log, 375 "ProcessGDBRemoteCommunicationServerLLGS::%s setting " 376 "inferior STDIO fd to %d", 377 __FUNCTION__, terminal_fd); 378 Status status = SetSTDIOFileDescriptor(terminal_fd); 379 if (status.Fail()) 380 return status; 381 } else { 382 LLDB_LOGF(log, 383 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring " 384 "inferior STDIO since terminal fd reported as %d", 385 __FUNCTION__, terminal_fd); 386 } 387 388 printf("Attached to process %" PRIu64 "...\n", pid); 389 return Status(); 390 } 391 392 Status GDBRemoteCommunicationServerLLGS::AttachWaitProcess( 393 llvm::StringRef process_name, bool include_existing) { 394 Log *log = GetLog(LLDBLog::Process); 395 396 std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1); 397 398 // Create the matcher used to search the process list. 399 ProcessInstanceInfoList exclusion_list; 400 ProcessInstanceInfoMatch match_info; 401 match_info.GetProcessInfo().GetExecutableFile().SetFile( 402 process_name, llvm::sys::path::Style::native); 403 match_info.SetNameMatchType(NameMatch::Equals); 404 405 if (include_existing) { 406 LLDB_LOG(log, "including existing processes in search"); 407 } else { 408 // Create the excluded process list before polling begins. 409 Host::FindProcesses(match_info, exclusion_list); 410 LLDB_LOG(log, "placed '{0}' processes in the exclusion list.", 411 exclusion_list.size()); 412 } 413 414 LLDB_LOG(log, "waiting for '{0}' to appear", process_name); 415 416 auto is_in_exclusion_list = 417 [&exclusion_list](const ProcessInstanceInfo &info) { 418 for (auto &excluded : exclusion_list) { 419 if (excluded.GetProcessID() == info.GetProcessID()) 420 return true; 421 } 422 return false; 423 }; 424 425 ProcessInstanceInfoList loop_process_list; 426 while (true) { 427 loop_process_list.clear(); 428 if (Host::FindProcesses(match_info, loop_process_list)) { 429 // Remove all the elements that are in the exclusion list. 430 llvm::erase_if(loop_process_list, is_in_exclusion_list); 431 432 // One match! We found the desired process. 433 if (loop_process_list.size() == 1) { 434 auto matching_process_pid = loop_process_list[0].GetProcessID(); 435 LLDB_LOG(log, "found pid {0}", matching_process_pid); 436 return AttachToProcess(matching_process_pid); 437 } 438 439 // Multiple matches! Return an error reporting the PIDs we found. 440 if (loop_process_list.size() > 1) { 441 StreamString error_stream; 442 error_stream.Format( 443 "Multiple executables with name: '{0}' found. Pids: ", 444 process_name); 445 for (size_t i = 0; i < loop_process_list.size() - 1; ++i) { 446 error_stream.Format("{0}, ", loop_process_list[i].GetProcessID()); 447 } 448 error_stream.Format("{0}.", loop_process_list.back().GetProcessID()); 449 450 Status error; 451 error.SetErrorString(error_stream.GetString()); 452 return error; 453 } 454 } 455 // No matches, we have not found the process. Sleep until next poll. 456 LLDB_LOG(log, "sleep {0} seconds", polling_interval); 457 std::this_thread::sleep_for(polling_interval); 458 } 459 } 460 461 void GDBRemoteCommunicationServerLLGS::InitializeDelegate( 462 NativeProcessProtocol *process) { 463 assert(process && "process cannot be NULL"); 464 Log *log = GetLog(LLDBLog::Process); 465 if (log) { 466 LLDB_LOGF(log, 467 "GDBRemoteCommunicationServerLLGS::%s called with " 468 "NativeProcessProtocol pid %" PRIu64 ", current state: %s", 469 __FUNCTION__, process->GetID(), 470 StateAsCString(process->GetState())); 471 } 472 } 473 474 GDBRemoteCommunication::PacketResult 475 GDBRemoteCommunicationServerLLGS::SendWResponse( 476 NativeProcessProtocol *process) { 477 assert(process && "process cannot be NULL"); 478 Log *log = GetLog(LLDBLog::Process); 479 480 // send W notification 481 auto wait_status = process->GetExitStatus(); 482 if (!wait_status) { 483 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status", 484 process->GetID()); 485 486 StreamGDBRemote response; 487 response.PutChar('E'); 488 response.PutHex8(GDBRemoteServerError::eErrorExitStatus); 489 return SendPacketNoLock(response.GetString()); 490 } 491 492 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(), 493 *wait_status); 494 495 // If the process was killed through vKill, return "OK". 496 if (bool(m_debugged_processes.at(process->GetID()).flags & 497 DebuggedProcess::Flag::vkilled)) 498 return SendOKResponse(); 499 500 StreamGDBRemote response; 501 response.Format("{0:g}", *wait_status); 502 if (bool(m_extensions_supported & 503 NativeProcessProtocol::Extension::multiprocess)) 504 response.Format(";process:{0:x-}", process->GetID()); 505 if (m_non_stop) 506 return SendNotificationPacketNoLock("Stop", m_stop_notification_queue, 507 response.GetString()); 508 return SendPacketNoLock(response.GetString()); 509 } 510 511 static void AppendHexValue(StreamString &response, const uint8_t *buf, 512 uint32_t buf_size, bool swap) { 513 int64_t i; 514 if (swap) { 515 for (i = buf_size - 1; i >= 0; i--) 516 response.PutHex8(buf[i]); 517 } else { 518 for (i = 0; i < buf_size; i++) 519 response.PutHex8(buf[i]); 520 } 521 } 522 523 static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) { 524 switch (reg_info.encoding) { 525 case eEncodingUint: 526 return "uint"; 527 case eEncodingSint: 528 return "sint"; 529 case eEncodingIEEE754: 530 return "ieee754"; 531 case eEncodingVector: 532 return "vector"; 533 default: 534 return ""; 535 } 536 } 537 538 static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) { 539 switch (reg_info.format) { 540 case eFormatBinary: 541 return "binary"; 542 case eFormatDecimal: 543 return "decimal"; 544 case eFormatHex: 545 return "hex"; 546 case eFormatFloat: 547 return "float"; 548 case eFormatVectorOfSInt8: 549 return "vector-sint8"; 550 case eFormatVectorOfUInt8: 551 return "vector-uint8"; 552 case eFormatVectorOfSInt16: 553 return "vector-sint16"; 554 case eFormatVectorOfUInt16: 555 return "vector-uint16"; 556 case eFormatVectorOfSInt32: 557 return "vector-sint32"; 558 case eFormatVectorOfUInt32: 559 return "vector-uint32"; 560 case eFormatVectorOfFloat32: 561 return "vector-float32"; 562 case eFormatVectorOfUInt64: 563 return "vector-uint64"; 564 case eFormatVectorOfUInt128: 565 return "vector-uint128"; 566 default: 567 return ""; 568 }; 569 } 570 571 static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) { 572 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) { 573 case LLDB_REGNUM_GENERIC_PC: 574 return "pc"; 575 case LLDB_REGNUM_GENERIC_SP: 576 return "sp"; 577 case LLDB_REGNUM_GENERIC_FP: 578 return "fp"; 579 case LLDB_REGNUM_GENERIC_RA: 580 return "ra"; 581 case LLDB_REGNUM_GENERIC_FLAGS: 582 return "flags"; 583 case LLDB_REGNUM_GENERIC_ARG1: 584 return "arg1"; 585 case LLDB_REGNUM_GENERIC_ARG2: 586 return "arg2"; 587 case LLDB_REGNUM_GENERIC_ARG3: 588 return "arg3"; 589 case LLDB_REGNUM_GENERIC_ARG4: 590 return "arg4"; 591 case LLDB_REGNUM_GENERIC_ARG5: 592 return "arg5"; 593 case LLDB_REGNUM_GENERIC_ARG6: 594 return "arg6"; 595 case LLDB_REGNUM_GENERIC_ARG7: 596 return "arg7"; 597 case LLDB_REGNUM_GENERIC_ARG8: 598 return "arg8"; 599 default: 600 return ""; 601 } 602 } 603 604 static void CollectRegNums(const uint32_t *reg_num, StreamString &response, 605 bool usehex) { 606 for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) { 607 if (i > 0) 608 response.PutChar(','); 609 if (usehex) 610 response.Printf("%" PRIx32, *reg_num); 611 else 612 response.Printf("%" PRIu32, *reg_num); 613 } 614 } 615 616 static void WriteRegisterValueInHexFixedWidth( 617 StreamString &response, NativeRegisterContext ®_ctx, 618 const RegisterInfo ®_info, const RegisterValue *reg_value_p, 619 lldb::ByteOrder byte_order) { 620 RegisterValue reg_value; 621 if (!reg_value_p) { 622 Status error = reg_ctx.ReadRegister(®_info, reg_value); 623 if (error.Success()) 624 reg_value_p = ®_value; 625 // else log. 626 } 627 628 if (reg_value_p) { 629 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(), 630 reg_value_p->GetByteSize(), 631 byte_order == lldb::eByteOrderLittle); 632 } else { 633 // Zero-out any unreadable values. 634 if (reg_info.byte_size > 0) { 635 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0'); 636 AppendHexValue(response, zeros.data(), zeros.size(), false); 637 } 638 } 639 } 640 641 static llvm::Optional<json::Object> 642 GetRegistersAsJSON(NativeThreadProtocol &thread) { 643 Log *log = GetLog(LLDBLog::Thread); 644 645 NativeRegisterContext& reg_ctx = thread.GetRegisterContext(); 646 647 json::Object register_object; 648 649 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET 650 const auto expedited_regs = 651 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full); 652 #else 653 const auto expedited_regs = 654 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal); 655 #endif 656 if (expedited_regs.empty()) 657 return llvm::None; 658 659 for (auto ®_num : expedited_regs) { 660 const RegisterInfo *const reg_info_p = 661 reg_ctx.GetRegisterInfoAtIndex(reg_num); 662 if (reg_info_p == nullptr) { 663 LLDB_LOGF(log, 664 "%s failed to get register info for register index %" PRIu32, 665 __FUNCTION__, reg_num); 666 continue; 667 } 668 669 if (reg_info_p->value_regs != nullptr) 670 continue; // Only expedite registers that are not contained in other 671 // registers. 672 673 RegisterValue reg_value; 674 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 675 if (error.Fail()) { 676 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s", 677 __FUNCTION__, 678 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 679 reg_num, error.AsCString()); 680 continue; 681 } 682 683 StreamString stream; 684 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p, 685 ®_value, lldb::eByteOrderBig); 686 687 register_object.try_emplace(llvm::to_string(reg_num), 688 stream.GetString().str()); 689 } 690 691 return register_object; 692 } 693 694 static const char *GetStopReasonString(StopReason stop_reason) { 695 switch (stop_reason) { 696 case eStopReasonTrace: 697 return "trace"; 698 case eStopReasonBreakpoint: 699 return "breakpoint"; 700 case eStopReasonWatchpoint: 701 return "watchpoint"; 702 case eStopReasonSignal: 703 return "signal"; 704 case eStopReasonException: 705 return "exception"; 706 case eStopReasonExec: 707 return "exec"; 708 case eStopReasonProcessorTrace: 709 return "processor trace"; 710 case eStopReasonFork: 711 return "fork"; 712 case eStopReasonVFork: 713 return "vfork"; 714 case eStopReasonVForkDone: 715 return "vforkdone"; 716 case eStopReasonInstrumentation: 717 case eStopReasonInvalid: 718 case eStopReasonPlanComplete: 719 case eStopReasonThreadExiting: 720 case eStopReasonNone: 721 break; // ignored 722 } 723 return nullptr; 724 } 725 726 static llvm::Expected<json::Array> 727 GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) { 728 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 729 730 json::Array threads_array; 731 732 // Ensure we can get info on the given thread. 733 for (NativeThreadProtocol &thread : process.Threads()) { 734 lldb::tid_t tid = thread.GetID(); 735 // Grab the reason this thread stopped. 736 struct ThreadStopInfo tid_stop_info; 737 std::string description; 738 if (!thread.GetStopReason(tid_stop_info, description)) 739 return llvm::make_error<llvm::StringError>( 740 "failed to get stop reason", llvm::inconvertibleErrorCode()); 741 742 const int signum = tid_stop_info.signo; 743 if (log) { 744 LLDB_LOGF(log, 745 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 746 " tid %" PRIu64 747 " got signal signo = %d, reason = %d, exc_type = %" PRIu64, 748 __FUNCTION__, process.GetID(), tid, signum, 749 tid_stop_info.reason, tid_stop_info.details.exception.type); 750 } 751 752 json::Object thread_obj; 753 754 if (!abridged) { 755 if (llvm::Optional<json::Object> registers = GetRegistersAsJSON(thread)) 756 thread_obj.try_emplace("registers", std::move(*registers)); 757 } 758 759 thread_obj.try_emplace("tid", static_cast<int64_t>(tid)); 760 761 if (signum != 0) 762 thread_obj.try_emplace("signal", signum); 763 764 const std::string thread_name = thread.GetName(); 765 if (!thread_name.empty()) 766 thread_obj.try_emplace("name", thread_name); 767 768 const char *stop_reason = GetStopReasonString(tid_stop_info.reason); 769 if (stop_reason) 770 thread_obj.try_emplace("reason", stop_reason); 771 772 if (!description.empty()) 773 thread_obj.try_emplace("description", description); 774 775 if ((tid_stop_info.reason == eStopReasonException) && 776 tid_stop_info.details.exception.type) { 777 thread_obj.try_emplace( 778 "metype", static_cast<int64_t>(tid_stop_info.details.exception.type)); 779 780 json::Array medata_array; 781 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; 782 ++i) { 783 medata_array.push_back( 784 static_cast<int64_t>(tid_stop_info.details.exception.data[i])); 785 } 786 thread_obj.try_emplace("medata", std::move(medata_array)); 787 } 788 threads_array.push_back(std::move(thread_obj)); 789 } 790 return threads_array; 791 } 792 793 StreamString 794 GDBRemoteCommunicationServerLLGS::PrepareStopReplyPacketForThread( 795 NativeThreadProtocol &thread) { 796 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 797 798 NativeProcessProtocol &process = thread.GetProcess(); 799 800 LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(), 801 thread.GetID()); 802 803 // Grab the reason this thread stopped. 804 StreamString response; 805 struct ThreadStopInfo tid_stop_info; 806 std::string description; 807 if (!thread.GetStopReason(tid_stop_info, description)) 808 return response; 809 810 // FIXME implement register handling for exec'd inferiors. 811 // if (tid_stop_info.reason == eStopReasonExec) { 812 // const bool force = true; 813 // InitializeRegisters(force); 814 // } 815 816 // Output the T packet with the thread 817 response.PutChar('T'); 818 int signum = tid_stop_info.signo; 819 LLDB_LOG( 820 log, 821 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}", 822 process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason), 823 tid_stop_info.details.exception.type); 824 825 // Print the signal number. 826 response.PutHex8(signum & 0xff); 827 828 // Include the (pid and) tid. 829 response.PutCString("thread:"); 830 AppendThreadIDToResponse(response, process.GetID(), thread.GetID()); 831 response.PutChar(';'); 832 833 // Include the thread name if there is one. 834 const std::string thread_name = thread.GetName(); 835 if (!thread_name.empty()) { 836 size_t thread_name_len = thread_name.length(); 837 838 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) { 839 response.PutCString("name:"); 840 response.PutCString(thread_name); 841 } else { 842 // The thread name contains special chars, send as hex bytes. 843 response.PutCString("hexname:"); 844 response.PutStringAsRawHex8(thread_name); 845 } 846 response.PutChar(';'); 847 } 848 849 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will 850 // send all thread IDs back in the "threads" key whose value is a list of hex 851 // thread IDs separated by commas: 852 // "threads:10a,10b,10c;" 853 // This will save the debugger from having to send a pair of qfThreadInfo and 854 // qsThreadInfo packets, but it also might take a lot of room in the stop 855 // reply packet, so it must be enabled only on systems where there are no 856 // limits on packet lengths. 857 if (m_list_threads_in_stop_reply) { 858 response.PutCString("threads:"); 859 860 uint32_t thread_num = 0; 861 for (NativeThreadProtocol &listed_thread : process.Threads()) { 862 if (thread_num > 0) 863 response.PutChar(','); 864 response.Printf("%" PRIx64, listed_thread.GetID()); 865 ++thread_num; 866 } 867 response.PutChar(';'); 868 869 // Include JSON info that describes the stop reason for any threads that 870 // actually have stop reasons. We use the new "jstopinfo" key whose values 871 // is hex ascii JSON that contains the thread IDs thread stop info only for 872 // threads that have stop reasons. Only send this if we have more than one 873 // thread otherwise this packet has all the info it needs. 874 if (thread_num > 1) { 875 const bool threads_with_valid_stop_info_only = true; 876 llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo( 877 *m_current_process, threads_with_valid_stop_info_only); 878 if (threads_info) { 879 response.PutCString("jstopinfo:"); 880 StreamString unescaped_response; 881 unescaped_response.AsRawOstream() << std::move(*threads_info); 882 response.PutStringAsRawHex8(unescaped_response.GetData()); 883 response.PutChar(';'); 884 } else { 885 LLDB_LOG_ERROR(log, threads_info.takeError(), 886 "failed to prepare a jstopinfo field for pid {1}: {0}", 887 process.GetID()); 888 } 889 } 890 891 response.PutCString("thread-pcs"); 892 char delimiter = ':'; 893 for (NativeThreadProtocol &thread : process.Threads()) { 894 NativeRegisterContext ®_ctx = thread.GetRegisterContext(); 895 896 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber( 897 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 898 const RegisterInfo *const reg_info_p = 899 reg_ctx.GetRegisterInfoAtIndex(reg_to_read); 900 901 RegisterValue reg_value; 902 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 903 if (error.Fail()) { 904 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s", 905 __FUNCTION__, 906 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 907 reg_to_read, error.AsCString()); 908 continue; 909 } 910 911 response.PutChar(delimiter); 912 delimiter = ','; 913 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p, 914 ®_value, endian::InlHostByteOrder()); 915 } 916 917 response.PutChar(';'); 918 } 919 920 // 921 // Expedite registers. 922 // 923 924 // Grab the register context. 925 NativeRegisterContext ®_ctx = thread.GetRegisterContext(); 926 const auto expedited_regs = 927 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full); 928 929 for (auto ®_num : expedited_regs) { 930 const RegisterInfo *const reg_info_p = 931 reg_ctx.GetRegisterInfoAtIndex(reg_num); 932 // Only expediate registers that are not contained in other registers. 933 if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) { 934 RegisterValue reg_value; 935 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value); 936 if (error.Success()) { 937 response.Printf("%.02x:", reg_num); 938 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p, 939 ®_value, lldb::eByteOrderBig); 940 response.PutChar(';'); 941 } else { 942 LLDB_LOGF(log, 943 "GDBRemoteCommunicationServerLLGS::%s failed to read " 944 "register '%s' index %" PRIu32 ": %s", 945 __FUNCTION__, 946 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", 947 reg_num, error.AsCString()); 948 } 949 } 950 } 951 952 const char *reason_str = GetStopReasonString(tid_stop_info.reason); 953 if (reason_str != nullptr) { 954 response.Printf("reason:%s;", reason_str); 955 } 956 957 if (!description.empty()) { 958 // Description may contains special chars, send as hex bytes. 959 response.PutCString("description:"); 960 response.PutStringAsRawHex8(description); 961 response.PutChar(';'); 962 } else if ((tid_stop_info.reason == eStopReasonException) && 963 tid_stop_info.details.exception.type) { 964 response.PutCString("metype:"); 965 response.PutHex64(tid_stop_info.details.exception.type); 966 response.PutCString(";mecount:"); 967 response.PutHex32(tid_stop_info.details.exception.data_count); 968 response.PutChar(';'); 969 970 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) { 971 response.PutCString("medata:"); 972 response.PutHex64(tid_stop_info.details.exception.data[i]); 973 response.PutChar(';'); 974 } 975 } 976 977 // Include child process PID/TID for forks. 978 if (tid_stop_info.reason == eStopReasonFork || 979 tid_stop_info.reason == eStopReasonVFork) { 980 assert(bool(m_extensions_supported & 981 NativeProcessProtocol::Extension::multiprocess)); 982 if (tid_stop_info.reason == eStopReasonFork) 983 assert(bool(m_extensions_supported & 984 NativeProcessProtocol::Extension::fork)); 985 if (tid_stop_info.reason == eStopReasonVFork) 986 assert(bool(m_extensions_supported & 987 NativeProcessProtocol::Extension::vfork)); 988 response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str, 989 tid_stop_info.details.fork.child_pid, 990 tid_stop_info.details.fork.child_tid); 991 } 992 993 return response; 994 } 995 996 GDBRemoteCommunication::PacketResult 997 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread( 998 NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) { 999 // Ensure we can get info on the given thread. 1000 NativeThreadProtocol *thread = process.GetThreadByID(tid); 1001 if (!thread) 1002 return SendErrorResponse(51); 1003 1004 StreamString response = PrepareStopReplyPacketForThread(*thread); 1005 if (response.Empty()) 1006 return SendErrorResponse(42); 1007 1008 if (m_non_stop && !force_synchronous) { 1009 PacketResult ret = SendNotificationPacketNoLock( 1010 "Stop", m_stop_notification_queue, response.GetString()); 1011 // Queue notification events for the remaining threads. 1012 EnqueueStopReplyPackets(tid); 1013 return ret; 1014 } 1015 1016 return SendPacketNoLock(response.GetString()); 1017 } 1018 1019 void GDBRemoteCommunicationServerLLGS::EnqueueStopReplyPackets( 1020 lldb::tid_t thread_to_skip) { 1021 if (!m_non_stop) 1022 return; 1023 1024 for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) { 1025 if (listed_thread.GetID() != thread_to_skip) 1026 m_stop_notification_queue.push_back( 1027 PrepareStopReplyPacketForThread(listed_thread).GetString().str()); 1028 } 1029 } 1030 1031 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited( 1032 NativeProcessProtocol *process) { 1033 assert(process && "process cannot be NULL"); 1034 1035 Log *log = GetLog(LLDBLog::Process); 1036 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1037 1038 PacketResult result = SendStopReasonForState( 1039 *process, StateType::eStateExited, /*force_synchronous=*/false); 1040 if (result != PacketResult::Success) { 1041 LLDB_LOGF(log, 1042 "GDBRemoteCommunicationServerLLGS::%s failed to send stop " 1043 "notification for PID %" PRIu64 ", state: eStateExited", 1044 __FUNCTION__, process->GetID()); 1045 } 1046 1047 if (m_current_process == process) 1048 m_current_process = nullptr; 1049 if (m_continue_process == process) 1050 m_continue_process = nullptr; 1051 1052 lldb::pid_t pid = process->GetID(); 1053 m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) { 1054 auto find_it = m_debugged_processes.find(pid); 1055 assert(find_it != m_debugged_processes.end()); 1056 bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled); 1057 m_debugged_processes.erase(find_it); 1058 // Terminate the main loop only if vKill has not been used. 1059 // When running in non-stop mode, wait for the vStopped to clear 1060 // the notification queue. 1061 if (m_debugged_processes.empty() && !m_non_stop && !vkilled) { 1062 // Close the pipe to the inferior terminal i/o if we launched it and set 1063 // one up. 1064 MaybeCloseInferiorTerminalConnection(); 1065 1066 // We are ready to exit the debug monitor. 1067 m_exit_now = true; 1068 loop.RequestTermination(); 1069 } 1070 }); 1071 } 1072 1073 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped( 1074 NativeProcessProtocol *process) { 1075 assert(process && "process cannot be NULL"); 1076 1077 Log *log = GetLog(LLDBLog::Process); 1078 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1079 1080 PacketResult result = SendStopReasonForState( 1081 *process, StateType::eStateStopped, /*force_synchronous=*/false); 1082 if (result != PacketResult::Success) { 1083 LLDB_LOGF(log, 1084 "GDBRemoteCommunicationServerLLGS::%s failed to send stop " 1085 "notification for PID %" PRIu64 ", state: eStateExited", 1086 __FUNCTION__, process->GetID()); 1087 } 1088 } 1089 1090 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged( 1091 NativeProcessProtocol *process, lldb::StateType state) { 1092 assert(process && "process cannot be NULL"); 1093 Log *log = GetLog(LLDBLog::Process); 1094 if (log) { 1095 LLDB_LOGF(log, 1096 "GDBRemoteCommunicationServerLLGS::%s called with " 1097 "NativeProcessProtocol pid %" PRIu64 ", state: %s", 1098 __FUNCTION__, process->GetID(), StateAsCString(state)); 1099 } 1100 1101 switch (state) { 1102 case StateType::eStateRunning: 1103 break; 1104 1105 case StateType::eStateStopped: 1106 // Make sure we get all of the pending stdout/stderr from the inferior and 1107 // send it to the lldb host before we send the state change notification 1108 SendProcessOutput(); 1109 // Then stop the forwarding, so that any late output (see llvm.org/pr25652) 1110 // does not interfere with our protocol. 1111 StopSTDIOForwarding(); 1112 HandleInferiorState_Stopped(process); 1113 break; 1114 1115 case StateType::eStateExited: 1116 // Same as above 1117 SendProcessOutput(); 1118 StopSTDIOForwarding(); 1119 HandleInferiorState_Exited(process); 1120 break; 1121 1122 default: 1123 if (log) { 1124 LLDB_LOGF(log, 1125 "GDBRemoteCommunicationServerLLGS::%s didn't handle state " 1126 "change for pid %" PRIu64 ", new state: %s", 1127 __FUNCTION__, process->GetID(), StateAsCString(state)); 1128 } 1129 break; 1130 } 1131 } 1132 1133 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) { 1134 ClearProcessSpecificData(); 1135 } 1136 1137 void GDBRemoteCommunicationServerLLGS::NewSubprocess( 1138 NativeProcessProtocol *parent_process, 1139 std::unique_ptr<NativeProcessProtocol> child_process) { 1140 lldb::pid_t child_pid = child_process->GetID(); 1141 assert(child_pid != LLDB_INVALID_PROCESS_ID); 1142 assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end()); 1143 m_debugged_processes.emplace( 1144 child_pid, 1145 DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}}); 1146 } 1147 1148 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() { 1149 Log *log = GetLog(GDBRLog::Comm); 1150 1151 bool interrupt = false; 1152 bool done = false; 1153 Status error; 1154 while (true) { 1155 const PacketResult result = GetPacketAndSendResponse( 1156 std::chrono::microseconds(0), error, interrupt, done); 1157 if (result == PacketResult::ErrorReplyTimeout) 1158 break; // No more packets in the queue 1159 1160 if ((result != PacketResult::Success)) { 1161 LLDB_LOGF(log, 1162 "GDBRemoteCommunicationServerLLGS::%s processing a packet " 1163 "failed: %s", 1164 __FUNCTION__, error.AsCString()); 1165 m_mainloop.RequestTermination(); 1166 break; 1167 } 1168 } 1169 } 1170 1171 Status GDBRemoteCommunicationServerLLGS::InitializeConnection( 1172 std::unique_ptr<Connection> connection) { 1173 IOObjectSP read_object_sp = connection->GetReadObject(); 1174 GDBRemoteCommunicationServer::SetConnection(std::move(connection)); 1175 1176 Status error; 1177 m_network_handle_up = m_mainloop.RegisterReadObject( 1178 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); }, 1179 error); 1180 return error; 1181 } 1182 1183 GDBRemoteCommunication::PacketResult 1184 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer, 1185 uint32_t len) { 1186 if ((buffer == nullptr) || (len == 0)) { 1187 // Nothing to send. 1188 return PacketResult::Success; 1189 } 1190 1191 StreamString response; 1192 response.PutChar('O'); 1193 response.PutBytesAsRawHex8(buffer, len); 1194 1195 return SendPacketNoLock(response.GetString()); 1196 } 1197 1198 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) { 1199 Status error; 1200 1201 // Set up the reading/handling of process I/O 1202 std::unique_ptr<ConnectionFileDescriptor> conn_up( 1203 new ConnectionFileDescriptor(fd, true)); 1204 if (!conn_up) { 1205 error.SetErrorString("failed to create ConnectionFileDescriptor"); 1206 return error; 1207 } 1208 1209 m_stdio_communication.SetCloseOnEOF(false); 1210 m_stdio_communication.SetConnection(std::move(conn_up)); 1211 if (!m_stdio_communication.IsConnected()) { 1212 error.SetErrorString( 1213 "failed to set connection for inferior I/O communication"); 1214 return error; 1215 } 1216 1217 return Status(); 1218 } 1219 1220 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() { 1221 // Don't forward if not connected (e.g. when attaching). 1222 if (!m_stdio_communication.IsConnected()) 1223 return; 1224 1225 Status error; 1226 assert(!m_stdio_handle_up); 1227 m_stdio_handle_up = m_mainloop.RegisterReadObject( 1228 m_stdio_communication.GetConnection()->GetReadObject(), 1229 [this](MainLoopBase &) { SendProcessOutput(); }, error); 1230 1231 if (!m_stdio_handle_up) { 1232 // Not much we can do about the failure. Log it and continue without 1233 // forwarding. 1234 if (Log *log = GetLog(LLDBLog::Process)) 1235 LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error); 1236 } 1237 } 1238 1239 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() { 1240 m_stdio_handle_up.reset(); 1241 } 1242 1243 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() { 1244 char buffer[1024]; 1245 ConnectionStatus status; 1246 Status error; 1247 while (true) { 1248 size_t bytes_read = m_stdio_communication.Read( 1249 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error); 1250 switch (status) { 1251 case eConnectionStatusSuccess: 1252 SendONotification(buffer, bytes_read); 1253 break; 1254 case eConnectionStatusLostConnection: 1255 case eConnectionStatusEndOfFile: 1256 case eConnectionStatusError: 1257 case eConnectionStatusNoConnection: 1258 if (Log *log = GetLog(LLDBLog::Process)) 1259 LLDB_LOGF(log, 1260 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio " 1261 "forwarding as communication returned status %d (error: " 1262 "%s)", 1263 __FUNCTION__, status, error.AsCString()); 1264 m_stdio_handle_up.reset(); 1265 return; 1266 1267 case eConnectionStatusInterrupted: 1268 case eConnectionStatusTimedOut: 1269 return; 1270 } 1271 } 1272 } 1273 1274 GDBRemoteCommunication::PacketResult 1275 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported( 1276 StringExtractorGDBRemote &packet) { 1277 1278 // Fail if we don't have a current process. 1279 if (!m_current_process || 1280 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1281 return SendErrorResponse(Status("Process not running.")); 1282 1283 return SendJSONResponse(m_current_process->TraceSupported()); 1284 } 1285 1286 GDBRemoteCommunication::PacketResult 1287 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop( 1288 StringExtractorGDBRemote &packet) { 1289 // Fail if we don't have a current process. 1290 if (!m_current_process || 1291 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1292 return SendErrorResponse(Status("Process not running.")); 1293 1294 packet.ConsumeFront("jLLDBTraceStop:"); 1295 Expected<TraceStopRequest> stop_request = 1296 json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest"); 1297 if (!stop_request) 1298 return SendErrorResponse(stop_request.takeError()); 1299 1300 if (Error err = m_current_process->TraceStop(*stop_request)) 1301 return SendErrorResponse(std::move(err)); 1302 1303 return SendOKResponse(); 1304 } 1305 1306 GDBRemoteCommunication::PacketResult 1307 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart( 1308 StringExtractorGDBRemote &packet) { 1309 1310 // Fail if we don't have a current process. 1311 if (!m_current_process || 1312 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1313 return SendErrorResponse(Status("Process not running.")); 1314 1315 packet.ConsumeFront("jLLDBTraceStart:"); 1316 Expected<TraceStartRequest> request = 1317 json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest"); 1318 if (!request) 1319 return SendErrorResponse(request.takeError()); 1320 1321 if (Error err = m_current_process->TraceStart(packet.Peek(), request->type)) 1322 return SendErrorResponse(std::move(err)); 1323 1324 return SendOKResponse(); 1325 } 1326 1327 GDBRemoteCommunication::PacketResult 1328 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState( 1329 StringExtractorGDBRemote &packet) { 1330 1331 // Fail if we don't have a current process. 1332 if (!m_current_process || 1333 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1334 return SendErrorResponse(Status("Process not running.")); 1335 1336 packet.ConsumeFront("jLLDBTraceGetState:"); 1337 Expected<TraceGetStateRequest> request = 1338 json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest"); 1339 if (!request) 1340 return SendErrorResponse(request.takeError()); 1341 1342 return SendJSONResponse(m_current_process->TraceGetState(request->type)); 1343 } 1344 1345 GDBRemoteCommunication::PacketResult 1346 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData( 1347 StringExtractorGDBRemote &packet) { 1348 1349 // Fail if we don't have a current process. 1350 if (!m_current_process || 1351 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1352 return SendErrorResponse(Status("Process not running.")); 1353 1354 packet.ConsumeFront("jLLDBTraceGetBinaryData:"); 1355 llvm::Expected<TraceGetBinaryDataRequest> request = 1356 llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(), 1357 "TraceGetBinaryDataRequest"); 1358 if (!request) 1359 return SendErrorResponse(Status(request.takeError())); 1360 1361 if (Expected<std::vector<uint8_t>> bytes = 1362 m_current_process->TraceGetBinaryData(*request)) { 1363 StreamGDBRemote response; 1364 response.PutEscapedBytes(bytes->data(), bytes->size()); 1365 return SendPacketNoLock(response.GetString()); 1366 } else 1367 return SendErrorResponse(bytes.takeError()); 1368 } 1369 1370 GDBRemoteCommunication::PacketResult 1371 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo( 1372 StringExtractorGDBRemote &packet) { 1373 // Fail if we don't have a current process. 1374 if (!m_current_process || 1375 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1376 return SendErrorResponse(68); 1377 1378 lldb::pid_t pid = m_current_process->GetID(); 1379 1380 if (pid == LLDB_INVALID_PROCESS_ID) 1381 return SendErrorResponse(1); 1382 1383 ProcessInstanceInfo proc_info; 1384 if (!Host::GetProcessInfo(pid, proc_info)) 1385 return SendErrorResponse(1); 1386 1387 StreamString response; 1388 CreateProcessInfoResponse_DebugServerStyle(proc_info, response); 1389 return SendPacketNoLock(response.GetString()); 1390 } 1391 1392 GDBRemoteCommunication::PacketResult 1393 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) { 1394 // Fail if we don't have a current process. 1395 if (!m_current_process || 1396 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1397 return SendErrorResponse(68); 1398 1399 // Make sure we set the current thread so g and p packets return the data the 1400 // gdb will expect. 1401 lldb::tid_t tid = m_current_process->GetCurrentThreadID(); 1402 SetCurrentThreadID(tid); 1403 1404 NativeThreadProtocol *thread = m_current_process->GetCurrentThread(); 1405 if (!thread) 1406 return SendErrorResponse(69); 1407 1408 StreamString response; 1409 response.PutCString("QC"); 1410 AppendThreadIDToResponse(response, m_current_process->GetID(), 1411 thread->GetID()); 1412 1413 return SendPacketNoLock(response.GetString()); 1414 } 1415 1416 GDBRemoteCommunication::PacketResult 1417 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) { 1418 Log *log = GetLog(LLDBLog::Process); 1419 1420 StopSTDIOForwarding(); 1421 1422 if (m_debugged_processes.empty()) { 1423 LLDB_LOG(log, "No debugged process found."); 1424 return PacketResult::Success; 1425 } 1426 1427 for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end(); 1428 ++it) { 1429 LLDB_LOG(log, "Killing process {0}", it->first); 1430 Status error = it->second.process_up->Kill(); 1431 if (error.Fail()) 1432 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first, 1433 error); 1434 } 1435 1436 // The response to kill packet is undefined per the spec. LLDB 1437 // follows the same rules as for continue packets, i.e. no response 1438 // in all-stop mode, and "OK" in non-stop mode; in both cases this 1439 // is followed by the actual stop reason. 1440 return SendContinueSuccessResponse(); 1441 } 1442 1443 GDBRemoteCommunication::PacketResult 1444 GDBRemoteCommunicationServerLLGS::Handle_vKill( 1445 StringExtractorGDBRemote &packet) { 1446 StopSTDIOForwarding(); 1447 1448 packet.SetFilePos(6); // vKill; 1449 uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 1450 if (pid == LLDB_INVALID_PROCESS_ID) 1451 return SendIllFormedResponse(packet, 1452 "vKill failed to parse the process id"); 1453 1454 auto it = m_debugged_processes.find(pid); 1455 if (it == m_debugged_processes.end()) 1456 return SendErrorResponse(42); 1457 1458 Status error = it->second.process_up->Kill(); 1459 if (error.Fail()) 1460 return SendErrorResponse(error.ToError()); 1461 1462 // OK response is sent when the process dies. 1463 it->second.flags |= DebuggedProcess::Flag::vkilled; 1464 return PacketResult::Success; 1465 } 1466 1467 GDBRemoteCommunication::PacketResult 1468 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR( 1469 StringExtractorGDBRemote &packet) { 1470 packet.SetFilePos(::strlen("QSetDisableASLR:")); 1471 if (packet.GetU32(0)) 1472 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR); 1473 else 1474 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR); 1475 return SendOKResponse(); 1476 } 1477 1478 GDBRemoteCommunication::PacketResult 1479 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir( 1480 StringExtractorGDBRemote &packet) { 1481 packet.SetFilePos(::strlen("QSetWorkingDir:")); 1482 std::string path; 1483 packet.GetHexByteString(path); 1484 m_process_launch_info.SetWorkingDirectory(FileSpec(path)); 1485 return SendOKResponse(); 1486 } 1487 1488 GDBRemoteCommunication::PacketResult 1489 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir( 1490 StringExtractorGDBRemote &packet) { 1491 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()}; 1492 if (working_dir) { 1493 StreamString response; 1494 response.PutStringAsRawHex8(working_dir.GetCString()); 1495 return SendPacketNoLock(response.GetString()); 1496 } 1497 1498 return SendErrorResponse(14); 1499 } 1500 1501 GDBRemoteCommunication::PacketResult 1502 GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported( 1503 StringExtractorGDBRemote &packet) { 1504 m_thread_suffix_supported = true; 1505 return SendOKResponse(); 1506 } 1507 1508 GDBRemoteCommunication::PacketResult 1509 GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply( 1510 StringExtractorGDBRemote &packet) { 1511 m_list_threads_in_stop_reply = true; 1512 return SendOKResponse(); 1513 } 1514 1515 GDBRemoteCommunication::PacketResult 1516 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) { 1517 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 1518 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1519 1520 // Ensure we have a native process. 1521 if (!m_continue_process) { 1522 LLDB_LOGF(log, 1523 "GDBRemoteCommunicationServerLLGS::%s no debugged process " 1524 "shared pointer", 1525 __FUNCTION__); 1526 return SendErrorResponse(0x36); 1527 } 1528 1529 // Pull out the signal number. 1530 packet.SetFilePos(::strlen("C")); 1531 if (packet.GetBytesLeft() < 1) { 1532 // Shouldn't be using a C without a signal. 1533 return SendIllFormedResponse(packet, "C packet specified without signal."); 1534 } 1535 const uint32_t signo = 1536 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1537 if (signo == std::numeric_limits<uint32_t>::max()) 1538 return SendIllFormedResponse(packet, "failed to parse signal number"); 1539 1540 // Handle optional continue address. 1541 if (packet.GetBytesLeft() > 0) { 1542 // FIXME add continue at address support for $C{signo}[;{continue-address}]. 1543 if (*packet.Peek() == ';') 1544 return SendUnimplementedResponse(packet.GetStringRef().data()); 1545 else 1546 return SendIllFormedResponse( 1547 packet, "unexpected content after $C{signal-number}"); 1548 } 1549 1550 ResumeActionList resume_actions(StateType::eStateRunning, 1551 LLDB_INVALID_SIGNAL_NUMBER); 1552 Status error; 1553 1554 // We have two branches: what to do if a continue thread is specified (in 1555 // which case we target sending the signal to that thread), or when we don't 1556 // have a continue thread set (in which case we send a signal to the 1557 // process). 1558 1559 // TODO discuss with Greg Clayton, make sure this makes sense. 1560 1561 lldb::tid_t signal_tid = GetContinueThreadID(); 1562 if (signal_tid != LLDB_INVALID_THREAD_ID) { 1563 // The resume action for the continue thread (or all threads if a continue 1564 // thread is not set). 1565 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning, 1566 static_cast<int>(signo)}; 1567 1568 // Add the action for the continue thread (or all threads when the continue 1569 // thread isn't present). 1570 resume_actions.Append(action); 1571 } else { 1572 // Send the signal to the process since we weren't targeting a specific 1573 // continue thread with the signal. 1574 error = m_continue_process->Signal(signo); 1575 if (error.Fail()) { 1576 LLDB_LOG(log, "failed to send signal for process {0}: {1}", 1577 m_continue_process->GetID(), error); 1578 1579 return SendErrorResponse(0x52); 1580 } 1581 } 1582 1583 // Resume the threads. 1584 error = m_continue_process->Resume(resume_actions); 1585 if (error.Fail()) { 1586 LLDB_LOG(log, "failed to resume threads for process {0}: {1}", 1587 m_continue_process->GetID(), error); 1588 1589 return SendErrorResponse(0x38); 1590 } 1591 1592 // Don't send an "OK" packet, except in non-stop mode; 1593 // otherwise, the response is the stopped/exited message. 1594 return SendContinueSuccessResponse(); 1595 } 1596 1597 GDBRemoteCommunication::PacketResult 1598 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) { 1599 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 1600 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__); 1601 1602 packet.SetFilePos(packet.GetFilePos() + ::strlen("c")); 1603 1604 // For now just support all continue. 1605 const bool has_continue_address = (packet.GetBytesLeft() > 0); 1606 if (has_continue_address) { 1607 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]", 1608 packet.Peek()); 1609 return SendUnimplementedResponse(packet.GetStringRef().data()); 1610 } 1611 1612 // Ensure we have a native process. 1613 if (!m_continue_process) { 1614 LLDB_LOGF(log, 1615 "GDBRemoteCommunicationServerLLGS::%s no debugged process " 1616 "shared pointer", 1617 __FUNCTION__); 1618 return SendErrorResponse(0x36); 1619 } 1620 1621 // Build the ResumeActionList 1622 ResumeActionList actions(StateType::eStateRunning, 1623 LLDB_INVALID_SIGNAL_NUMBER); 1624 1625 Status error = m_continue_process->Resume(actions); 1626 if (error.Fail()) { 1627 LLDB_LOG(log, "c failed for process {0}: {1}", m_continue_process->GetID(), 1628 error); 1629 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1630 } 1631 1632 LLDB_LOG(log, "continued process {0}", m_continue_process->GetID()); 1633 1634 return SendContinueSuccessResponse(); 1635 } 1636 1637 GDBRemoteCommunication::PacketResult 1638 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions( 1639 StringExtractorGDBRemote &packet) { 1640 StreamString response; 1641 response.Printf("vCont;c;C;s;S;t"); 1642 1643 return SendPacketNoLock(response.GetString()); 1644 } 1645 1646 GDBRemoteCommunication::PacketResult 1647 GDBRemoteCommunicationServerLLGS::Handle_vCont( 1648 StringExtractorGDBRemote &packet) { 1649 Log *log = GetLog(LLDBLog::Process); 1650 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet", 1651 __FUNCTION__); 1652 1653 packet.SetFilePos(::strlen("vCont")); 1654 1655 if (packet.GetBytesLeft() == 0) { 1656 LLDB_LOGF(log, 1657 "GDBRemoteCommunicationServerLLGS::%s missing action from " 1658 "vCont package", 1659 __FUNCTION__); 1660 return SendIllFormedResponse(packet, "Missing action from vCont package"); 1661 } 1662 1663 if (::strcmp(packet.Peek(), ";s") == 0) { 1664 // Move past the ';', then do a simple 's'. 1665 packet.SetFilePos(packet.GetFilePos() + 1); 1666 return Handle_s(packet); 1667 } else if (m_non_stop && ::strcmp(packet.Peek(), ";t") == 0) { 1668 // TODO: add full support for "t" action 1669 return SendOKResponse(); 1670 } 1671 1672 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions; 1673 1674 while (packet.GetBytesLeft() && *packet.Peek() == ';') { 1675 // Skip the semi-colon. 1676 packet.GetChar(); 1677 1678 // Build up the thread action. 1679 ResumeAction thread_action; 1680 thread_action.tid = LLDB_INVALID_THREAD_ID; 1681 thread_action.state = eStateInvalid; 1682 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER; 1683 1684 const char action = packet.GetChar(); 1685 switch (action) { 1686 case 'C': 1687 thread_action.signal = packet.GetHexMaxU32(false, 0); 1688 if (thread_action.signal == 0) 1689 return SendIllFormedResponse( 1690 packet, "Could not parse signal in vCont packet C action"); 1691 LLVM_FALLTHROUGH; 1692 1693 case 'c': 1694 // Continue 1695 thread_action.state = eStateRunning; 1696 break; 1697 1698 case 'S': 1699 thread_action.signal = packet.GetHexMaxU32(false, 0); 1700 if (thread_action.signal == 0) 1701 return SendIllFormedResponse( 1702 packet, "Could not parse signal in vCont packet S action"); 1703 LLVM_FALLTHROUGH; 1704 1705 case 's': 1706 // Step 1707 thread_action.state = eStateStepping; 1708 break; 1709 1710 case 't': 1711 // Stop 1712 thread_action.state = eStateSuspended; 1713 break; 1714 1715 default: 1716 return SendIllFormedResponse(packet, "Unsupported vCont action"); 1717 break; 1718 } 1719 1720 lldb::pid_t pid = StringExtractorGDBRemote::AllProcesses; 1721 lldb::tid_t tid = StringExtractorGDBRemote::AllThreads; 1722 1723 // Parse out optional :{thread-id} value. 1724 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) { 1725 // Consume the separator. 1726 packet.GetChar(); 1727 1728 auto pid_tid = packet.GetPidTid(StringExtractorGDBRemote::AllProcesses); 1729 if (!pid_tid) 1730 return SendIllFormedResponse(packet, "Malformed thread-id"); 1731 1732 pid = pid_tid->first; 1733 tid = pid_tid->second; 1734 } 1735 1736 if (pid == StringExtractorGDBRemote::AllProcesses) { 1737 if (m_debugged_processes.size() > 1) 1738 return SendIllFormedResponse( 1739 packet, "Resuming multiple processes not supported yet"); 1740 if (!m_continue_process) { 1741 LLDB_LOG(log, "no debugged process"); 1742 return SendErrorResponse(0x36); 1743 } 1744 pid = m_continue_process->GetID(); 1745 } 1746 1747 if (tid == StringExtractorGDBRemote::AllThreads) 1748 tid = LLDB_INVALID_THREAD_ID; 1749 1750 thread_action.tid = tid; 1751 1752 thread_actions[pid].Append(thread_action); 1753 } 1754 1755 assert(thread_actions.size() >= 1); 1756 if (thread_actions.size() > 1) 1757 return SendIllFormedResponse( 1758 packet, "Resuming multiple processes not supported yet"); 1759 1760 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) { 1761 auto process_it = m_debugged_processes.find(x.first); 1762 if (process_it == m_debugged_processes.end()) { 1763 LLDB_LOG(log, "vCont failed for process {0}: process not debugged", 1764 x.first); 1765 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1766 } 1767 1768 Status error = process_it->second.process_up->Resume(x.second); 1769 if (error.Fail()) { 1770 LLDB_LOG(log, "vCont failed for process {0}: {1}", x.first, error); 1771 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 1772 } 1773 1774 LLDB_LOG(log, "continued process {0}", x.first); 1775 } 1776 1777 return SendContinueSuccessResponse(); 1778 } 1779 1780 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) { 1781 Log *log = GetLog(LLDBLog::Thread); 1782 LLDB_LOG(log, "setting current thread id to {0}", tid); 1783 1784 m_current_tid = tid; 1785 if (m_current_process) 1786 m_current_process->SetCurrentThreadID(m_current_tid); 1787 } 1788 1789 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) { 1790 Log *log = GetLog(LLDBLog::Thread); 1791 LLDB_LOG(log, "setting continue thread id to {0}", tid); 1792 1793 m_continue_tid = tid; 1794 } 1795 1796 GDBRemoteCommunication::PacketResult 1797 GDBRemoteCommunicationServerLLGS::Handle_stop_reason( 1798 StringExtractorGDBRemote &packet) { 1799 // Handle the $? gdbremote command. 1800 1801 if (m_non_stop) { 1802 // Clear the notification queue first, except for pending exit 1803 // notifications. 1804 llvm::erase_if(m_stop_notification_queue, [](const std::string &x) { 1805 return x.front() != 'W' && x.front() != 'X'; 1806 }); 1807 1808 if (m_current_process) { 1809 // Queue stop reply packets for all active threads. Start with 1810 // the current thread (for clients that don't actually support multiple 1811 // stop reasons). 1812 NativeThreadProtocol *thread = m_current_process->GetCurrentThread(); 1813 if (thread) 1814 m_stop_notification_queue.push_back( 1815 PrepareStopReplyPacketForThread(*thread).GetString().str()); 1816 EnqueueStopReplyPackets(thread ? thread->GetID() 1817 : LLDB_INVALID_THREAD_ID); 1818 } 1819 1820 // If the notification queue is empty (i.e. everything is running), send OK. 1821 if (m_stop_notification_queue.empty()) 1822 return SendOKResponse(); 1823 1824 // Send the first item from the new notification queue synchronously. 1825 return SendPacketNoLock(m_stop_notification_queue.front()); 1826 } 1827 1828 // If no process, indicate error 1829 if (!m_current_process) 1830 return SendErrorResponse(02); 1831 1832 return SendStopReasonForState(*m_current_process, 1833 m_current_process->GetState(), 1834 /*force_synchronous=*/true); 1835 } 1836 1837 GDBRemoteCommunication::PacketResult 1838 GDBRemoteCommunicationServerLLGS::SendStopReasonForState( 1839 NativeProcessProtocol &process, lldb::StateType process_state, 1840 bool force_synchronous) { 1841 Log *log = GetLog(LLDBLog::Process); 1842 1843 switch (process_state) { 1844 case eStateAttaching: 1845 case eStateLaunching: 1846 case eStateRunning: 1847 case eStateStepping: 1848 case eStateDetached: 1849 // NOTE: gdb protocol doc looks like it should return $OK 1850 // when everything is running (i.e. no stopped result). 1851 return PacketResult::Success; // Ignore 1852 1853 case eStateSuspended: 1854 case eStateStopped: 1855 case eStateCrashed: { 1856 lldb::tid_t tid = process.GetCurrentThreadID(); 1857 // Make sure we set the current thread so g and p packets return the data 1858 // the gdb will expect. 1859 SetCurrentThreadID(tid); 1860 return SendStopReplyPacketForThread(process, tid, force_synchronous); 1861 } 1862 1863 case eStateInvalid: 1864 case eStateUnloaded: 1865 case eStateExited: 1866 return SendWResponse(&process); 1867 1868 default: 1869 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}", 1870 process.GetID(), process_state); 1871 break; 1872 } 1873 1874 return SendErrorResponse(0); 1875 } 1876 1877 GDBRemoteCommunication::PacketResult 1878 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo( 1879 StringExtractorGDBRemote &packet) { 1880 // Fail if we don't have a current process. 1881 if (!m_current_process || 1882 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 1883 return SendErrorResponse(68); 1884 1885 // Ensure we have a thread. 1886 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0); 1887 if (!thread) 1888 return SendErrorResponse(69); 1889 1890 // Get the register context for the first thread. 1891 NativeRegisterContext ®_context = thread->GetRegisterContext(); 1892 1893 // Parse out the register number from the request. 1894 packet.SetFilePos(strlen("qRegisterInfo")); 1895 const uint32_t reg_index = 1896 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 1897 if (reg_index == std::numeric_limits<uint32_t>::max()) 1898 return SendErrorResponse(69); 1899 1900 // Return the end of registers response if we've iterated one past the end of 1901 // the register set. 1902 if (reg_index >= reg_context.GetUserRegisterCount()) 1903 return SendErrorResponse(69); 1904 1905 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 1906 if (!reg_info) 1907 return SendErrorResponse(69); 1908 1909 // Build the reginfos response. 1910 StreamGDBRemote response; 1911 1912 response.PutCString("name:"); 1913 response.PutCString(reg_info->name); 1914 response.PutChar(';'); 1915 1916 if (reg_info->alt_name && reg_info->alt_name[0]) { 1917 response.PutCString("alt-name:"); 1918 response.PutCString(reg_info->alt_name); 1919 response.PutChar(';'); 1920 } 1921 1922 response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8); 1923 1924 if (!reg_context.RegisterOffsetIsDynamic()) 1925 response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset); 1926 1927 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info); 1928 if (!encoding.empty()) 1929 response << "encoding:" << encoding << ';'; 1930 1931 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info); 1932 if (!format.empty()) 1933 response << "format:" << format << ';'; 1934 1935 const char *const register_set_name = 1936 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index); 1937 if (register_set_name) 1938 response << "set:" << register_set_name << ';'; 1939 1940 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != 1941 LLDB_INVALID_REGNUM) 1942 response.Printf("ehframe:%" PRIu32 ";", 1943 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]); 1944 1945 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM) 1946 response.Printf("dwarf:%" PRIu32 ";", 1947 reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 1948 1949 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info); 1950 if (!kind_generic.empty()) 1951 response << "generic:" << kind_generic << ';'; 1952 1953 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) { 1954 response.PutCString("container-regs:"); 1955 CollectRegNums(reg_info->value_regs, response, true); 1956 response.PutChar(';'); 1957 } 1958 1959 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) { 1960 response.PutCString("invalidate-regs:"); 1961 CollectRegNums(reg_info->invalidate_regs, response, true); 1962 response.PutChar(';'); 1963 } 1964 1965 return SendPacketNoLock(response.GetString()); 1966 } 1967 1968 void GDBRemoteCommunicationServerLLGS::AddProcessThreads( 1969 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) { 1970 Log *log = GetLog(LLDBLog::Thread); 1971 1972 lldb::pid_t pid = process.GetID(); 1973 if (pid == LLDB_INVALID_PROCESS_ID) 1974 return; 1975 1976 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID()); 1977 for (NativeThreadProtocol &thread : process.Threads()) { 1978 LLDB_LOG(log, "iterated thread tid={0}", thread.GetID()); 1979 response.PutChar(had_any ? ',' : 'm'); 1980 AppendThreadIDToResponse(response, pid, thread.GetID()); 1981 had_any = true; 1982 } 1983 } 1984 1985 GDBRemoteCommunication::PacketResult 1986 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo( 1987 StringExtractorGDBRemote &packet) { 1988 assert(m_debugged_processes.size() == 1 || 1989 bool(m_extensions_supported & 1990 NativeProcessProtocol::Extension::multiprocess)); 1991 1992 bool had_any = false; 1993 StreamGDBRemote response; 1994 1995 for (auto &pid_ptr : m_debugged_processes) 1996 AddProcessThreads(response, *pid_ptr.second.process_up, had_any); 1997 1998 if (!had_any) 1999 return SendOKResponse(); 2000 return SendPacketNoLock(response.GetString()); 2001 } 2002 2003 GDBRemoteCommunication::PacketResult 2004 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo( 2005 StringExtractorGDBRemote &packet) { 2006 // FIXME for now we return the full thread list in the initial packet and 2007 // always do nothing here. 2008 return SendPacketNoLock("l"); 2009 } 2010 2011 GDBRemoteCommunication::PacketResult 2012 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) { 2013 Log *log = GetLog(LLDBLog::Thread); 2014 2015 // Move past packet name. 2016 packet.SetFilePos(strlen("g")); 2017 2018 // Get the thread to use. 2019 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2020 if (!thread) { 2021 LLDB_LOG(log, "failed, no thread available"); 2022 return SendErrorResponse(0x15); 2023 } 2024 2025 // Get the thread's register context. 2026 NativeRegisterContext ®_ctx = thread->GetRegisterContext(); 2027 2028 std::vector<uint8_t> regs_buffer; 2029 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount(); 2030 ++reg_num) { 2031 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num); 2032 2033 if (reg_info == nullptr) { 2034 LLDB_LOG(log, "failed to get register info for register index {0}", 2035 reg_num); 2036 return SendErrorResponse(0x15); 2037 } 2038 2039 if (reg_info->value_regs != nullptr) 2040 continue; // skip registers that are contained in other registers 2041 2042 RegisterValue reg_value; 2043 Status error = reg_ctx.ReadRegister(reg_info, reg_value); 2044 if (error.Fail()) { 2045 LLDB_LOG(log, "failed to read register at index {0}", reg_num); 2046 return SendErrorResponse(0x15); 2047 } 2048 2049 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size()) 2050 // Resize the buffer to guarantee it can store the register offsetted 2051 // data. 2052 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size); 2053 2054 // Copy the register offsetted data to the buffer. 2055 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(), 2056 reg_info->byte_size); 2057 } 2058 2059 // Write the response. 2060 StreamGDBRemote response; 2061 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size()); 2062 2063 return SendPacketNoLock(response.GetString()); 2064 } 2065 2066 GDBRemoteCommunication::PacketResult 2067 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) { 2068 Log *log = GetLog(LLDBLog::Thread); 2069 2070 // Parse out the register number from the request. 2071 packet.SetFilePos(strlen("p")); 2072 const uint32_t reg_index = 2073 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2074 if (reg_index == std::numeric_limits<uint32_t>::max()) { 2075 LLDB_LOGF(log, 2076 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 2077 "parse register number from request \"%s\"", 2078 __FUNCTION__, packet.GetStringRef().data()); 2079 return SendErrorResponse(0x15); 2080 } 2081 2082 // Get the thread to use. 2083 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2084 if (!thread) { 2085 LLDB_LOG(log, "failed, no thread available"); 2086 return SendErrorResponse(0x15); 2087 } 2088 2089 // Get the thread's register context. 2090 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2091 2092 // Return the end of registers response if we've iterated one past the end of 2093 // the register set. 2094 if (reg_index >= reg_context.GetUserRegisterCount()) { 2095 LLDB_LOGF(log, 2096 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2097 "register %" PRIu32 " beyond register count %" PRIu32, 2098 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 2099 return SendErrorResponse(0x15); 2100 } 2101 2102 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 2103 if (!reg_info) { 2104 LLDB_LOGF(log, 2105 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2106 "register %" PRIu32 " returned NULL", 2107 __FUNCTION__, reg_index); 2108 return SendErrorResponse(0x15); 2109 } 2110 2111 // Build the reginfos response. 2112 StreamGDBRemote response; 2113 2114 // Retrieve the value 2115 RegisterValue reg_value; 2116 Status error = reg_context.ReadRegister(reg_info, reg_value); 2117 if (error.Fail()) { 2118 LLDB_LOGF(log, 2119 "GDBRemoteCommunicationServerLLGS::%s failed, read of " 2120 "requested register %" PRIu32 " (%s) failed: %s", 2121 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 2122 return SendErrorResponse(0x15); 2123 } 2124 2125 const uint8_t *const data = 2126 static_cast<const uint8_t *>(reg_value.GetBytes()); 2127 if (!data) { 2128 LLDB_LOGF(log, 2129 "GDBRemoteCommunicationServerLLGS::%s failed to get data " 2130 "bytes from requested register %" PRIu32, 2131 __FUNCTION__, reg_index); 2132 return SendErrorResponse(0x15); 2133 } 2134 2135 // FIXME flip as needed to get data in big/little endian format for this host. 2136 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i) 2137 response.PutHex8(data[i]); 2138 2139 return SendPacketNoLock(response.GetString()); 2140 } 2141 2142 GDBRemoteCommunication::PacketResult 2143 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) { 2144 Log *log = GetLog(LLDBLog::Thread); 2145 2146 // Ensure there is more content. 2147 if (packet.GetBytesLeft() < 1) 2148 return SendIllFormedResponse(packet, "Empty P packet"); 2149 2150 // Parse out the register number from the request. 2151 packet.SetFilePos(strlen("P")); 2152 const uint32_t reg_index = 2153 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2154 if (reg_index == std::numeric_limits<uint32_t>::max()) { 2155 LLDB_LOGF(log, 2156 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 2157 "parse register number from request \"%s\"", 2158 __FUNCTION__, packet.GetStringRef().data()); 2159 return SendErrorResponse(0x29); 2160 } 2161 2162 // Note debugserver would send an E30 here. 2163 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '=')) 2164 return SendIllFormedResponse( 2165 packet, "P packet missing '=' char after register number"); 2166 2167 // Parse out the value. 2168 uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize]; 2169 size_t reg_size = packet.GetHexBytesAvail(reg_bytes); 2170 2171 // Get the thread to use. 2172 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2173 if (!thread) { 2174 LLDB_LOGF(log, 2175 "GDBRemoteCommunicationServerLLGS::%s failed, no thread " 2176 "available (thread index 0)", 2177 __FUNCTION__); 2178 return SendErrorResponse(0x28); 2179 } 2180 2181 // Get the thread's register context. 2182 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2183 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 2184 if (!reg_info) { 2185 LLDB_LOGF(log, 2186 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2187 "register %" PRIu32 " returned NULL", 2188 __FUNCTION__, reg_index); 2189 return SendErrorResponse(0x48); 2190 } 2191 2192 // Return the end of registers response if we've iterated one past the end of 2193 // the register set. 2194 if (reg_index >= reg_context.GetUserRegisterCount()) { 2195 LLDB_LOGF(log, 2196 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2197 "register %" PRIu32 " beyond register count %" PRIu32, 2198 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 2199 return SendErrorResponse(0x47); 2200 } 2201 2202 if (reg_size != reg_info->byte_size) 2203 return SendIllFormedResponse(packet, "P packet register size is incorrect"); 2204 2205 // Build the reginfos response. 2206 StreamGDBRemote response; 2207 2208 RegisterValue reg_value(makeArrayRef(reg_bytes, reg_size), 2209 m_current_process->GetArchitecture().GetByteOrder()); 2210 Status error = reg_context.WriteRegister(reg_info, reg_value); 2211 if (error.Fail()) { 2212 LLDB_LOGF(log, 2213 "GDBRemoteCommunicationServerLLGS::%s failed, write of " 2214 "requested register %" PRIu32 " (%s) failed: %s", 2215 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 2216 return SendErrorResponse(0x32); 2217 } 2218 2219 return SendOKResponse(); 2220 } 2221 2222 GDBRemoteCommunication::PacketResult 2223 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) { 2224 Log *log = GetLog(LLDBLog::Thread); 2225 2226 // Parse out which variant of $H is requested. 2227 packet.SetFilePos(strlen("H")); 2228 if (packet.GetBytesLeft() < 1) { 2229 LLDB_LOGF(log, 2230 "GDBRemoteCommunicationServerLLGS::%s failed, H command " 2231 "missing {g,c} variant", 2232 __FUNCTION__); 2233 return SendIllFormedResponse(packet, "H command missing {g,c} variant"); 2234 } 2235 2236 const char h_variant = packet.GetChar(); 2237 NativeProcessProtocol *default_process; 2238 switch (h_variant) { 2239 case 'g': 2240 default_process = m_current_process; 2241 break; 2242 2243 case 'c': 2244 default_process = m_continue_process; 2245 break; 2246 2247 default: 2248 LLDB_LOGF( 2249 log, 2250 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", 2251 __FUNCTION__, h_variant); 2252 return SendIllFormedResponse(packet, 2253 "H variant unsupported, should be c or g"); 2254 } 2255 2256 // Parse out the thread number. 2257 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID() 2258 : LLDB_INVALID_PROCESS_ID); 2259 if (!pid_tid) 2260 return SendErrorResponse(llvm::make_error<StringError>( 2261 inconvertibleErrorCode(), "Malformed thread-id")); 2262 2263 lldb::pid_t pid = pid_tid->first; 2264 lldb::tid_t tid = pid_tid->second; 2265 2266 if (pid == StringExtractorGDBRemote::AllProcesses) 2267 return SendUnimplementedResponse("Selecting all processes not supported"); 2268 if (pid == LLDB_INVALID_PROCESS_ID) 2269 return SendErrorResponse(llvm::make_error<StringError>( 2270 inconvertibleErrorCode(), "No current process and no PID provided")); 2271 2272 // Check the process ID and find respective process instance. 2273 auto new_process_it = m_debugged_processes.find(pid); 2274 if (new_process_it == m_debugged_processes.end()) 2275 return SendErrorResponse(llvm::make_error<StringError>( 2276 inconvertibleErrorCode(), 2277 llvm::formatv("No process with PID {0} debugged", pid))); 2278 2279 // Ensure we have the given thread when not specifying -1 (all threads) or 0 2280 // (any thread). 2281 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) { 2282 NativeThreadProtocol *thread = 2283 new_process_it->second.process_up->GetThreadByID(tid); 2284 if (!thread) { 2285 LLDB_LOGF(log, 2286 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 2287 " not found", 2288 __FUNCTION__, tid); 2289 return SendErrorResponse(0x15); 2290 } 2291 } 2292 2293 // Now switch the given process and thread type. 2294 switch (h_variant) { 2295 case 'g': 2296 m_current_process = new_process_it->second.process_up.get(); 2297 SetCurrentThreadID(tid); 2298 break; 2299 2300 case 'c': 2301 m_continue_process = new_process_it->second.process_up.get(); 2302 SetContinueThreadID(tid); 2303 break; 2304 2305 default: 2306 assert(false && "unsupported $H variant - shouldn't get here"); 2307 return SendIllFormedResponse(packet, 2308 "H variant unsupported, should be c or g"); 2309 } 2310 2311 return SendOKResponse(); 2312 } 2313 2314 GDBRemoteCommunication::PacketResult 2315 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) { 2316 Log *log = GetLog(LLDBLog::Thread); 2317 2318 // Fail if we don't have a current process. 2319 if (!m_current_process || 2320 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2321 LLDB_LOGF( 2322 log, 2323 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2324 __FUNCTION__); 2325 return SendErrorResponse(0x15); 2326 } 2327 2328 packet.SetFilePos(::strlen("I")); 2329 uint8_t tmp[4096]; 2330 for (;;) { 2331 size_t read = packet.GetHexBytesAvail(tmp); 2332 if (read == 0) { 2333 break; 2334 } 2335 // write directly to stdin *this might block if stdin buffer is full* 2336 // TODO: enqueue this block in circular buffer and send window size to 2337 // remote host 2338 ConnectionStatus status; 2339 Status error; 2340 m_stdio_communication.Write(tmp, read, status, &error); 2341 if (error.Fail()) { 2342 return SendErrorResponse(0x15); 2343 } 2344 } 2345 2346 return SendOKResponse(); 2347 } 2348 2349 GDBRemoteCommunication::PacketResult 2350 GDBRemoteCommunicationServerLLGS::Handle_interrupt( 2351 StringExtractorGDBRemote &packet) { 2352 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 2353 2354 // Fail if we don't have a current process. 2355 if (!m_current_process || 2356 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2357 LLDB_LOG(log, "failed, no process available"); 2358 return SendErrorResponse(0x15); 2359 } 2360 2361 // Interrupt the process. 2362 Status error = m_current_process->Interrupt(); 2363 if (error.Fail()) { 2364 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(), 2365 error); 2366 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 2367 } 2368 2369 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID()); 2370 2371 // No response required from stop all. 2372 return PacketResult::Success; 2373 } 2374 2375 GDBRemoteCommunication::PacketResult 2376 GDBRemoteCommunicationServerLLGS::Handle_memory_read( 2377 StringExtractorGDBRemote &packet) { 2378 Log *log = GetLog(LLDBLog::Process); 2379 2380 if (!m_current_process || 2381 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2382 LLDB_LOGF( 2383 log, 2384 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2385 __FUNCTION__); 2386 return SendErrorResponse(0x15); 2387 } 2388 2389 // Parse out the memory address. 2390 packet.SetFilePos(strlen("m")); 2391 if (packet.GetBytesLeft() < 1) 2392 return SendIllFormedResponse(packet, "Too short m packet"); 2393 2394 // Read the address. Punting on validation. 2395 // FIXME replace with Hex U64 read with no default value that fails on failed 2396 // read. 2397 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2398 2399 // Validate comma. 2400 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2401 return SendIllFormedResponse(packet, "Comma sep missing in m packet"); 2402 2403 // Get # bytes to read. 2404 if (packet.GetBytesLeft() < 1) 2405 return SendIllFormedResponse(packet, "Length missing in m packet"); 2406 2407 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2408 if (byte_count == 0) { 2409 LLDB_LOGF(log, 2410 "GDBRemoteCommunicationServerLLGS::%s nothing to read: " 2411 "zero-length packet", 2412 __FUNCTION__); 2413 return SendOKResponse(); 2414 } 2415 2416 // Allocate the response buffer. 2417 std::string buf(byte_count, '\0'); 2418 if (buf.empty()) 2419 return SendErrorResponse(0x78); 2420 2421 // Retrieve the process memory. 2422 size_t bytes_read = 0; 2423 Status error = m_current_process->ReadMemoryWithoutTrap( 2424 read_addr, &buf[0], byte_count, bytes_read); 2425 if (error.Fail()) { 2426 LLDB_LOGF(log, 2427 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2428 " mem 0x%" PRIx64 ": failed to read. Error: %s", 2429 __FUNCTION__, m_current_process->GetID(), read_addr, 2430 error.AsCString()); 2431 return SendErrorResponse(0x08); 2432 } 2433 2434 if (bytes_read == 0) { 2435 LLDB_LOGF(log, 2436 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2437 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes", 2438 __FUNCTION__, m_current_process->GetID(), read_addr, byte_count); 2439 return SendErrorResponse(0x08); 2440 } 2441 2442 StreamGDBRemote response; 2443 packet.SetFilePos(0); 2444 char kind = packet.GetChar('?'); 2445 if (kind == 'x') 2446 response.PutEscapedBytes(buf.data(), byte_count); 2447 else { 2448 assert(kind == 'm'); 2449 for (size_t i = 0; i < bytes_read; ++i) 2450 response.PutHex8(buf[i]); 2451 } 2452 2453 return SendPacketNoLock(response.GetString()); 2454 } 2455 2456 GDBRemoteCommunication::PacketResult 2457 GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) { 2458 Log *log = GetLog(LLDBLog::Process); 2459 2460 if (!m_current_process || 2461 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2462 LLDB_LOGF( 2463 log, 2464 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2465 __FUNCTION__); 2466 return SendErrorResponse(0x15); 2467 } 2468 2469 // Parse out the memory address. 2470 packet.SetFilePos(strlen("_M")); 2471 if (packet.GetBytesLeft() < 1) 2472 return SendIllFormedResponse(packet, "Too short _M packet"); 2473 2474 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2475 if (size == LLDB_INVALID_ADDRESS) 2476 return SendIllFormedResponse(packet, "Address not valid"); 2477 if (packet.GetChar() != ',') 2478 return SendIllFormedResponse(packet, "Bad packet"); 2479 Permissions perms = {}; 2480 while (packet.GetBytesLeft() > 0) { 2481 switch (packet.GetChar()) { 2482 case 'r': 2483 perms |= ePermissionsReadable; 2484 break; 2485 case 'w': 2486 perms |= ePermissionsWritable; 2487 break; 2488 case 'x': 2489 perms |= ePermissionsExecutable; 2490 break; 2491 default: 2492 return SendIllFormedResponse(packet, "Bad permissions"); 2493 } 2494 } 2495 2496 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms); 2497 if (!addr) 2498 return SendErrorResponse(addr.takeError()); 2499 2500 StreamGDBRemote response; 2501 response.PutHex64(*addr); 2502 return SendPacketNoLock(response.GetString()); 2503 } 2504 2505 GDBRemoteCommunication::PacketResult 2506 GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) { 2507 Log *log = GetLog(LLDBLog::Process); 2508 2509 if (!m_current_process || 2510 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2511 LLDB_LOGF( 2512 log, 2513 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2514 __FUNCTION__); 2515 return SendErrorResponse(0x15); 2516 } 2517 2518 // Parse out the memory address. 2519 packet.SetFilePos(strlen("_m")); 2520 if (packet.GetBytesLeft() < 1) 2521 return SendIllFormedResponse(packet, "Too short m packet"); 2522 2523 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2524 if (addr == LLDB_INVALID_ADDRESS) 2525 return SendIllFormedResponse(packet, "Address not valid"); 2526 2527 if (llvm::Error Err = m_current_process->DeallocateMemory(addr)) 2528 return SendErrorResponse(std::move(Err)); 2529 2530 return SendOKResponse(); 2531 } 2532 2533 GDBRemoteCommunication::PacketResult 2534 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) { 2535 Log *log = GetLog(LLDBLog::Process); 2536 2537 if (!m_current_process || 2538 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2539 LLDB_LOGF( 2540 log, 2541 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2542 __FUNCTION__); 2543 return SendErrorResponse(0x15); 2544 } 2545 2546 // Parse out the memory address. 2547 packet.SetFilePos(strlen("M")); 2548 if (packet.GetBytesLeft() < 1) 2549 return SendIllFormedResponse(packet, "Too short M packet"); 2550 2551 // Read the address. Punting on validation. 2552 // FIXME replace with Hex U64 read with no default value that fails on failed 2553 // read. 2554 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0); 2555 2556 // Validate comma. 2557 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2558 return SendIllFormedResponse(packet, "Comma sep missing in M packet"); 2559 2560 // Get # bytes to read. 2561 if (packet.GetBytesLeft() < 1) 2562 return SendIllFormedResponse(packet, "Length missing in M packet"); 2563 2564 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2565 if (byte_count == 0) { 2566 LLDB_LOG(log, "nothing to write: zero-length packet"); 2567 return PacketResult::Success; 2568 } 2569 2570 // Validate colon. 2571 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':')) 2572 return SendIllFormedResponse( 2573 packet, "Comma sep missing in M packet after byte length"); 2574 2575 // Allocate the conversion buffer. 2576 std::vector<uint8_t> buf(byte_count, 0); 2577 if (buf.empty()) 2578 return SendErrorResponse(0x78); 2579 2580 // Convert the hex memory write contents to bytes. 2581 StreamGDBRemote response; 2582 const uint64_t convert_count = packet.GetHexBytes(buf, 0); 2583 if (convert_count != byte_count) { 2584 LLDB_LOG(log, 2585 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} " 2586 "to convert.", 2587 m_current_process->GetID(), write_addr, byte_count, convert_count); 2588 return SendIllFormedResponse(packet, "M content byte length specified did " 2589 "not match hex-encoded content " 2590 "length"); 2591 } 2592 2593 // Write the process memory. 2594 size_t bytes_written = 0; 2595 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count, 2596 bytes_written); 2597 if (error.Fail()) { 2598 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}", 2599 m_current_process->GetID(), write_addr, error); 2600 return SendErrorResponse(0x09); 2601 } 2602 2603 if (bytes_written == 0) { 2604 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes", 2605 m_current_process->GetID(), write_addr, byte_count); 2606 return SendErrorResponse(0x09); 2607 } 2608 2609 return SendOKResponse(); 2610 } 2611 2612 GDBRemoteCommunication::PacketResult 2613 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported( 2614 StringExtractorGDBRemote &packet) { 2615 Log *log = GetLog(LLDBLog::Process); 2616 2617 // Currently only the NativeProcessProtocol knows if it can handle a 2618 // qMemoryRegionInfoSupported request, but we're not guaranteed to be 2619 // attached to a process. For now we'll assume the client only asks this 2620 // when a process is being debugged. 2621 2622 // Ensure we have a process running; otherwise, we can't figure this out 2623 // since we won't have a NativeProcessProtocol. 2624 if (!m_current_process || 2625 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2626 LLDB_LOGF( 2627 log, 2628 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2629 __FUNCTION__); 2630 return SendErrorResponse(0x15); 2631 } 2632 2633 // Test if we can get any region back when asking for the region around NULL. 2634 MemoryRegionInfo region_info; 2635 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info); 2636 if (error.Fail()) { 2637 // We don't support memory region info collection for this 2638 // NativeProcessProtocol. 2639 return SendUnimplementedResponse(""); 2640 } 2641 2642 return SendOKResponse(); 2643 } 2644 2645 GDBRemoteCommunication::PacketResult 2646 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo( 2647 StringExtractorGDBRemote &packet) { 2648 Log *log = GetLog(LLDBLog::Process); 2649 2650 // Ensure we have a process. 2651 if (!m_current_process || 2652 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2653 LLDB_LOGF( 2654 log, 2655 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2656 __FUNCTION__); 2657 return SendErrorResponse(0x15); 2658 } 2659 2660 // Parse out the memory address. 2661 packet.SetFilePos(strlen("qMemoryRegionInfo:")); 2662 if (packet.GetBytesLeft() < 1) 2663 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet"); 2664 2665 // Read the address. Punting on validation. 2666 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2667 2668 StreamGDBRemote response; 2669 2670 // Get the memory region info for the target address. 2671 MemoryRegionInfo region_info; 2672 const Status error = 2673 m_current_process->GetMemoryRegionInfo(read_addr, region_info); 2674 if (error.Fail()) { 2675 // Return the error message. 2676 2677 response.PutCString("error:"); 2678 response.PutStringAsRawHex8(error.AsCString()); 2679 response.PutChar(';'); 2680 } else { 2681 // Range start and size. 2682 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";", 2683 region_info.GetRange().GetRangeBase(), 2684 region_info.GetRange().GetByteSize()); 2685 2686 // Permissions. 2687 if (region_info.GetReadable() || region_info.GetWritable() || 2688 region_info.GetExecutable()) { 2689 // Write permissions info. 2690 response.PutCString("permissions:"); 2691 2692 if (region_info.GetReadable()) 2693 response.PutChar('r'); 2694 if (region_info.GetWritable()) 2695 response.PutChar('w'); 2696 if (region_info.GetExecutable()) 2697 response.PutChar('x'); 2698 2699 response.PutChar(';'); 2700 } 2701 2702 // Flags 2703 MemoryRegionInfo::OptionalBool memory_tagged = 2704 region_info.GetMemoryTagged(); 2705 if (memory_tagged != MemoryRegionInfo::eDontKnow) { 2706 response.PutCString("flags:"); 2707 if (memory_tagged == MemoryRegionInfo::eYes) { 2708 response.PutCString("mt"); 2709 } 2710 response.PutChar(';'); 2711 } 2712 2713 // Name 2714 ConstString name = region_info.GetName(); 2715 if (name) { 2716 response.PutCString("name:"); 2717 response.PutStringAsRawHex8(name.GetStringRef()); 2718 response.PutChar(';'); 2719 } 2720 } 2721 2722 return SendPacketNoLock(response.GetString()); 2723 } 2724 2725 GDBRemoteCommunication::PacketResult 2726 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) { 2727 // Ensure we have a process. 2728 if (!m_current_process || 2729 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2730 Log *log = GetLog(LLDBLog::Process); 2731 LLDB_LOG(log, "failed, no process available"); 2732 return SendErrorResponse(0x15); 2733 } 2734 2735 // Parse out software or hardware breakpoint or watchpoint requested. 2736 packet.SetFilePos(strlen("Z")); 2737 if (packet.GetBytesLeft() < 1) 2738 return SendIllFormedResponse( 2739 packet, "Too short Z packet, missing software/hardware specifier"); 2740 2741 bool want_breakpoint = true; 2742 bool want_hardware = false; 2743 uint32_t watch_flags = 0; 2744 2745 const GDBStoppointType stoppoint_type = 2746 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2747 switch (stoppoint_type) { 2748 case eBreakpointSoftware: 2749 want_hardware = false; 2750 want_breakpoint = true; 2751 break; 2752 case eBreakpointHardware: 2753 want_hardware = true; 2754 want_breakpoint = true; 2755 break; 2756 case eWatchpointWrite: 2757 watch_flags = 1; 2758 want_hardware = true; 2759 want_breakpoint = false; 2760 break; 2761 case eWatchpointRead: 2762 watch_flags = 2; 2763 want_hardware = true; 2764 want_breakpoint = false; 2765 break; 2766 case eWatchpointReadWrite: 2767 watch_flags = 3; 2768 want_hardware = true; 2769 want_breakpoint = false; 2770 break; 2771 case eStoppointInvalid: 2772 return SendIllFormedResponse( 2773 packet, "Z packet had invalid software/hardware specifier"); 2774 } 2775 2776 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2777 return SendIllFormedResponse( 2778 packet, "Malformed Z packet, expecting comma after stoppoint type"); 2779 2780 // Parse out the stoppoint address. 2781 if (packet.GetBytesLeft() < 1) 2782 return SendIllFormedResponse(packet, "Too short Z packet, missing address"); 2783 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2784 2785 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2786 return SendIllFormedResponse( 2787 packet, "Malformed Z packet, expecting comma after address"); 2788 2789 // Parse out the stoppoint size (i.e. size hint for opcode size). 2790 const uint32_t size = 2791 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2792 if (size == std::numeric_limits<uint32_t>::max()) 2793 return SendIllFormedResponse( 2794 packet, "Malformed Z packet, failed to parse size argument"); 2795 2796 if (want_breakpoint) { 2797 // Try to set the breakpoint. 2798 const Status error = 2799 m_current_process->SetBreakpoint(addr, size, want_hardware); 2800 if (error.Success()) 2801 return SendOKResponse(); 2802 Log *log = GetLog(LLDBLog::Breakpoints); 2803 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}", 2804 m_current_process->GetID(), error); 2805 return SendErrorResponse(0x09); 2806 } else { 2807 // Try to set the watchpoint. 2808 const Status error = m_current_process->SetWatchpoint( 2809 addr, size, watch_flags, want_hardware); 2810 if (error.Success()) 2811 return SendOKResponse(); 2812 Log *log = GetLog(LLDBLog::Watchpoints); 2813 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}", 2814 m_current_process->GetID(), error); 2815 return SendErrorResponse(0x09); 2816 } 2817 } 2818 2819 GDBRemoteCommunication::PacketResult 2820 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) { 2821 // Ensure we have a process. 2822 if (!m_current_process || 2823 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2824 Log *log = GetLog(LLDBLog::Process); 2825 LLDB_LOG(log, "failed, no process available"); 2826 return SendErrorResponse(0x15); 2827 } 2828 2829 // Parse out software or hardware breakpoint or watchpoint requested. 2830 packet.SetFilePos(strlen("z")); 2831 if (packet.GetBytesLeft() < 1) 2832 return SendIllFormedResponse( 2833 packet, "Too short z packet, missing software/hardware specifier"); 2834 2835 bool want_breakpoint = true; 2836 bool want_hardware = false; 2837 2838 const GDBStoppointType stoppoint_type = 2839 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2840 switch (stoppoint_type) { 2841 case eBreakpointHardware: 2842 want_breakpoint = true; 2843 want_hardware = true; 2844 break; 2845 case eBreakpointSoftware: 2846 want_breakpoint = true; 2847 break; 2848 case eWatchpointWrite: 2849 want_breakpoint = false; 2850 break; 2851 case eWatchpointRead: 2852 want_breakpoint = false; 2853 break; 2854 case eWatchpointReadWrite: 2855 want_breakpoint = false; 2856 break; 2857 default: 2858 return SendIllFormedResponse( 2859 packet, "z packet had invalid software/hardware specifier"); 2860 } 2861 2862 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2863 return SendIllFormedResponse( 2864 packet, "Malformed z packet, expecting comma after stoppoint type"); 2865 2866 // Parse out the stoppoint address. 2867 if (packet.GetBytesLeft() < 1) 2868 return SendIllFormedResponse(packet, "Too short z packet, missing address"); 2869 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2870 2871 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2872 return SendIllFormedResponse( 2873 packet, "Malformed z packet, expecting comma after address"); 2874 2875 /* 2876 // Parse out the stoppoint size (i.e. size hint for opcode size). 2877 const uint32_t size = packet.GetHexMaxU32 (false, 2878 std::numeric_limits<uint32_t>::max ()); 2879 if (size == std::numeric_limits<uint32_t>::max ()) 2880 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse 2881 size argument"); 2882 */ 2883 2884 if (want_breakpoint) { 2885 // Try to clear the breakpoint. 2886 const Status error = 2887 m_current_process->RemoveBreakpoint(addr, want_hardware); 2888 if (error.Success()) 2889 return SendOKResponse(); 2890 Log *log = GetLog(LLDBLog::Breakpoints); 2891 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}", 2892 m_current_process->GetID(), error); 2893 return SendErrorResponse(0x09); 2894 } else { 2895 // Try to clear the watchpoint. 2896 const Status error = m_current_process->RemoveWatchpoint(addr); 2897 if (error.Success()) 2898 return SendOKResponse(); 2899 Log *log = GetLog(LLDBLog::Watchpoints); 2900 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}", 2901 m_current_process->GetID(), error); 2902 return SendErrorResponse(0x09); 2903 } 2904 } 2905 2906 GDBRemoteCommunication::PacketResult 2907 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) { 2908 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 2909 2910 // Ensure we have a process. 2911 if (!m_continue_process || 2912 (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2913 LLDB_LOGF( 2914 log, 2915 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2916 __FUNCTION__); 2917 return SendErrorResponse(0x32); 2918 } 2919 2920 // We first try to use a continue thread id. If any one or any all set, use 2921 // the current thread. Bail out if we don't have a thread id. 2922 lldb::tid_t tid = GetContinueThreadID(); 2923 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID) 2924 tid = GetCurrentThreadID(); 2925 if (tid == LLDB_INVALID_THREAD_ID) 2926 return SendErrorResponse(0x33); 2927 2928 // Double check that we have such a thread. 2929 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here. 2930 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid); 2931 if (!thread) 2932 return SendErrorResponse(0x33); 2933 2934 // Create the step action for the given thread. 2935 ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER}; 2936 2937 // Setup the actions list. 2938 ResumeActionList actions; 2939 actions.Append(action); 2940 2941 // All other threads stop while we're single stepping a thread. 2942 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); 2943 Status error = m_continue_process->Resume(actions); 2944 if (error.Fail()) { 2945 LLDB_LOGF(log, 2946 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2947 " tid %" PRIu64 " Resume() failed with error: %s", 2948 __FUNCTION__, m_continue_process->GetID(), tid, 2949 error.AsCString()); 2950 return SendErrorResponse(0x49); 2951 } 2952 2953 // No response here, unless in non-stop mode. 2954 // Otherwise, the stop or exit will come from the resulting action. 2955 return SendContinueSuccessResponse(); 2956 } 2957 2958 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 2959 GDBRemoteCommunicationServerLLGS::BuildTargetXml() { 2960 // Ensure we have a thread. 2961 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0); 2962 if (!thread) 2963 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2964 "No thread available"); 2965 2966 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 2967 // Get the register context for the first thread. 2968 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2969 2970 StreamString response; 2971 2972 response.Printf("<?xml version=\"1.0\"?>"); 2973 response.Printf("<target version=\"1.0\">"); 2974 2975 response.Printf("<architecture>%s</architecture>", 2976 m_current_process->GetArchitecture() 2977 .GetTriple() 2978 .getArchName() 2979 .str() 2980 .c_str()); 2981 2982 response.Printf("<feature>"); 2983 2984 const int registers_count = reg_context.GetUserRegisterCount(); 2985 for (int reg_index = 0; reg_index < registers_count; reg_index++) { 2986 const RegisterInfo *reg_info = 2987 reg_context.GetRegisterInfoAtIndex(reg_index); 2988 2989 if (!reg_info) { 2990 LLDB_LOGF(log, 2991 "%s failed to get register info for register index %" PRIu32, 2992 "target.xml", reg_index); 2993 continue; 2994 } 2995 2996 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" regnum=\"%d\" ", 2997 reg_info->name, reg_info->byte_size * 8, reg_index); 2998 2999 if (!reg_context.RegisterOffsetIsDynamic()) 3000 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset); 3001 3002 if (reg_info->alt_name && reg_info->alt_name[0]) 3003 response.Printf("altname=\"%s\" ", reg_info->alt_name); 3004 3005 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info); 3006 if (!encoding.empty()) 3007 response << "encoding=\"" << encoding << "\" "; 3008 3009 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info); 3010 if (!format.empty()) 3011 response << "format=\"" << format << "\" "; 3012 3013 const char *const register_set_name = 3014 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index); 3015 if (register_set_name) 3016 response << "group=\"" << register_set_name << "\" "; 3017 3018 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != 3019 LLDB_INVALID_REGNUM) 3020 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ", 3021 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]); 3022 3023 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != 3024 LLDB_INVALID_REGNUM) 3025 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ", 3026 reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 3027 3028 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info); 3029 if (!kind_generic.empty()) 3030 response << "generic=\"" << kind_generic << "\" "; 3031 3032 if (reg_info->value_regs && 3033 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) { 3034 response.PutCString("value_regnums=\""); 3035 CollectRegNums(reg_info->value_regs, response, false); 3036 response.Printf("\" "); 3037 } 3038 3039 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) { 3040 response.PutCString("invalidate_regnums=\""); 3041 CollectRegNums(reg_info->invalidate_regs, response, false); 3042 response.Printf("\" "); 3043 } 3044 3045 response.Printf("/>"); 3046 } 3047 3048 response.Printf("</feature>"); 3049 response.Printf("</target>"); 3050 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml"); 3051 } 3052 3053 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 3054 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object, 3055 llvm::StringRef annex) { 3056 // Make sure we have a valid process. 3057 if (!m_current_process || 3058 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3059 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3060 "No process available"); 3061 } 3062 3063 if (object == "auxv") { 3064 // Grab the auxv data. 3065 auto buffer_or_error = m_current_process->GetAuxvData(); 3066 if (!buffer_or_error) 3067 return llvm::errorCodeToError(buffer_or_error.getError()); 3068 return std::move(*buffer_or_error); 3069 } 3070 3071 if (object == "siginfo") { 3072 NativeThreadProtocol *thread = m_current_process->GetCurrentThread(); 3073 if (!thread) 3074 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3075 "no current thread"); 3076 3077 auto buffer_or_error = thread->GetSiginfo(); 3078 if (!buffer_or_error) 3079 return buffer_or_error.takeError(); 3080 return std::move(*buffer_or_error); 3081 } 3082 3083 if (object == "libraries-svr4") { 3084 auto library_list = m_current_process->GetLoadedSVR4Libraries(); 3085 if (!library_list) 3086 return library_list.takeError(); 3087 3088 StreamString response; 3089 response.Printf("<library-list-svr4 version=\"1.0\">"); 3090 for (auto const &library : *library_list) { 3091 response.Printf("<library name=\"%s\" ", 3092 XMLEncodeAttributeValue(library.name.c_str()).c_str()); 3093 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map); 3094 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr); 3095 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr); 3096 } 3097 response.Printf("</library-list-svr4>"); 3098 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__); 3099 } 3100 3101 if (object == "features" && annex == "target.xml") 3102 return BuildTargetXml(); 3103 3104 return llvm::make_error<UnimplementedError>(); 3105 } 3106 3107 GDBRemoteCommunication::PacketResult 3108 GDBRemoteCommunicationServerLLGS::Handle_qXfer( 3109 StringExtractorGDBRemote &packet) { 3110 SmallVector<StringRef, 5> fields; 3111 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length" 3112 StringRef(packet.GetStringRef()).split(fields, ':', 4); 3113 if (fields.size() != 5) 3114 return SendIllFormedResponse(packet, "malformed qXfer packet"); 3115 StringRef &xfer_object = fields[1]; 3116 StringRef &xfer_action = fields[2]; 3117 StringRef &xfer_annex = fields[3]; 3118 StringExtractor offset_data(fields[4]); 3119 if (xfer_action != "read") 3120 return SendUnimplementedResponse("qXfer action not supported"); 3121 // Parse offset. 3122 const uint64_t xfer_offset = 3123 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 3124 if (xfer_offset == std::numeric_limits<uint64_t>::max()) 3125 return SendIllFormedResponse(packet, "qXfer packet missing offset"); 3126 // Parse out comma. 3127 if (offset_data.GetChar() != ',') 3128 return SendIllFormedResponse(packet, 3129 "qXfer packet missing comma after offset"); 3130 // Parse out the length. 3131 const uint64_t xfer_length = 3132 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 3133 if (xfer_length == std::numeric_limits<uint64_t>::max()) 3134 return SendIllFormedResponse(packet, "qXfer packet missing length"); 3135 3136 // Get a previously constructed buffer if it exists or create it now. 3137 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str(); 3138 auto buffer_it = m_xfer_buffer_map.find(buffer_key); 3139 if (buffer_it == m_xfer_buffer_map.end()) { 3140 auto buffer_up = ReadXferObject(xfer_object, xfer_annex); 3141 if (!buffer_up) 3142 return SendErrorResponse(buffer_up.takeError()); 3143 buffer_it = m_xfer_buffer_map 3144 .insert(std::make_pair(buffer_key, std::move(*buffer_up))) 3145 .first; 3146 } 3147 3148 // Send back the response 3149 StreamGDBRemote response; 3150 bool done_with_buffer = false; 3151 llvm::StringRef buffer = buffer_it->second->getBuffer(); 3152 if (xfer_offset >= buffer.size()) { 3153 // We have nothing left to send. Mark the buffer as complete. 3154 response.PutChar('l'); 3155 done_with_buffer = true; 3156 } else { 3157 // Figure out how many bytes are available starting at the given offset. 3158 buffer = buffer.drop_front(xfer_offset); 3159 // Mark the response type according to whether we're reading the remainder 3160 // of the data. 3161 if (xfer_length >= buffer.size()) { 3162 // There will be nothing left to read after this 3163 response.PutChar('l'); 3164 done_with_buffer = true; 3165 } else { 3166 // There will still be bytes to read after this request. 3167 response.PutChar('m'); 3168 buffer = buffer.take_front(xfer_length); 3169 } 3170 // Now write the data in encoded binary form. 3171 response.PutEscapedBytes(buffer.data(), buffer.size()); 3172 } 3173 3174 if (done_with_buffer) 3175 m_xfer_buffer_map.erase(buffer_it); 3176 3177 return SendPacketNoLock(response.GetString()); 3178 } 3179 3180 GDBRemoteCommunication::PacketResult 3181 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState( 3182 StringExtractorGDBRemote &packet) { 3183 Log *log = GetLog(LLDBLog::Thread); 3184 3185 // Move past packet name. 3186 packet.SetFilePos(strlen("QSaveRegisterState")); 3187 3188 // Get the thread to use. 3189 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3190 if (!thread) { 3191 if (m_thread_suffix_supported) 3192 return SendIllFormedResponse( 3193 packet, "No thread specified in QSaveRegisterState packet"); 3194 else 3195 return SendIllFormedResponse(packet, 3196 "No thread was is set with the Hg packet"); 3197 } 3198 3199 // Grab the register context for the thread. 3200 NativeRegisterContext& reg_context = thread->GetRegisterContext(); 3201 3202 // Save registers to a buffer. 3203 WritableDataBufferSP register_data_sp; 3204 Status error = reg_context.ReadAllRegisterValues(register_data_sp); 3205 if (error.Fail()) { 3206 LLDB_LOG(log, "pid {0} failed to save all register values: {1}", 3207 m_current_process->GetID(), error); 3208 return SendErrorResponse(0x75); 3209 } 3210 3211 // Allocate a new save id. 3212 const uint32_t save_id = GetNextSavedRegistersID(); 3213 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) && 3214 "GetNextRegisterSaveID() returned an existing register save id"); 3215 3216 // Save the register data buffer under the save id. 3217 { 3218 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3219 m_saved_registers_map[save_id] = register_data_sp; 3220 } 3221 3222 // Write the response. 3223 StreamGDBRemote response; 3224 response.Printf("%" PRIu32, save_id); 3225 return SendPacketNoLock(response.GetString()); 3226 } 3227 3228 GDBRemoteCommunication::PacketResult 3229 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState( 3230 StringExtractorGDBRemote &packet) { 3231 Log *log = GetLog(LLDBLog::Thread); 3232 3233 // Parse out save id. 3234 packet.SetFilePos(strlen("QRestoreRegisterState:")); 3235 if (packet.GetBytesLeft() < 1) 3236 return SendIllFormedResponse( 3237 packet, "QRestoreRegisterState packet missing register save id"); 3238 3239 const uint32_t save_id = packet.GetU32(0); 3240 if (save_id == 0) { 3241 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, " 3242 "expecting decimal uint32_t"); 3243 return SendErrorResponse(0x76); 3244 } 3245 3246 // Get the thread to use. 3247 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3248 if (!thread) { 3249 if (m_thread_suffix_supported) 3250 return SendIllFormedResponse( 3251 packet, "No thread specified in QRestoreRegisterState packet"); 3252 else 3253 return SendIllFormedResponse(packet, 3254 "No thread was is set with the Hg packet"); 3255 } 3256 3257 // Grab the register context for the thread. 3258 NativeRegisterContext ®_context = thread->GetRegisterContext(); 3259 3260 // Retrieve register state buffer, then remove from the list. 3261 DataBufferSP register_data_sp; 3262 { 3263 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3264 3265 // Find the register set buffer for the given save id. 3266 auto it = m_saved_registers_map.find(save_id); 3267 if (it == m_saved_registers_map.end()) { 3268 LLDB_LOG(log, 3269 "pid {0} does not have a register set save buffer for id {1}", 3270 m_current_process->GetID(), save_id); 3271 return SendErrorResponse(0x77); 3272 } 3273 register_data_sp = it->second; 3274 3275 // Remove it from the map. 3276 m_saved_registers_map.erase(it); 3277 } 3278 3279 Status error = reg_context.WriteAllRegisterValues(register_data_sp); 3280 if (error.Fail()) { 3281 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}", 3282 m_current_process->GetID(), error); 3283 return SendErrorResponse(0x77); 3284 } 3285 3286 return SendOKResponse(); 3287 } 3288 3289 GDBRemoteCommunication::PacketResult 3290 GDBRemoteCommunicationServerLLGS::Handle_vAttach( 3291 StringExtractorGDBRemote &packet) { 3292 Log *log = GetLog(LLDBLog::Process); 3293 3294 // Consume the ';' after vAttach. 3295 packet.SetFilePos(strlen("vAttach")); 3296 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3297 return SendIllFormedResponse(packet, "vAttach missing expected ';'"); 3298 3299 // Grab the PID to which we will attach (assume hex encoding). 3300 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3301 if (pid == LLDB_INVALID_PROCESS_ID) 3302 return SendIllFormedResponse(packet, 3303 "vAttach failed to parse the process id"); 3304 3305 // Attempt to attach. 3306 LLDB_LOGF(log, 3307 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to " 3308 "pid %" PRIu64, 3309 __FUNCTION__, pid); 3310 3311 Status error = AttachToProcess(pid); 3312 3313 if (error.Fail()) { 3314 LLDB_LOGF(log, 3315 "GDBRemoteCommunicationServerLLGS::%s failed to attach to " 3316 "pid %" PRIu64 ": %s\n", 3317 __FUNCTION__, pid, error.AsCString()); 3318 return SendErrorResponse(error); 3319 } 3320 3321 // Notify we attached by sending a stop packet. 3322 assert(m_current_process); 3323 return SendStopReasonForState(*m_current_process, 3324 m_current_process->GetState(), 3325 /*force_synchronous=*/false); 3326 } 3327 3328 GDBRemoteCommunication::PacketResult 3329 GDBRemoteCommunicationServerLLGS::Handle_vAttachWait( 3330 StringExtractorGDBRemote &packet) { 3331 Log *log = GetLog(LLDBLog::Process); 3332 3333 // Consume the ';' after the identifier. 3334 packet.SetFilePos(strlen("vAttachWait")); 3335 3336 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3337 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'"); 3338 3339 // Allocate the buffer for the process name from vAttachWait. 3340 std::string process_name; 3341 if (!packet.GetHexByteString(process_name)) 3342 return SendIllFormedResponse(packet, 3343 "vAttachWait failed to parse process name"); 3344 3345 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name); 3346 3347 Status error = AttachWaitProcess(process_name, false); 3348 if (error.Fail()) { 3349 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name, 3350 error); 3351 return SendErrorResponse(error); 3352 } 3353 3354 // Notify we attached by sending a stop packet. 3355 assert(m_current_process); 3356 return SendStopReasonForState(*m_current_process, 3357 m_current_process->GetState(), 3358 /*force_synchronous=*/false); 3359 } 3360 3361 GDBRemoteCommunication::PacketResult 3362 GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported( 3363 StringExtractorGDBRemote &packet) { 3364 return SendOKResponse(); 3365 } 3366 3367 GDBRemoteCommunication::PacketResult 3368 GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait( 3369 StringExtractorGDBRemote &packet) { 3370 Log *log = GetLog(LLDBLog::Process); 3371 3372 // Consume the ';' after the identifier. 3373 packet.SetFilePos(strlen("vAttachOrWait")); 3374 3375 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3376 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'"); 3377 3378 // Allocate the buffer for the process name from vAttachWait. 3379 std::string process_name; 3380 if (!packet.GetHexByteString(process_name)) 3381 return SendIllFormedResponse(packet, 3382 "vAttachOrWait failed to parse process name"); 3383 3384 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name); 3385 3386 Status error = AttachWaitProcess(process_name, true); 3387 if (error.Fail()) { 3388 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name, 3389 error); 3390 return SendErrorResponse(error); 3391 } 3392 3393 // Notify we attached by sending a stop packet. 3394 assert(m_current_process); 3395 return SendStopReasonForState(*m_current_process, 3396 m_current_process->GetState(), 3397 /*force_synchronous=*/false); 3398 } 3399 3400 GDBRemoteCommunication::PacketResult 3401 GDBRemoteCommunicationServerLLGS::Handle_vRun( 3402 StringExtractorGDBRemote &packet) { 3403 Log *log = GetLog(LLDBLog::Process); 3404 3405 llvm::StringRef s = packet.GetStringRef(); 3406 if (!s.consume_front("vRun;")) 3407 return SendErrorResponse(8); 3408 3409 llvm::SmallVector<llvm::StringRef, 16> argv; 3410 s.split(argv, ';'); 3411 3412 for (llvm::StringRef hex_arg : argv) { 3413 StringExtractor arg_ext{hex_arg}; 3414 std::string arg; 3415 arg_ext.GetHexByteString(arg); 3416 m_process_launch_info.GetArguments().AppendArgument(arg); 3417 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__, 3418 arg.c_str()); 3419 } 3420 3421 if (!argv.empty()) { 3422 m_process_launch_info.GetExecutableFile().SetFile( 3423 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native); 3424 m_process_launch_error = LaunchProcess(); 3425 if (m_process_launch_error.Success()) { 3426 assert(m_current_process); 3427 return SendStopReasonForState(*m_current_process, 3428 m_current_process->GetState(), 3429 /*force_synchronous=*/true); 3430 } 3431 LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error); 3432 } 3433 return SendErrorResponse(8); 3434 } 3435 3436 GDBRemoteCommunication::PacketResult 3437 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) { 3438 Log *log = GetLog(LLDBLog::Process); 3439 StopSTDIOForwarding(); 3440 3441 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 3442 3443 // Consume the ';' after D. 3444 packet.SetFilePos(1); 3445 if (packet.GetBytesLeft()) { 3446 if (packet.GetChar() != ';') 3447 return SendIllFormedResponse(packet, "D missing expected ';'"); 3448 3449 // Grab the PID from which we will detach (assume hex encoding). 3450 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3451 if (pid == LLDB_INVALID_PROCESS_ID) 3452 return SendIllFormedResponse(packet, "D failed to parse the process id"); 3453 } 3454 3455 // Detach forked children if their PID was specified *or* no PID was requested 3456 // (i.e. detach-all packet). 3457 llvm::Error detach_error = llvm::Error::success(); 3458 bool detached = false; 3459 for (auto it = m_debugged_processes.begin(); 3460 it != m_debugged_processes.end();) { 3461 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) { 3462 LLDB_LOGF(log, 3463 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64, 3464 __FUNCTION__, it->first); 3465 if (llvm::Error e = it->second.process_up->Detach().ToError()) 3466 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e)); 3467 else { 3468 if (it->second.process_up.get() == m_current_process) 3469 m_current_process = nullptr; 3470 if (it->second.process_up.get() == m_continue_process) 3471 m_continue_process = nullptr; 3472 it = m_debugged_processes.erase(it); 3473 detached = true; 3474 continue; 3475 } 3476 } 3477 ++it; 3478 } 3479 3480 if (detach_error) 3481 return SendErrorResponse(std::move(detach_error)); 3482 if (!detached) 3483 return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid)); 3484 return SendOKResponse(); 3485 } 3486 3487 GDBRemoteCommunication::PacketResult 3488 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo( 3489 StringExtractorGDBRemote &packet) { 3490 Log *log = GetLog(LLDBLog::Thread); 3491 3492 if (!m_current_process || 3493 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3494 return SendErrorResponse(50); 3495 3496 packet.SetFilePos(strlen("qThreadStopInfo")); 3497 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 3498 if (tid == LLDB_INVALID_THREAD_ID) { 3499 LLDB_LOGF(log, 3500 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 3501 "parse thread id from request \"%s\"", 3502 __FUNCTION__, packet.GetStringRef().data()); 3503 return SendErrorResponse(0x15); 3504 } 3505 return SendStopReplyPacketForThread(*m_current_process, tid, 3506 /*force_synchronous=*/true); 3507 } 3508 3509 GDBRemoteCommunication::PacketResult 3510 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo( 3511 StringExtractorGDBRemote &) { 3512 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 3513 3514 // Ensure we have a debugged process. 3515 if (!m_current_process || 3516 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3517 return SendErrorResponse(50); 3518 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID()); 3519 3520 StreamString response; 3521 const bool threads_with_valid_stop_info_only = false; 3522 llvm::Expected<json::Value> threads_info = 3523 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only); 3524 if (!threads_info) { 3525 LLDB_LOG_ERROR(log, threads_info.takeError(), 3526 "failed to prepare a packet for pid {1}: {0}", 3527 m_current_process->GetID()); 3528 return SendErrorResponse(52); 3529 } 3530 3531 response.AsRawOstream() << *threads_info; 3532 StreamGDBRemote escaped_response; 3533 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize()); 3534 return SendPacketNoLock(escaped_response.GetString()); 3535 } 3536 3537 GDBRemoteCommunication::PacketResult 3538 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo( 3539 StringExtractorGDBRemote &packet) { 3540 // Fail if we don't have a current process. 3541 if (!m_current_process || 3542 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3543 return SendErrorResponse(68); 3544 3545 packet.SetFilePos(strlen("qWatchpointSupportInfo")); 3546 if (packet.GetBytesLeft() == 0) 3547 return SendOKResponse(); 3548 if (packet.GetChar() != ':') 3549 return SendErrorResponse(67); 3550 3551 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo(); 3552 3553 StreamGDBRemote response; 3554 if (hw_debug_cap == llvm::None) 3555 response.Printf("num:0;"); 3556 else 3557 response.Printf("num:%d;", hw_debug_cap->second); 3558 3559 return SendPacketNoLock(response.GetString()); 3560 } 3561 3562 GDBRemoteCommunication::PacketResult 3563 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress( 3564 StringExtractorGDBRemote &packet) { 3565 // Fail if we don't have a current process. 3566 if (!m_current_process || 3567 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3568 return SendErrorResponse(67); 3569 3570 packet.SetFilePos(strlen("qFileLoadAddress:")); 3571 if (packet.GetBytesLeft() == 0) 3572 return SendErrorResponse(68); 3573 3574 std::string file_name; 3575 packet.GetHexByteString(file_name); 3576 3577 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS; 3578 Status error = 3579 m_current_process->GetFileLoadAddress(file_name, file_load_address); 3580 if (error.Fail()) 3581 return SendErrorResponse(69); 3582 3583 if (file_load_address == LLDB_INVALID_ADDRESS) 3584 return SendErrorResponse(1); // File not loaded 3585 3586 StreamGDBRemote response; 3587 response.PutHex64(file_load_address); 3588 return SendPacketNoLock(response.GetString()); 3589 } 3590 3591 GDBRemoteCommunication::PacketResult 3592 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals( 3593 StringExtractorGDBRemote &packet) { 3594 std::vector<int> signals; 3595 packet.SetFilePos(strlen("QPassSignals:")); 3596 3597 // Read sequence of hex signal numbers divided by a semicolon and optionally 3598 // spaces. 3599 while (packet.GetBytesLeft() > 0) { 3600 int signal = packet.GetS32(-1, 16); 3601 if (signal < 0) 3602 return SendIllFormedResponse(packet, "Failed to parse signal number."); 3603 signals.push_back(signal); 3604 3605 packet.SkipSpaces(); 3606 char separator = packet.GetChar(); 3607 if (separator == '\0') 3608 break; // End of string 3609 if (separator != ';') 3610 return SendIllFormedResponse(packet, "Invalid separator," 3611 " expected semicolon."); 3612 } 3613 3614 // Fail if we don't have a current process. 3615 if (!m_current_process) 3616 return SendErrorResponse(68); 3617 3618 Status error = m_current_process->IgnoreSignals(signals); 3619 if (error.Fail()) 3620 return SendErrorResponse(69); 3621 3622 return SendOKResponse(); 3623 } 3624 3625 GDBRemoteCommunication::PacketResult 3626 GDBRemoteCommunicationServerLLGS::Handle_qMemTags( 3627 StringExtractorGDBRemote &packet) { 3628 Log *log = GetLog(LLDBLog::Process); 3629 3630 // Ensure we have a process. 3631 if (!m_current_process || 3632 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3633 LLDB_LOGF( 3634 log, 3635 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 3636 __FUNCTION__); 3637 return SendErrorResponse(1); 3638 } 3639 3640 // We are expecting 3641 // qMemTags:<hex address>,<hex length>:<hex type> 3642 3643 // Address 3644 packet.SetFilePos(strlen("qMemTags:")); 3645 const char *current_char = packet.Peek(); 3646 if (!current_char || *current_char == ',') 3647 return SendIllFormedResponse(packet, "Missing address in qMemTags packet"); 3648 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3649 3650 // Length 3651 char previous_char = packet.GetChar(); 3652 current_char = packet.Peek(); 3653 // If we don't have a separator or the length field is empty 3654 if (previous_char != ',' || (current_char && *current_char == ':')) 3655 return SendIllFormedResponse(packet, 3656 "Invalid addr,length pair in qMemTags packet"); 3657 3658 if (packet.GetBytesLeft() < 1) 3659 return SendIllFormedResponse( 3660 packet, "Too short qMemtags: packet (looking for length)"); 3661 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3662 3663 // Type 3664 const char *invalid_type_err = "Invalid type field in qMemTags: packet"; 3665 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3666 return SendIllFormedResponse(packet, invalid_type_err); 3667 3668 // Type is a signed integer but packed into the packet as its raw bytes. 3669 // However, our GetU64 uses strtoull which allows +/-. We do not want this. 3670 const char *first_type_char = packet.Peek(); 3671 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-')) 3672 return SendIllFormedResponse(packet, invalid_type_err); 3673 3674 // Extract type as unsigned then cast to signed. 3675 // Using a uint64_t here so that we have some value outside of the 32 bit 3676 // range to use as the invalid return value. 3677 uint64_t raw_type = 3678 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16); 3679 3680 if ( // Make sure the cast below would be valid 3681 raw_type > std::numeric_limits<uint32_t>::max() || 3682 // To catch inputs like "123aardvark" that will parse but clearly aren't 3683 // valid in this case. 3684 packet.GetBytesLeft()) { 3685 return SendIllFormedResponse(packet, invalid_type_err); 3686 } 3687 3688 // First narrow to 32 bits otherwise the copy into type would take 3689 // the wrong 4 bytes on big endian. 3690 uint32_t raw_type_32 = raw_type; 3691 int32_t type = reinterpret_cast<int32_t &>(raw_type_32); 3692 3693 StreamGDBRemote response; 3694 std::vector<uint8_t> tags; 3695 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags); 3696 if (error.Fail()) 3697 return SendErrorResponse(1); 3698 3699 // This m is here in case we want to support multi part replies in the future. 3700 // In the same manner as qfThreadInfo/qsThreadInfo. 3701 response.PutChar('m'); 3702 response.PutBytesAsRawHex8(tags.data(), tags.size()); 3703 return SendPacketNoLock(response.GetString()); 3704 } 3705 3706 GDBRemoteCommunication::PacketResult 3707 GDBRemoteCommunicationServerLLGS::Handle_QMemTags( 3708 StringExtractorGDBRemote &packet) { 3709 Log *log = GetLog(LLDBLog::Process); 3710 3711 // Ensure we have a process. 3712 if (!m_current_process || 3713 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3714 LLDB_LOGF( 3715 log, 3716 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 3717 __FUNCTION__); 3718 return SendErrorResponse(1); 3719 } 3720 3721 // We are expecting 3722 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes> 3723 3724 // Address 3725 packet.SetFilePos(strlen("QMemTags:")); 3726 const char *current_char = packet.Peek(); 3727 if (!current_char || *current_char == ',') 3728 return SendIllFormedResponse(packet, "Missing address in QMemTags packet"); 3729 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3730 3731 // Length 3732 char previous_char = packet.GetChar(); 3733 current_char = packet.Peek(); 3734 // If we don't have a separator or the length field is empty 3735 if (previous_char != ',' || (current_char && *current_char == ':')) 3736 return SendIllFormedResponse(packet, 3737 "Invalid addr,length pair in QMemTags packet"); 3738 3739 if (packet.GetBytesLeft() < 1) 3740 return SendIllFormedResponse( 3741 packet, "Too short QMemtags: packet (looking for length)"); 3742 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3743 3744 // Type 3745 const char *invalid_type_err = "Invalid type field in QMemTags: packet"; 3746 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3747 return SendIllFormedResponse(packet, invalid_type_err); 3748 3749 // Our GetU64 uses strtoull which allows leading +/-, we don't want that. 3750 const char *first_type_char = packet.Peek(); 3751 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-')) 3752 return SendIllFormedResponse(packet, invalid_type_err); 3753 3754 // The type is a signed integer but is in the packet as its raw bytes. 3755 // So parse first as unsigned then cast to signed later. 3756 // We extract to 64 bit, even though we only expect 32, so that we've 3757 // got some invalid value we can check for. 3758 uint64_t raw_type = 3759 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16); 3760 if (raw_type > std::numeric_limits<uint32_t>::max()) 3761 return SendIllFormedResponse(packet, invalid_type_err); 3762 3763 // First narrow to 32 bits. Otherwise the copy below would get the wrong 3764 // 4 bytes on big endian. 3765 uint32_t raw_type_32 = raw_type; 3766 int32_t type = reinterpret_cast<int32_t &>(raw_type_32); 3767 3768 // Tag data 3769 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3770 return SendIllFormedResponse(packet, 3771 "Missing tag data in QMemTags: packet"); 3772 3773 // Must be 2 chars per byte 3774 const char *invalid_data_err = "Invalid tag data in QMemTags: packet"; 3775 if (packet.GetBytesLeft() % 2) 3776 return SendIllFormedResponse(packet, invalid_data_err); 3777 3778 // This is bytes here and is unpacked into target specific tags later 3779 // We cannot assume that number of bytes == length here because the server 3780 // can repeat tags to fill a given range. 3781 std::vector<uint8_t> tag_data; 3782 // Zero length writes will not have any tag data 3783 // (but we pass them on because it will still check that tagging is enabled) 3784 if (packet.GetBytesLeft()) { 3785 size_t byte_count = packet.GetBytesLeft() / 2; 3786 tag_data.resize(byte_count); 3787 size_t converted_bytes = packet.GetHexBytes(tag_data, 0); 3788 if (converted_bytes != byte_count) { 3789 return SendIllFormedResponse(packet, invalid_data_err); 3790 } 3791 } 3792 3793 Status status = 3794 m_current_process->WriteMemoryTags(type, addr, length, tag_data); 3795 return status.Success() ? SendOKResponse() : SendErrorResponse(1); 3796 } 3797 3798 GDBRemoteCommunication::PacketResult 3799 GDBRemoteCommunicationServerLLGS::Handle_qSaveCore( 3800 StringExtractorGDBRemote &packet) { 3801 // Fail if we don't have a current process. 3802 if (!m_current_process || 3803 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3804 return SendErrorResponse(Status("Process not running.")); 3805 3806 std::string path_hint; 3807 3808 StringRef packet_str{packet.GetStringRef()}; 3809 assert(packet_str.startswith("qSaveCore")); 3810 if (packet_str.consume_front("qSaveCore;")) { 3811 for (auto x : llvm::split(packet_str, ';')) { 3812 if (x.consume_front("path-hint:")) 3813 StringExtractor(x).GetHexByteString(path_hint); 3814 else 3815 return SendErrorResponse(Status("Unsupported qSaveCore option")); 3816 } 3817 } 3818 3819 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint); 3820 if (!ret) 3821 return SendErrorResponse(ret.takeError()); 3822 3823 StreamString response; 3824 response.PutCString("core-path:"); 3825 response.PutStringAsRawHex8(ret.get()); 3826 return SendPacketNoLock(response.GetString()); 3827 } 3828 3829 GDBRemoteCommunication::PacketResult 3830 GDBRemoteCommunicationServerLLGS::Handle_QNonStop( 3831 StringExtractorGDBRemote &packet) { 3832 StringRef packet_str{packet.GetStringRef()}; 3833 assert(packet_str.startswith("QNonStop:")); 3834 packet_str.consume_front("QNonStop:"); 3835 if (packet_str == "0") { 3836 m_non_stop = false; 3837 // TODO: stop all threads 3838 } else if (packet_str == "1") { 3839 m_non_stop = true; 3840 } else 3841 return SendErrorResponse(Status("Invalid QNonStop packet")); 3842 return SendOKResponse(); 3843 } 3844 3845 GDBRemoteCommunication::PacketResult 3846 GDBRemoteCommunicationServerLLGS::Handle_vStopped( 3847 StringExtractorGDBRemote &packet) { 3848 // Per the protocol, the first message put into the queue is sent 3849 // immediately. However, it remains the queue until the client ACKs 3850 // it via vStopped -- then we pop it and send the next message. 3851 // The process repeats until the last message in the queue is ACK-ed, 3852 // in which case the vStopped packet sends an OK response. 3853 3854 if (m_stop_notification_queue.empty()) 3855 return SendErrorResponse(Status("No pending notification to ack")); 3856 m_stop_notification_queue.pop_front(); 3857 if (!m_stop_notification_queue.empty()) 3858 return SendPacketNoLock(m_stop_notification_queue.front()); 3859 // If this was the last notification and all the processes exited, 3860 // terminate the server. 3861 if (m_debugged_processes.empty()) { 3862 m_exit_now = true; 3863 m_mainloop.RequestTermination(); 3864 } 3865 return SendOKResponse(); 3866 } 3867 3868 GDBRemoteCommunication::PacketResult 3869 GDBRemoteCommunicationServerLLGS::Handle_vCtrlC( 3870 StringExtractorGDBRemote &packet) { 3871 if (!m_non_stop) 3872 return SendErrorResponse(Status("vCtrl is only valid in non-stop mode")); 3873 3874 PacketResult interrupt_res = Handle_interrupt(packet); 3875 // If interrupting the process failed, pass the result through. 3876 if (interrupt_res != PacketResult::Success) 3877 return interrupt_res; 3878 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not). 3879 return SendOKResponse(); 3880 } 3881 3882 GDBRemoteCommunication::PacketResult 3883 GDBRemoteCommunicationServerLLGS::Handle_T(StringExtractorGDBRemote &packet) { 3884 packet.SetFilePos(strlen("T")); 3885 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID() 3886 : LLDB_INVALID_PROCESS_ID); 3887 if (!pid_tid) 3888 return SendErrorResponse(llvm::make_error<StringError>( 3889 inconvertibleErrorCode(), "Malformed thread-id")); 3890 3891 lldb::pid_t pid = pid_tid->first; 3892 lldb::tid_t tid = pid_tid->second; 3893 3894 // Technically, this would also be caught by the PID check but let's be more 3895 // explicit about the error. 3896 if (pid == LLDB_INVALID_PROCESS_ID) 3897 return SendErrorResponse(llvm::make_error<StringError>( 3898 inconvertibleErrorCode(), "No current process and no PID provided")); 3899 3900 // Check the process ID and find respective process instance. 3901 auto new_process_it = m_debugged_processes.find(pid); 3902 if (new_process_it == m_debugged_processes.end()) 3903 return SendErrorResponse(1); 3904 3905 // Check the thread ID 3906 if (!new_process_it->second.process_up->GetThreadByID(tid)) 3907 return SendErrorResponse(2); 3908 3909 return SendOKResponse(); 3910 } 3911 3912 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() { 3913 Log *log = GetLog(LLDBLog::Process); 3914 3915 // Tell the stdio connection to shut down. 3916 if (m_stdio_communication.IsConnected()) { 3917 auto connection = m_stdio_communication.GetConnection(); 3918 if (connection) { 3919 Status error; 3920 connection->Disconnect(&error); 3921 3922 if (error.Success()) { 3923 LLDB_LOGF(log, 3924 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3925 "terminal stdio - SUCCESS", 3926 __FUNCTION__); 3927 } else { 3928 LLDB_LOGF(log, 3929 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3930 "terminal stdio - FAIL: %s", 3931 __FUNCTION__, error.AsCString()); 3932 } 3933 } 3934 } 3935 } 3936 3937 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix( 3938 StringExtractorGDBRemote &packet) { 3939 // We have no thread if we don't have a process. 3940 if (!m_current_process || 3941 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3942 return nullptr; 3943 3944 // If the client hasn't asked for thread suffix support, there will not be a 3945 // thread suffix. Use the current thread in that case. 3946 if (!m_thread_suffix_supported) { 3947 const lldb::tid_t current_tid = GetCurrentThreadID(); 3948 if (current_tid == LLDB_INVALID_THREAD_ID) 3949 return nullptr; 3950 else if (current_tid == 0) { 3951 // Pick a thread. 3952 return m_current_process->GetThreadAtIndex(0); 3953 } else 3954 return m_current_process->GetThreadByID(current_tid); 3955 } 3956 3957 Log *log = GetLog(LLDBLog::Thread); 3958 3959 // Parse out the ';'. 3960 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') { 3961 LLDB_LOGF(log, 3962 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3963 "error: expected ';' prior to start of thread suffix: packet " 3964 "contents = '%s'", 3965 __FUNCTION__, packet.GetStringRef().data()); 3966 return nullptr; 3967 } 3968 3969 if (!packet.GetBytesLeft()) 3970 return nullptr; 3971 3972 // Parse out thread: portion. 3973 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) { 3974 LLDB_LOGF(log, 3975 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3976 "error: expected 'thread:' but not found, packet contents = " 3977 "'%s'", 3978 __FUNCTION__, packet.GetStringRef().data()); 3979 return nullptr; 3980 } 3981 packet.SetFilePos(packet.GetFilePos() + strlen("thread:")); 3982 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0); 3983 if (tid != 0) 3984 return m_current_process->GetThreadByID(tid); 3985 3986 return nullptr; 3987 } 3988 3989 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const { 3990 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) { 3991 // Use whatever the debug process says is the current thread id since the 3992 // protocol either didn't specify or specified we want any/all threads 3993 // marked as the current thread. 3994 if (!m_current_process) 3995 return LLDB_INVALID_THREAD_ID; 3996 return m_current_process->GetCurrentThreadID(); 3997 } 3998 // Use the specific current thread id set by the gdb remote protocol. 3999 return m_current_tid; 4000 } 4001 4002 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() { 4003 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 4004 return m_next_saved_registers_id++; 4005 } 4006 4007 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() { 4008 Log *log = GetLog(LLDBLog::Process); 4009 4010 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size()); 4011 m_xfer_buffer_map.clear(); 4012 } 4013 4014 FileSpec 4015 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path, 4016 const ArchSpec &arch) { 4017 if (m_current_process) { 4018 FileSpec file_spec; 4019 if (m_current_process 4020 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec) 4021 .Success()) { 4022 if (FileSystem::Instance().Exists(file_spec)) 4023 return file_spec; 4024 } 4025 } 4026 4027 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch); 4028 } 4029 4030 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue( 4031 llvm::StringRef value) { 4032 std::string result; 4033 for (const char &c : value) { 4034 switch (c) { 4035 case '\'': 4036 result += "'"; 4037 break; 4038 case '"': 4039 result += """; 4040 break; 4041 case '<': 4042 result += "<"; 4043 break; 4044 case '>': 4045 result += ">"; 4046 break; 4047 default: 4048 result += c; 4049 break; 4050 } 4051 } 4052 return result; 4053 } 4054 4055 std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures( 4056 const llvm::ArrayRef<llvm::StringRef> client_features) { 4057 std::vector<std::string> ret = 4058 GDBRemoteCommunicationServerCommon::HandleFeatures(client_features); 4059 ret.insert(ret.end(), { 4060 "QThreadSuffixSupported+", 4061 "QListThreadsInStopReply+", 4062 "qXfer:features:read+", 4063 "QNonStop+", 4064 }); 4065 4066 // report server-only features 4067 using Extension = NativeProcessProtocol::Extension; 4068 Extension plugin_features = m_process_factory.GetSupportedExtensions(); 4069 if (bool(plugin_features & Extension::pass_signals)) 4070 ret.push_back("QPassSignals+"); 4071 if (bool(plugin_features & Extension::auxv)) 4072 ret.push_back("qXfer:auxv:read+"); 4073 if (bool(plugin_features & Extension::libraries_svr4)) 4074 ret.push_back("qXfer:libraries-svr4:read+"); 4075 if (bool(plugin_features & Extension::siginfo_read)) 4076 ret.push_back("qXfer:siginfo:read+"); 4077 if (bool(plugin_features & Extension::memory_tagging)) 4078 ret.push_back("memory-tagging+"); 4079 if (bool(plugin_features & Extension::savecore)) 4080 ret.push_back("qSaveCore+"); 4081 4082 // check for client features 4083 m_extensions_supported = {}; 4084 for (llvm::StringRef x : client_features) 4085 m_extensions_supported |= 4086 llvm::StringSwitch<Extension>(x) 4087 .Case("multiprocess+", Extension::multiprocess) 4088 .Case("fork-events+", Extension::fork) 4089 .Case("vfork-events+", Extension::vfork) 4090 .Default({}); 4091 4092 m_extensions_supported &= plugin_features; 4093 4094 // fork & vfork require multiprocess 4095 if (!bool(m_extensions_supported & Extension::multiprocess)) 4096 m_extensions_supported &= ~(Extension::fork | Extension::vfork); 4097 4098 // report only if actually supported 4099 if (bool(m_extensions_supported & Extension::multiprocess)) 4100 ret.push_back("multiprocess+"); 4101 if (bool(m_extensions_supported & Extension::fork)) 4102 ret.push_back("fork-events+"); 4103 if (bool(m_extensions_supported & Extension::vfork)) 4104 ret.push_back("vfork-events+"); 4105 4106 for (auto &x : m_debugged_processes) 4107 SetEnabledExtensions(*x.second.process_up); 4108 return ret; 4109 } 4110 4111 void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions( 4112 NativeProcessProtocol &process) { 4113 NativeProcessProtocol::Extension flags = m_extensions_supported; 4114 assert(!bool(flags & ~m_process_factory.GetSupportedExtensions())); 4115 process.SetEnabledExtensions(flags); 4116 } 4117 4118 GDBRemoteCommunication::PacketResult 4119 GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() { 4120 // TODO: how to handle forwarding in non-stop mode? 4121 StartSTDIOForwarding(); 4122 return m_non_stop ? SendOKResponse() : PacketResult::Success; 4123 } 4124 4125 void GDBRemoteCommunicationServerLLGS::AppendThreadIDToResponse( 4126 Stream &response, lldb::pid_t pid, lldb::tid_t tid) { 4127 if (bool(m_extensions_supported & 4128 NativeProcessProtocol::Extension::multiprocess)) 4129 response.Format("p{0:x-}.", pid); 4130 response.Format("{0:x-}", tid); 4131 } 4132 4133 std::string 4134 lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg, 4135 bool reverse_connect) { 4136 // Try parsing the argument as URL. 4137 if (llvm::Optional<URI> url = URI::Parse(url_arg)) { 4138 if (reverse_connect) 4139 return url_arg.str(); 4140 4141 // Translate the scheme from LLGS notation to ConnectionFileDescriptor. 4142 // If the scheme doesn't match any, pass it through to support using CFD 4143 // schemes directly. 4144 std::string new_url = llvm::StringSwitch<std::string>(url->scheme) 4145 .Case("tcp", "listen") 4146 .Case("unix", "unix-accept") 4147 .Case("unix-abstract", "unix-abstract-accept") 4148 .Default(url->scheme.str()); 4149 llvm::append_range(new_url, url_arg.substr(url->scheme.size())); 4150 return new_url; 4151 } 4152 4153 std::string host_port = url_arg.str(); 4154 // If host_and_port starts with ':', default the host to be "localhost" and 4155 // expect the remainder to be the port. 4156 if (url_arg.startswith(":")) 4157 host_port.insert(0, "localhost"); 4158 4159 // Try parsing the (preprocessed) argument as host:port pair. 4160 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError())) 4161 return (reverse_connect ? "connect://" : "listen://") + host_port; 4162 4163 // If none of the above applied, interpret the argument as UNIX socket path. 4164 return (reverse_connect ? "unix-connect://" : "unix-accept://") + 4165 url_arg.str(); 4166 } 4167