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