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