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