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