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