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 void GDBRemoteCommunicationServerLLGS::AddProcessThreads( 1980 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) { 1981 Log *log = GetLog(LLDBLog::Thread); 1982 1983 lldb::pid_t pid = process.GetID(); 1984 if (pid == LLDB_INVALID_PROCESS_ID) 1985 return; 1986 1987 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID()); 1988 NativeThreadProtocol *thread; 1989 uint32_t thread_index; 1990 for (thread_index = 0, thread = process.GetThreadAtIndex(thread_index); 1991 thread; 1992 ++thread_index, thread = process.GetThreadAtIndex(thread_index)) { 1993 LLDB_LOG(log, "iterated thread {0} (tid={1})", thread_index, 1994 thread->GetID()); 1995 response.PutChar(had_any ? ',' : 'm'); 1996 AppendThreadIDToResponse(response, pid, thread->GetID()); 1997 had_any = true; 1998 } 1999 } 2000 2001 GDBRemoteCommunication::PacketResult 2002 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo( 2003 StringExtractorGDBRemote &packet) { 2004 assert(m_debugged_processes.size() == 1 || 2005 bool(m_extensions_supported & 2006 NativeProcessProtocol::Extension::multiprocess)); 2007 2008 bool had_any = false; 2009 StreamGDBRemote response; 2010 2011 for (auto &pid_ptr : m_debugged_processes) 2012 AddProcessThreads(response, *pid_ptr.second, had_any); 2013 2014 if (!had_any) 2015 return SendOKResponse(); 2016 return SendPacketNoLock(response.GetString()); 2017 } 2018 2019 GDBRemoteCommunication::PacketResult 2020 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo( 2021 StringExtractorGDBRemote &packet) { 2022 // FIXME for now we return the full thread list in the initial packet and 2023 // always do nothing here. 2024 return SendPacketNoLock("l"); 2025 } 2026 2027 GDBRemoteCommunication::PacketResult 2028 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) { 2029 Log *log = GetLog(LLDBLog::Thread); 2030 2031 // Move past packet name. 2032 packet.SetFilePos(strlen("g")); 2033 2034 // Get the thread to use. 2035 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2036 if (!thread) { 2037 LLDB_LOG(log, "failed, no thread available"); 2038 return SendErrorResponse(0x15); 2039 } 2040 2041 // Get the thread's register context. 2042 NativeRegisterContext ®_ctx = thread->GetRegisterContext(); 2043 2044 std::vector<uint8_t> regs_buffer; 2045 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount(); 2046 ++reg_num) { 2047 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num); 2048 2049 if (reg_info == nullptr) { 2050 LLDB_LOG(log, "failed to get register info for register index {0}", 2051 reg_num); 2052 return SendErrorResponse(0x15); 2053 } 2054 2055 if (reg_info->value_regs != nullptr) 2056 continue; // skip registers that are contained in other registers 2057 2058 RegisterValue reg_value; 2059 Status error = reg_ctx.ReadRegister(reg_info, reg_value); 2060 if (error.Fail()) { 2061 LLDB_LOG(log, "failed to read register at index {0}", reg_num); 2062 return SendErrorResponse(0x15); 2063 } 2064 2065 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size()) 2066 // Resize the buffer to guarantee it can store the register offsetted 2067 // data. 2068 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size); 2069 2070 // Copy the register offsetted data to the buffer. 2071 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(), 2072 reg_info->byte_size); 2073 } 2074 2075 // Write the response. 2076 StreamGDBRemote response; 2077 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size()); 2078 2079 return SendPacketNoLock(response.GetString()); 2080 } 2081 2082 GDBRemoteCommunication::PacketResult 2083 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) { 2084 Log *log = GetLog(LLDBLog::Thread); 2085 2086 // Parse out the register number from the request. 2087 packet.SetFilePos(strlen("p")); 2088 const uint32_t reg_index = 2089 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2090 if (reg_index == std::numeric_limits<uint32_t>::max()) { 2091 LLDB_LOGF(log, 2092 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 2093 "parse register number from request \"%s\"", 2094 __FUNCTION__, packet.GetStringRef().data()); 2095 return SendErrorResponse(0x15); 2096 } 2097 2098 // Get the thread to use. 2099 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2100 if (!thread) { 2101 LLDB_LOG(log, "failed, no thread available"); 2102 return SendErrorResponse(0x15); 2103 } 2104 2105 // Get the thread's register context. 2106 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2107 2108 // Return the end of registers response if we've iterated one past the end of 2109 // the register set. 2110 if (reg_index >= reg_context.GetUserRegisterCount()) { 2111 LLDB_LOGF(log, 2112 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2113 "register %" PRIu32 " beyond register count %" PRIu32, 2114 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 2115 return SendErrorResponse(0x15); 2116 } 2117 2118 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 2119 if (!reg_info) { 2120 LLDB_LOGF(log, 2121 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2122 "register %" PRIu32 " returned NULL", 2123 __FUNCTION__, reg_index); 2124 return SendErrorResponse(0x15); 2125 } 2126 2127 // Build the reginfos response. 2128 StreamGDBRemote response; 2129 2130 // Retrieve the value 2131 RegisterValue reg_value; 2132 Status error = reg_context.ReadRegister(reg_info, reg_value); 2133 if (error.Fail()) { 2134 LLDB_LOGF(log, 2135 "GDBRemoteCommunicationServerLLGS::%s failed, read of " 2136 "requested register %" PRIu32 " (%s) failed: %s", 2137 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 2138 return SendErrorResponse(0x15); 2139 } 2140 2141 const uint8_t *const data = 2142 static_cast<const uint8_t *>(reg_value.GetBytes()); 2143 if (!data) { 2144 LLDB_LOGF(log, 2145 "GDBRemoteCommunicationServerLLGS::%s failed to get data " 2146 "bytes from requested register %" PRIu32, 2147 __FUNCTION__, reg_index); 2148 return SendErrorResponse(0x15); 2149 } 2150 2151 // FIXME flip as needed to get data in big/little endian format for this host. 2152 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i) 2153 response.PutHex8(data[i]); 2154 2155 return SendPacketNoLock(response.GetString()); 2156 } 2157 2158 GDBRemoteCommunication::PacketResult 2159 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) { 2160 Log *log = GetLog(LLDBLog::Thread); 2161 2162 // Ensure there is more content. 2163 if (packet.GetBytesLeft() < 1) 2164 return SendIllFormedResponse(packet, "Empty P packet"); 2165 2166 // Parse out the register number from the request. 2167 packet.SetFilePos(strlen("P")); 2168 const uint32_t reg_index = 2169 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2170 if (reg_index == std::numeric_limits<uint32_t>::max()) { 2171 LLDB_LOGF(log, 2172 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 2173 "parse register number from request \"%s\"", 2174 __FUNCTION__, packet.GetStringRef().data()); 2175 return SendErrorResponse(0x29); 2176 } 2177 2178 // Note debugserver would send an E30 here. 2179 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '=')) 2180 return SendIllFormedResponse( 2181 packet, "P packet missing '=' char after register number"); 2182 2183 // Parse out the value. 2184 uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize]; 2185 size_t reg_size = packet.GetHexBytesAvail(reg_bytes); 2186 2187 // Get the thread to use. 2188 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 2189 if (!thread) { 2190 LLDB_LOGF(log, 2191 "GDBRemoteCommunicationServerLLGS::%s failed, no thread " 2192 "available (thread index 0)", 2193 __FUNCTION__); 2194 return SendErrorResponse(0x28); 2195 } 2196 2197 // Get the thread's register context. 2198 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2199 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index); 2200 if (!reg_info) { 2201 LLDB_LOGF(log, 2202 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2203 "register %" PRIu32 " returned NULL", 2204 __FUNCTION__, reg_index); 2205 return SendErrorResponse(0x48); 2206 } 2207 2208 // Return the end of registers response if we've iterated one past the end of 2209 // the register set. 2210 if (reg_index >= reg_context.GetUserRegisterCount()) { 2211 LLDB_LOGF(log, 2212 "GDBRemoteCommunicationServerLLGS::%s failed, requested " 2213 "register %" PRIu32 " beyond register count %" PRIu32, 2214 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount()); 2215 return SendErrorResponse(0x47); 2216 } 2217 2218 if (reg_size != reg_info->byte_size) 2219 return SendIllFormedResponse(packet, "P packet register size is incorrect"); 2220 2221 // Build the reginfos response. 2222 StreamGDBRemote response; 2223 2224 RegisterValue reg_value(makeArrayRef(reg_bytes, reg_size), 2225 m_current_process->GetArchitecture().GetByteOrder()); 2226 Status error = reg_context.WriteRegister(reg_info, reg_value); 2227 if (error.Fail()) { 2228 LLDB_LOGF(log, 2229 "GDBRemoteCommunicationServerLLGS::%s failed, write of " 2230 "requested register %" PRIu32 " (%s) failed: %s", 2231 __FUNCTION__, reg_index, reg_info->name, error.AsCString()); 2232 return SendErrorResponse(0x32); 2233 } 2234 2235 return SendOKResponse(); 2236 } 2237 2238 GDBRemoteCommunication::PacketResult 2239 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) { 2240 Log *log = GetLog(LLDBLog::Thread); 2241 2242 // Parse out which variant of $H is requested. 2243 packet.SetFilePos(strlen("H")); 2244 if (packet.GetBytesLeft() < 1) { 2245 LLDB_LOGF(log, 2246 "GDBRemoteCommunicationServerLLGS::%s failed, H command " 2247 "missing {g,c} variant", 2248 __FUNCTION__); 2249 return SendIllFormedResponse(packet, "H command missing {g,c} variant"); 2250 } 2251 2252 const char h_variant = packet.GetChar(); 2253 NativeProcessProtocol *default_process; 2254 switch (h_variant) { 2255 case 'g': 2256 default_process = m_current_process; 2257 break; 2258 2259 case 'c': 2260 default_process = m_continue_process; 2261 break; 2262 2263 default: 2264 LLDB_LOGF( 2265 log, 2266 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", 2267 __FUNCTION__, h_variant); 2268 return SendIllFormedResponse(packet, 2269 "H variant unsupported, should be c or g"); 2270 } 2271 2272 // Parse out the thread number. 2273 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID() 2274 : LLDB_INVALID_PROCESS_ID); 2275 if (!pid_tid) 2276 return SendErrorResponse(llvm::make_error<StringError>( 2277 inconvertibleErrorCode(), "Malformed thread-id")); 2278 2279 lldb::pid_t pid = pid_tid->first; 2280 lldb::tid_t tid = pid_tid->second; 2281 2282 if (pid == StringExtractorGDBRemote::AllProcesses) 2283 return SendUnimplementedResponse("Selecting all processes not supported"); 2284 if (pid == LLDB_INVALID_PROCESS_ID) 2285 return SendErrorResponse(llvm::make_error<StringError>( 2286 inconvertibleErrorCode(), "No current process and no PID provided")); 2287 2288 // Check the process ID and find respective process instance. 2289 auto new_process_it = m_debugged_processes.find(pid); 2290 if (new_process_it == m_debugged_processes.end()) 2291 return SendErrorResponse(llvm::make_error<StringError>( 2292 inconvertibleErrorCode(), 2293 llvm::formatv("No process with PID {0} debugged", pid))); 2294 2295 // Ensure we have the given thread when not specifying -1 (all threads) or 0 2296 // (any thread). 2297 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) { 2298 NativeThreadProtocol *thread = new_process_it->second->GetThreadByID(tid); 2299 if (!thread) { 2300 LLDB_LOGF(log, 2301 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 2302 " not found", 2303 __FUNCTION__, tid); 2304 return SendErrorResponse(0x15); 2305 } 2306 } 2307 2308 // Now switch the given process and thread type. 2309 switch (h_variant) { 2310 case 'g': 2311 m_current_process = new_process_it->second.get(); 2312 SetCurrentThreadID(tid); 2313 break; 2314 2315 case 'c': 2316 m_continue_process = new_process_it->second.get(); 2317 SetContinueThreadID(tid); 2318 break; 2319 2320 default: 2321 assert(false && "unsupported $H variant - shouldn't get here"); 2322 return SendIllFormedResponse(packet, 2323 "H variant unsupported, should be c or g"); 2324 } 2325 2326 return SendOKResponse(); 2327 } 2328 2329 GDBRemoteCommunication::PacketResult 2330 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) { 2331 Log *log = GetLog(LLDBLog::Thread); 2332 2333 // Fail if we don't have a current process. 2334 if (!m_current_process || 2335 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2336 LLDB_LOGF( 2337 log, 2338 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2339 __FUNCTION__); 2340 return SendErrorResponse(0x15); 2341 } 2342 2343 packet.SetFilePos(::strlen("I")); 2344 uint8_t tmp[4096]; 2345 for (;;) { 2346 size_t read = packet.GetHexBytesAvail(tmp); 2347 if (read == 0) { 2348 break; 2349 } 2350 // write directly to stdin *this might block if stdin buffer is full* 2351 // TODO: enqueue this block in circular buffer and send window size to 2352 // remote host 2353 ConnectionStatus status; 2354 Status error; 2355 m_stdio_communication.Write(tmp, read, status, &error); 2356 if (error.Fail()) { 2357 return SendErrorResponse(0x15); 2358 } 2359 } 2360 2361 return SendOKResponse(); 2362 } 2363 2364 GDBRemoteCommunication::PacketResult 2365 GDBRemoteCommunicationServerLLGS::Handle_interrupt( 2366 StringExtractorGDBRemote &packet) { 2367 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 2368 2369 // Fail if we don't have a current process. 2370 if (!m_current_process || 2371 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2372 LLDB_LOG(log, "failed, no process available"); 2373 return SendErrorResponse(0x15); 2374 } 2375 2376 // Interrupt the process. 2377 Status error = m_current_process->Interrupt(); 2378 if (error.Fail()) { 2379 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(), 2380 error); 2381 return SendErrorResponse(GDBRemoteServerError::eErrorResume); 2382 } 2383 2384 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID()); 2385 2386 // No response required from stop all. 2387 return PacketResult::Success; 2388 } 2389 2390 GDBRemoteCommunication::PacketResult 2391 GDBRemoteCommunicationServerLLGS::Handle_memory_read( 2392 StringExtractorGDBRemote &packet) { 2393 Log *log = GetLog(LLDBLog::Process); 2394 2395 if (!m_current_process || 2396 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2397 LLDB_LOGF( 2398 log, 2399 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2400 __FUNCTION__); 2401 return SendErrorResponse(0x15); 2402 } 2403 2404 // Parse out the memory address. 2405 packet.SetFilePos(strlen("m")); 2406 if (packet.GetBytesLeft() < 1) 2407 return SendIllFormedResponse(packet, "Too short m packet"); 2408 2409 // Read the address. Punting on validation. 2410 // FIXME replace with Hex U64 read with no default value that fails on failed 2411 // read. 2412 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2413 2414 // Validate comma. 2415 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2416 return SendIllFormedResponse(packet, "Comma sep missing in m packet"); 2417 2418 // Get # bytes to read. 2419 if (packet.GetBytesLeft() < 1) 2420 return SendIllFormedResponse(packet, "Length missing in m packet"); 2421 2422 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2423 if (byte_count == 0) { 2424 LLDB_LOGF(log, 2425 "GDBRemoteCommunicationServerLLGS::%s nothing to read: " 2426 "zero-length packet", 2427 __FUNCTION__); 2428 return SendOKResponse(); 2429 } 2430 2431 // Allocate the response buffer. 2432 std::string buf(byte_count, '\0'); 2433 if (buf.empty()) 2434 return SendErrorResponse(0x78); 2435 2436 // Retrieve the process memory. 2437 size_t bytes_read = 0; 2438 Status error = m_current_process->ReadMemoryWithoutTrap( 2439 read_addr, &buf[0], byte_count, bytes_read); 2440 if (error.Fail()) { 2441 LLDB_LOGF(log, 2442 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2443 " mem 0x%" PRIx64 ": failed to read. Error: %s", 2444 __FUNCTION__, m_current_process->GetID(), read_addr, 2445 error.AsCString()); 2446 return SendErrorResponse(0x08); 2447 } 2448 2449 if (bytes_read == 0) { 2450 LLDB_LOGF(log, 2451 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2452 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes", 2453 __FUNCTION__, m_current_process->GetID(), read_addr, byte_count); 2454 return SendErrorResponse(0x08); 2455 } 2456 2457 StreamGDBRemote response; 2458 packet.SetFilePos(0); 2459 char kind = packet.GetChar('?'); 2460 if (kind == 'x') 2461 response.PutEscapedBytes(buf.data(), byte_count); 2462 else { 2463 assert(kind == 'm'); 2464 for (size_t i = 0; i < bytes_read; ++i) 2465 response.PutHex8(buf[i]); 2466 } 2467 2468 return SendPacketNoLock(response.GetString()); 2469 } 2470 2471 GDBRemoteCommunication::PacketResult 2472 GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) { 2473 Log *log = GetLog(LLDBLog::Process); 2474 2475 if (!m_current_process || 2476 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2477 LLDB_LOGF( 2478 log, 2479 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2480 __FUNCTION__); 2481 return SendErrorResponse(0x15); 2482 } 2483 2484 // Parse out the memory address. 2485 packet.SetFilePos(strlen("_M")); 2486 if (packet.GetBytesLeft() < 1) 2487 return SendIllFormedResponse(packet, "Too short _M packet"); 2488 2489 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2490 if (size == LLDB_INVALID_ADDRESS) 2491 return SendIllFormedResponse(packet, "Address not valid"); 2492 if (packet.GetChar() != ',') 2493 return SendIllFormedResponse(packet, "Bad packet"); 2494 Permissions perms = {}; 2495 while (packet.GetBytesLeft() > 0) { 2496 switch (packet.GetChar()) { 2497 case 'r': 2498 perms |= ePermissionsReadable; 2499 break; 2500 case 'w': 2501 perms |= ePermissionsWritable; 2502 break; 2503 case 'x': 2504 perms |= ePermissionsExecutable; 2505 break; 2506 default: 2507 return SendIllFormedResponse(packet, "Bad permissions"); 2508 } 2509 } 2510 2511 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms); 2512 if (!addr) 2513 return SendErrorResponse(addr.takeError()); 2514 2515 StreamGDBRemote response; 2516 response.PutHex64(*addr); 2517 return SendPacketNoLock(response.GetString()); 2518 } 2519 2520 GDBRemoteCommunication::PacketResult 2521 GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) { 2522 Log *log = GetLog(LLDBLog::Process); 2523 2524 if (!m_current_process || 2525 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2526 LLDB_LOGF( 2527 log, 2528 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2529 __FUNCTION__); 2530 return SendErrorResponse(0x15); 2531 } 2532 2533 // Parse out the memory address. 2534 packet.SetFilePos(strlen("_m")); 2535 if (packet.GetBytesLeft() < 1) 2536 return SendIllFormedResponse(packet, "Too short m packet"); 2537 2538 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2539 if (addr == LLDB_INVALID_ADDRESS) 2540 return SendIllFormedResponse(packet, "Address not valid"); 2541 2542 if (llvm::Error Err = m_current_process->DeallocateMemory(addr)) 2543 return SendErrorResponse(std::move(Err)); 2544 2545 return SendOKResponse(); 2546 } 2547 2548 GDBRemoteCommunication::PacketResult 2549 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) { 2550 Log *log = GetLog(LLDBLog::Process); 2551 2552 if (!m_current_process || 2553 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2554 LLDB_LOGF( 2555 log, 2556 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2557 __FUNCTION__); 2558 return SendErrorResponse(0x15); 2559 } 2560 2561 // Parse out the memory address. 2562 packet.SetFilePos(strlen("M")); 2563 if (packet.GetBytesLeft() < 1) 2564 return SendIllFormedResponse(packet, "Too short M packet"); 2565 2566 // Read the address. Punting on validation. 2567 // FIXME replace with Hex U64 read with no default value that fails on failed 2568 // read. 2569 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0); 2570 2571 // Validate comma. 2572 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ',')) 2573 return SendIllFormedResponse(packet, "Comma sep missing in M packet"); 2574 2575 // Get # bytes to read. 2576 if (packet.GetBytesLeft() < 1) 2577 return SendIllFormedResponse(packet, "Length missing in M packet"); 2578 2579 const uint64_t byte_count = packet.GetHexMaxU64(false, 0); 2580 if (byte_count == 0) { 2581 LLDB_LOG(log, "nothing to write: zero-length packet"); 2582 return PacketResult::Success; 2583 } 2584 2585 // Validate colon. 2586 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':')) 2587 return SendIllFormedResponse( 2588 packet, "Comma sep missing in M packet after byte length"); 2589 2590 // Allocate the conversion buffer. 2591 std::vector<uint8_t> buf(byte_count, 0); 2592 if (buf.empty()) 2593 return SendErrorResponse(0x78); 2594 2595 // Convert the hex memory write contents to bytes. 2596 StreamGDBRemote response; 2597 const uint64_t convert_count = packet.GetHexBytes(buf, 0); 2598 if (convert_count != byte_count) { 2599 LLDB_LOG(log, 2600 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} " 2601 "to convert.", 2602 m_current_process->GetID(), write_addr, byte_count, convert_count); 2603 return SendIllFormedResponse(packet, "M content byte length specified did " 2604 "not match hex-encoded content " 2605 "length"); 2606 } 2607 2608 // Write the process memory. 2609 size_t bytes_written = 0; 2610 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count, 2611 bytes_written); 2612 if (error.Fail()) { 2613 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}", 2614 m_current_process->GetID(), write_addr, error); 2615 return SendErrorResponse(0x09); 2616 } 2617 2618 if (bytes_written == 0) { 2619 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes", 2620 m_current_process->GetID(), write_addr, byte_count); 2621 return SendErrorResponse(0x09); 2622 } 2623 2624 return SendOKResponse(); 2625 } 2626 2627 GDBRemoteCommunication::PacketResult 2628 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported( 2629 StringExtractorGDBRemote &packet) { 2630 Log *log = GetLog(LLDBLog::Process); 2631 2632 // Currently only the NativeProcessProtocol knows if it can handle a 2633 // qMemoryRegionInfoSupported request, but we're not guaranteed to be 2634 // attached to a process. For now we'll assume the client only asks this 2635 // when a process is being debugged. 2636 2637 // Ensure we have a process running; otherwise, we can't figure this out 2638 // since we won't have a NativeProcessProtocol. 2639 if (!m_current_process || 2640 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2641 LLDB_LOGF( 2642 log, 2643 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2644 __FUNCTION__); 2645 return SendErrorResponse(0x15); 2646 } 2647 2648 // Test if we can get any region back when asking for the region around NULL. 2649 MemoryRegionInfo region_info; 2650 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info); 2651 if (error.Fail()) { 2652 // We don't support memory region info collection for this 2653 // NativeProcessProtocol. 2654 return SendUnimplementedResponse(""); 2655 } 2656 2657 return SendOKResponse(); 2658 } 2659 2660 GDBRemoteCommunication::PacketResult 2661 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo( 2662 StringExtractorGDBRemote &packet) { 2663 Log *log = GetLog(LLDBLog::Process); 2664 2665 // Ensure we have a process. 2666 if (!m_current_process || 2667 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2668 LLDB_LOGF( 2669 log, 2670 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2671 __FUNCTION__); 2672 return SendErrorResponse(0x15); 2673 } 2674 2675 // Parse out the memory address. 2676 packet.SetFilePos(strlen("qMemoryRegionInfo:")); 2677 if (packet.GetBytesLeft() < 1) 2678 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet"); 2679 2680 // Read the address. Punting on validation. 2681 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0); 2682 2683 StreamGDBRemote response; 2684 2685 // Get the memory region info for the target address. 2686 MemoryRegionInfo region_info; 2687 const Status error = 2688 m_current_process->GetMemoryRegionInfo(read_addr, region_info); 2689 if (error.Fail()) { 2690 // Return the error message. 2691 2692 response.PutCString("error:"); 2693 response.PutStringAsRawHex8(error.AsCString()); 2694 response.PutChar(';'); 2695 } else { 2696 // Range start and size. 2697 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";", 2698 region_info.GetRange().GetRangeBase(), 2699 region_info.GetRange().GetByteSize()); 2700 2701 // Permissions. 2702 if (region_info.GetReadable() || region_info.GetWritable() || 2703 region_info.GetExecutable()) { 2704 // Write permissions info. 2705 response.PutCString("permissions:"); 2706 2707 if (region_info.GetReadable()) 2708 response.PutChar('r'); 2709 if (region_info.GetWritable()) 2710 response.PutChar('w'); 2711 if (region_info.GetExecutable()) 2712 response.PutChar('x'); 2713 2714 response.PutChar(';'); 2715 } 2716 2717 // Flags 2718 MemoryRegionInfo::OptionalBool memory_tagged = 2719 region_info.GetMemoryTagged(); 2720 if (memory_tagged != MemoryRegionInfo::eDontKnow) { 2721 response.PutCString("flags:"); 2722 if (memory_tagged == MemoryRegionInfo::eYes) { 2723 response.PutCString("mt"); 2724 } 2725 response.PutChar(';'); 2726 } 2727 2728 // Name 2729 ConstString name = region_info.GetName(); 2730 if (name) { 2731 response.PutCString("name:"); 2732 response.PutStringAsRawHex8(name.GetStringRef()); 2733 response.PutChar(';'); 2734 } 2735 } 2736 2737 return SendPacketNoLock(response.GetString()); 2738 } 2739 2740 GDBRemoteCommunication::PacketResult 2741 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) { 2742 // Ensure we have a process. 2743 if (!m_current_process || 2744 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2745 Log *log = GetLog(LLDBLog::Process); 2746 LLDB_LOG(log, "failed, no process available"); 2747 return SendErrorResponse(0x15); 2748 } 2749 2750 // Parse out software or hardware breakpoint or watchpoint requested. 2751 packet.SetFilePos(strlen("Z")); 2752 if (packet.GetBytesLeft() < 1) 2753 return SendIllFormedResponse( 2754 packet, "Too short Z packet, missing software/hardware specifier"); 2755 2756 bool want_breakpoint = true; 2757 bool want_hardware = false; 2758 uint32_t watch_flags = 0; 2759 2760 const GDBStoppointType stoppoint_type = 2761 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2762 switch (stoppoint_type) { 2763 case eBreakpointSoftware: 2764 want_hardware = false; 2765 want_breakpoint = true; 2766 break; 2767 case eBreakpointHardware: 2768 want_hardware = true; 2769 want_breakpoint = true; 2770 break; 2771 case eWatchpointWrite: 2772 watch_flags = 1; 2773 want_hardware = true; 2774 want_breakpoint = false; 2775 break; 2776 case eWatchpointRead: 2777 watch_flags = 2; 2778 want_hardware = true; 2779 want_breakpoint = false; 2780 break; 2781 case eWatchpointReadWrite: 2782 watch_flags = 3; 2783 want_hardware = true; 2784 want_breakpoint = false; 2785 break; 2786 case eStoppointInvalid: 2787 return SendIllFormedResponse( 2788 packet, "Z packet had invalid software/hardware specifier"); 2789 } 2790 2791 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2792 return SendIllFormedResponse( 2793 packet, "Malformed Z packet, expecting comma after stoppoint type"); 2794 2795 // Parse out the stoppoint address. 2796 if (packet.GetBytesLeft() < 1) 2797 return SendIllFormedResponse(packet, "Too short Z packet, missing address"); 2798 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2799 2800 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2801 return SendIllFormedResponse( 2802 packet, "Malformed Z packet, expecting comma after address"); 2803 2804 // Parse out the stoppoint size (i.e. size hint for opcode size). 2805 const uint32_t size = 2806 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max()); 2807 if (size == std::numeric_limits<uint32_t>::max()) 2808 return SendIllFormedResponse( 2809 packet, "Malformed Z packet, failed to parse size argument"); 2810 2811 if (want_breakpoint) { 2812 // Try to set the breakpoint. 2813 const Status error = 2814 m_current_process->SetBreakpoint(addr, size, want_hardware); 2815 if (error.Success()) 2816 return SendOKResponse(); 2817 Log *log = GetLog(LLDBLog::Breakpoints); 2818 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}", 2819 m_current_process->GetID(), error); 2820 return SendErrorResponse(0x09); 2821 } else { 2822 // Try to set the watchpoint. 2823 const Status error = m_current_process->SetWatchpoint( 2824 addr, size, watch_flags, want_hardware); 2825 if (error.Success()) 2826 return SendOKResponse(); 2827 Log *log = GetLog(LLDBLog::Watchpoints); 2828 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}", 2829 m_current_process->GetID(), error); 2830 return SendErrorResponse(0x09); 2831 } 2832 } 2833 2834 GDBRemoteCommunication::PacketResult 2835 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) { 2836 // Ensure we have a process. 2837 if (!m_current_process || 2838 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2839 Log *log = GetLog(LLDBLog::Process); 2840 LLDB_LOG(log, "failed, no process available"); 2841 return SendErrorResponse(0x15); 2842 } 2843 2844 // Parse out software or hardware breakpoint or watchpoint requested. 2845 packet.SetFilePos(strlen("z")); 2846 if (packet.GetBytesLeft() < 1) 2847 return SendIllFormedResponse( 2848 packet, "Too short z packet, missing software/hardware specifier"); 2849 2850 bool want_breakpoint = true; 2851 bool want_hardware = false; 2852 2853 const GDBStoppointType stoppoint_type = 2854 GDBStoppointType(packet.GetS32(eStoppointInvalid)); 2855 switch (stoppoint_type) { 2856 case eBreakpointHardware: 2857 want_breakpoint = true; 2858 want_hardware = true; 2859 break; 2860 case eBreakpointSoftware: 2861 want_breakpoint = true; 2862 break; 2863 case eWatchpointWrite: 2864 want_breakpoint = false; 2865 break; 2866 case eWatchpointRead: 2867 want_breakpoint = false; 2868 break; 2869 case eWatchpointReadWrite: 2870 want_breakpoint = false; 2871 break; 2872 default: 2873 return SendIllFormedResponse( 2874 packet, "z packet had invalid software/hardware specifier"); 2875 } 2876 2877 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2878 return SendIllFormedResponse( 2879 packet, "Malformed z packet, expecting comma after stoppoint type"); 2880 2881 // Parse out the stoppoint address. 2882 if (packet.GetBytesLeft() < 1) 2883 return SendIllFormedResponse(packet, "Too short z packet, missing address"); 2884 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0); 2885 2886 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',') 2887 return SendIllFormedResponse( 2888 packet, "Malformed z packet, expecting comma after address"); 2889 2890 /* 2891 // Parse out the stoppoint size (i.e. size hint for opcode size). 2892 const uint32_t size = packet.GetHexMaxU32 (false, 2893 std::numeric_limits<uint32_t>::max ()); 2894 if (size == std::numeric_limits<uint32_t>::max ()) 2895 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse 2896 size argument"); 2897 */ 2898 2899 if (want_breakpoint) { 2900 // Try to clear the breakpoint. 2901 const Status error = 2902 m_current_process->RemoveBreakpoint(addr, want_hardware); 2903 if (error.Success()) 2904 return SendOKResponse(); 2905 Log *log = GetLog(LLDBLog::Breakpoints); 2906 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}", 2907 m_current_process->GetID(), error); 2908 return SendErrorResponse(0x09); 2909 } else { 2910 // Try to clear the watchpoint. 2911 const Status error = m_current_process->RemoveWatchpoint(addr); 2912 if (error.Success()) 2913 return SendOKResponse(); 2914 Log *log = GetLog(LLDBLog::Watchpoints); 2915 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}", 2916 m_current_process->GetID(), error); 2917 return SendErrorResponse(0x09); 2918 } 2919 } 2920 2921 GDBRemoteCommunication::PacketResult 2922 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) { 2923 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 2924 2925 // Ensure we have a process. 2926 if (!m_continue_process || 2927 (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 2928 LLDB_LOGF( 2929 log, 2930 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 2931 __FUNCTION__); 2932 return SendErrorResponse(0x32); 2933 } 2934 2935 // We first try to use a continue thread id. If any one or any all set, use 2936 // the current thread. Bail out if we don't have a thread id. 2937 lldb::tid_t tid = GetContinueThreadID(); 2938 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID) 2939 tid = GetCurrentThreadID(); 2940 if (tid == LLDB_INVALID_THREAD_ID) 2941 return SendErrorResponse(0x33); 2942 2943 // Double check that we have such a thread. 2944 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here. 2945 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid); 2946 if (!thread) 2947 return SendErrorResponse(0x33); 2948 2949 // Create the step action for the given thread. 2950 ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER}; 2951 2952 // Setup the actions list. 2953 ResumeActionList actions; 2954 actions.Append(action); 2955 2956 // All other threads stop while we're single stepping a thread. 2957 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); 2958 Status error = m_continue_process->Resume(actions); 2959 if (error.Fail()) { 2960 LLDB_LOGF(log, 2961 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 2962 " tid %" PRIu64 " Resume() failed with error: %s", 2963 __FUNCTION__, m_continue_process->GetID(), tid, 2964 error.AsCString()); 2965 return SendErrorResponse(0x49); 2966 } 2967 2968 // No response here, unless in non-stop mode. 2969 // Otherwise, the stop or exit will come from the resulting action. 2970 return SendContinueSuccessResponse(); 2971 } 2972 2973 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 2974 GDBRemoteCommunicationServerLLGS::BuildTargetXml() { 2975 // Ensure we have a thread. 2976 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0); 2977 if (!thread) 2978 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2979 "No thread available"); 2980 2981 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 2982 // Get the register context for the first thread. 2983 NativeRegisterContext ®_context = thread->GetRegisterContext(); 2984 2985 StreamString response; 2986 2987 response.Printf("<?xml version=\"1.0\"?>"); 2988 response.Printf("<target version=\"1.0\">"); 2989 2990 response.Printf("<architecture>%s</architecture>", 2991 m_current_process->GetArchitecture() 2992 .GetTriple() 2993 .getArchName() 2994 .str() 2995 .c_str()); 2996 2997 response.Printf("<feature>"); 2998 2999 const int registers_count = reg_context.GetUserRegisterCount(); 3000 for (int reg_index = 0; reg_index < registers_count; reg_index++) { 3001 const RegisterInfo *reg_info = 3002 reg_context.GetRegisterInfoAtIndex(reg_index); 3003 3004 if (!reg_info) { 3005 LLDB_LOGF(log, 3006 "%s failed to get register info for register index %" PRIu32, 3007 "target.xml", reg_index); 3008 continue; 3009 } 3010 3011 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" regnum=\"%d\" ", 3012 reg_info->name, reg_info->byte_size * 8, reg_index); 3013 3014 if (!reg_context.RegisterOffsetIsDynamic()) 3015 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset); 3016 3017 if (reg_info->alt_name && reg_info->alt_name[0]) 3018 response.Printf("altname=\"%s\" ", reg_info->alt_name); 3019 3020 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info); 3021 if (!encoding.empty()) 3022 response << "encoding=\"" << encoding << "\" "; 3023 3024 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info); 3025 if (!format.empty()) 3026 response << "format=\"" << format << "\" "; 3027 3028 const char *const register_set_name = 3029 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index); 3030 if (register_set_name) 3031 response << "group=\"" << register_set_name << "\" "; 3032 3033 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != 3034 LLDB_INVALID_REGNUM) 3035 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ", 3036 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]); 3037 3038 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != 3039 LLDB_INVALID_REGNUM) 3040 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ", 3041 reg_info->kinds[RegisterKind::eRegisterKindDWARF]); 3042 3043 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info); 3044 if (!kind_generic.empty()) 3045 response << "generic=\"" << kind_generic << "\" "; 3046 3047 if (reg_info->value_regs && 3048 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) { 3049 response.PutCString("value_regnums=\""); 3050 CollectRegNums(reg_info->value_regs, response, false); 3051 response.Printf("\" "); 3052 } 3053 3054 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) { 3055 response.PutCString("invalidate_regnums=\""); 3056 CollectRegNums(reg_info->invalidate_regs, response, false); 3057 response.Printf("\" "); 3058 } 3059 3060 response.Printf("/>"); 3061 } 3062 3063 response.Printf("</feature>"); 3064 response.Printf("</target>"); 3065 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml"); 3066 } 3067 3068 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> 3069 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object, 3070 llvm::StringRef annex) { 3071 // Make sure we have a valid process. 3072 if (!m_current_process || 3073 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3074 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3075 "No process available"); 3076 } 3077 3078 if (object == "auxv") { 3079 // Grab the auxv data. 3080 auto buffer_or_error = m_current_process->GetAuxvData(); 3081 if (!buffer_or_error) 3082 return llvm::errorCodeToError(buffer_or_error.getError()); 3083 return std::move(*buffer_or_error); 3084 } 3085 3086 if (object == "siginfo") { 3087 NativeThreadProtocol *thread = m_current_process->GetCurrentThread(); 3088 if (!thread) 3089 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3090 "no current thread"); 3091 3092 auto buffer_or_error = thread->GetSiginfo(); 3093 if (!buffer_or_error) 3094 return buffer_or_error.takeError(); 3095 return std::move(*buffer_or_error); 3096 } 3097 3098 if (object == "libraries-svr4") { 3099 auto library_list = m_current_process->GetLoadedSVR4Libraries(); 3100 if (!library_list) 3101 return library_list.takeError(); 3102 3103 StreamString response; 3104 response.Printf("<library-list-svr4 version=\"1.0\">"); 3105 for (auto const &library : *library_list) { 3106 response.Printf("<library name=\"%s\" ", 3107 XMLEncodeAttributeValue(library.name.c_str()).c_str()); 3108 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map); 3109 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr); 3110 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr); 3111 } 3112 response.Printf("</library-list-svr4>"); 3113 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__); 3114 } 3115 3116 if (object == "features" && annex == "target.xml") 3117 return BuildTargetXml(); 3118 3119 return llvm::make_error<UnimplementedError>(); 3120 } 3121 3122 GDBRemoteCommunication::PacketResult 3123 GDBRemoteCommunicationServerLLGS::Handle_qXfer( 3124 StringExtractorGDBRemote &packet) { 3125 SmallVector<StringRef, 5> fields; 3126 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length" 3127 StringRef(packet.GetStringRef()).split(fields, ':', 4); 3128 if (fields.size() != 5) 3129 return SendIllFormedResponse(packet, "malformed qXfer packet"); 3130 StringRef &xfer_object = fields[1]; 3131 StringRef &xfer_action = fields[2]; 3132 StringRef &xfer_annex = fields[3]; 3133 StringExtractor offset_data(fields[4]); 3134 if (xfer_action != "read") 3135 return SendUnimplementedResponse("qXfer action not supported"); 3136 // Parse offset. 3137 const uint64_t xfer_offset = 3138 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 3139 if (xfer_offset == std::numeric_limits<uint64_t>::max()) 3140 return SendIllFormedResponse(packet, "qXfer packet missing offset"); 3141 // Parse out comma. 3142 if (offset_data.GetChar() != ',') 3143 return SendIllFormedResponse(packet, 3144 "qXfer packet missing comma after offset"); 3145 // Parse out the length. 3146 const uint64_t xfer_length = 3147 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max()); 3148 if (xfer_length == std::numeric_limits<uint64_t>::max()) 3149 return SendIllFormedResponse(packet, "qXfer packet missing length"); 3150 3151 // Get a previously constructed buffer if it exists or create it now. 3152 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str(); 3153 auto buffer_it = m_xfer_buffer_map.find(buffer_key); 3154 if (buffer_it == m_xfer_buffer_map.end()) { 3155 auto buffer_up = ReadXferObject(xfer_object, xfer_annex); 3156 if (!buffer_up) 3157 return SendErrorResponse(buffer_up.takeError()); 3158 buffer_it = m_xfer_buffer_map 3159 .insert(std::make_pair(buffer_key, std::move(*buffer_up))) 3160 .first; 3161 } 3162 3163 // Send back the response 3164 StreamGDBRemote response; 3165 bool done_with_buffer = false; 3166 llvm::StringRef buffer = buffer_it->second->getBuffer(); 3167 if (xfer_offset >= buffer.size()) { 3168 // We have nothing left to send. Mark the buffer as complete. 3169 response.PutChar('l'); 3170 done_with_buffer = true; 3171 } else { 3172 // Figure out how many bytes are available starting at the given offset. 3173 buffer = buffer.drop_front(xfer_offset); 3174 // Mark the response type according to whether we're reading the remainder 3175 // of the data. 3176 if (xfer_length >= buffer.size()) { 3177 // There will be nothing left to read after this 3178 response.PutChar('l'); 3179 done_with_buffer = true; 3180 } else { 3181 // There will still be bytes to read after this request. 3182 response.PutChar('m'); 3183 buffer = buffer.take_front(xfer_length); 3184 } 3185 // Now write the data in encoded binary form. 3186 response.PutEscapedBytes(buffer.data(), buffer.size()); 3187 } 3188 3189 if (done_with_buffer) 3190 m_xfer_buffer_map.erase(buffer_it); 3191 3192 return SendPacketNoLock(response.GetString()); 3193 } 3194 3195 GDBRemoteCommunication::PacketResult 3196 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState( 3197 StringExtractorGDBRemote &packet) { 3198 Log *log = GetLog(LLDBLog::Thread); 3199 3200 // Move past packet name. 3201 packet.SetFilePos(strlen("QSaveRegisterState")); 3202 3203 // Get the thread to use. 3204 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3205 if (!thread) { 3206 if (m_thread_suffix_supported) 3207 return SendIllFormedResponse( 3208 packet, "No thread specified in QSaveRegisterState packet"); 3209 else 3210 return SendIllFormedResponse(packet, 3211 "No thread was is set with the Hg packet"); 3212 } 3213 3214 // Grab the register context for the thread. 3215 NativeRegisterContext& reg_context = thread->GetRegisterContext(); 3216 3217 // Save registers to a buffer. 3218 WritableDataBufferSP register_data_sp; 3219 Status error = reg_context.ReadAllRegisterValues(register_data_sp); 3220 if (error.Fail()) { 3221 LLDB_LOG(log, "pid {0} failed to save all register values: {1}", 3222 m_current_process->GetID(), error); 3223 return SendErrorResponse(0x75); 3224 } 3225 3226 // Allocate a new save id. 3227 const uint32_t save_id = GetNextSavedRegistersID(); 3228 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) && 3229 "GetNextRegisterSaveID() returned an existing register save id"); 3230 3231 // Save the register data buffer under the save id. 3232 { 3233 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3234 m_saved_registers_map[save_id] = register_data_sp; 3235 } 3236 3237 // Write the response. 3238 StreamGDBRemote response; 3239 response.Printf("%" PRIu32, save_id); 3240 return SendPacketNoLock(response.GetString()); 3241 } 3242 3243 GDBRemoteCommunication::PacketResult 3244 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState( 3245 StringExtractorGDBRemote &packet) { 3246 Log *log = GetLog(LLDBLog::Thread); 3247 3248 // Parse out save id. 3249 packet.SetFilePos(strlen("QRestoreRegisterState:")); 3250 if (packet.GetBytesLeft() < 1) 3251 return SendIllFormedResponse( 3252 packet, "QRestoreRegisterState packet missing register save id"); 3253 3254 const uint32_t save_id = packet.GetU32(0); 3255 if (save_id == 0) { 3256 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, " 3257 "expecting decimal uint32_t"); 3258 return SendErrorResponse(0x76); 3259 } 3260 3261 // Get the thread to use. 3262 NativeThreadProtocol *thread = GetThreadFromSuffix(packet); 3263 if (!thread) { 3264 if (m_thread_suffix_supported) 3265 return SendIllFormedResponse( 3266 packet, "No thread specified in QRestoreRegisterState packet"); 3267 else 3268 return SendIllFormedResponse(packet, 3269 "No thread was is set with the Hg packet"); 3270 } 3271 3272 // Grab the register context for the thread. 3273 NativeRegisterContext ®_context = thread->GetRegisterContext(); 3274 3275 // Retrieve register state buffer, then remove from the list. 3276 DataBufferSP register_data_sp; 3277 { 3278 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 3279 3280 // Find the register set buffer for the given save id. 3281 auto it = m_saved_registers_map.find(save_id); 3282 if (it == m_saved_registers_map.end()) { 3283 LLDB_LOG(log, 3284 "pid {0} does not have a register set save buffer for id {1}", 3285 m_current_process->GetID(), save_id); 3286 return SendErrorResponse(0x77); 3287 } 3288 register_data_sp = it->second; 3289 3290 // Remove it from the map. 3291 m_saved_registers_map.erase(it); 3292 } 3293 3294 Status error = reg_context.WriteAllRegisterValues(register_data_sp); 3295 if (error.Fail()) { 3296 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}", 3297 m_current_process->GetID(), error); 3298 return SendErrorResponse(0x77); 3299 } 3300 3301 return SendOKResponse(); 3302 } 3303 3304 GDBRemoteCommunication::PacketResult 3305 GDBRemoteCommunicationServerLLGS::Handle_vAttach( 3306 StringExtractorGDBRemote &packet) { 3307 Log *log = GetLog(LLDBLog::Process); 3308 3309 // Consume the ';' after vAttach. 3310 packet.SetFilePos(strlen("vAttach")); 3311 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3312 return SendIllFormedResponse(packet, "vAttach missing expected ';'"); 3313 3314 // Grab the PID to which we will attach (assume hex encoding). 3315 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3316 if (pid == LLDB_INVALID_PROCESS_ID) 3317 return SendIllFormedResponse(packet, 3318 "vAttach failed to parse the process id"); 3319 3320 // Attempt to attach. 3321 LLDB_LOGF(log, 3322 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to " 3323 "pid %" PRIu64, 3324 __FUNCTION__, pid); 3325 3326 Status error = AttachToProcess(pid); 3327 3328 if (error.Fail()) { 3329 LLDB_LOGF(log, 3330 "GDBRemoteCommunicationServerLLGS::%s failed to attach to " 3331 "pid %" PRIu64 ": %s\n", 3332 __FUNCTION__, pid, error.AsCString()); 3333 return SendErrorResponse(error); 3334 } 3335 3336 // Notify we attached by sending a stop packet. 3337 assert(m_current_process); 3338 return SendStopReasonForState(*m_current_process, 3339 m_current_process->GetState(), 3340 /*force_synchronous=*/false); 3341 } 3342 3343 GDBRemoteCommunication::PacketResult 3344 GDBRemoteCommunicationServerLLGS::Handle_vAttachWait( 3345 StringExtractorGDBRemote &packet) { 3346 Log *log = GetLog(LLDBLog::Process); 3347 3348 // Consume the ';' after the identifier. 3349 packet.SetFilePos(strlen("vAttachWait")); 3350 3351 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3352 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'"); 3353 3354 // Allocate the buffer for the process name from vAttachWait. 3355 std::string process_name; 3356 if (!packet.GetHexByteString(process_name)) 3357 return SendIllFormedResponse(packet, 3358 "vAttachWait failed to parse process name"); 3359 3360 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name); 3361 3362 Status error = AttachWaitProcess(process_name, false); 3363 if (error.Fail()) { 3364 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name, 3365 error); 3366 return SendErrorResponse(error); 3367 } 3368 3369 // Notify we attached by sending a stop packet. 3370 assert(m_current_process); 3371 return SendStopReasonForState(*m_current_process, 3372 m_current_process->GetState(), 3373 /*force_synchronous=*/false); 3374 } 3375 3376 GDBRemoteCommunication::PacketResult 3377 GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported( 3378 StringExtractorGDBRemote &packet) { 3379 return SendOKResponse(); 3380 } 3381 3382 GDBRemoteCommunication::PacketResult 3383 GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait( 3384 StringExtractorGDBRemote &packet) { 3385 Log *log = GetLog(LLDBLog::Process); 3386 3387 // Consume the ';' after the identifier. 3388 packet.SetFilePos(strlen("vAttachOrWait")); 3389 3390 if (!packet.GetBytesLeft() || packet.GetChar() != ';') 3391 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'"); 3392 3393 // Allocate the buffer for the process name from vAttachWait. 3394 std::string process_name; 3395 if (!packet.GetHexByteString(process_name)) 3396 return SendIllFormedResponse(packet, 3397 "vAttachOrWait failed to parse process name"); 3398 3399 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name); 3400 3401 Status error = AttachWaitProcess(process_name, true); 3402 if (error.Fail()) { 3403 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name, 3404 error); 3405 return SendErrorResponse(error); 3406 } 3407 3408 // Notify we attached by sending a stop packet. 3409 assert(m_current_process); 3410 return SendStopReasonForState(*m_current_process, 3411 m_current_process->GetState(), 3412 /*force_synchronous=*/false); 3413 } 3414 3415 GDBRemoteCommunication::PacketResult 3416 GDBRemoteCommunicationServerLLGS::Handle_vRun( 3417 StringExtractorGDBRemote &packet) { 3418 Log *log = GetLog(LLDBLog::Process); 3419 3420 llvm::StringRef s = packet.GetStringRef(); 3421 if (!s.consume_front("vRun;")) 3422 return SendErrorResponse(8); 3423 3424 llvm::SmallVector<llvm::StringRef, 16> argv; 3425 s.split(argv, ';'); 3426 3427 for (llvm::StringRef hex_arg : argv) { 3428 StringExtractor arg_ext{hex_arg}; 3429 std::string arg; 3430 arg_ext.GetHexByteString(arg); 3431 m_process_launch_info.GetArguments().AppendArgument(arg); 3432 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__, 3433 arg.c_str()); 3434 } 3435 3436 if (!argv.empty()) { 3437 m_process_launch_info.GetExecutableFile().SetFile( 3438 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native); 3439 m_process_launch_error = LaunchProcess(); 3440 if (m_process_launch_error.Success()) { 3441 assert(m_current_process); 3442 return SendStopReasonForState(*m_current_process, 3443 m_current_process->GetState(), 3444 /*force_synchronous=*/true); 3445 } 3446 LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error); 3447 } 3448 return SendErrorResponse(8); 3449 } 3450 3451 GDBRemoteCommunication::PacketResult 3452 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) { 3453 Log *log = GetLog(LLDBLog::Process); 3454 StopSTDIOForwarding(); 3455 3456 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 3457 3458 // Consume the ';' after D. 3459 packet.SetFilePos(1); 3460 if (packet.GetBytesLeft()) { 3461 if (packet.GetChar() != ';') 3462 return SendIllFormedResponse(packet, "D missing expected ';'"); 3463 3464 // Grab the PID from which we will detach (assume hex encoding). 3465 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16); 3466 if (pid == LLDB_INVALID_PROCESS_ID) 3467 return SendIllFormedResponse(packet, "D failed to parse the process id"); 3468 } 3469 3470 // Detach forked children if their PID was specified *or* no PID was requested 3471 // (i.e. detach-all packet). 3472 llvm::Error detach_error = llvm::Error::success(); 3473 bool detached = false; 3474 for (auto it = m_debugged_processes.begin(); 3475 it != m_debugged_processes.end();) { 3476 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) { 3477 LLDB_LOGF(log, 3478 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64, 3479 __FUNCTION__, it->first); 3480 if (llvm::Error e = it->second->Detach().ToError()) 3481 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e)); 3482 else { 3483 if (it->second.get() == m_current_process) 3484 m_current_process = nullptr; 3485 if (it->second.get() == m_continue_process) 3486 m_continue_process = nullptr; 3487 it = m_debugged_processes.erase(it); 3488 detached = true; 3489 continue; 3490 } 3491 } 3492 ++it; 3493 } 3494 3495 if (detach_error) 3496 return SendErrorResponse(std::move(detach_error)); 3497 if (!detached) 3498 return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid)); 3499 return SendOKResponse(); 3500 } 3501 3502 GDBRemoteCommunication::PacketResult 3503 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo( 3504 StringExtractorGDBRemote &packet) { 3505 Log *log = GetLog(LLDBLog::Thread); 3506 3507 if (!m_current_process || 3508 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3509 return SendErrorResponse(50); 3510 3511 packet.SetFilePos(strlen("qThreadStopInfo")); 3512 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 3513 if (tid == LLDB_INVALID_THREAD_ID) { 3514 LLDB_LOGF(log, 3515 "GDBRemoteCommunicationServerLLGS::%s failed, could not " 3516 "parse thread id from request \"%s\"", 3517 __FUNCTION__, packet.GetStringRef().data()); 3518 return SendErrorResponse(0x15); 3519 } 3520 return SendStopReplyPacketForThread(*m_current_process, tid, 3521 /*force_synchronous=*/true); 3522 } 3523 3524 GDBRemoteCommunication::PacketResult 3525 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo( 3526 StringExtractorGDBRemote &) { 3527 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread); 3528 3529 // Ensure we have a debugged process. 3530 if (!m_current_process || 3531 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3532 return SendErrorResponse(50); 3533 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID()); 3534 3535 StreamString response; 3536 const bool threads_with_valid_stop_info_only = false; 3537 llvm::Expected<json::Value> threads_info = 3538 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only); 3539 if (!threads_info) { 3540 LLDB_LOG_ERROR(log, threads_info.takeError(), 3541 "failed to prepare a packet for pid {1}: {0}", 3542 m_current_process->GetID()); 3543 return SendErrorResponse(52); 3544 } 3545 3546 response.AsRawOstream() << *threads_info; 3547 StreamGDBRemote escaped_response; 3548 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize()); 3549 return SendPacketNoLock(escaped_response.GetString()); 3550 } 3551 3552 GDBRemoteCommunication::PacketResult 3553 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo( 3554 StringExtractorGDBRemote &packet) { 3555 // Fail if we don't have a current process. 3556 if (!m_current_process || 3557 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3558 return SendErrorResponse(68); 3559 3560 packet.SetFilePos(strlen("qWatchpointSupportInfo")); 3561 if (packet.GetBytesLeft() == 0) 3562 return SendOKResponse(); 3563 if (packet.GetChar() != ':') 3564 return SendErrorResponse(67); 3565 3566 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo(); 3567 3568 StreamGDBRemote response; 3569 if (hw_debug_cap == llvm::None) 3570 response.Printf("num:0;"); 3571 else 3572 response.Printf("num:%d;", hw_debug_cap->second); 3573 3574 return SendPacketNoLock(response.GetString()); 3575 } 3576 3577 GDBRemoteCommunication::PacketResult 3578 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress( 3579 StringExtractorGDBRemote &packet) { 3580 // Fail if we don't have a current process. 3581 if (!m_current_process || 3582 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3583 return SendErrorResponse(67); 3584 3585 packet.SetFilePos(strlen("qFileLoadAddress:")); 3586 if (packet.GetBytesLeft() == 0) 3587 return SendErrorResponse(68); 3588 3589 std::string file_name; 3590 packet.GetHexByteString(file_name); 3591 3592 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS; 3593 Status error = 3594 m_current_process->GetFileLoadAddress(file_name, file_load_address); 3595 if (error.Fail()) 3596 return SendErrorResponse(69); 3597 3598 if (file_load_address == LLDB_INVALID_ADDRESS) 3599 return SendErrorResponse(1); // File not loaded 3600 3601 StreamGDBRemote response; 3602 response.PutHex64(file_load_address); 3603 return SendPacketNoLock(response.GetString()); 3604 } 3605 3606 GDBRemoteCommunication::PacketResult 3607 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals( 3608 StringExtractorGDBRemote &packet) { 3609 std::vector<int> signals; 3610 packet.SetFilePos(strlen("QPassSignals:")); 3611 3612 // Read sequence of hex signal numbers divided by a semicolon and optionally 3613 // spaces. 3614 while (packet.GetBytesLeft() > 0) { 3615 int signal = packet.GetS32(-1, 16); 3616 if (signal < 0) 3617 return SendIllFormedResponse(packet, "Failed to parse signal number."); 3618 signals.push_back(signal); 3619 3620 packet.SkipSpaces(); 3621 char separator = packet.GetChar(); 3622 if (separator == '\0') 3623 break; // End of string 3624 if (separator != ';') 3625 return SendIllFormedResponse(packet, "Invalid separator," 3626 " expected semicolon."); 3627 } 3628 3629 // Fail if we don't have a current process. 3630 if (!m_current_process) 3631 return SendErrorResponse(68); 3632 3633 Status error = m_current_process->IgnoreSignals(signals); 3634 if (error.Fail()) 3635 return SendErrorResponse(69); 3636 3637 return SendOKResponse(); 3638 } 3639 3640 GDBRemoteCommunication::PacketResult 3641 GDBRemoteCommunicationServerLLGS::Handle_qMemTags( 3642 StringExtractorGDBRemote &packet) { 3643 Log *log = GetLog(LLDBLog::Process); 3644 3645 // Ensure we have a process. 3646 if (!m_current_process || 3647 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3648 LLDB_LOGF( 3649 log, 3650 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 3651 __FUNCTION__); 3652 return SendErrorResponse(1); 3653 } 3654 3655 // We are expecting 3656 // qMemTags:<hex address>,<hex length>:<hex type> 3657 3658 // Address 3659 packet.SetFilePos(strlen("qMemTags:")); 3660 const char *current_char = packet.Peek(); 3661 if (!current_char || *current_char == ',') 3662 return SendIllFormedResponse(packet, "Missing address in qMemTags packet"); 3663 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3664 3665 // Length 3666 char previous_char = packet.GetChar(); 3667 current_char = packet.Peek(); 3668 // If we don't have a separator or the length field is empty 3669 if (previous_char != ',' || (current_char && *current_char == ':')) 3670 return SendIllFormedResponse(packet, 3671 "Invalid addr,length pair in qMemTags packet"); 3672 3673 if (packet.GetBytesLeft() < 1) 3674 return SendIllFormedResponse( 3675 packet, "Too short qMemtags: packet (looking for length)"); 3676 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3677 3678 // Type 3679 const char *invalid_type_err = "Invalid type field in qMemTags: packet"; 3680 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3681 return SendIllFormedResponse(packet, invalid_type_err); 3682 3683 // Type is a signed integer but packed into the packet as its raw bytes. 3684 // However, our GetU64 uses strtoull which allows +/-. We do not want this. 3685 const char *first_type_char = packet.Peek(); 3686 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-')) 3687 return SendIllFormedResponse(packet, invalid_type_err); 3688 3689 // Extract type as unsigned then cast to signed. 3690 // Using a uint64_t here so that we have some value outside of the 32 bit 3691 // range to use as the invalid return value. 3692 uint64_t raw_type = 3693 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16); 3694 3695 if ( // Make sure the cast below would be valid 3696 raw_type > std::numeric_limits<uint32_t>::max() || 3697 // To catch inputs like "123aardvark" that will parse but clearly aren't 3698 // valid in this case. 3699 packet.GetBytesLeft()) { 3700 return SendIllFormedResponse(packet, invalid_type_err); 3701 } 3702 3703 // First narrow to 32 bits otherwise the copy into type would take 3704 // the wrong 4 bytes on big endian. 3705 uint32_t raw_type_32 = raw_type; 3706 int32_t type = reinterpret_cast<int32_t &>(raw_type_32); 3707 3708 StreamGDBRemote response; 3709 std::vector<uint8_t> tags; 3710 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags); 3711 if (error.Fail()) 3712 return SendErrorResponse(1); 3713 3714 // This m is here in case we want to support multi part replies in the future. 3715 // In the same manner as qfThreadInfo/qsThreadInfo. 3716 response.PutChar('m'); 3717 response.PutBytesAsRawHex8(tags.data(), tags.size()); 3718 return SendPacketNoLock(response.GetString()); 3719 } 3720 3721 GDBRemoteCommunication::PacketResult 3722 GDBRemoteCommunicationServerLLGS::Handle_QMemTags( 3723 StringExtractorGDBRemote &packet) { 3724 Log *log = GetLog(LLDBLog::Process); 3725 3726 // Ensure we have a process. 3727 if (!m_current_process || 3728 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) { 3729 LLDB_LOGF( 3730 log, 3731 "GDBRemoteCommunicationServerLLGS::%s failed, no process available", 3732 __FUNCTION__); 3733 return SendErrorResponse(1); 3734 } 3735 3736 // We are expecting 3737 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes> 3738 3739 // Address 3740 packet.SetFilePos(strlen("QMemTags:")); 3741 const char *current_char = packet.Peek(); 3742 if (!current_char || *current_char == ',') 3743 return SendIllFormedResponse(packet, "Missing address in QMemTags packet"); 3744 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3745 3746 // Length 3747 char previous_char = packet.GetChar(); 3748 current_char = packet.Peek(); 3749 // If we don't have a separator or the length field is empty 3750 if (previous_char != ',' || (current_char && *current_char == ':')) 3751 return SendIllFormedResponse(packet, 3752 "Invalid addr,length pair in QMemTags packet"); 3753 3754 if (packet.GetBytesLeft() < 1) 3755 return SendIllFormedResponse( 3756 packet, "Too short QMemtags: packet (looking for length)"); 3757 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0); 3758 3759 // Type 3760 const char *invalid_type_err = "Invalid type field in QMemTags: packet"; 3761 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3762 return SendIllFormedResponse(packet, invalid_type_err); 3763 3764 // Our GetU64 uses strtoull which allows leading +/-, we don't want that. 3765 const char *first_type_char = packet.Peek(); 3766 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-')) 3767 return SendIllFormedResponse(packet, invalid_type_err); 3768 3769 // The type is a signed integer but is in the packet as its raw bytes. 3770 // So parse first as unsigned then cast to signed later. 3771 // We extract to 64 bit, even though we only expect 32, so that we've 3772 // got some invalid value we can check for. 3773 uint64_t raw_type = 3774 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16); 3775 if (raw_type > std::numeric_limits<uint32_t>::max()) 3776 return SendIllFormedResponse(packet, invalid_type_err); 3777 3778 // First narrow to 32 bits. Otherwise the copy below would get the wrong 3779 // 4 bytes on big endian. 3780 uint32_t raw_type_32 = raw_type; 3781 int32_t type = reinterpret_cast<int32_t &>(raw_type_32); 3782 3783 // Tag data 3784 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':') 3785 return SendIllFormedResponse(packet, 3786 "Missing tag data in QMemTags: packet"); 3787 3788 // Must be 2 chars per byte 3789 const char *invalid_data_err = "Invalid tag data in QMemTags: packet"; 3790 if (packet.GetBytesLeft() % 2) 3791 return SendIllFormedResponse(packet, invalid_data_err); 3792 3793 // This is bytes here and is unpacked into target specific tags later 3794 // We cannot assume that number of bytes == length here because the server 3795 // can repeat tags to fill a given range. 3796 std::vector<uint8_t> tag_data; 3797 // Zero length writes will not have any tag data 3798 // (but we pass them on because it will still check that tagging is enabled) 3799 if (packet.GetBytesLeft()) { 3800 size_t byte_count = packet.GetBytesLeft() / 2; 3801 tag_data.resize(byte_count); 3802 size_t converted_bytes = packet.GetHexBytes(tag_data, 0); 3803 if (converted_bytes != byte_count) { 3804 return SendIllFormedResponse(packet, invalid_data_err); 3805 } 3806 } 3807 3808 Status status = 3809 m_current_process->WriteMemoryTags(type, addr, length, tag_data); 3810 return status.Success() ? SendOKResponse() : SendErrorResponse(1); 3811 } 3812 3813 GDBRemoteCommunication::PacketResult 3814 GDBRemoteCommunicationServerLLGS::Handle_qSaveCore( 3815 StringExtractorGDBRemote &packet) { 3816 // Fail if we don't have a current process. 3817 if (!m_current_process || 3818 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) 3819 return SendErrorResponse(Status("Process not running.")); 3820 3821 std::string path_hint; 3822 3823 StringRef packet_str{packet.GetStringRef()}; 3824 assert(packet_str.startswith("qSaveCore")); 3825 if (packet_str.consume_front("qSaveCore;")) { 3826 for (auto x : llvm::split(packet_str, ';')) { 3827 if (x.consume_front("path-hint:")) 3828 StringExtractor(x).GetHexByteString(path_hint); 3829 else 3830 return SendErrorResponse(Status("Unsupported qSaveCore option")); 3831 } 3832 } 3833 3834 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint); 3835 if (!ret) 3836 return SendErrorResponse(ret.takeError()); 3837 3838 StreamString response; 3839 response.PutCString("core-path:"); 3840 response.PutStringAsRawHex8(ret.get()); 3841 return SendPacketNoLock(response.GetString()); 3842 } 3843 3844 GDBRemoteCommunication::PacketResult 3845 GDBRemoteCommunicationServerLLGS::Handle_QNonStop( 3846 StringExtractorGDBRemote &packet) { 3847 StringRef packet_str{packet.GetStringRef()}; 3848 assert(packet_str.startswith("QNonStop:")); 3849 packet_str.consume_front("QNonStop:"); 3850 if (packet_str == "0") { 3851 m_non_stop = false; 3852 // TODO: stop all threads 3853 } else if (packet_str == "1") { 3854 m_non_stop = true; 3855 } else 3856 return SendErrorResponse(Status("Invalid QNonStop packet")); 3857 return SendOKResponse(); 3858 } 3859 3860 GDBRemoteCommunication::PacketResult 3861 GDBRemoteCommunicationServerLLGS::Handle_vStopped( 3862 StringExtractorGDBRemote &packet) { 3863 // Per the protocol, the first message put into the queue is sent 3864 // immediately. However, it remains the queue until the client ACKs 3865 // it via vStopped -- then we pop it and send the next message. 3866 // The process repeats until the last message in the queue is ACK-ed, 3867 // in which case the vStopped packet sends an OK response. 3868 3869 if (m_stop_notification_queue.empty()) 3870 return SendErrorResponse(Status("No pending notification to ack")); 3871 m_stop_notification_queue.pop_front(); 3872 if (!m_stop_notification_queue.empty()) 3873 return SendPacketNoLock(m_stop_notification_queue.front()); 3874 // If this was the last notification and the process exited, terminate 3875 // the server. 3876 if (m_inferior_prev_state == eStateExited) { 3877 m_exit_now = true; 3878 m_mainloop.RequestTermination(); 3879 } 3880 return SendOKResponse(); 3881 } 3882 3883 GDBRemoteCommunication::PacketResult 3884 GDBRemoteCommunicationServerLLGS::Handle_vCtrlC( 3885 StringExtractorGDBRemote &packet) { 3886 if (!m_non_stop) 3887 return SendErrorResponse(Status("vCtrl is only valid in non-stop mode")); 3888 3889 PacketResult interrupt_res = Handle_interrupt(packet); 3890 // If interrupting the process failed, pass the result through. 3891 if (interrupt_res != PacketResult::Success) 3892 return interrupt_res; 3893 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not). 3894 return SendOKResponse(); 3895 } 3896 3897 GDBRemoteCommunication::PacketResult 3898 GDBRemoteCommunicationServerLLGS::Handle_T(StringExtractorGDBRemote &packet) { 3899 packet.SetFilePos(strlen("T")); 3900 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID() 3901 : LLDB_INVALID_PROCESS_ID); 3902 if (!pid_tid) 3903 return SendErrorResponse(llvm::make_error<StringError>( 3904 inconvertibleErrorCode(), "Malformed thread-id")); 3905 3906 lldb::pid_t pid = pid_tid->first; 3907 lldb::tid_t tid = pid_tid->second; 3908 3909 // Technically, this would also be caught by the PID check but let's be more 3910 // explicit about the error. 3911 if (pid == LLDB_INVALID_PROCESS_ID) 3912 return SendErrorResponse(llvm::make_error<StringError>( 3913 inconvertibleErrorCode(), "No current process and no PID provided")); 3914 3915 // Check the process ID and find respective process instance. 3916 auto new_process_it = m_debugged_processes.find(pid); 3917 if (new_process_it == m_debugged_processes.end()) 3918 return SendErrorResponse(1); 3919 3920 // Check the thread ID 3921 if (!new_process_it->second->GetThreadByID(tid)) 3922 return SendErrorResponse(2); 3923 3924 return SendOKResponse(); 3925 } 3926 3927 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() { 3928 Log *log = GetLog(LLDBLog::Process); 3929 3930 // Tell the stdio connection to shut down. 3931 if (m_stdio_communication.IsConnected()) { 3932 auto connection = m_stdio_communication.GetConnection(); 3933 if (connection) { 3934 Status error; 3935 connection->Disconnect(&error); 3936 3937 if (error.Success()) { 3938 LLDB_LOGF(log, 3939 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3940 "terminal stdio - SUCCESS", 3941 __FUNCTION__); 3942 } else { 3943 LLDB_LOGF(log, 3944 "GDBRemoteCommunicationServerLLGS::%s disconnect process " 3945 "terminal stdio - FAIL: %s", 3946 __FUNCTION__, error.AsCString()); 3947 } 3948 } 3949 } 3950 } 3951 3952 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix( 3953 StringExtractorGDBRemote &packet) { 3954 // We have no thread if we don't have a process. 3955 if (!m_current_process || 3956 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID) 3957 return nullptr; 3958 3959 // If the client hasn't asked for thread suffix support, there will not be a 3960 // thread suffix. Use the current thread in that case. 3961 if (!m_thread_suffix_supported) { 3962 const lldb::tid_t current_tid = GetCurrentThreadID(); 3963 if (current_tid == LLDB_INVALID_THREAD_ID) 3964 return nullptr; 3965 else if (current_tid == 0) { 3966 // Pick a thread. 3967 return m_current_process->GetThreadAtIndex(0); 3968 } else 3969 return m_current_process->GetThreadByID(current_tid); 3970 } 3971 3972 Log *log = GetLog(LLDBLog::Thread); 3973 3974 // Parse out the ';'. 3975 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') { 3976 LLDB_LOGF(log, 3977 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3978 "error: expected ';' prior to start of thread suffix: packet " 3979 "contents = '%s'", 3980 __FUNCTION__, packet.GetStringRef().data()); 3981 return nullptr; 3982 } 3983 3984 if (!packet.GetBytesLeft()) 3985 return nullptr; 3986 3987 // Parse out thread: portion. 3988 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) { 3989 LLDB_LOGF(log, 3990 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse " 3991 "error: expected 'thread:' but not found, packet contents = " 3992 "'%s'", 3993 __FUNCTION__, packet.GetStringRef().data()); 3994 return nullptr; 3995 } 3996 packet.SetFilePos(packet.GetFilePos() + strlen("thread:")); 3997 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0); 3998 if (tid != 0) 3999 return m_current_process->GetThreadByID(tid); 4000 4001 return nullptr; 4002 } 4003 4004 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const { 4005 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) { 4006 // Use whatever the debug process says is the current thread id since the 4007 // protocol either didn't specify or specified we want any/all threads 4008 // marked as the current thread. 4009 if (!m_current_process) 4010 return LLDB_INVALID_THREAD_ID; 4011 return m_current_process->GetCurrentThreadID(); 4012 } 4013 // Use the specific current thread id set by the gdb remote protocol. 4014 return m_current_tid; 4015 } 4016 4017 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() { 4018 std::lock_guard<std::mutex> guard(m_saved_registers_mutex); 4019 return m_next_saved_registers_id++; 4020 } 4021 4022 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() { 4023 Log *log = GetLog(LLDBLog::Process); 4024 4025 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size()); 4026 m_xfer_buffer_map.clear(); 4027 } 4028 4029 FileSpec 4030 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path, 4031 const ArchSpec &arch) { 4032 if (m_current_process) { 4033 FileSpec file_spec; 4034 if (m_current_process 4035 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec) 4036 .Success()) { 4037 if (FileSystem::Instance().Exists(file_spec)) 4038 return file_spec; 4039 } 4040 } 4041 4042 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch); 4043 } 4044 4045 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue( 4046 llvm::StringRef value) { 4047 std::string result; 4048 for (const char &c : value) { 4049 switch (c) { 4050 case '\'': 4051 result += "'"; 4052 break; 4053 case '"': 4054 result += """; 4055 break; 4056 case '<': 4057 result += "<"; 4058 break; 4059 case '>': 4060 result += ">"; 4061 break; 4062 default: 4063 result += c; 4064 break; 4065 } 4066 } 4067 return result; 4068 } 4069 4070 std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures( 4071 const llvm::ArrayRef<llvm::StringRef> client_features) { 4072 std::vector<std::string> ret = 4073 GDBRemoteCommunicationServerCommon::HandleFeatures(client_features); 4074 ret.insert(ret.end(), { 4075 "QThreadSuffixSupported+", 4076 "QListThreadsInStopReply+", 4077 "qXfer:features:read+", 4078 "QNonStop+", 4079 }); 4080 4081 // report server-only features 4082 using Extension = NativeProcessProtocol::Extension; 4083 Extension plugin_features = m_process_factory.GetSupportedExtensions(); 4084 if (bool(plugin_features & Extension::pass_signals)) 4085 ret.push_back("QPassSignals+"); 4086 if (bool(plugin_features & Extension::auxv)) 4087 ret.push_back("qXfer:auxv:read+"); 4088 if (bool(plugin_features & Extension::libraries_svr4)) 4089 ret.push_back("qXfer:libraries-svr4:read+"); 4090 if (bool(plugin_features & Extension::siginfo_read)) 4091 ret.push_back("qXfer:siginfo:read+"); 4092 if (bool(plugin_features & Extension::memory_tagging)) 4093 ret.push_back("memory-tagging+"); 4094 if (bool(plugin_features & Extension::savecore)) 4095 ret.push_back("qSaveCore+"); 4096 4097 // check for client features 4098 m_extensions_supported = {}; 4099 for (llvm::StringRef x : client_features) 4100 m_extensions_supported |= 4101 llvm::StringSwitch<Extension>(x) 4102 .Case("multiprocess+", Extension::multiprocess) 4103 .Case("fork-events+", Extension::fork) 4104 .Case("vfork-events+", Extension::vfork) 4105 .Default({}); 4106 4107 m_extensions_supported &= plugin_features; 4108 4109 // fork & vfork require multiprocess 4110 if (!bool(m_extensions_supported & Extension::multiprocess)) 4111 m_extensions_supported &= ~(Extension::fork | Extension::vfork); 4112 4113 // report only if actually supported 4114 if (bool(m_extensions_supported & Extension::multiprocess)) 4115 ret.push_back("multiprocess+"); 4116 if (bool(m_extensions_supported & Extension::fork)) 4117 ret.push_back("fork-events+"); 4118 if (bool(m_extensions_supported & Extension::vfork)) 4119 ret.push_back("vfork-events+"); 4120 4121 for (auto &x : m_debugged_processes) 4122 SetEnabledExtensions(*x.second); 4123 return ret; 4124 } 4125 4126 void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions( 4127 NativeProcessProtocol &process) { 4128 NativeProcessProtocol::Extension flags = m_extensions_supported; 4129 assert(!bool(flags & ~m_process_factory.GetSupportedExtensions())); 4130 process.SetEnabledExtensions(flags); 4131 } 4132 4133 GDBRemoteCommunication::PacketResult 4134 GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() { 4135 // TODO: how to handle forwarding in non-stop mode? 4136 StartSTDIOForwarding(); 4137 return m_non_stop ? SendOKResponse() : PacketResult::Success; 4138 } 4139 4140 void GDBRemoteCommunicationServerLLGS::AppendThreadIDToResponse( 4141 Stream &response, lldb::pid_t pid, lldb::tid_t tid) { 4142 if (bool(m_extensions_supported & 4143 NativeProcessProtocol::Extension::multiprocess)) 4144 response.Format("p{0:x-}.", pid); 4145 response.Format("{0:x-}", tid); 4146 } 4147 4148 std::string 4149 lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg, 4150 bool reverse_connect) { 4151 // Try parsing the argument as URL. 4152 if (llvm::Optional<URI> url = URI::Parse(url_arg)) { 4153 if (reverse_connect) 4154 return url_arg.str(); 4155 4156 // Translate the scheme from LLGS notation to ConnectionFileDescriptor. 4157 // If the scheme doesn't match any, pass it through to support using CFD 4158 // schemes directly. 4159 std::string new_url = llvm::StringSwitch<std::string>(url->scheme) 4160 .Case("tcp", "listen") 4161 .Case("unix", "unix-accept") 4162 .Case("unix-abstract", "unix-abstract-accept") 4163 .Default(url->scheme.str()); 4164 llvm::append_range(new_url, url_arg.substr(url->scheme.size())); 4165 return new_url; 4166 } 4167 4168 std::string host_port = url_arg.str(); 4169 // If host_and_port starts with ':', default the host to be "localhost" and 4170 // expect the remainder to be the port. 4171 if (url_arg.startswith(":")) 4172 host_port.insert(0, "localhost"); 4173 4174 // Try parsing the (preprocessed) argument as host:port pair. 4175 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError())) 4176 return (reverse_connect ? "connect://" : "listen://") + host_port; 4177 4178 // If none of the above applied, interpret the argument as UNIX socket path. 4179 return (reverse_connect ? "unix-connect://" : "unix-accept://") + 4180 url_arg.str(); 4181 } 4182