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