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