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