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