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