1 //===-- GDBRemoteCommunicationServerCommon.cpp ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "GDBRemoteCommunicationServerCommon.h" 10 11 #include <cerrno> 12 13 #ifdef __APPLE__ 14 #include <TargetConditionals.h> 15 #endif 16 17 #include <chrono> 18 #include <cstring> 19 #include <optional> 20 21 #include "lldb/Core/ModuleSpec.h" 22 #include "lldb/Host/Config.h" 23 #include "lldb/Host/File.h" 24 #include "lldb/Host/FileAction.h" 25 #include "lldb/Host/FileSystem.h" 26 #include "lldb/Host/Host.h" 27 #include "lldb/Host/HostInfo.h" 28 #include "lldb/Host/SafeMachO.h" 29 #include "lldb/Interpreter/OptionArgParser.h" 30 #include "lldb/Symbol/ObjectFile.h" 31 #include "lldb/Target/Platform.h" 32 #include "lldb/Utility/Endian.h" 33 #include "lldb/Utility/GDBRemote.h" 34 #include "lldb/Utility/LLDBLog.h" 35 #include "lldb/Utility/Log.h" 36 #include "lldb/Utility/StreamString.h" 37 #include "lldb/Utility/StructuredData.h" 38 #include "llvm/ADT/StringSwitch.h" 39 #include "llvm/Support/JSON.h" 40 #include "llvm/TargetParser/Triple.h" 41 42 #include "ProcessGDBRemoteLog.h" 43 #include "lldb/Utility/StringExtractorGDBRemote.h" 44 45 #ifdef __ANDROID__ 46 #include "lldb/Host/android/HostInfoAndroid.h" 47 #include "lldb/Host/common/ZipFileResolver.h" 48 #endif 49 50 using namespace lldb; 51 using namespace lldb_private::process_gdb_remote; 52 using namespace lldb_private; 53 54 #ifdef __ANDROID__ 55 const static uint32_t g_default_packet_timeout_sec = 20; // seconds 56 #else 57 const static uint32_t g_default_packet_timeout_sec = 0; // not specified 58 #endif 59 60 // GDBRemoteCommunicationServerCommon constructor 61 GDBRemoteCommunicationServerCommon::GDBRemoteCommunicationServerCommon() 62 : GDBRemoteCommunicationServer(), m_process_launch_info(), 63 m_process_launch_error(), m_proc_infos(), m_proc_infos_index(0) { 64 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_A, 65 &GDBRemoteCommunicationServerCommon::Handle_A); 66 RegisterMemberFunctionHandler( 67 StringExtractorGDBRemote::eServerPacketType_QEnvironment, 68 &GDBRemoteCommunicationServerCommon::Handle_QEnvironment); 69 RegisterMemberFunctionHandler( 70 StringExtractorGDBRemote::eServerPacketType_QEnvironmentHexEncoded, 71 &GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded); 72 RegisterMemberFunctionHandler( 73 StringExtractorGDBRemote::eServerPacketType_qfProcessInfo, 74 &GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo); 75 RegisterMemberFunctionHandler( 76 StringExtractorGDBRemote::eServerPacketType_qGroupName, 77 &GDBRemoteCommunicationServerCommon::Handle_qGroupName); 78 RegisterMemberFunctionHandler( 79 StringExtractorGDBRemote::eServerPacketType_qHostInfo, 80 &GDBRemoteCommunicationServerCommon::Handle_qHostInfo); 81 RegisterMemberFunctionHandler( 82 StringExtractorGDBRemote::eServerPacketType_QLaunchArch, 83 &GDBRemoteCommunicationServerCommon::Handle_QLaunchArch); 84 RegisterMemberFunctionHandler( 85 StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess, 86 &GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess); 87 RegisterMemberFunctionHandler( 88 StringExtractorGDBRemote::eServerPacketType_qEcho, 89 &GDBRemoteCommunicationServerCommon::Handle_qEcho); 90 RegisterMemberFunctionHandler( 91 StringExtractorGDBRemote::eServerPacketType_qModuleInfo, 92 &GDBRemoteCommunicationServerCommon::Handle_qModuleInfo); 93 RegisterMemberFunctionHandler( 94 StringExtractorGDBRemote::eServerPacketType_jModulesInfo, 95 &GDBRemoteCommunicationServerCommon::Handle_jModulesInfo); 96 RegisterMemberFunctionHandler( 97 StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod, 98 &GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod); 99 RegisterMemberFunctionHandler( 100 StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir, 101 &GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir); 102 RegisterMemberFunctionHandler( 103 StringExtractorGDBRemote::eServerPacketType_qPlatform_shell, 104 &GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell); 105 RegisterMemberFunctionHandler( 106 StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID, 107 &GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID); 108 RegisterMemberFunctionHandler( 109 StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError, 110 &GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError); 111 RegisterMemberFunctionHandler( 112 StringExtractorGDBRemote::eServerPacketType_QSetSTDERR, 113 &GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR); 114 RegisterMemberFunctionHandler( 115 StringExtractorGDBRemote::eServerPacketType_QSetSTDIN, 116 &GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN); 117 RegisterMemberFunctionHandler( 118 StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT, 119 &GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT); 120 RegisterMemberFunctionHandler( 121 StringExtractorGDBRemote::eServerPacketType_qSpeedTest, 122 &GDBRemoteCommunicationServerCommon::Handle_qSpeedTest); 123 RegisterMemberFunctionHandler( 124 StringExtractorGDBRemote::eServerPacketType_qsProcessInfo, 125 &GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo); 126 RegisterMemberFunctionHandler( 127 StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode, 128 &GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode); 129 RegisterMemberFunctionHandler( 130 StringExtractorGDBRemote::eServerPacketType_qSupported, 131 &GDBRemoteCommunicationServerCommon::Handle_qSupported); 132 RegisterMemberFunctionHandler( 133 StringExtractorGDBRemote::eServerPacketType_qUserName, 134 &GDBRemoteCommunicationServerCommon::Handle_qUserName); 135 RegisterMemberFunctionHandler( 136 StringExtractorGDBRemote::eServerPacketType_vFile_close, 137 &GDBRemoteCommunicationServerCommon::Handle_vFile_Close); 138 RegisterMemberFunctionHandler( 139 StringExtractorGDBRemote::eServerPacketType_vFile_exists, 140 &GDBRemoteCommunicationServerCommon::Handle_vFile_Exists); 141 RegisterMemberFunctionHandler( 142 StringExtractorGDBRemote::eServerPacketType_vFile_md5, 143 &GDBRemoteCommunicationServerCommon::Handle_vFile_MD5); 144 RegisterMemberFunctionHandler( 145 StringExtractorGDBRemote::eServerPacketType_vFile_mode, 146 &GDBRemoteCommunicationServerCommon::Handle_vFile_Mode); 147 RegisterMemberFunctionHandler( 148 StringExtractorGDBRemote::eServerPacketType_vFile_open, 149 &GDBRemoteCommunicationServerCommon::Handle_vFile_Open); 150 RegisterMemberFunctionHandler( 151 StringExtractorGDBRemote::eServerPacketType_vFile_pread, 152 &GDBRemoteCommunicationServerCommon::Handle_vFile_pRead); 153 RegisterMemberFunctionHandler( 154 StringExtractorGDBRemote::eServerPacketType_vFile_pwrite, 155 &GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite); 156 RegisterMemberFunctionHandler( 157 StringExtractorGDBRemote::eServerPacketType_vFile_size, 158 &GDBRemoteCommunicationServerCommon::Handle_vFile_Size); 159 RegisterMemberFunctionHandler( 160 StringExtractorGDBRemote::eServerPacketType_vFile_fstat, 161 &GDBRemoteCommunicationServerCommon::Handle_vFile_FStat); 162 RegisterMemberFunctionHandler( 163 StringExtractorGDBRemote::eServerPacketType_vFile_stat, 164 &GDBRemoteCommunicationServerCommon::Handle_vFile_Stat); 165 RegisterMemberFunctionHandler( 166 StringExtractorGDBRemote::eServerPacketType_vFile_symlink, 167 &GDBRemoteCommunicationServerCommon::Handle_vFile_symlink); 168 RegisterMemberFunctionHandler( 169 StringExtractorGDBRemote::eServerPacketType_vFile_unlink, 170 &GDBRemoteCommunicationServerCommon::Handle_vFile_unlink); 171 } 172 173 // Destructor 174 GDBRemoteCommunicationServerCommon::~GDBRemoteCommunicationServerCommon() = 175 default; 176 177 GDBRemoteCommunication::PacketResult 178 GDBRemoteCommunicationServerCommon::Handle_qHostInfo( 179 StringExtractorGDBRemote &packet) { 180 StreamString response; 181 182 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00 183 184 ArchSpec host_arch(HostInfo::GetArchitecture()); 185 const llvm::Triple &host_triple = host_arch.GetTriple(); 186 response.PutCString("triple:"); 187 response.PutStringAsRawHex8(host_triple.getTriple()); 188 response.Printf(";ptrsize:%u;", host_arch.GetAddressByteSize()); 189 190 llvm::StringRef distribution_id = HostInfo::GetDistributionId(); 191 if (!distribution_id.empty()) { 192 response.PutCString("distribution_id:"); 193 response.PutStringAsRawHex8(distribution_id); 194 response.PutCString(";"); 195 } 196 197 #if defined(__APPLE__) 198 // For parity with debugserver, we'll include the vendor key. 199 response.PutCString("vendor:apple;"); 200 201 // Send out MachO info. 202 uint32_t cpu = host_arch.GetMachOCPUType(); 203 uint32_t sub = host_arch.GetMachOCPUSubType(); 204 if (cpu != LLDB_INVALID_CPUTYPE) 205 response.Printf("cputype:%u;", cpu); 206 if (sub != LLDB_INVALID_CPUTYPE) 207 response.Printf("cpusubtype:%u;", sub); 208 209 if (cpu == llvm::MachO::CPU_TYPE_ARM || cpu == llvm::MachO::CPU_TYPE_ARM64) { 210 // Indicate the OS type. 211 #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1 212 response.PutCString("ostype:tvos;"); 213 #elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1 214 response.PutCString("ostype:watchos;"); 215 #elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1 216 response.PutCString("ostype:bridgeos;"); 217 #else 218 response.PutCString("ostype:ios;"); 219 #endif 220 221 // On arm, we use "synchronous" watchpoints which means the exception is 222 // delivered before the instruction executes. 223 response.PutCString("watchpoint_exceptions_received:before;"); 224 } else { 225 response.PutCString("ostype:macosx;"); 226 response.Printf("watchpoint_exceptions_received:after;"); 227 } 228 229 #else 230 if (host_arch.GetMachine() == llvm::Triple::aarch64 || 231 host_arch.GetMachine() == llvm::Triple::aarch64_32 || 232 host_arch.GetMachine() == llvm::Triple::aarch64_be || 233 host_arch.GetMachine() == llvm::Triple::arm || 234 host_arch.GetMachine() == llvm::Triple::armeb || host_arch.IsMIPS()) 235 response.Printf("watchpoint_exceptions_received:before;"); 236 else 237 response.Printf("watchpoint_exceptions_received:after;"); 238 #endif 239 240 switch (endian::InlHostByteOrder()) { 241 case eByteOrderBig: 242 response.PutCString("endian:big;"); 243 break; 244 case eByteOrderLittle: 245 response.PutCString("endian:little;"); 246 break; 247 case eByteOrderPDP: 248 response.PutCString("endian:pdp;"); 249 break; 250 default: 251 response.PutCString("endian:unknown;"); 252 break; 253 } 254 255 llvm::VersionTuple version = HostInfo::GetOSVersion(); 256 if (!version.empty()) { 257 response.Format("os_version:{0}", version.getAsString()); 258 response.PutChar(';'); 259 } 260 261 #if defined(__APPLE__) 262 llvm::VersionTuple maccatalyst_version = HostInfo::GetMacCatalystVersion(); 263 if (!maccatalyst_version.empty()) { 264 response.Format("maccatalyst_version:{0}", 265 maccatalyst_version.getAsString()); 266 response.PutChar(';'); 267 } 268 #endif 269 270 if (std::optional<std::string> s = HostInfo::GetOSBuildString()) { 271 response.PutCString("os_build:"); 272 response.PutStringAsRawHex8(*s); 273 response.PutChar(';'); 274 } 275 if (std::optional<std::string> s = HostInfo::GetOSKernelDescription()) { 276 response.PutCString("os_kernel:"); 277 response.PutStringAsRawHex8(*s); 278 response.PutChar(';'); 279 } 280 281 std::string s; 282 #if defined(__APPLE__) 283 284 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) 285 // For iOS devices, we are connected through a USB Mux so we never pretend to 286 // actually have a hostname as far as the remote lldb that is connecting to 287 // this lldb-platform is concerned 288 response.PutCString("hostname:"); 289 response.PutStringAsRawHex8("127.0.0.1"); 290 response.PutChar(';'); 291 #else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) 292 if (HostInfo::GetHostname(s)) { 293 response.PutCString("hostname:"); 294 response.PutStringAsRawHex8(s); 295 response.PutChar(';'); 296 } 297 #endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) 298 299 #else // #if defined(__APPLE__) 300 if (HostInfo::GetHostname(s)) { 301 response.PutCString("hostname:"); 302 response.PutStringAsRawHex8(s); 303 response.PutChar(';'); 304 } 305 #endif // #if defined(__APPLE__) 306 // coverity[unsigned_compare] 307 if (g_default_packet_timeout_sec > 0) 308 response.Printf("default_packet_timeout:%u;", g_default_packet_timeout_sec); 309 310 return SendPacketNoLock(response.GetString()); 311 } 312 313 GDBRemoteCommunication::PacketResult 314 GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID( 315 StringExtractorGDBRemote &packet) { 316 // Packet format: "qProcessInfoPID:%i" where %i is the pid 317 packet.SetFilePos(::strlen("qProcessInfoPID:")); 318 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID); 319 if (pid != LLDB_INVALID_PROCESS_ID) { 320 ProcessInstanceInfo proc_info; 321 if (Host::GetProcessInfo(pid, proc_info)) { 322 StreamString response; 323 CreateProcessInfoResponse(proc_info, response); 324 return SendPacketNoLock(response.GetString()); 325 } 326 } 327 return SendErrorResponse(1); 328 } 329 330 GDBRemoteCommunication::PacketResult 331 GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo( 332 StringExtractorGDBRemote &packet) { 333 m_proc_infos_index = 0; 334 m_proc_infos.clear(); 335 336 ProcessInstanceInfoMatch match_info; 337 packet.SetFilePos(::strlen("qfProcessInfo")); 338 if (packet.GetChar() == ':') { 339 llvm::StringRef key; 340 llvm::StringRef value; 341 while (packet.GetNameColonValue(key, value)) { 342 bool success = true; 343 if (key == "name") { 344 StringExtractor extractor(value); 345 std::string file; 346 extractor.GetHexByteString(file); 347 match_info.GetProcessInfo().GetExecutableFile().SetFile( 348 file, FileSpec::Style::native); 349 } else if (key == "name_match") { 350 NameMatch name_match = llvm::StringSwitch<NameMatch>(value) 351 .Case("equals", NameMatch::Equals) 352 .Case("starts_with", NameMatch::StartsWith) 353 .Case("ends_with", NameMatch::EndsWith) 354 .Case("contains", NameMatch::Contains) 355 .Case("regex", NameMatch::RegularExpression) 356 .Default(NameMatch::Ignore); 357 match_info.SetNameMatchType(name_match); 358 if (name_match == NameMatch::Ignore) 359 return SendErrorResponse(2); 360 } else if (key == "pid") { 361 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 362 if (value.getAsInteger(0, pid)) 363 return SendErrorResponse(2); 364 match_info.GetProcessInfo().SetProcessID(pid); 365 } else if (key == "parent_pid") { 366 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 367 if (value.getAsInteger(0, pid)) 368 return SendErrorResponse(2); 369 match_info.GetProcessInfo().SetParentProcessID(pid); 370 } else if (key == "uid") { 371 uint32_t uid = UINT32_MAX; 372 if (value.getAsInteger(0, uid)) 373 return SendErrorResponse(2); 374 match_info.GetProcessInfo().SetUserID(uid); 375 } else if (key == "gid") { 376 uint32_t gid = UINT32_MAX; 377 if (value.getAsInteger(0, gid)) 378 return SendErrorResponse(2); 379 match_info.GetProcessInfo().SetGroupID(gid); 380 } else if (key == "euid") { 381 uint32_t uid = UINT32_MAX; 382 if (value.getAsInteger(0, uid)) 383 return SendErrorResponse(2); 384 match_info.GetProcessInfo().SetEffectiveUserID(uid); 385 } else if (key == "egid") { 386 uint32_t gid = UINT32_MAX; 387 if (value.getAsInteger(0, gid)) 388 return SendErrorResponse(2); 389 match_info.GetProcessInfo().SetEffectiveGroupID(gid); 390 } else if (key == "all_users") { 391 match_info.SetMatchAllUsers( 392 OptionArgParser::ToBoolean(value, false, &success)); 393 } else if (key == "triple") { 394 match_info.GetProcessInfo().GetArchitecture() = 395 HostInfo::GetAugmentedArchSpec(value); 396 } else { 397 success = false; 398 } 399 400 if (!success) 401 return SendErrorResponse(2); 402 } 403 } 404 405 if (Host::FindProcesses(match_info, m_proc_infos)) { 406 // We found something, return the first item by calling the get subsequent 407 // process info packet handler... 408 return Handle_qsProcessInfo(packet); 409 } 410 return SendErrorResponse(3); 411 } 412 413 GDBRemoteCommunication::PacketResult 414 GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo( 415 StringExtractorGDBRemote &packet) { 416 if (m_proc_infos_index < m_proc_infos.size()) { 417 StreamString response; 418 CreateProcessInfoResponse(m_proc_infos[m_proc_infos_index], response); 419 ++m_proc_infos_index; 420 return SendPacketNoLock(response.GetString()); 421 } 422 return SendErrorResponse(4); 423 } 424 425 GDBRemoteCommunication::PacketResult 426 GDBRemoteCommunicationServerCommon::Handle_qUserName( 427 StringExtractorGDBRemote &packet) { 428 #if LLDB_ENABLE_POSIX 429 Log *log = GetLog(LLDBLog::Process); 430 LLDB_LOGF(log, "GDBRemoteCommunicationServerCommon::%s begin", __FUNCTION__); 431 432 // Packet format: "qUserName:%i" where %i is the uid 433 packet.SetFilePos(::strlen("qUserName:")); 434 uint32_t uid = packet.GetU32(UINT32_MAX); 435 if (uid != UINT32_MAX) { 436 if (std::optional<llvm::StringRef> name = 437 HostInfo::GetUserIDResolver().GetUserName(uid)) { 438 StreamString response; 439 response.PutStringAsRawHex8(*name); 440 return SendPacketNoLock(response.GetString()); 441 } 442 } 443 LLDB_LOGF(log, "GDBRemoteCommunicationServerCommon::%s end", __FUNCTION__); 444 #endif 445 return SendErrorResponse(5); 446 } 447 448 GDBRemoteCommunication::PacketResult 449 GDBRemoteCommunicationServerCommon::Handle_qGroupName( 450 StringExtractorGDBRemote &packet) { 451 #if LLDB_ENABLE_POSIX 452 // Packet format: "qGroupName:%i" where %i is the gid 453 packet.SetFilePos(::strlen("qGroupName:")); 454 uint32_t gid = packet.GetU32(UINT32_MAX); 455 if (gid != UINT32_MAX) { 456 if (std::optional<llvm::StringRef> name = 457 HostInfo::GetUserIDResolver().GetGroupName(gid)) { 458 StreamString response; 459 response.PutStringAsRawHex8(*name); 460 return SendPacketNoLock(response.GetString()); 461 } 462 } 463 #endif 464 return SendErrorResponse(6); 465 } 466 467 GDBRemoteCommunication::PacketResult 468 GDBRemoteCommunicationServerCommon::Handle_qSpeedTest( 469 StringExtractorGDBRemote &packet) { 470 packet.SetFilePos(::strlen("qSpeedTest:")); 471 472 llvm::StringRef key; 473 llvm::StringRef value; 474 bool success = packet.GetNameColonValue(key, value); 475 if (success && key == "response_size") { 476 uint32_t response_size = 0; 477 if (!value.getAsInteger(0, response_size)) { 478 if (response_size == 0) 479 return SendOKResponse(); 480 StreamString response; 481 uint32_t bytes_left = response_size; 482 response.PutCString("data:"); 483 while (bytes_left > 0) { 484 if (bytes_left >= 26) { 485 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); 486 bytes_left -= 26; 487 } else { 488 response.Printf("%*.*s;", bytes_left, bytes_left, 489 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); 490 bytes_left = 0; 491 } 492 } 493 return SendPacketNoLock(response.GetString()); 494 } 495 } 496 return SendErrorResponse(7); 497 } 498 499 static GDBErrno system_errno_to_gdb(int err) { 500 switch (err) { 501 #define HANDLE_ERRNO(name, value) \ 502 case name: \ 503 return GDB_##name; 504 #include "Plugins/Process/gdb-remote/GDBRemoteErrno.def" 505 default: 506 return GDB_EUNKNOWN; 507 } 508 } 509 510 GDBRemoteCommunication::PacketResult 511 GDBRemoteCommunicationServerCommon::Handle_vFile_Open( 512 StringExtractorGDBRemote &packet) { 513 packet.SetFilePos(::strlen("vFile:open:")); 514 std::string path; 515 packet.GetHexByteStringTerminatedBy(path, ','); 516 if (!path.empty()) { 517 if (packet.GetChar() == ',') { 518 auto flags = File::OpenOptions(packet.GetHexMaxU32(false, 0)); 519 if (packet.GetChar() == ',') { 520 mode_t mode = packet.GetHexMaxU32(false, 0600); 521 FileSpec path_spec(path); 522 FileSystem::Instance().Resolve(path_spec); 523 // Do not close fd. 524 auto file = FileSystem::Instance().Open(path_spec, flags, mode, false); 525 526 StreamString response; 527 response.PutChar('F'); 528 529 int descriptor = File::kInvalidDescriptor; 530 if (file) { 531 descriptor = file.get()->GetDescriptor(); 532 response.Printf("%x", descriptor); 533 } else { 534 response.PutCString("-1"); 535 std::error_code code = errorToErrorCode(file.takeError()); 536 response.Printf(",%x", system_errno_to_gdb(code.value())); 537 } 538 539 return SendPacketNoLock(response.GetString()); 540 } 541 } 542 } 543 return SendErrorResponse(18); 544 } 545 546 GDBRemoteCommunication::PacketResult 547 GDBRemoteCommunicationServerCommon::Handle_vFile_Close( 548 StringExtractorGDBRemote &packet) { 549 packet.SetFilePos(::strlen("vFile:close:")); 550 int fd = packet.GetS32(-1, 16); 551 int err = -1; 552 int save_errno = 0; 553 if (fd >= 0) { 554 NativeFile file(fd, File::OpenOptions(0), true); 555 Status error = file.Close(); 556 err = 0; 557 save_errno = error.GetError(); 558 } else { 559 save_errno = EINVAL; 560 } 561 StreamString response; 562 response.PutChar('F'); 563 response.Printf("%x", err); 564 if (save_errno) 565 response.Printf(",%x", system_errno_to_gdb(save_errno)); 566 return SendPacketNoLock(response.GetString()); 567 } 568 569 GDBRemoteCommunication::PacketResult 570 GDBRemoteCommunicationServerCommon::Handle_vFile_pRead( 571 StringExtractorGDBRemote &packet) { 572 StreamGDBRemote response; 573 packet.SetFilePos(::strlen("vFile:pread:")); 574 int fd = packet.GetS32(-1, 16); 575 if (packet.GetChar() == ',') { 576 size_t count = packet.GetHexMaxU64(false, SIZE_MAX); 577 if (packet.GetChar() == ',') { 578 off_t offset = packet.GetHexMaxU32(false, UINT32_MAX); 579 if (count == SIZE_MAX) { 580 response.Printf("F-1:%x", EINVAL); 581 return SendPacketNoLock(response.GetString()); 582 } 583 584 std::string buffer(count, 0); 585 NativeFile file(fd, File::eOpenOptionReadOnly, false); 586 Status error = file.Read(static_cast<void *>(&buffer[0]), count, offset); 587 const int save_errno = error.GetError(); 588 response.PutChar('F'); 589 if (error.Success()) { 590 response.Printf("%zx", count); 591 response.PutChar(';'); 592 response.PutEscapedBytes(&buffer[0], count); 593 } else { 594 response.PutCString("-1"); 595 if (save_errno) 596 response.Printf(",%x", system_errno_to_gdb(save_errno)); 597 } 598 return SendPacketNoLock(response.GetString()); 599 } 600 } 601 return SendErrorResponse(21); 602 } 603 604 GDBRemoteCommunication::PacketResult 605 GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite( 606 StringExtractorGDBRemote &packet) { 607 packet.SetFilePos(::strlen("vFile:pwrite:")); 608 609 StreamGDBRemote response; 610 response.PutChar('F'); 611 612 int fd = packet.GetS32(-1, 16); 613 if (packet.GetChar() == ',') { 614 off_t offset = packet.GetHexMaxU32(false, UINT32_MAX); 615 if (packet.GetChar() == ',') { 616 std::string buffer; 617 if (packet.GetEscapedBinaryData(buffer)) { 618 NativeFile file(fd, File::eOpenOptionWriteOnly, false); 619 size_t count = buffer.size(); 620 Status error = 621 file.Write(static_cast<const void *>(&buffer[0]), count, offset); 622 const int save_errno = error.GetError(); 623 if (error.Success()) 624 response.Printf("%zx", count); 625 else { 626 response.PutCString("-1"); 627 if (save_errno) 628 response.Printf(",%x", system_errno_to_gdb(save_errno)); 629 } 630 } else { 631 response.Printf("-1,%x", EINVAL); 632 } 633 return SendPacketNoLock(response.GetString()); 634 } 635 } 636 return SendErrorResponse(27); 637 } 638 639 GDBRemoteCommunication::PacketResult 640 GDBRemoteCommunicationServerCommon::Handle_vFile_Size( 641 StringExtractorGDBRemote &packet) { 642 packet.SetFilePos(::strlen("vFile:size:")); 643 std::string path; 644 packet.GetHexByteString(path); 645 if (!path.empty()) { 646 uint64_t Size; 647 if (llvm::sys::fs::file_size(path, Size)) 648 return SendErrorResponse(5); 649 StreamString response; 650 response.PutChar('F'); 651 response.PutHex64(Size); 652 if (Size == UINT64_MAX) { 653 response.PutChar(','); 654 response.PutHex64(Size); // TODO: replace with Host::GetSyswideErrorCode() 655 } 656 return SendPacketNoLock(response.GetString()); 657 } 658 return SendErrorResponse(22); 659 } 660 661 GDBRemoteCommunication::PacketResult 662 GDBRemoteCommunicationServerCommon::Handle_vFile_Mode( 663 StringExtractorGDBRemote &packet) { 664 packet.SetFilePos(::strlen("vFile:mode:")); 665 std::string path; 666 packet.GetHexByteString(path); 667 if (!path.empty()) { 668 FileSpec file_spec(path); 669 FileSystem::Instance().Resolve(file_spec); 670 std::error_code ec; 671 const uint32_t mode = FileSystem::Instance().GetPermissions(file_spec, ec); 672 StreamString response; 673 if (mode != llvm::sys::fs::perms_not_known) 674 response.Printf("F%x", mode); 675 else 676 response.Printf("F-1,%x", (int)Status(ec).GetError()); 677 return SendPacketNoLock(response.GetString()); 678 } 679 return SendErrorResponse(23); 680 } 681 682 GDBRemoteCommunication::PacketResult 683 GDBRemoteCommunicationServerCommon::Handle_vFile_Exists( 684 StringExtractorGDBRemote &packet) { 685 packet.SetFilePos(::strlen("vFile:exists:")); 686 std::string path; 687 packet.GetHexByteString(path); 688 if (!path.empty()) { 689 bool retcode = llvm::sys::fs::exists(path); 690 StreamString response; 691 response.PutChar('F'); 692 response.PutChar(','); 693 if (retcode) 694 response.PutChar('1'); 695 else 696 response.PutChar('0'); 697 return SendPacketNoLock(response.GetString()); 698 } 699 return SendErrorResponse(24); 700 } 701 702 GDBRemoteCommunication::PacketResult 703 GDBRemoteCommunicationServerCommon::Handle_vFile_symlink( 704 StringExtractorGDBRemote &packet) { 705 packet.SetFilePos(::strlen("vFile:symlink:")); 706 std::string dst, src; 707 packet.GetHexByteStringTerminatedBy(dst, ','); 708 packet.GetChar(); // Skip ',' char 709 packet.GetHexByteString(src); 710 711 FileSpec src_spec(src); 712 FileSystem::Instance().Resolve(src_spec); 713 Status error = FileSystem::Instance().Symlink(src_spec, FileSpec(dst)); 714 715 StreamString response; 716 response.Printf("F%x,%x", error.GetError(), error.GetError()); 717 return SendPacketNoLock(response.GetString()); 718 } 719 720 GDBRemoteCommunication::PacketResult 721 GDBRemoteCommunicationServerCommon::Handle_vFile_unlink( 722 StringExtractorGDBRemote &packet) { 723 packet.SetFilePos(::strlen("vFile:unlink:")); 724 std::string path; 725 packet.GetHexByteString(path); 726 Status error(llvm::sys::fs::remove(path)); 727 StreamString response; 728 response.Printf("F%x,%x", error.GetError(), 729 system_errno_to_gdb(error.GetError())); 730 return SendPacketNoLock(response.GetString()); 731 } 732 733 GDBRemoteCommunication::PacketResult 734 GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell( 735 StringExtractorGDBRemote &packet) { 736 packet.SetFilePos(::strlen("qPlatform_shell:")); 737 std::string path; 738 std::string working_dir; 739 packet.GetHexByteStringTerminatedBy(path, ','); 740 if (!path.empty()) { 741 if (packet.GetChar() == ',') { 742 // FIXME: add timeout to qPlatform_shell packet 743 // uint32_t timeout = packet.GetHexMaxU32(false, 32); 744 if (packet.GetChar() == ',') 745 packet.GetHexByteString(working_dir); 746 int status, signo; 747 std::string output; 748 FileSpec working_spec(working_dir); 749 FileSystem::Instance().Resolve(working_spec); 750 Status err = 751 Host::RunShellCommand(path.c_str(), working_spec, &status, &signo, 752 &output, std::chrono::seconds(10)); 753 StreamGDBRemote response; 754 if (err.Fail()) { 755 response.PutCString("F,"); 756 response.PutHex32(UINT32_MAX); 757 } else { 758 response.PutCString("F,"); 759 response.PutHex32(status); 760 response.PutChar(','); 761 response.PutHex32(signo); 762 response.PutChar(','); 763 response.PutEscapedBytes(output.c_str(), output.size()); 764 } 765 return SendPacketNoLock(response.GetString()); 766 } 767 } 768 return SendErrorResponse(24); 769 } 770 771 template <typename T, typename U> 772 static void fill_clamp(T &dest, U src, typename T::value_type fallback) { 773 static_assert(std::is_unsigned<typename T::value_type>::value, 774 "Destination type must be unsigned."); 775 using UU = std::make_unsigned_t<U>; 776 constexpr auto T_max = std::numeric_limits<typename T::value_type>::max(); 777 dest = src >= 0 && static_cast<UU>(src) <= T_max ? src : fallback; 778 } 779 780 GDBRemoteCommunication::PacketResult 781 GDBRemoteCommunicationServerCommon::Handle_vFile_FStat( 782 StringExtractorGDBRemote &packet) { 783 StreamGDBRemote response; 784 packet.SetFilePos(::strlen("vFile:fstat:")); 785 int fd = packet.GetS32(-1, 16); 786 787 struct stat file_stats; 788 if (::fstat(fd, &file_stats) == -1) { 789 const int save_errno = errno; 790 response.Printf("F-1,%x", system_errno_to_gdb(save_errno)); 791 return SendPacketNoLock(response.GetString()); 792 } 793 794 GDBRemoteFStatData data; 795 fill_clamp(data.gdb_st_dev, file_stats.st_dev, 0); 796 fill_clamp(data.gdb_st_ino, file_stats.st_ino, 0); 797 data.gdb_st_mode = file_stats.st_mode; 798 fill_clamp(data.gdb_st_nlink, file_stats.st_nlink, UINT32_MAX); 799 fill_clamp(data.gdb_st_uid, file_stats.st_uid, 0); 800 fill_clamp(data.gdb_st_gid, file_stats.st_gid, 0); 801 fill_clamp(data.gdb_st_rdev, file_stats.st_rdev, 0); 802 data.gdb_st_size = file_stats.st_size; 803 #if !defined(_WIN32) 804 data.gdb_st_blksize = file_stats.st_blksize; 805 data.gdb_st_blocks = file_stats.st_blocks; 806 #else 807 data.gdb_st_blksize = 0; 808 data.gdb_st_blocks = 0; 809 #endif 810 fill_clamp(data.gdb_st_atime, file_stats.st_atime, 0); 811 fill_clamp(data.gdb_st_mtime, file_stats.st_mtime, 0); 812 fill_clamp(data.gdb_st_ctime, file_stats.st_ctime, 0); 813 814 response.Printf("F%zx;", sizeof(data)); 815 response.PutEscapedBytes(&data, sizeof(data)); 816 return SendPacketNoLock(response.GetString()); 817 } 818 819 GDBRemoteCommunication::PacketResult 820 GDBRemoteCommunicationServerCommon::Handle_vFile_Stat( 821 StringExtractorGDBRemote &packet) { 822 return SendUnimplementedResponse( 823 "GDBRemoteCommunicationServerCommon::Handle_vFile_Stat() unimplemented"); 824 } 825 826 GDBRemoteCommunication::PacketResult 827 GDBRemoteCommunicationServerCommon::Handle_vFile_MD5( 828 StringExtractorGDBRemote &packet) { 829 packet.SetFilePos(::strlen("vFile:MD5:")); 830 std::string path; 831 packet.GetHexByteString(path); 832 if (!path.empty()) { 833 StreamGDBRemote response; 834 auto Result = llvm::sys::fs::md5_contents(path); 835 if (!Result) { 836 response.PutCString("F,"); 837 response.PutCString("x"); 838 } else { 839 response.PutCString("F,"); 840 response.PutHex64(Result->low()); 841 response.PutHex64(Result->high()); 842 } 843 return SendPacketNoLock(response.GetString()); 844 } 845 return SendErrorResponse(25); 846 } 847 848 GDBRemoteCommunication::PacketResult 849 GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir( 850 StringExtractorGDBRemote &packet) { 851 packet.SetFilePos(::strlen("qPlatform_mkdir:")); 852 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX); 853 if (packet.GetChar() == ',') { 854 std::string path; 855 packet.GetHexByteString(path); 856 Status error(llvm::sys::fs::create_directory(path, mode)); 857 858 StreamGDBRemote response; 859 response.Printf("F%x", error.GetError()); 860 861 return SendPacketNoLock(response.GetString()); 862 } 863 return SendErrorResponse(20); 864 } 865 866 GDBRemoteCommunication::PacketResult 867 GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod( 868 StringExtractorGDBRemote &packet) { 869 packet.SetFilePos(::strlen("qPlatform_chmod:")); 870 871 auto perms = 872 static_cast<llvm::sys::fs::perms>(packet.GetHexMaxU32(false, UINT32_MAX)); 873 if (packet.GetChar() == ',') { 874 std::string path; 875 packet.GetHexByteString(path); 876 Status error(llvm::sys::fs::setPermissions(path, perms)); 877 878 StreamGDBRemote response; 879 response.Printf("F%x", error.GetError()); 880 881 return SendPacketNoLock(response.GetString()); 882 } 883 return SendErrorResponse(19); 884 } 885 886 GDBRemoteCommunication::PacketResult 887 GDBRemoteCommunicationServerCommon::Handle_qSupported( 888 StringExtractorGDBRemote &packet) { 889 // Parse client-indicated features. 890 llvm::SmallVector<llvm::StringRef, 4> client_features; 891 packet.GetStringRef().split(client_features, ';'); 892 return SendPacketNoLock(llvm::join(HandleFeatures(client_features), ";")); 893 } 894 895 GDBRemoteCommunication::PacketResult 896 GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError( 897 StringExtractorGDBRemote &packet) { 898 packet.SetFilePos(::strlen("QSetDetachOnError:")); 899 if (packet.GetU32(0)) 900 m_process_launch_info.GetFlags().Set(eLaunchFlagDetachOnError); 901 else 902 m_process_launch_info.GetFlags().Clear(eLaunchFlagDetachOnError); 903 return SendOKResponse(); 904 } 905 906 GDBRemoteCommunication::PacketResult 907 GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode( 908 StringExtractorGDBRemote &packet) { 909 // Send response first before changing m_send_acks to we ack this packet 910 PacketResult packet_result = SendOKResponse(); 911 m_send_acks = false; 912 return packet_result; 913 } 914 915 GDBRemoteCommunication::PacketResult 916 GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN( 917 StringExtractorGDBRemote &packet) { 918 packet.SetFilePos(::strlen("QSetSTDIN:")); 919 FileAction file_action; 920 std::string path; 921 packet.GetHexByteString(path); 922 const bool read = true; 923 const bool write = false; 924 if (file_action.Open(STDIN_FILENO, FileSpec(path), read, write)) { 925 m_process_launch_info.AppendFileAction(file_action); 926 return SendOKResponse(); 927 } 928 return SendErrorResponse(15); 929 } 930 931 GDBRemoteCommunication::PacketResult 932 GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT( 933 StringExtractorGDBRemote &packet) { 934 packet.SetFilePos(::strlen("QSetSTDOUT:")); 935 FileAction file_action; 936 std::string path; 937 packet.GetHexByteString(path); 938 const bool read = false; 939 const bool write = true; 940 if (file_action.Open(STDOUT_FILENO, FileSpec(path), read, write)) { 941 m_process_launch_info.AppendFileAction(file_action); 942 return SendOKResponse(); 943 } 944 return SendErrorResponse(16); 945 } 946 947 GDBRemoteCommunication::PacketResult 948 GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR( 949 StringExtractorGDBRemote &packet) { 950 packet.SetFilePos(::strlen("QSetSTDERR:")); 951 FileAction file_action; 952 std::string path; 953 packet.GetHexByteString(path); 954 const bool read = false; 955 const bool write = true; 956 if (file_action.Open(STDERR_FILENO, FileSpec(path), read, write)) { 957 m_process_launch_info.AppendFileAction(file_action); 958 return SendOKResponse(); 959 } 960 return SendErrorResponse(17); 961 } 962 963 GDBRemoteCommunication::PacketResult 964 GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess( 965 StringExtractorGDBRemote &packet) { 966 if (m_process_launch_error.Success()) 967 return SendOKResponse(); 968 StreamString response; 969 response.PutChar('E'); 970 response.PutCString(m_process_launch_error.AsCString("<unknown error>")); 971 return SendPacketNoLock(response.GetString()); 972 } 973 974 GDBRemoteCommunication::PacketResult 975 GDBRemoteCommunicationServerCommon::Handle_QEnvironment( 976 StringExtractorGDBRemote &packet) { 977 packet.SetFilePos(::strlen("QEnvironment:")); 978 const uint32_t bytes_left = packet.GetBytesLeft(); 979 if (bytes_left > 0) { 980 m_process_launch_info.GetEnvironment().insert(packet.Peek()); 981 return SendOKResponse(); 982 } 983 return SendErrorResponse(12); 984 } 985 986 GDBRemoteCommunication::PacketResult 987 GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded( 988 StringExtractorGDBRemote &packet) { 989 packet.SetFilePos(::strlen("QEnvironmentHexEncoded:")); 990 const uint32_t bytes_left = packet.GetBytesLeft(); 991 if (bytes_left > 0) { 992 std::string str; 993 packet.GetHexByteString(str); 994 m_process_launch_info.GetEnvironment().insert(str); 995 return SendOKResponse(); 996 } 997 return SendErrorResponse(12); 998 } 999 1000 GDBRemoteCommunication::PacketResult 1001 GDBRemoteCommunicationServerCommon::Handle_QLaunchArch( 1002 StringExtractorGDBRemote &packet) { 1003 packet.SetFilePos(::strlen("QLaunchArch:")); 1004 const uint32_t bytes_left = packet.GetBytesLeft(); 1005 if (bytes_left > 0) { 1006 const char *arch_triple = packet.Peek(); 1007 m_process_launch_info.SetArchitecture( 1008 HostInfo::GetAugmentedArchSpec(arch_triple)); 1009 return SendOKResponse(); 1010 } 1011 return SendErrorResponse(13); 1012 } 1013 1014 GDBRemoteCommunication::PacketResult 1015 GDBRemoteCommunicationServerCommon::Handle_A(StringExtractorGDBRemote &packet) { 1016 // The 'A' packet is the most over designed packet ever here with redundant 1017 // argument indexes, redundant argument lengths and needed hex encoded 1018 // argument string values. Really all that is needed is a comma separated hex 1019 // encoded argument value list, but we will stay true to the documented 1020 // version of the 'A' packet here... 1021 1022 Log *log = GetLog(LLDBLog::Process); 1023 int actual_arg_index = 0; 1024 1025 packet.SetFilePos(1); // Skip the 'A' 1026 bool success = true; 1027 while (success && packet.GetBytesLeft() > 0) { 1028 // Decode the decimal argument string length. This length is the number of 1029 // hex nibbles in the argument string value. 1030 const uint32_t arg_len = packet.GetU32(UINT32_MAX); 1031 if (arg_len == UINT32_MAX) 1032 success = false; 1033 else { 1034 // Make sure the argument hex string length is followed by a comma 1035 if (packet.GetChar() != ',') 1036 success = false; 1037 else { 1038 // Decode the argument index. We ignore this really because who would 1039 // really send down the arguments in a random order??? 1040 const uint32_t arg_idx = packet.GetU32(UINT32_MAX); 1041 if (arg_idx == UINT32_MAX) 1042 success = false; 1043 else { 1044 // Make sure the argument index is followed by a comma 1045 if (packet.GetChar() != ',') 1046 success = false; 1047 else { 1048 // Decode the argument string value from hex bytes back into a UTF8 1049 // string and make sure the length matches the one supplied in the 1050 // packet 1051 std::string arg; 1052 if (packet.GetHexByteStringFixedLength(arg, arg_len) != 1053 (arg_len / 2)) 1054 success = false; 1055 else { 1056 // If there are any bytes left 1057 if (packet.GetBytesLeft()) { 1058 if (packet.GetChar() != ',') 1059 success = false; 1060 } 1061 1062 if (success) { 1063 if (arg_idx == 0) 1064 m_process_launch_info.GetExecutableFile().SetFile( 1065 arg, FileSpec::Style::native); 1066 m_process_launch_info.GetArguments().AppendArgument(arg); 1067 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg %d: \"%s\"", 1068 __FUNCTION__, actual_arg_index, arg.c_str()); 1069 ++actual_arg_index; 1070 } 1071 } 1072 } 1073 } 1074 } 1075 } 1076 } 1077 1078 if (success) { 1079 m_process_launch_error = LaunchProcess(); 1080 if (m_process_launch_error.Success()) 1081 return SendOKResponse(); 1082 LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error); 1083 } 1084 return SendErrorResponse(8); 1085 } 1086 1087 GDBRemoteCommunication::PacketResult 1088 GDBRemoteCommunicationServerCommon::Handle_qEcho( 1089 StringExtractorGDBRemote &packet) { 1090 // Just echo back the exact same packet for qEcho... 1091 return SendPacketNoLock(packet.GetStringRef()); 1092 } 1093 1094 GDBRemoteCommunication::PacketResult 1095 GDBRemoteCommunicationServerCommon::Handle_qModuleInfo( 1096 StringExtractorGDBRemote &packet) { 1097 packet.SetFilePos(::strlen("qModuleInfo:")); 1098 1099 std::string module_path; 1100 packet.GetHexByteStringTerminatedBy(module_path, ';'); 1101 if (module_path.empty()) 1102 return SendErrorResponse(1); 1103 1104 if (packet.GetChar() != ';') 1105 return SendErrorResponse(2); 1106 1107 std::string triple; 1108 packet.GetHexByteString(triple); 1109 1110 ModuleSpec matched_module_spec = GetModuleInfo(module_path, triple); 1111 if (!matched_module_spec.GetFileSpec()) 1112 return SendErrorResponse(3); 1113 1114 const auto file_offset = matched_module_spec.GetObjectOffset(); 1115 const auto file_size = matched_module_spec.GetObjectSize(); 1116 const auto uuid_str = matched_module_spec.GetUUID().GetAsString(""); 1117 1118 StreamGDBRemote response; 1119 1120 if (uuid_str.empty()) { 1121 auto Result = llvm::sys::fs::md5_contents( 1122 matched_module_spec.GetFileSpec().GetPath()); 1123 if (!Result) 1124 return SendErrorResponse(5); 1125 response.PutCString("md5:"); 1126 response.PutStringAsRawHex8(Result->digest()); 1127 } else { 1128 response.PutCString("uuid:"); 1129 response.PutStringAsRawHex8(uuid_str); 1130 } 1131 response.PutChar(';'); 1132 1133 const auto &module_arch = matched_module_spec.GetArchitecture(); 1134 response.PutCString("triple:"); 1135 response.PutStringAsRawHex8(module_arch.GetTriple().getTriple()); 1136 response.PutChar(';'); 1137 1138 response.PutCString("file_path:"); 1139 response.PutStringAsRawHex8( 1140 matched_module_spec.GetFileSpec().GetPath().c_str()); 1141 response.PutChar(';'); 1142 response.PutCString("file_offset:"); 1143 response.PutHex64(file_offset); 1144 response.PutChar(';'); 1145 response.PutCString("file_size:"); 1146 response.PutHex64(file_size); 1147 response.PutChar(';'); 1148 1149 return SendPacketNoLock(response.GetString()); 1150 } 1151 1152 GDBRemoteCommunication::PacketResult 1153 GDBRemoteCommunicationServerCommon::Handle_jModulesInfo( 1154 StringExtractorGDBRemote &packet) { 1155 namespace json = llvm::json; 1156 1157 packet.SetFilePos(::strlen("jModulesInfo:")); 1158 1159 StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(packet.Peek()); 1160 if (!object_sp) 1161 return SendErrorResponse(1); 1162 1163 StructuredData::Array *packet_array = object_sp->GetAsArray(); 1164 if (!packet_array) 1165 return SendErrorResponse(2); 1166 1167 json::Array response_array; 1168 for (size_t i = 0; i < packet_array->GetSize(); ++i) { 1169 StructuredData::Dictionary *query = 1170 packet_array->GetItemAtIndex(i)->GetAsDictionary(); 1171 if (!query) 1172 continue; 1173 llvm::StringRef file, triple; 1174 if (!query->GetValueForKeyAsString("file", file) || 1175 !query->GetValueForKeyAsString("triple", triple)) 1176 continue; 1177 1178 ModuleSpec matched_module_spec = GetModuleInfo(file, triple); 1179 if (!matched_module_spec.GetFileSpec()) 1180 continue; 1181 1182 const auto file_offset = matched_module_spec.GetObjectOffset(); 1183 const auto file_size = matched_module_spec.GetObjectSize(); 1184 const auto uuid_str = matched_module_spec.GetUUID().GetAsString(""); 1185 if (uuid_str.empty()) 1186 continue; 1187 const auto triple_str = 1188 matched_module_spec.GetArchitecture().GetTriple().getTriple(); 1189 const auto file_path = matched_module_spec.GetFileSpec().GetPath(); 1190 1191 json::Object response{{"uuid", uuid_str}, 1192 {"triple", triple_str}, 1193 {"file_path", file_path}, 1194 {"file_offset", static_cast<int64_t>(file_offset)}, 1195 {"file_size", static_cast<int64_t>(file_size)}}; 1196 response_array.push_back(std::move(response)); 1197 } 1198 1199 StreamString response; 1200 response.AsRawOstream() << std::move(response_array); 1201 StreamGDBRemote escaped_response; 1202 escaped_response.PutEscapedBytes(response.GetString().data(), 1203 response.GetSize()); 1204 return SendPacketNoLock(escaped_response.GetString()); 1205 } 1206 1207 void GDBRemoteCommunicationServerCommon::CreateProcessInfoResponse( 1208 const ProcessInstanceInfo &proc_info, StreamString &response) { 1209 response.Printf( 1210 "pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;", 1211 proc_info.GetProcessID(), proc_info.GetParentProcessID(), 1212 proc_info.GetUserID(), proc_info.GetGroupID(), 1213 proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID()); 1214 response.PutCString("name:"); 1215 response.PutStringAsRawHex8(proc_info.GetExecutableFile().GetPath().c_str()); 1216 1217 response.PutChar(';'); 1218 response.PutCString("args:"); 1219 response.PutStringAsRawHex8(proc_info.GetArg0()); 1220 for (auto &arg : proc_info.GetArguments()) { 1221 response.PutChar('-'); 1222 response.PutStringAsRawHex8(arg.ref()); 1223 } 1224 1225 response.PutChar(';'); 1226 const ArchSpec &proc_arch = proc_info.GetArchitecture(); 1227 if (proc_arch.IsValid()) { 1228 const llvm::Triple &proc_triple = proc_arch.GetTriple(); 1229 response.PutCString("triple:"); 1230 response.PutStringAsRawHex8(proc_triple.getTriple()); 1231 response.PutChar(';'); 1232 } 1233 } 1234 1235 void GDBRemoteCommunicationServerCommon:: 1236 CreateProcessInfoResponse_DebugServerStyle( 1237 const ProcessInstanceInfo &proc_info, StreamString &response) { 1238 response.Printf("pid:%" PRIx64 ";parent-pid:%" PRIx64 1239 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;", 1240 proc_info.GetProcessID(), proc_info.GetParentProcessID(), 1241 proc_info.GetUserID(), proc_info.GetGroupID(), 1242 proc_info.GetEffectiveUserID(), 1243 proc_info.GetEffectiveGroupID()); 1244 1245 const ArchSpec &proc_arch = proc_info.GetArchitecture(); 1246 if (proc_arch.IsValid()) { 1247 const llvm::Triple &proc_triple = proc_arch.GetTriple(); 1248 #if defined(__APPLE__) 1249 // We'll send cputype/cpusubtype. 1250 const uint32_t cpu_type = proc_arch.GetMachOCPUType(); 1251 if (cpu_type != 0) 1252 response.Printf("cputype:%" PRIx32 ";", cpu_type); 1253 1254 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType(); 1255 if (cpu_subtype != 0) 1256 response.Printf("cpusubtype:%" PRIx32 ";", cpu_subtype); 1257 1258 const std::string vendor = proc_triple.getVendorName().str(); 1259 if (!vendor.empty()) 1260 response.Printf("vendor:%s;", vendor.c_str()); 1261 #else 1262 // We'll send the triple. 1263 response.PutCString("triple:"); 1264 response.PutStringAsRawHex8(proc_triple.getTriple()); 1265 response.PutChar(';'); 1266 #endif 1267 std::string ostype = std::string(proc_triple.getOSName()); 1268 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64. 1269 if (proc_triple.getVendor() == llvm::Triple::Apple) { 1270 switch (proc_triple.getArch()) { 1271 case llvm::Triple::arm: 1272 case llvm::Triple::thumb: 1273 case llvm::Triple::aarch64: 1274 case llvm::Triple::aarch64_32: 1275 ostype = "ios"; 1276 break; 1277 default: 1278 // No change. 1279 break; 1280 } 1281 } 1282 response.Printf("ostype:%s;", ostype.c_str()); 1283 1284 switch (proc_arch.GetByteOrder()) { 1285 case lldb::eByteOrderLittle: 1286 response.PutCString("endian:little;"); 1287 break; 1288 case lldb::eByteOrderBig: 1289 response.PutCString("endian:big;"); 1290 break; 1291 case lldb::eByteOrderPDP: 1292 response.PutCString("endian:pdp;"); 1293 break; 1294 default: 1295 // Nothing. 1296 break; 1297 } 1298 // In case of MIPS64, pointer size is depend on ELF ABI For N32 the pointer 1299 // size is 4 and for N64 it is 8 1300 std::string abi = proc_arch.GetTargetABI(); 1301 if (!abi.empty()) 1302 response.Printf("elf_abi:%s;", abi.c_str()); 1303 response.Printf("ptrsize:%d;", proc_arch.GetAddressByteSize()); 1304 } 1305 } 1306 1307 FileSpec GDBRemoteCommunicationServerCommon::FindModuleFile( 1308 const std::string &module_path, const ArchSpec &arch) { 1309 #ifdef __ANDROID__ 1310 return HostInfoAndroid::ResolveLibraryPath(module_path, arch); 1311 #else 1312 FileSpec file_spec(module_path); 1313 FileSystem::Instance().Resolve(file_spec); 1314 return file_spec; 1315 #endif 1316 } 1317 1318 ModuleSpec 1319 GDBRemoteCommunicationServerCommon::GetModuleInfo(llvm::StringRef module_path, 1320 llvm::StringRef triple) { 1321 ArchSpec arch(triple); 1322 1323 FileSpec req_module_path_spec(module_path); 1324 FileSystem::Instance().Resolve(req_module_path_spec); 1325 1326 const FileSpec module_path_spec = 1327 FindModuleFile(req_module_path_spec.GetPath(), arch); 1328 1329 lldb::offset_t file_offset = 0; 1330 lldb::offset_t file_size = 0; 1331 #ifdef __ANDROID__ 1332 // In Android API level 23 and above, dynamic loader is able to load .so file 1333 // directly from zip file. In that case, module_path will be 1334 // "zip_path!/so_path". Resolve the zip file path, .so file offset and size. 1335 ZipFileResolver::FileKind file_kind = ZipFileResolver::eFileKindInvalid; 1336 std::string file_path; 1337 if (!ZipFileResolver::ResolveSharedLibraryPath( 1338 module_path_spec, file_kind, file_path, file_offset, file_size)) { 1339 return ModuleSpec(); 1340 } 1341 lldbassert(file_kind != ZipFileResolver::eFileKindInvalid); 1342 // For zip .so file, this file_path will contain only the actual zip file 1343 // path for the object file processing. Otherwise it is the same as 1344 // module_path. 1345 const FileSpec actual_module_path_spec(file_path); 1346 #else 1347 // It is just module_path_spec reference for other platforms. 1348 const FileSpec &actual_module_path_spec = module_path_spec; 1349 #endif 1350 1351 const ModuleSpec module_spec(actual_module_path_spec, arch); 1352 1353 ModuleSpecList module_specs; 1354 if (!ObjectFile::GetModuleSpecifications(actual_module_path_spec, file_offset, 1355 file_size, module_specs)) 1356 return ModuleSpec(); 1357 1358 ModuleSpec matched_module_spec; 1359 if (!module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec)) 1360 return ModuleSpec(); 1361 1362 #ifdef __ANDROID__ 1363 if (file_kind == ZipFileResolver::eFileKindZip) { 1364 // For zip .so file, matched_module_spec contains only the actual zip file 1365 // path for the object file processing. Overwrite the matched_module_spec 1366 // file spec with the original module_path_spec to pass "zip_path!/so_path" 1367 // through to PlatformAndroid::DownloadModuleSlice. 1368 *matched_module_spec.GetFileSpecPtr() = module_path_spec; 1369 } 1370 #endif 1371 1372 return matched_module_spec; 1373 } 1374 1375 std::vector<std::string> GDBRemoteCommunicationServerCommon::HandleFeatures( 1376 const llvm::ArrayRef<llvm::StringRef> client_features) { 1377 // 128KBytes is a reasonable max packet size--debugger can always use less. 1378 constexpr uint32_t max_packet_size = 128 * 1024; 1379 1380 // Features common to platform server and llgs. 1381 return { 1382 llvm::formatv("PacketSize={0}", max_packet_size), 1383 "QStartNoAckMode+", 1384 "qEcho+", 1385 "native-signals+", 1386 }; 1387 } 1388