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