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