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