9 #include "lldb/Host/Config.h"
14 #include <netinet/in.h>
16 #include <sys/socket.h>
20 #if defined(__APPLE__)
21 #include <sys/sysctl.h>
24 #include <sys/types.h>
86 #include "llvm/ADT/ScopeExit.h"
87 #include "llvm/ADT/StringSwitch.h"
88 #include "llvm/Support/Threading.h"
89 #include "llvm/Support/raw_ostream.h"
91 #define DEBUGSERVER_BASENAME "debugserver"
106 auto file = FileSystem::Instance().Open(
107 FileSpec(path), File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate);
109 llvm::consumeError(file.takeError());
119 #define LLDB_PROPERTIES_processgdbremote
120 #include "ProcessGDBRemoteProperties.inc"
123 #define LLDB_PROPERTIES_processgdbremote
124 #include "ProcessGDBRemotePropertiesEnum.inc"
130 return ConstString(ProcessGDBRemote::GetPluginNameStatic());
134 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
135 m_collection_sp->Initialize(g_processgdbremote_properties);
138 ~PluginProperties()
override =
default;
140 uint64_t GetPacketTimeout() {
141 const uint32_t idx = ePropertyPacketTimeout;
142 return m_collection_sp->GetPropertyAtIndexAsUInt64(
143 nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
146 bool SetPacketTimeout(uint64_t timeout) {
147 const uint32_t idx = ePropertyPacketTimeout;
148 return m_collection_sp->SetPropertyAtIndexAsUInt64(
nullptr, idx, timeout);
151 FileSpec GetTargetDefinitionFile()
const {
152 const uint32_t idx = ePropertyTargetDefinitionFile;
153 return m_collection_sp->GetPropertyAtIndexAsFileSpec(
nullptr, idx);
156 bool GetUseSVR4()
const {
157 const uint32_t idx = ePropertyUseSVR4;
158 return m_collection_sp->GetPropertyAtIndexAsBoolean(
160 g_processgdbremote_properties[idx].default_uint_value != 0);
163 bool GetUseGPacketForReading()
const {
164 const uint32_t idx = ePropertyUseGPacketForReading;
165 return m_collection_sp->GetPropertyAtIndexAsBoolean(
nullptr, idx,
true);
169 static PluginProperties &GetGlobalPluginProperties() {
170 static PluginProperties g_settings;
180 #if defined(__APPLE__)
181 #define LOW_PORT (IPPORT_RESERVED)
182 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
184 #define LOW_PORT (1024u)
185 #define HIGH_PORT (49151u)
188 llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() {
189 return "GDB Remote protocol based debugging plug-in.";
192 void ProcessGDBRemote::Terminate() {
193 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
197 ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
198 ListenerSP listener_sp,
201 lldb::ProcessSP process_sp;
202 if (crash_file_path ==
nullptr)
203 process_sp = std::make_shared<ProcessGDBRemote>(target_sp, listener_sp);
207 std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() {
208 return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
211 ArchSpec ProcessGDBRemote::GetSystemArchitecture() {
212 return m_gdb_comm.GetHostArchitecture();
215 bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
216 bool plugin_specified_by_name) {
217 if (plugin_specified_by_name)
221 Module *exe_module = target_sp->GetExecutableModulePointer();
225 switch (exe_objfile->
GetType()) {
226 case ObjectFile::eTypeInvalid:
227 case ObjectFile::eTypeCoreFile:
228 case ObjectFile::eTypeDebugInfo:
229 case ObjectFile::eTypeObjectFile:
230 case ObjectFile::eTypeSharedLibrary:
231 case ObjectFile::eTypeStubLibrary:
232 case ObjectFile::eTypeJIT:
234 case ObjectFile::eTypeExecutable:
235 case ObjectFile::eTypeDynamicLinker:
236 case ObjectFile::eTypeUnknown:
239 return FileSystem::Instance().Exists(exe_module->
GetFileSpec());
247 ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
248 ListenerSP listener_sp)
249 :
Process(target_sp, listener_sp),
251 m_async_broadcaster(nullptr,
"lldb.process.gdb-remote.async-broadcaster"),
253 Listener::MakeListener(
"lldb.process.gdb-remote.async-listener")),
254 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
255 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
256 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
257 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
258 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
259 m_waiting_for_attach(false),
260 m_command_sp(), m_breakpoint_pc_offset(0),
262 m_erased_flash_ranges(), m_vfork_in_progress(false) {
264 "async thread should exit");
266 "async thread continue");
268 "async thread did exit");
284 "ProcessGDBRemote::%s failed to listen for "
285 "m_async_broadcaster events",
289 const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit;
291 &
m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
293 "ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
297 const uint64_t timeout_seconds =
298 GetGlobalPluginProperties().GetPacketTimeout();
299 if (timeout_seconds > 0)
303 GetGlobalPluginProperties().GetUseGPacketForReading();
325 const FileSpec &target_definition_fspec) {
331 if (module_object_sp) {
334 "gdb-server-target-definition",
error));
336 if (target_definition_sp) {
338 target_definition_sp->GetValueForKey(
"host-info"));
340 if (
auto host_info_dict = target_object->GetAsDictionary()) {
342 host_info_dict->GetValueForKey(
"triple");
343 if (
auto triple_string_value = triple_value->GetAsString()) {
346 ArchSpec host_arch(triple_string.c_str());
355 target_definition_sp->GetValueForKey(
"breakpoint-pc-offset");
356 if (breakpoint_pc_offset_value) {
357 if (
auto breakpoint_pc_int_value =
358 breakpoint_pc_offset_value->GetAsInteger())
363 *target_definition_sp,
GetTarget().GetArchitecture()) > 0) {
372 const llvm::StringRef &comma_separated_register_numbers,
373 std::vector<uint32_t> &
regnums,
int base) {
375 for (llvm::StringRef x : llvm::split(comma_separated_register_numbers,
',')) {
377 if (llvm::to_integer(x, reg, base))
393 if (host_packet_timeout > std::chrono::seconds(0)) {
394 GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
405 GetGlobalPluginProperties().GetTargetDefinitionFile();
411 if (target_definition_fspec) {
417 target_definition_fspec.
GetPath() +
428 if (remote_process_arch.
IsValid())
429 arch_to_use = remote_process_arch;
431 arch_to_use = remote_host_arch;
434 arch_to_use = target_arch;
440 std::vector<DynamicRegisterInfo::Register> registers;
445 const int packet_len =
446 ::snprintf(packet,
sizeof(packet),
"qRegisterInfo%x", reg_num);
447 assert(packet_len < (
int)
sizeof(packet));
454 llvm::StringRef name;
455 llvm::StringRef value;
459 if (name.equals(
"name")) {
461 }
else if (name.equals(
"alt-name")) {
463 }
else if (name.equals(
"bitsize")) {
464 if (!value.getAsInteger(0, reg_info.
byte_size))
466 }
else if (name.equals(
"offset")) {
468 }
else if (name.equals(
"encoding")) {
472 }
else if (name.equals(
"format")) {
476 llvm::StringSwitch<Format>(value)
491 }
else if (name.equals(
"set")) {
493 }
else if (name.equals(
"gcc") || name.equals(
"ehframe")) {
495 }
else if (name.equals(
"dwarf")) {
497 }
else if (name.equals(
"generic")) {
499 }
else if (name.equals(
"container-regs")) {
501 }
else if (name.equals(
"invalidate-regs")) {
507 registers.push_back(reg_info);
516 if (registers.empty())
531 bool wait_for_launch) {
576 UUID standalone_uuid;
578 bool standalone_value_is_offset;
580 standalone_uuid, standalone_value, standalone_value_is_offset)) {
583 if (standalone_uuid.
IsValid()) {
585 module_spec.
GetUUID() = standalone_uuid;
590 nullptr,
nullptr,
nullptr);
600 module_sp = std::make_shared<Module>(module_spec);
607 !standalone_value_is_offset) {
609 snprintf(namebuf,
sizeof(namebuf),
"mem-image-0x%" PRIx64,
616 if (module_sp.get()) {
619 bool changed =
false;
620 if (module_sp->GetObjectFile()) {
623 log->
Printf(
"Loading binary UUID %s at %s 0x%" PRIx64,
625 standalone_value_is_offset ?
"offset" :
"address",
627 module_sp->SetLoadAddress(target, standalone_value,
628 standalone_value_is_offset, changed);
633 log->
Printf(
"Loading binary UUID %s at file address",
635 const bool value_is_slide =
true;
636 module_sp->SetLoadAddress(target, 0, value_is_slide, changed);
641 log->
Printf(
"Loading binary UUID %s from memory",
643 const bool value_is_slide =
true;
644 module_sp->SetLoadAddress(target, 0, value_is_slide, changed);
648 added_module.
Append(module_sp,
false);
652 log->
Printf(
"Unable to find binary with UUID %s and load it at "
655 standalone_value_is_offset ?
"offset" :
"address",
665 error.SetErrorStringWithFormat(
666 "Process %" PRIu64
" was reported after connecting to "
667 "'%s', but state was not stopped: %s",
670 error.SetErrorStringWithFormat(
"Process %" PRIu64
671 " was reported after connecting to '%s', "
672 "but no stop reply packet was received",
673 pid, remote_url.str().c_str());
677 "ProcessGDBRemote::%s pid %" PRIu64
678 ": normalizing target architecture initial triple: %s "
679 "(GetTarget().GetArchitecture().IsValid() %s, "
680 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
681 __FUNCTION__,
GetID(),
682 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
697 "ProcessGDBRemote::%s pid %" PRIu64
698 ": normalized target architecture triple: %s",
699 __FUNCTION__,
GetID(),
700 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
717 LLDB_LOGF(log,
"ProcessGDBRemote::%s() entered", __FUNCTION__);
743 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
745 "ProcessGDBRemote::%s provided with STDIO paths via "
746 "launch_info: stdin=%s, stdout=%s, stderr=%s",
748 stdin_file_spec ? stdin_file_spec.GetCString() :
"<null>",
749 stdout_file_spec ? stdout_file_spec.GetCString() :
"<null>",
750 stderr_file_spec ? stderr_file_spec.GetCString() :
"<null>");
753 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
757 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
758 if (stdin_file_spec || disable_stdio) {
773 if (
error.Success()) {
775 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
777 PlatformSP platform_sp(
GetTarget().GetPlatform());
780 if (!stdin_file_spec)
782 FileSpec::Style::native);
783 if (!stdout_file_spec)
785 FileSpec::Style::native);
786 if (!stderr_file_spec)
788 FileSpec::Style::native);
789 }
else if (platform_sp && platform_sp->IsHost()) {
794 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
798 if (!stdin_file_spec)
799 stdin_file_spec = secondary_name;
801 if (!stdout_file_spec)
802 stdout_file_spec = secondary_name;
804 if (!stderr_file_spec)
805 stderr_file_spec = secondary_name;
809 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
810 "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
813 stdin_file_spec ? stdin_file_spec.GetCString() :
"<null>",
814 stdout_file_spec ? stdout_file_spec.GetCString() :
"<null>",
815 stderr_file_spec ? stderr_file_spec.GetCString() :
"<null>");
819 "ProcessGDBRemote::%s final STDIO paths after all "
820 "adjustments: stdin=%s, stdout=%s, stderr=%s",
822 stdin_file_spec ? stdin_file_spec.GetCString() :
"<null>",
823 stdout_file_spec ? stdout_file_spec.GetCString() :
"<null>",
824 stderr_file_spec ? stderr_file_spec.GetCString() :
"<null>");
828 if (stdout_file_spec)
830 if (stderr_file_spec)
837 GetTarget().GetArchitecture().GetArchitectureName());
840 if (launch_event_data !=
nullptr && *launch_event_data !=
'\0')
853 std::chrono::seconds(10));
856 if (arg_packet_err == 0) {
861 error.SetErrorString(error_str.c_str());
864 error.SetErrorStringWithFormat(
"'A' packet returned an error: %i",
870 LLDB_LOGF(log,
"failed to connect to debugserver: %s",
892 if (!disable_stdio) {
898 LLDB_LOGF(log,
"failed to connect to debugserver: %s",
error.AsCString());
908 if (!connect_url.empty()) {
909 LLDB_LOGF(log,
"ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
910 connect_url.str().c_str());
911 std::unique_ptr<ConnectionFileDescriptor> conn_up(
914 const uint32_t max_retry_count = 50;
924 if (retry_count >= max_retry_count)
927 std::this_thread::sleep_for(std::chrono::milliseconds(100));
934 error.SetErrorString(
"not connected to remote gdb server");
945 error.SetErrorString(
"not connected to remote gdb server");
958 auto handle_cmds = [&] (
const Args &args) ->
void {
962 entry.c_str(), response);
968 handle_cmds(platform_sp->GetExtraStartupCommands());
985 if (remote_process_arch.
IsValid()) {
986 process_arch = remote_process_arch;
987 LLDB_LOG(log,
"gdb-remote had process architecture, using {0} {1}",
993 "gdb-remote did not have process architecture, using gdb-remote "
994 "host architecture {0} {1}",
1000 lldb::addr_t address_mask = ~((1ULL << addresssable_bits) - 1);
1008 LLDB_LOG(log,
"analyzing target arch, currently {0} {1}",
1020 if ((process_arch.
GetMachine() == llvm::Triple::arm ||
1021 process_arch.
GetMachine() == llvm::Triple::thumb) &&
1022 process_arch.
GetTriple().getVendor() == llvm::Triple::Apple) {
1025 "remote process is ARM/Apple, "
1026 "setting target arch to {0} {1}",
1031 const llvm::Triple &remote_triple = process_arch.
GetTriple();
1032 llvm::Triple new_target_triple = target_arch.
GetTriple();
1033 if (new_target_triple.getVendorName().size() == 0) {
1034 new_target_triple.setVendor(remote_triple.getVendor());
1036 if (new_target_triple.getOSName().size() == 0) {
1037 new_target_triple.setOS(remote_triple.getOS());
1039 if (new_target_triple.getEnvironmentName().size() == 0)
1040 new_target_triple.setEnvironment(remote_triple.getEnvironment());
1043 ArchSpec new_target_arch = target_arch;
1044 new_target_arch.
SetTriple(new_target_triple);
1050 "final target arch after adjustments for remote architecture: "
1075 if (platform_sp && platform_sp->IsConnected())
1092 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1093 offsets->offsets.size();
1097 bool changed =
false;
1098 module_sp->SetLoadAddress(
GetTarget(), offsets->offsets[0],
1102 list.Append(module_sp);
1117 LLDB_LOGF(log,
"ProcessGDBRemote::%s()", __FUNCTION__);
1123 if (
error.Success()) {
1127 const int packet_len =
1128 ::snprintf(packet,
sizeof(packet),
"vAttach;%" PRIx64, attach_pid);
1145 if (process_name && process_name[0]) {
1147 if (
error.Success()) {
1190 llvm::Expected<std::string>
1195 llvm::Expected<std::vector<uint8_t>>
1207 process_arch.
Clear();
1224 LLDB_LOGF(log,
"ProcessGDBRemote::Resume()");
1226 ListenerSP listener_sp(
1228 if (listener_sp->StartListeningForEvents(
1230 listener_sp->StartListeningForEvents(
1237 bool continue_packet_error =
false;
1249 for (tid_collection::const_iterator
1252 t_pos != t_end; ++t_pos)
1253 continue_packet.
Printf(
";c:%4.4" PRIx64, *t_pos);
1255 continue_packet_error =
true;
1260 for (tid_sig_collection::const_iterator
1263 s_pos != s_end; ++s_pos)
1264 continue_packet.
Printf(
";C%2.2x:%4.4" PRIx64, s_pos->second,
1267 continue_packet_error =
true;
1272 for (tid_collection::const_iterator
1275 t_pos != t_end; ++t_pos)
1276 continue_packet.
Printf(
";s:%4.4" PRIx64, *t_pos);
1278 continue_packet_error =
true;
1283 for (tid_sig_collection::const_iterator
1286 s_pos != s_end; ++s_pos)
1287 continue_packet.
Printf(
";S%2.2x:%4.4" PRIx64, s_pos->second,
1290 continue_packet_error =
true;
1293 if (continue_packet_error)
1294 continue_packet.
Clear();
1297 continue_packet_error =
true;
1299 if (continue_packet_error) {
1307 if (num_continue_c_tids > 0) {
1308 if (num_continue_c_tids == num_threads) {
1312 continue_packet_error =
false;
1313 }
else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1314 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1318 continue_packet_error =
false;
1322 if (continue_packet_error && num_continue_C_tids > 0) {
1323 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1324 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1325 num_continue_S_tids == 0) {
1328 if (num_continue_C_tids > 1) {
1333 if (num_continue_C_tids > 1) {
1334 continue_packet_error =
false;
1337 continue_packet_error =
true;
1340 if (!continue_packet_error)
1344 continue_packet_error =
false;
1347 if (!continue_packet_error) {
1349 continue_packet.
Printf(
"C%2.2x", continue_signo);
1354 if (continue_packet_error && num_continue_s_tids > 0) {
1355 if (num_continue_s_tids == num_threads) {
1361 continue_packet_error =
false;
1362 }
else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1363 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1367 continue_packet_error =
false;
1371 if (!continue_packet_error && num_continue_S_tids > 0) {
1372 if (num_continue_S_tids == num_threads) {
1375 continue_packet_error =
false;
1376 if (num_continue_S_tids > 1) {
1377 for (
size_t i = 1; i < num_threads; ++i) {
1379 continue_packet_error =
true;
1382 if (!continue_packet_error) {
1385 continue_packet.
Printf(
"S%2.2x", step_signo);
1387 }
else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1388 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1392 continue_packet_error =
false;
1397 if (continue_packet_error) {
1398 error.SetErrorString(
"can't make continue packet for this resume");
1402 error.SetErrorString(
"Trying to resume but the async thread is dead.");
1403 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Trying to resume but the "
1404 "async thread is dead.");
1413 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1414 error.SetErrorString(
"Resume timed out.");
1415 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Resume timed out.");
1417 error.SetErrorString(
"Broadcast continue, but the async thread was "
1418 "killed before we got an ack back.");
1420 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1421 "async thread was killed before we got an ack back.");
1437 llvm::StringRef value) {
1443 auto pid_tid = thread_ids.
GetPidTid(pid);
1444 if (pid_tid && pid_tid->first == pid) {
1450 }
while (thread_ids.GetChar() ==
',');
1456 llvm::StringRef value) {
1458 for (llvm::StringRef x : llvm::split(value,
',')) {
1460 if (llvm::to_integer(x,
pc, 16))
1472 if (thread_infos && thread_infos->
GetSize() > 0) {
1499 const size_t thread_pcs_pos = stop_info_str.find(
";thread-pcs:");
1500 if (thread_pcs_pos != std::string::npos) {
1501 const size_t start = thread_pcs_pos + strlen(
";thread-pcs:");
1502 const size_t end = stop_info_str.find(
';', start);
1503 if (end != std::string::npos) {
1504 std::string value = stop_info_str.substr(start, end - start);
1509 const size_t threads_pos = stop_info_str.find(
";threads:");
1510 if (threads_pos != std::string::npos) {
1511 const size_t start = threads_pos + strlen(
";threads:");
1512 const size_t end = stop_info_str.find(
';', start);
1513 if (end != std::string::npos) {
1514 std::string value = stop_info_str.substr(start, end - start);
1522 bool sequence_mutex_unavailable =
false;
1524 if (sequence_mutex_unavailable) {
1539 if (num_thread_ids == 0) {
1545 ThreadList old_thread_list_copy(old_thread_list);
1546 if (num_thread_ids > 0) {
1547 for (
size_t i = 0; i < num_thread_ids; ++i) {
1552 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1553 LLDB_LOGV(log,
"Making new thread: {0} for thread ID: {1:x}.",
1554 thread_sp.get(), thread_sp->GetID());
1556 LLDB_LOGV(log,
"Found old thread: {0} for thread ID: {1:x}.",
1557 thread_sp.get(), thread_sp->GetID());
1567 size_t old_num_thread_ids = old_thread_list_copy.
GetSize(
false);
1568 for (
size_t i = 0; i < old_num_thread_ids; i++) {
1570 if (old_thread_sp) {
1571 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1584 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1586 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1599 if (thread_infos_sp) {
1603 const size_t n = thread_infos->
GetSize();
1604 for (
size_t i = 0; i < n; ++i) {
1610 if (tid == thread->
GetID())
1650 const std::vector<addr_t> &exc_data,
addr_t thread_dispatch_qaddr,
1651 bool queue_vars_valid,
1653 LazyBool associated_with_dispatch_queue,
addr_t dispatch_queue_t,
1662 std::lock_guard<std::recursive_mutex> guard(
1668 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1678 gdb_reg_ctx_sp->InvalidateIfNeeded(
true);
1685 for (
const auto &pair : expedited_register_map) {
1689 reg_value_extractor.
GetHexBytes(buffer_sp->GetData(),
'\xcc');
1691 gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1709 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1714 if (queue_vars_valid)
1715 gdb_thread->
SetQueueInfo(std::move(queue_name), queue_kind,
1716 queue_serial, dispatch_queue_t,
1717 associated_with_dispatch_queue);
1722 associated_with_dispatch_queue);
1728 if (!thread_sp->StopInfoIsUpToDate()) {
1729 thread_sp->SetStopInfo(StopInfoSP());
1732 if (ThreadSP memory_thread_sp =
1734 thread_sp = memory_thread_sp;
1736 if (exc_type != 0) {
1737 const size_t exc_data_size = exc_data.size();
1739 thread_sp->SetStopInfo(
1741 *thread_sp, exc_type, exc_data_size,
1742 exc_data_size >= 1 ? exc_data[0] : 0,
1743 exc_data_size >= 2 ? exc_data[1] : 0,
1744 exc_data_size >= 3 ? exc_data[2] : 0));
1746 bool handled =
false;
1747 bool did_exec =
false;
1748 if (!reason.empty()) {
1749 if (reason ==
"trace") {
1750 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1751 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1752 ->GetBreakpointSiteList()
1758 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1759 thread_sp->SetStopInfo(
1761 *thread_sp, bp_site_sp->GetID()));
1763 thread_sp->SetStopInfo(
1766 }
else if (reason ==
"breakpoint") {
1767 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1768 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1769 ->GetBreakpointSiteList()
1778 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1779 thread_sp->SetStopInfo(
1781 *thread_sp, bp_site_sp->GetID()));
1783 StopInfoSP invalid_stop_info_sp;
1784 thread_sp->SetStopInfo(invalid_stop_info_sp);
1787 }
else if (reason ==
"trap") {
1789 }
else if (reason ==
"watchpoint") {
1808 wp_sp->SetHardwareIndex(wp_index);
1809 watch_id = wp_sp->GetID();
1814 LLDB_LOGF(log,
"failed to find watchpoint");
1817 *thread_sp, watch_id, wp_hit_addr));
1819 }
else if (reason ==
"exception") {
1821 *thread_sp, description.c_str()));
1823 }
else if (reason ==
"exec") {
1825 thread_sp->SetStopInfo(
1828 }
else if (reason ==
"processor trace") {
1830 *thread_sp, description.c_str()));
1831 }
else if (reason ==
"fork") {
1838 *thread_sp, child_pid, child_tid));
1840 }
else if (reason ==
"vfork") {
1847 *thread_sp, child_pid, child_tid));
1849 }
else if (reason ==
"vforkdone") {
1850 thread_sp->SetStopInfo(
1854 }
else if (!signo) {
1855 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1856 lldb::BreakpointSiteSP bp_site_sp =
1857 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1865 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1866 thread_sp->SetStopInfo(
1868 *thread_sp, bp_site_sp->GetID()));
1873 if (!handled && signo && !did_exec) {
1878 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1880 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1881 ->GetBreakpointSiteList()
1890 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1892 thread_sp->GetRegisterContext()->SetPC(
pc);
1893 thread_sp->SetStopInfo(
1895 *thread_sp, bp_site_sp->GetID()));
1897 StopInfoSP invalid_stop_info_sp;
1898 thread_sp->SetStopInfo(invalid_stop_info_sp);
1906 thread_sp->SetStopInfo(
1910 *thread_sp, signo, description.c_str()));
1915 *thread_sp, signo, description.c_str()));
1918 if (!description.empty()) {
1919 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1921 const char *stop_info_desc = stop_info_sp->GetDescription();
1922 if (!stop_info_desc || !stop_info_desc[0])
1923 stop_info_sp->SetDescription(description.c_str());
1926 *thread_sp, description.c_str()));
1944 static ConstString g_key_dispatch_queue_t(
"dispatch_queue_t");
1945 static ConstString g_key_associated_with_dispatch_queue(
1946 "associated_with_dispatch_queue");
1949 static ConstString g_key_queue_serial_number(
"qserialnum");
1954 static ConstString g_key_description(
"description");
1965 std::vector<addr_t> exc_data;
1968 bool queue_vars_valid =
false;
1973 uint64_t queue_serial_number = 0;
1978 thread_dict->
ForEach([
this, &tid, &expedited_register_map, &thread_name,
1979 &signo, &reason, &description, &exc_type, &exc_data,
1980 &thread_dispatch_qaddr, &queue_vars_valid,
1981 &associated_with_dispatch_queue, &dispatch_queue_t,
1982 &queue_name, &queue_kind, &queue_serial_number](
1985 if (key == g_key_tid) {
1988 }
else if (key == g_key_metype) {
1990 exc_type =
object->GetIntegerValue(0);
1991 }
else if (key == g_key_medata) {
2000 }
else if (key == g_key_name) {
2002 }
else if (key == g_key_qaddr) {
2004 }
else if (key == g_key_queue_name) {
2005 queue_vars_valid =
true;
2007 }
else if (key == g_key_queue_kind) {
2009 if (queue_kind_str ==
"serial") {
2010 queue_vars_valid =
true;
2012 }
else if (queue_kind_str ==
"concurrent") {
2013 queue_vars_valid =
true;
2016 }
else if (key == g_key_queue_serial_number) {
2017 queue_serial_number =
object->GetIntegerValue(0);
2018 if (queue_serial_number != 0)
2019 queue_vars_valid =
true;
2020 }
else if (key == g_key_dispatch_queue_t) {
2021 dispatch_queue_t =
object->GetIntegerValue(0);
2023 queue_vars_valid =
true;
2024 }
else if (key == g_key_associated_with_dispatch_queue) {
2025 queue_vars_valid =
true;
2026 bool associated =
object->GetBooleanValue();
2031 }
else if (key == g_key_reason) {
2033 }
else if (key == g_key_description) {
2035 }
else if (key == g_key_registers) {
2038 if (registers_dict) {
2043 if (llvm::to_integer(key.
AsCString(), reg))
2044 expedited_register_map[reg] =
2049 }
else if (key == g_key_memory) {
2055 if (mem_cache_dict) {
2058 "address", mem_cache_addr)) {
2059 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2060 llvm::StringRef str;
2061 if (mem_cache_dict->GetValueForKeyAsString(
"bytes", str)) {
2062 StringExtractor bytes(str);
2063 bytes.SetFilePos(0);
2065 const size_t byte_size = bytes.GetStringRef().size() / 2;
2066 WritableDataBufferSP data_buffer_sp(
2067 new DataBufferHeap(byte_size, 0));
2068 const size_t bytes_copied =
2069 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2070 if (bytes_copied == byte_size)
2071 m_memory_cache.AddL1CacheData(mem_cache_addr,
2081 }
else if (key == g_key_signal)
2086 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2087 reason, description, exc_type, exc_data,
2088 thread_dispatch_qaddr, queue_vars_valid,
2089 associated_with_dispatch_queue, dispatch_queue_t,
2090 queue_name, queue_kind, queue_serial_number);
2094 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2096 const char stop_type = stop_packet.
GetChar();
2097 switch (stop_type) {
2105 const uint32_t stop_id = GetStopID();
2111 BuildDynamicRegisterInfo(
true);
2116 const uint8_t signo = stop_packet.
GetHexU8();
2117 llvm::StringRef key;
2118 llvm::StringRef value;
2123 std::vector<addr_t> exc_data;
2125 bool queue_vars_valid =
2131 uint64_t queue_serial_number = 0;
2134 if (key.compare(
"metype") == 0) {
2136 value.getAsInteger(16, exc_type);
2137 }
else if (key.compare(
"medata") == 0) {
2140 value.getAsInteger(16, x);
2141 exc_data.push_back(x);
2142 }
else if (key.compare(
"thread") == 0) {
2145 auto pid_tid = thread_id.
GetPidTid(pid);
2147 stop_pid = pid_tid->first;
2148 tid = pid_tid->second;
2151 }
else if (key.compare(
"threads") == 0) {
2152 std::lock_guard<std::recursive_mutex> guard(
2153 m_thread_list_real.GetMutex());
2154 UpdateThreadIDsFromStopReplyThreadsValue(value);
2155 }
else if (key.compare(
"thread-pcs") == 0) {
2156 m_thread_pcs.clear();
2160 while (!value.empty()) {
2161 llvm::StringRef pc_str;
2162 std::tie(pc_str, value) = value.split(
',');
2163 if (pc_str.getAsInteger(16,
pc))
2165 m_thread_pcs.push_back(
pc);
2167 }
else if (key.compare(
"jstopinfo") == 0) {
2176 }
else if (key.compare(
"hexname") == 0) {
2181 }
else if (key.compare(
"name") == 0) {
2183 }
else if (key.compare(
"qaddr") == 0) {
2184 value.getAsInteger(16, thread_dispatch_qaddr);
2185 }
else if (key.compare(
"dispatch_queue_t") == 0) {
2186 queue_vars_valid =
true;
2187 value.getAsInteger(16, dispatch_queue_t);
2188 }
else if (key.compare(
"qname") == 0) {
2189 queue_vars_valid =
true;
2193 }
else if (key.compare(
"qkind") == 0) {
2194 queue_kind = llvm::StringSwitch<QueueKind>(value)
2199 }
else if (key.compare(
"qserialnum") == 0) {
2200 if (!value.getAsInteger(0, queue_serial_number))
2201 queue_vars_valid =
true;
2202 }
else if (key.compare(
"reason") == 0) {
2204 }
else if (key.compare(
"description") == 0) {
2208 }
else if (key.compare(
"memory") == 0) {
2222 llvm::StringRef addr_str, bytes_str;
2223 std::tie(addr_str, bytes_str) = value.split(
'=');
2224 if (!addr_str.empty() && !bytes_str.empty()) {
2226 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2229 WritableDataBufferSP data_buffer_sp(
2231 const size_t bytes_copied =
2233 if (bytes_copied == byte_size)
2234 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2237 }
else if (key.compare(
"watch") == 0 || key.compare(
"rwatch") == 0 ||
2238 key.compare(
"awatch") == 0) {
2241 value.getAsInteger(16, wp_addr);
2243 WatchpointSP wp_sp =
2244 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2248 wp_index = wp_sp->GetHardwareIndex();
2250 reason =
"watchpoint";
2252 ostr.
Printf(
"%" PRIu64
" %" PRIu32, wp_addr, wp_index);
2254 }
else if (key.compare(
"library") == 0) {
2255 auto error = LoadModules();
2260 }
else if (key.compare(
"fork") == 0 || key.compare(
"vfork") == 0) {
2266 LLDB_LOG(log,
"Invalid PID/TID to fork: {0}", value);
2272 ostr.
Printf(
"%" PRIu64
" %" PRIu64, pid_tid->first, pid_tid->second);
2274 }
else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2276 if (!key.getAsInteger(16, reg))
2277 expedited_register_map[reg] =
std::string(std::move(value));
2284 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2294 UpdateThreadIDList();
2296 if (!m_thread_ids.empty()) {
2297 tid = m_thread_ids.front();
2301 ThreadSP thread_sp = SetThreadStopInfo(
2302 tid, expedited_register_map, signo, thread_name, reason, description,
2303 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2304 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2305 queue_kind, queue_serial_number);
2321 void ProcessGDBRemote::RefreshStateAfterStop() {
2322 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2324 m_thread_ids.clear();
2325 m_thread_pcs.clear();
2331 if (m_thread_ids.empty()) {
2333 UpdateThreadIDList();
2338 UpdateThreadListIfNeeded();
2340 if (m_last_stop_packet)
2341 SetThreadStopInfo(*m_last_stop_packet);
2342 m_last_stop_packet.reset();
2346 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2352 m_thread_list_real.RefreshStateAfterStop();
2355 Status ProcessGDBRemote::DoHalt(
bool &caused_stop) {
2361 m_gdb_comm.Disconnect();
2363 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2367 Status ProcessGDBRemote::DoDetach(
bool keep_stopped) {
2370 LLDB_LOGF(log,
"ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2372 error = m_gdb_comm.Detach(keep_stopped);
2374 if (
error.Success())
2376 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2379 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2380 error.AsCString() ?
error.AsCString() :
"<unknown error>");
2383 if (!
error.Success())
2390 ResumePrivateStateThread();
2399 LLDB_LOGF(log,
"ProcessGDBRemote::DoDestroy()");
2402 int exit_status = SIGABRT;
2405 if (m_gdb_comm.IsConnected()) {
2409 std::chrono::seconds(3));
2411 if (m_gdb_comm.SendPacketAndWaitForResponse(
"k", response,
2412 GetInterruptTimeout()) ==
2413 GDBRemoteCommunication::PacketResult::Success) {
2414 char packet_cmd = response.
GetChar(0);
2416 if (packet_cmd ==
'W' || packet_cmd ==
'X') {
2417 #if defined(__APPLE__)
2428 PlatformSP platform_sp(GetTarget().GetPlatform());
2429 if (platform_sp && platform_sp->IsHost()) {
2432 reap_pid = waitpid(GetID(), &status, WNOHANG);
2433 LLDB_LOGF(log,
"Reaped pid: %d, status: %d.\n", reap_pid, status);
2436 SetLastStopPacket(response);
2437 ClearThreadIDList();
2441 "ProcessGDBRemote::DoDestroy - got unexpected response "
2444 exit_string.assign(
"got unexpected response to k packet: ");
2448 LLDB_LOGF(log,
"ProcessGDBRemote::DoDestroy - failed to send k packet");
2449 exit_string.assign(
"failed to send the k packet");
2453 "ProcessGDBRemote::DoDestroy - killed or interrupted while "
2455 exit_string.assign(
"killed or interrupted while attaching.");
2461 exit_string.assign(
"destroying when not connected to debugserver");
2464 SetExitStatus(exit_status, exit_string.c_str());
2467 KillDebugserverProcess();
2471 void ProcessGDBRemote::SetLastStopPacket(
2473 const bool did_exec =
2474 response.
GetStringRef().find(
";reason:exec;") != std::string::npos;
2477 LLDB_LOGF(log,
"ProcessGDBRemote::SetLastStopPacket () - detected exec");
2479 m_thread_list_real.Clear();
2480 m_thread_list.Clear();
2481 BuildDynamicRegisterInfo(
true);
2482 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2485 m_last_stop_packet = response;
2488 void ProcessGDBRemote::SetUnixSignals(
const UnixSignalsSP &signals_sp) {
2494 bool ProcessGDBRemote::IsAlive() {
2498 addr_t ProcessGDBRemote::GetImageInfoAddress() {
2504 llvm::Expected<LoadedModuleInfoList>
list = GetLoadedModuleList();
2509 addr =
list->m_link_map;
2516 void ProcessGDBRemote::WillPublicStop() {
2522 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2524 if (m_jthreadsinfo_sp) {
2529 const size_t n = thread_infos->
GetSize();
2530 for (
size_t i = 0; i < n; ++i) {
2534 SetThreadStopInfo(thread_dict);
2541 size_t ProcessGDBRemote::DoReadMemory(
addr_t addr,
void *buf,
size_t size,
2544 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2546 size_t max_memory_size =
2547 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2548 if (size > max_memory_size) {
2552 size = max_memory_size;
2557 packet_len = ::snprintf(packet,
sizeof(packet),
"%c%" PRIx64
",%" PRIx64,
2558 binary_memory_read ?
'x' :
'm', (uint64_t)addr,
2560 assert(packet_len + 1 < (
int)
sizeof(packet));
2563 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2564 GetInterruptTimeout()) ==
2565 GDBRemoteCommunication::PacketResult::Success) {
2568 if (binary_memory_read) {
2574 if (data_received_size > size) {
2577 data_received_size = size;
2579 memcpy(buf, response.
GetStringRef().data(), data_received_size);
2580 return data_received_size;
2583 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size),
'\xdd');
2586 error.SetErrorStringWithFormat(
"memory read failed for 0x%" PRIx64, addr);
2588 error.SetErrorStringWithFormat(
2589 "GDB server does not support reading memory");
2591 error.SetErrorStringWithFormat(
2592 "unexpected response to GDB server memory read packet '%s': '%s'",
2595 error.SetErrorStringWithFormat(
"failed to send packet: '%s'", packet);
2600 bool ProcessGDBRemote::SupportsMemoryTagging() {
2601 return m_gdb_comm.GetMemoryTaggingSupported();
2604 llvm::Expected<std::vector<uint8_t>>
2609 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2611 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2612 "Error reading memory tags from remote");
2616 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2617 std::vector<uint8_t> got;
2618 got.reserve(tag_data.size());
2619 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2625 const std::vector<uint8_t> &tags) {
2628 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2632 std::vector<ObjectFile::LoadableData> entries) {
2637 std::begin(entries), std::end(entries),
2641 m_allow_flash_writes =
true;
2643 if (
error.Success())
2644 error = FlashDone();
2651 m_allow_flash_writes =
false;
2656 auto size = m_erased_flash_ranges.GetSize();
2657 for (
size_t i = 0; i < size; ++i)
2658 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2667 status = GetMemoryRegionInfo(addr, region);
2676 status.
SetErrorString(
"Unable to erase flash in multiple regions");
2681 if (blocksize == 0) {
2682 status.
SetErrorString(
"Unable to erase flash because blocksize is 0");
2688 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2689 size += (addr - block_start_addr);
2690 if ((size % blocksize) != 0)
2691 size += (blocksize - size % blocksize);
2695 if (HasErased(range))
2701 if (!m_erased_flash_ranges.IsEmpty()) {
2705 const auto &last_range = *m_erased_flash_ranges.Back();
2707 auto overlap = last_range.GetRangeEnd() - range.
GetRangeBase();
2720 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.
GetString(), response,
2721 GetInterruptTimeout()) ==
2722 GDBRemoteCommunication::PacketResult::Success) {
2724 m_erased_flash_ranges.Insert(range,
true);
2733 "unexpected response to GDB server flash erase packet '%s': '%s'",
2747 if (m_erased_flash_ranges.IsEmpty())
2750 if (m_gdb_comm.SendPacketAndWaitForResponse(
"vFlashDone", response,
2751 GetInterruptTimeout()) ==
2752 GDBRemoteCommunication::PacketResult::Success) {
2754 m_erased_flash_ranges.
Clear();
2762 "unexpected response to GDB server flash done packet: '%s'",
2771 size_t ProcessGDBRemote::DoWriteMemory(
addr_t addr,
const void *buf,
2775 size_t max_memory_size = m_max_memory_size / 2;
2776 if (size > max_memory_size) {
2780 size = max_memory_size;
2786 Status region_status = GetMemoryRegionInfo(addr, region);
2792 if (!m_allow_flash_writes) {
2793 error.SetErrorString(
"Writing to flash memory is not allowed");
2800 error = FlashErase(addr, size);
2801 if (!
error.Success())
2803 packet.
Printf(
"vFlashWrite:%" PRIx64
":", addr);
2806 packet.
Printf(
"M%" PRIx64
",%" PRIx64
":", addr, (uint64_t)size);
2811 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.
GetString(), response,
2812 GetInterruptTimeout()) ==
2813 GDBRemoteCommunication::PacketResult::Success) {
2818 error.SetErrorStringWithFormat(
"memory write failed for 0x%" PRIx64,
2821 error.SetErrorStringWithFormat(
2822 "GDB server does not support writing memory");
2824 error.SetErrorStringWithFormat(
2825 "unexpected response to GDB server memory write packet '%s': '%s'",
2828 error.SetErrorStringWithFormat(
"failed to send packet: '%s'",
2840 if (m_gdb_comm.SupportsAllocDeallocMemory() !=
eLazyBoolNo) {
2841 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2843 m_gdb_comm.SupportsAllocDeallocMemory() ==
eLazyBoolYes)
2844 return allocated_addr;
2847 if (m_gdb_comm.SupportsAllocDeallocMemory() ==
eLazyBoolNo) {
2850 if (permissions & lldb::ePermissionsReadable)
2852 if (permissions & lldb::ePermissionsWritable)
2854 if (permissions & lldb::ePermissionsExecutable)
2859 m_addr_to_mmap_size[allocated_addr] = size;
2863 "ProcessGDBRemote::%s no direct stub support for memory "
2864 "allocation, and InferiorCallMmap also failed - is stub "
2865 "missing register context save/restore capability?",
2871 error.SetErrorStringWithFormat(
2872 "unable to allocate %" PRIu64
" bytes of memory with permissions %s",
2876 return allocated_addr;
2882 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2888 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
2894 num, after, GetTarget().GetArchitecture()));
2900 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2902 switch (supported) {
2906 error.SetErrorString(
2907 "tried to deallocate memory without ever allocating memory");
2911 if (!m_gdb_comm.DeallocateMemory(addr))
2912 error.SetErrorStringWithFormat(
2913 "unable to deallocate memory at 0x%" PRIx64, addr);
2919 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2920 if (pos != m_addr_to_mmap_size.end() &&
2922 m_addr_to_mmap_size.erase(pos);
2924 error.SetErrorStringWithFormat(
2925 "unable to deallocate memory at 0x%" PRIx64, addr);
2934 size_t ProcessGDBRemote::PutSTDIN(
const char *src,
size_t src_len,
2936 if (m_stdio_communication.IsConnected()) {
2938 m_stdio_communication.Write(src, src_len, status,
nullptr);
2939 }
else if (m_stdin_forward) {
2940 m_gdb_comm.SendStdinNotification(src, src_len);
2947 assert(bp_site !=
nullptr);
2950 Log *log =
GetLog(GDBRLog::Breakpoints);
2958 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2959 ") address = 0x%" PRIx64,
2960 site_id, (uint64_t)addr);
2965 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2966 ") address = 0x%" PRIx64
" -- SUCCESS (already enabled)",
2967 site_id, (uint64_t)addr);
2972 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2986 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2988 if (error_no == 0) {
3004 if (error_no != UINT8_MAX)
3005 error.SetErrorStringWithFormat(
3006 "error: %d sending the breakpoint request", error_no);
3008 error.SetErrorString(
"error sending the breakpoint request");
3015 LLDB_LOGF(log,
"Software breakpoints are unsupported");
3026 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3028 if (error_no == 0) {
3039 if (error_no != UINT8_MAX)
3040 error.SetErrorStringWithFormat(
3041 "error: %d sending the hardware breakpoint request "
3042 "(hardware breakpoint resources might be exhausted or unavailable)",
3045 error.SetErrorString(
"error sending the hardware breakpoint request "
3046 "(hardware breakpoint resources "
3047 "might be exhausted or unavailable)");
3053 LLDB_LOGF(log,
"Hardware breakpoints are unsupported");
3060 error.SetErrorString(
"hardware breakpoints are not supported");
3066 return EnableSoftwareBreakpoint(bp_site);
3071 assert(bp_site !=
nullptr);
3074 Log *log =
GetLog(GDBRLog::Breakpoints);
3076 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3077 ") addr = 0x%8.8" PRIx64,
3078 site_id, (uint64_t)addr);
3081 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3086 error = DisableSoftwareBreakpoint(bp_site);
3092 GetInterruptTimeout()))
3093 error.SetErrorToGenericError();
3099 GetInterruptTimeout()))
3100 error.SetErrorToGenericError();
3103 if (
error.Success())
3107 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3108 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3109 site_id, (uint64_t)addr);
3113 if (
error.Success())
3114 error.SetErrorToGenericError();
3125 assert(watch_read || watch_write);
3126 if (watch_read && watch_write)
3128 else if (watch_read)
3140 LLDB_LOGF(log,
"ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
")",
3144 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3145 ") addr = 0x%8.8" PRIx64
": watchpoint already enabled.",
3146 watchID, (uint64_t)addr);
3152 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3153 if (m_gdb_comm.SendGDBStoppointTypePacket(type,
true, addr,
3155 GetInterruptTimeout()) == 0) {
3159 error.SetErrorString(
"sending gdb watchpoint packet failed");
3161 error.SetErrorString(
"watchpoints not supported");
3163 error.SetErrorString(
"Watchpoint argument was NULL.");
3165 if (
error.Success())
3166 error.SetErrorToGenericError();
3180 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3181 ") addr = 0x%8.8" PRIx64,
3182 watchID, (uint64_t)addr);
3186 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3187 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3188 watchID, (uint64_t)addr);
3199 if (m_gdb_comm.SendGDBStoppointTypePacket(type,
false, addr,
3201 GetInterruptTimeout()) == 0) {
3205 error.SetErrorString(
"sending gdb watchpoint packet failed");
3209 error.SetErrorString(
"Watchpoint argument was NULL.");
3211 if (
error.Success())
3212 error.SetErrorToGenericError();
3216 void ProcessGDBRemote::Clear() {
3217 m_thread_list_real.Clear();
3218 m_thread_list.Clear();
3221 Status ProcessGDBRemote::DoSignal(
int signo) {
3224 LLDB_LOGF(log,
"ProcessGDBRemote::DoSignal (signal = %d)", signo);
3226 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3227 error.SetErrorStringWithFormat(
"failed to send signal %i", signo);
3232 ProcessGDBRemote::EstablishConnectionIfNeeded(
const ProcessInfo &process_info) {
3234 if (m_gdb_comm.IsConnected())
3237 PlatformSP platform_sp(GetTarget().GetPlatform());
3238 if (platform_sp && !platform_sp->IsHost())
3239 return Status(
"Lost debug server connection");
3241 auto error = LaunchAndConnectToDebugserver(process_info);
3243 const char *error_string =
error.AsCString();
3244 if (error_string ==
nullptr)
3249 #if !defined(_WIN32)
3250 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3253 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3255 #if defined(FD_CLOEXEC)
3256 int flags = ::fcntl(fd, F_GETFD);
3259 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3266 Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3268 using namespace std::placeholders;
3273 static FileSpec g_debugserver_file_spec;
3280 const std::weak_ptr<ProcessGDBRemote> this_wp =
3281 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3283 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3286 #if defined(__APPLE__)
3290 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3292 struct kinfo_proc processInfo;
3293 size_t bufsize =
sizeof(processInfo);
3294 if (sysctl(mib, (
unsigned)(
sizeof(mib)/
sizeof(
int)), &processInfo,
3295 &bufsize, NULL, 0) == 0 && bufsize > 0) {
3296 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3297 FileSpec rosetta_debugserver(
"/Library/Apple/usr/libexec/oah/debugserver");
3303 int communication_fd = -1;
3304 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3308 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3309 error.SetErrorToErrno();
3313 int our_socket = sockets[0];
3314 int gdb_socket = sockets[1];
3315 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3316 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3320 communication_fd = gdb_socket;
3323 error = m_gdb_comm.StartDebugserverProcess(
3324 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3325 nullptr,
nullptr, communication_fd);
3327 if (
error.Success())
3328 m_debugserver_pid = debugserver_launch_info.
GetProcessID();
3333 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3336 cleanup_our.release();
3337 m_gdb_comm.SetConnection(
3338 std::make_unique<ConnectionFileDescriptor>(our_socket,
true));
3346 LLDB_LOGF(log,
"failed to start debugserver process: %s",
3351 if (m_gdb_comm.IsConnected()) {
3354 error = ConnectToDebugserver(
"");
3356 error.SetErrorString(
"connection failed");
3362 void ProcessGDBRemote::MonitorDebugserverProcess(
3363 std::weak_ptr<ProcessGDBRemote> process_wp,
lldb::pid_t debugserver_pid,
3372 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3373 ", signo=%i (0x%x), exit_status=%i)",
3374 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3376 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3377 LLDB_LOGF(log,
"ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3378 static_cast<void *
>(process_sp.get()));
3379 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3385 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3389 const StateType state = process_sp->GetState();
3393 char error_str[1024];
3395 const char *signal_cstr =
3396 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3398 ::snprintf(error_str,
sizeof(error_str),
3401 ::snprintf(error_str,
sizeof(error_str),
3404 ::snprintf(error_str,
sizeof(error_str),
3409 process_sp->SetExitStatus(-1, error_str);
3416 void ProcessGDBRemote::KillDebugserverProcess() {
3417 m_gdb_comm.Disconnect();
3424 void ProcessGDBRemote::Initialize() {
3425 static llvm::once_flag g_once_flag;
3427 llvm::call_once(g_once_flag, []() {
3429 GetPluginDescriptionStatic(), CreateInstance,
3430 DebuggerInitialize);
3434 void ProcessGDBRemote::DebuggerInitialize(
Debugger &debugger) {
3436 debugger, PluginProperties::GetSettingName())) {
3437 const bool is_global_setting =
true;
3439 debugger, GetGlobalPluginProperties().GetValueProperties(),
3440 ConstString(
"Properties for the gdb-remote process plug-in."),
3445 bool ProcessGDBRemote::StartAsyncThread() {
3448 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3450 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3451 if (!m_async_thread.IsJoinable()) {
3455 llvm::Expected<HostThread> async_thread =
3457 return ProcessGDBRemote::AsyncThread();
3459 if (!async_thread) {
3461 "failed to launch host thread: {}");
3464 m_async_thread = *async_thread;
3467 "ProcessGDBRemote::%s () - Called when Async thread was "
3471 return m_async_thread.IsJoinable();
3474 void ProcessGDBRemote::StopAsyncThread() {
3477 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3479 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3480 if (m_async_thread.IsJoinable()) {
3481 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3484 m_gdb_comm.Disconnect();
3487 m_async_thread.Join(
nullptr);
3488 m_async_thread.Reset();
3492 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3498 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread starting...",
3499 __FUNCTION__, GetID());
3517 "ProcessGDBRemote::%s(pid = %" PRIu64
3518 ") listener.WaitForEvent (NULL, event_sp)...",
3519 __FUNCTION__, GetID());
3521 if (m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3522 const uint32_t event_type = event_sp->GetType();
3523 if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
3525 "ProcessGDBRemote::%s(pid = %" PRIu64
3526 ") Got an event of type: %d...",
3527 __FUNCTION__, GetID(), event_type);
3529 switch (event_type) {
3530 case eBroadcastBitAsyncContinue: {
3534 if (continue_packet) {
3535 const char *continue_cstr =
3536 (
const char *)continue_packet->
GetBytes();
3537 const size_t continue_cstr_len = continue_packet->
GetByteSize();
3539 "ProcessGDBRemote::%s(pid = %" PRIu64
3540 ") got eBroadcastBitAsyncContinue: %s",
3541 __FUNCTION__, GetID(), continue_cstr);
3543 if (::strstr(continue_cstr,
"vAttach") ==
nullptr)
3548 GetGDBRemote().SendContinuePacketAndWaitForResponse(
3549 *
this, *GetUnixSignals(),
3550 llvm::StringRef(continue_cstr, continue_cstr_len),
3551 GetInterruptTimeout(), response);
3559 ClearThreadIDList();
3561 switch (stop_state) {
3565 SetLastStopPacket(response);
3566 SetPrivateState(stop_state);
3570 SetLastStopPacket(response);
3571 ClearThreadIDList();
3574 int exit_status = response.
GetHexU8();
3577 llvm::StringRef desc_str;
3578 llvm::StringRef desc_token;
3580 if (desc_token !=
"description")
3586 SetExitStatus(exit_status, desc_string.c_str());
3595 if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3597 SetExitStatus(-1,
"cannot attach to process due to "
3598 "System Integrity Protection");
3599 }
else if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3603 SetExitStatus(-1,
"lost connection");
3610 SetPrivateState(stop_state);
3617 case eBroadcastBitAsyncThreadShouldExit:
3619 "ProcessGDBRemote::%s(pid = %" PRIu64
3620 ") got eBroadcastBitAsyncThreadShouldExit...",
3621 __FUNCTION__, GetID());
3627 "ProcessGDBRemote::%s(pid = %" PRIu64
3628 ") got unknown event 0x%8.8x",
3629 __FUNCTION__, GetID(), event_type);
3633 }
else if (event_sp->BroadcasterIs(&m_gdb_comm)) {
3634 switch (event_type) {
3635 case Communication::eBroadcastBitReadThreadDidExit:
3636 SetExitStatus(-1,
"lost connection");
3642 "ProcessGDBRemote::%s(pid = %" PRIu64
3643 ") got unknown event 0x%8.8x",
3644 __FUNCTION__, GetID(), event_type);
3651 "ProcessGDBRemote::%s(pid = %" PRIu64
3652 ") listener.WaitForEvent (NULL, event_sp) => false",
3653 __FUNCTION__, GetID());
3658 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread exiting...",
3659 __FUNCTION__, GetID());
3684 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3691 LLDB_LOGF(log,
"Hit New Thread Notification breakpoint.");
3695 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3697 LLDB_LOG(log,
"Check if need to update ignored signals");
3701 if (!m_gdb_comm.GetQPassSignalsSupported())
3705 if (m_unix_signals_sp ==
nullptr)
3709 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3710 if (new_signals_version == m_last_signals_version) {
3711 LLDB_LOG(log,
"Signals' version hasn't changed. version={0}",
3712 m_last_signals_version);
3716 auto signals_to_ignore =
3717 m_unix_signals_sp->GetFilteredSignals(
false,
false,
false);
3718 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3721 "Signals' version changed. old version={0}, new version={1}, "
3722 "signals ignored={2}, update result={3}",
3723 m_last_signals_version, new_signals_version,
3724 signals_to_ignore.size(),
error);
3726 if (
error.Success())
3727 m_last_signals_version = new_signals_version;
3732 bool ProcessGDBRemote::StartNoticingNewThreads() {
3734 if (m_thread_create_bp_sp) {
3736 LLDB_LOGF(log,
"Enabled noticing new thread breakpoint.");
3737 m_thread_create_bp_sp->SetEnabled(
true);
3739 PlatformSP platform_sp(GetTarget().GetPlatform());
3741 m_thread_create_bp_sp =
3742 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3743 if (m_thread_create_bp_sp) {
3746 log,
"Successfully created new thread notification breakpoint %i",
3747 m_thread_create_bp_sp->GetID());
3748 m_thread_create_bp_sp->SetCallback(
3749 ProcessGDBRemote::NewThreadNotifyBreakpointHit,
this,
true);
3751 LLDB_LOGF(log,
"Failed to create new thread notification breakpoint.");
3755 return m_thread_create_bp_sp.get() !=
nullptr;
3758 bool ProcessGDBRemote::StopNoticingNewThreads() {
3761 LLDB_LOGF(log,
"Disabling new thread notification breakpoint.");
3763 if (m_thread_create_bp_sp)
3764 m_thread_create_bp_sp->SetEnabled(
false);
3770 if (m_dyld_up.get() ==
nullptr)
3772 return m_dyld_up.get();
3775 Status ProcessGDBRemote::SendEventData(
const char *data) {
3781 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3782 if (return_value != 0) {
3784 error.SetErrorString(
"Sending events is not supported for this process.");
3786 error.SetErrorStringWithFormat(
"Error sending event data: %d.",
3794 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3795 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature(
"auxv",
"");
3797 buf = std::make_shared<DataBufferHeap>(response->c_str(),
3798 response->length());
3802 return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
3809 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3815 args_dict->GetAsDictionary()->AddIntegerItem(
"thread", tid);
3818 packet <<
"jThreadExtendedInfo:";
3819 args_dict->Dump(packet,
false);
3826 packet << (char)(0x7d ^ 0
x20);
3830 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.
GetString(), response) ==
3831 GDBRemoteCommunication::PacketResult::Success) {
3835 if (!response.
Empty()) {
3849 args_dict->GetAsDictionary()->AddIntegerItem(
"image_list_address",
3850 image_list_address);
3851 args_dict->GetAsDictionary()->AddIntegerItem(
"image_count", image_count);
3853 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3859 args_dict->GetAsDictionary()->AddBooleanItem(
"fetch_all_solibs",
true);
3861 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3865 const std::vector<lldb::addr_t> &load_addresses) {
3869 for (
auto addr : load_addresses) {
3871 addresses->AddItem(addr_sp);
3874 args_dict->GetAsDictionary()->AddItem(
"solib_addresses", addresses);
3876 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3880 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3884 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3887 std::chrono::seconds(10));
3890 packet <<
"jGetLoadedDynamicLibrariesInfos:";
3891 args_dict->Dump(packet,
false);
3898 packet << (char)(0x7d ^ 0
x20);
3902 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.
GetString(), response) ==
3903 GDBRemoteCommunication::PacketResult::Success) {
3907 if (!response.
Empty()) {
3921 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3923 packet <<
"jGetSharedCacheInfo:";
3924 args_dict->Dump(packet,
false);
3931 packet << (char)(0x7d ^ 0
x20);
3935 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.
GetString(), response) ==
3936 GDBRemoteCommunication::PacketResult::Success) {
3940 if (!response.
Empty()) {
3950 Status ProcessGDBRemote::ConfigureStructuredData(
3952 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
3964 void ProcessGDBRemote::GetMaxMemorySize() {
3965 const uint64_t reasonable_largeish_default = 128 * 1024;
3966 const uint64_t conservative_default = 512;
3968 if (m_max_memory_size == 0) {
3969 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3970 if (stub_max_size !=
UINT64_MAX && stub_max_size != 0) {
3972 m_remote_stub_max_memory_size = stub_max_size;
3976 if (stub_max_size > reasonable_largeish_default) {
3977 stub_max_size = reasonable_largeish_default;
3983 if (stub_max_size > 70)
3984 stub_max_size -= 32 + 32 + 6;
3988 Log *log(
GetLog(GDBRLog::Comm | GDBRLog::Memory));
3990 log->
Warning(
"Packet size is too small. "
3991 "LLDB may face problems while writing memory");
3994 m_max_memory_size = stub_max_size;
3996 m_max_memory_size = conservative_default;
4001 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4002 uint64_t user_specified_max) {
4003 if (user_specified_max != 0) {
4006 if (m_remote_stub_max_memory_size != 0) {
4007 if (m_remote_stub_max_memory_size < user_specified_max) {
4008 m_max_memory_size = m_remote_stub_max_memory_size;
4013 m_max_memory_size = user_specified_max;
4022 bool ProcessGDBRemote::GetModuleSpec(
const FileSpec &module_file_spec,
4029 auto cached = m_cached_module_specs.find(key);
4030 if (cached != m_cached_module_specs.end()) {
4031 module_spec = cached->second;
4032 return bool(module_spec);
4035 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4036 LLDB_LOGF(log,
"ProcessGDBRemote::%s - failed to get module info for %s:%s",
4037 __FUNCTION__, module_file_spec.
GetPath().c_str(),
4044 module_spec.
Dump(stream);
4045 LLDB_LOGF(log,
"ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4046 __FUNCTION__, module_file_spec.
GetPath().c_str(),
4050 m_cached_module_specs[key] = module_spec;
4054 void ProcessGDBRemote::PrefetchModuleSpecs(
4055 llvm::ArrayRef<FileSpec> module_file_specs,
const llvm::Triple &triple) {
4056 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4058 for (
const FileSpec &spec : module_file_specs)
4062 m_cached_module_specs[
ModuleCacheKey(spec.GetFileSpec().GetPath(),
4063 triple.getTriple())] = spec;
4067 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4068 return m_gdb_comm.GetOSVersion();
4071 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
4072 return m_gdb_comm.GetMacCatalystVersion();
4077 typedef std::vector<std::string> stringVec;
4079 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4080 struct RegisterSetInfo {
4084 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4086 struct GdbServerTargetInfo {
4090 RegisterSetMap reg_set_map;
4093 bool ParseRegisters(
XMLNode feature_node, GdbServerTargetInfo &target_info,
4094 std::vector<DynamicRegisterInfo::Register> ®isters) {
4099 "reg", [&target_info, ®isters](
const XMLNode ®_node) ->
bool {
4103 bool encoding_set =
false;
4104 bool format_set =
false;
4108 &encoding_set, &format_set, ®_info](
4109 const llvm::StringRef &name,
4110 const llvm::StringRef &value) ->
bool {
4111 if (name ==
"name") {
4113 }
else if (name ==
"bitsize") {
4114 if (llvm::to_integer(value, reg_info.
byte_size))
4116 llvm::divideCeil(reg_info.
byte_size, CHAR_BIT);
4117 }
else if (name ==
"type") {
4118 gdb_type = value.str();
4119 }
else if (name ==
"group") {
4120 gdb_group = value.str();
4121 }
else if (name ==
"regnum") {
4123 }
else if (name ==
"offset") {
4125 }
else if (name ==
"altname") {
4127 }
else if (name ==
"encoding") {
4128 encoding_set =
true;
4130 }
else if (name ==
"format") {
4136 llvm::StringSwitch<lldb::Format>(value)
4147 }
else if (name ==
"group_id") {
4149 llvm::to_integer(value, set_id);
4150 RegisterSetMap::const_iterator pos =
4151 target_info.reg_set_map.find(set_id);
4152 if (pos != target_info.reg_set_map.end())
4153 reg_info.
set_name = pos->second.name;
4154 }
else if (name ==
"gcc_regnum" || name ==
"ehframe_regnum") {
4156 }
else if (name ==
"dwarf_regnum") {
4158 }
else if (name ==
"generic") {
4160 }
else if (name ==
"value_regnums") {
4163 }
else if (name ==
"invalidate_regnums") {
4169 "ProcessGDBRemote::%s unhandled reg attribute %s = %s",
4170 __FUNCTION__, name.data(), value.data());
4175 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4176 if (llvm::StringRef(gdb_type).startswith(
"int")) {
4179 }
else if (gdb_type ==
"data_ptr" || gdb_type ==
"code_ptr") {
4182 }
else if (gdb_type ==
"float") {
4185 }
else if (gdb_type ==
"aarch64v" ||
4186 llvm::StringRef(gdb_type).startswith(
"vec") ||
4187 gdb_type ==
"i387_ext" || gdb_type ==
"uint128") {
4199 if (!gdb_group.empty()) {
4211 "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4214 registers.push_back(reg_info);
4228 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4230 std::vector<DynamicRegisterInfo::Register> ®isters) {
4232 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature(
"features", xml_filename);
4233 if (errorToBool(raw.takeError()))
4238 if (xml_document.
ParseMemory(raw->c_str(), raw->size(),
4239 xml_filename.c_str())) {
4240 GdbServerTargetInfo target_info;
4241 std::vector<XMLNode> feature_nodes;
4247 const XMLNode &node) ->
bool {
4248 llvm::StringRef name = node.
GetName();
4249 if (name ==
"architecture") {
4251 }
else if (name ==
"osabi") {
4253 }
else if (name ==
"xi:include" || name ==
"include") {
4256 target_info.includes.push_back(href);
4257 }
else if (name ==
"feature") {
4258 feature_nodes.push_back(node);
4259 }
else if (name ==
"groups") {
4261 "group", [&target_info](
const XMLNode &node) ->
bool {
4263 RegisterSetInfo set_info;
4266 [&set_id, &set_info](
const llvm::StringRef &name,
4267 const llvm::StringRef &value) ->
bool {
4270 llvm::to_integer(value, set_id);
4277 target_info.reg_set_map[set_id] = set_info;
4290 feature_nodes.push_back(feature_node);
4292 const XMLNode &node) ->
bool {
4293 llvm::StringRef name = node.
GetName();
4294 if (name ==
"xi:include" || name ==
"include") {
4297 target_info.includes.push_back(href);
4311 if (!arch_to_use.
IsValid() && !target_info.arch.empty()) {
4313 arch_to_use.
SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4314 .Case(
"i386:x86-64",
"x86_64")
4315 .Default(target_info.arch) +
4319 GetTarget().MergeArchitecture(arch_to_use);
4323 for (
auto &feature_node : feature_nodes) {
4324 ParseRegisters(feature_node, target_info,
4328 for (
const auto &include : target_info.includes) {
4329 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4339 void ProcessGDBRemote::AddRemoteRegisters(
4340 std::vector<DynamicRegisterInfo::Register> ®isters,
4342 std::map<uint32_t, uint32_t> remote_to_local_map;
4344 for (
auto it : llvm::enumerate(registers)) {
4352 remote_to_local_map[remote_reg_info.
regnum_remote] = it.index();
4358 auto proc_to_lldb = [&remote_to_local_map](
uint32_t process_regnum) {
4359 auto lldb_regit = remote_to_local_map.find(process_regnum);
4360 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4364 llvm::transform(remote_reg_info.value_regs,
4365 remote_reg_info.value_regs.begin(), proc_to_lldb);
4366 llvm::transform(remote_reg_info.invalidate_regs,
4367 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4374 abi_sp->AugmentRegisterInfo(registers);
4376 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4381 bool ProcessGDBRemote::GetGDBServerRegisterInfo(
ArchSpec &arch_to_use) {
4387 if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4390 std::vector<DynamicRegisterInfo::Register> registers;
4391 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use,
"target.xml",
4393 AddRemoteRegisters(registers, arch_to_use);
4395 return m_register_info_sp->GetNumRegisters() > 0;
4398 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4401 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4402 "XML parsing not available");
4405 LLDB_LOGF(log,
"ProcessGDBRemote::%s", __FUNCTION__);
4409 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
4414 llvm::Expected<std::string> raw = comm.
ReadExtFeature(
"libraries-svr4",
"");
4416 return raw.takeError();
4419 LLDB_LOGF(log,
"parsing: %s", raw->c_str());
4422 if (!doc.
ParseMemory(raw->c_str(), raw->size(),
"noname.xml"))
4423 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4424 "Error reading noname.xml");
4428 return llvm::createStringError(
4429 llvm::inconvertibleErrorCode(),
4430 "Error finding library-list-svr4 xml element");
4435 if (!main_lm.empty())
4436 llvm::to_integer(main_lm,
list.m_link_map);
4439 "library", [log, &
list](
const XMLNode &library) ->
bool {
4444 [&module](
const llvm::StringRef &name,
4445 const llvm::StringRef &value) ->
bool {
4449 else if (name ==
"lm") {
4451 llvm::to_integer(value, uint_value);
4453 }
else if (name ==
"l_addr") {
4456 llvm::to_integer(value, uint_value);
4461 }
else if (name ==
"l_ld") {
4463 llvm::to_integer(value, uint_value);
4473 bool base_is_offset;
4482 "found (link_map:0x%08" PRIx64
", base:0x%08" PRIx64
4483 "[%s], ld:0x%08" PRIx64
", name:'%s')",
4484 lm, base, (base_is_offset ?
"offset" :
"absolute"), ld,
4494 LLDB_LOGF(log,
"found %" PRId32
" modules in total",
4495 (
int)
list.m_list.size());
4499 llvm::Expected<std::string> raw = comm.
ReadExtFeature(
"libraries",
"");
4502 return raw.takeError();
4504 LLDB_LOGF(log,
"parsing: %s", raw->c_str());
4507 if (!doc.
ParseMemory(raw->c_str(), raw->size(),
"noname.xml"))
4508 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4509 "Error reading noname.xml");
4513 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4514 "Error finding library-list xml element");
4518 "library", [log, &
list](
const XMLNode &library) ->
bool {
4531 llvm::to_integer(address, address_value);
4539 bool base_is_offset;
4544 LLDB_LOGF(log,
"found (base:0x%08" PRIx64
"[%s], name:'%s')", base,
4545 (base_is_offset ?
"offset" :
"absolute"), name.c_str());
4554 LLDB_LOGF(log,
"found %" PRId32
" modules in total",
4555 (
int)
list.m_list.size());
4558 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4559 "Remote libraries not supported");
4563 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(
const FileSpec &file,
4566 bool value_is_offset) {
4579 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4581 return module_list.takeError();
4590 bool mod_base_is_offset;
4593 valid &= modInfo.
get_name(mod_name);
4594 valid &= modInfo.
get_base(mod_base);
4604 lldb::ModuleSP module_sp =
4605 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4607 if (module_sp.get())
4608 new_modules.
Append(module_sp);
4611 if (new_modules.
GetSize() > 0) {
4613 Target &target = GetTarget();
4614 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4616 for (
size_t i = 0; i < loaded_modules.
GetSize(); ++i) {
4620 for (
size_t j = 0; j < new_modules.
GetSize(); ++j) {
4629 removed_modules.
Append(loaded_module);
4633 loaded_modules.
Remove(removed_modules);
4634 m_process->GetTarget().ModulesDidUnload(removed_modules,
false);
4636 new_modules.
ForEach([&target](
const lldb::ModuleSP module_sp) ->
bool {
4641 if (obj->
GetType() != ObjectFile::Type::eTypeExecutable)
4644 lldb::ModuleSP module_copy_sp = module_sp;
4650 m_process->GetTarget().ModulesDidLoad(new_modules);
4653 return llvm::ErrorSuccess();
4663 if (file_path.empty())
4664 return Status(
"Empty file name specified");
4671 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.
GetString(), response) !=
4672 GDBRemoteCommunication::PacketResult::Success)
4673 return Status(
"Sending qFileLoadAddress packet failed");
4684 "Fetching file load address from remote server returned an error");
4694 "Unknown error happened during sending the load address packet");
4704 m_gdb_comm.ServeSymbolLookups(
this);
4707 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4708 AppendSTDOUT(out.data(), out.size());
4714 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4716 if (m_partial_profile_data.length() > 0) {
4717 m_partial_profile_data.append(input);
4718 input = m_partial_profile_data;
4719 m_partial_profile_data.clear();
4722 size_t found, pos = 0, len = input.length();
4723 while ((found = input.find(
end_delimiter, pos)) != std::string::npos) {
4725 input.substr(pos, found).c_str());
4727 HarmonizeThreadIdsForProfileData(profileDataExtractor);
4728 BroadcastAsyncProfileData(profile_data);
4735 m_partial_profile_data = input.substr(pos);
4741 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4743 llvm::raw_string_ostream output_stream(output);
4744 llvm::StringRef name, value;
4748 if (name.compare(
"thread_used_id") == 0) {
4750 uint64_t thread_id = threadIDHexExtractor.
GetHexMaxU64(
false, 0);
4752 bool has_used_usec =
false;
4754 llvm::StringRef usec_name, usec_value;
4757 if (usec_name.equals(
"thread_used_usec")) {
4758 has_used_usec =
true;
4759 usec_value.getAsInteger(0, curr_used_usec);
4763 profileDataExtractor.
SetFilePos(input_file_pos);
4767 if (has_used_usec) {
4769 std::map<uint64_t, uint32_t>::iterator iterator =
4770 m_thread_id_to_used_usec_map.find(thread_id);
4771 if (iterator != m_thread_id_to_used_usec_map.end()) {
4772 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4775 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4777 bool good_first_time =
4778 (prev_used_usec == 0) && (real_used_usec > 250000);
4779 bool good_subsequent_time =
4780 (prev_used_usec > 0) &&
4781 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4783 if (good_first_time || good_subsequent_time) {
4787 output_stream << name <<
":";
4788 int32_t index_id = AssignIndexIDToThread(thread_id);
4789 output_stream << index_id <<
";";
4791 output_stream << usec_name <<
":" << usec_value <<
";";
4794 llvm::StringRef local_name, local_value;
4800 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4803 output_stream << name <<
":" << value <<
";";
4806 output_stream << name <<
":" << value <<
";";
4810 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
4812 return output_stream.str();
4815 void ProcessGDBRemote::HandleStopReply() {
4816 if (GetStopID() != 0)
4820 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4824 BuildDynamicRegisterInfo(
true);
4827 llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
4828 if (!m_gdb_comm.GetSaveCoreSupported())
4836 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.
GetString(), response) ==
4837 GDBRemoteCommunication::PacketResult::Success) {
4841 return llvm::createStringError(
4842 llvm::inconvertibleErrorCode(),
4843 llvm::formatv(
"qSaveCore returned an error"));
4848 for (
auto x : llvm::split(response.
GetStringRef(),
';')) {
4849 if (x.consume_front(
"core-path:"))
4855 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4856 "qSaveCore returned no core path");
4859 FileSpec remote_core{llvm::StringRef(path)};
4860 Platform &platform = *GetTarget().GetPlatform();
4865 platform.
Unlink(remote_core);
4867 return error.ToError();
4873 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4874 "Unable to send qSaveCore");
4887 "GDBRemoteCommunicationClientBase::%s() received $J packet "
4888 "but was not a StructuredData packet: packet starts with "
4902 json_sp->Dump(json_str,
true);
4905 "ProcessGDBRemote::%s() "
4906 "received Async StructuredData packet: %s",
4907 __FUNCTION__, json_str.
GetData());
4910 "ProcessGDBRemote::%s"
4911 "() received StructuredData packet:"
4919 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
4921 if (structured_data_sp)
4922 RouteAsyncStructuredData(structured_data_sp);
4929 "Tests packet speeds of various sizes to determine "
4930 "the performance characteristics of the GDB remote "
4935 "The number of packets to send of each varying size "
4936 "(default is 1000).",
4939 "The maximum number of bytes to send in a packet. Sizes "
4940 "increase in powers of 2 while the size is less than or "
4941 "equal to this option value. (default 1024).",
4944 "The maximum number of bytes to receive in a packet. Sizes "
4945 "increase in powers of 2 while the size is less than or "
4946 "equal to this option value. (default 1024).",
4949 "Print the output as JSON data for easy parsing.", false, true) {
4954 m_option_group.Finalize();
4968 StreamSP output_stream_sp(
4969 m_interpreter.GetDebugger().GetAsyncOutputStream());
4973 (
uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4974 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4975 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4976 const bool json = m_json.GetOptionValue().GetCurrentValue();
4977 const uint64_t k_recv_amount =
4980 num_packets, max_send, max_recv, k_recv_amount, json,
4987 m_cmd_name.c_str());
5006 "Dumps the packet history buffer. ", nullptr) {}
5028 interpreter,
"process plugin packet xfer-size",
5029 "Maximum size that lldb will try to read/write one one chunk.",
5032 m_arguments.push_back({max_arg});
5041 "amount to be transferred when "
5043 m_cmd_name.c_str());
5052 uint64_t user_specified_max = strtoul(packet_size,
nullptr, 10);
5053 if (errno == 0 && user_specified_max != 0) {
5069 "Send a custom packet through the GDB remote "
5070 "protocol and print the answer. "
5071 "The packet header and footer will automatically "
5072 "be added to the packet prior to sending and "
5073 "stripped from the result.",
5076 m_arguments.push_back({packet_arg});
5085 "'%s' takes a one or more packet content arguments",
5086 m_cmd_name.c_str());
5093 for (
size_t i = 0; i < argc; ++i) {
5100 output_strm.
Printf(
" packet: %s\n", packet_cstr);
5103 if (strstr(packet_cstr,
"qGetProfileData") !=
nullptr) {
5107 if (response_str.empty())
5108 output_strm.
PutCString(
"response: \nerror: UNIMPLEMENTED\n");
5122 "Send a qRcmd packet through the GDB remote protocol "
5123 "and print the response."
5124 "The argument passed to this command will be hex "
5125 "encoded into a valid 'qRcmd' packet, sent and the "
5126 "response will be printed.") {}
5132 if (command.empty()) {
5134 m_cmd_name.c_str());
5149 [&output_strm](llvm::StringRef output) { output_strm << output; });
5154 if (response_str.empty())
5155 output_strm.
PutCString(
"response: \nerror: UNIMPLEMENTED\n");
5168 "Commands that deal with GDB remote packets.",
5175 "send", CommandObjectSP(
5185 LoadSubCommand(
"speed-test",
5197 interpreter,
"process plugin",
5198 "Commands for operating on a ProcessGDBRemote process.",
5199 "process plugin <subcommand> [<subcommand-options>]") {
5210 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5211 GetTarget().GetDebugger().GetCommandInterpreter());
5212 return m_command_sp.get();
5215 void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(
bool enable) {
5216 GetBreakpointSiteList().ForEach([
this, enable](
BreakpointSite *bp_site) {
5220 m_gdb_comm.SendGDBStoppointTypePacket(
5221 eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
5222 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5227 void ProcessGDBRemote::DidForkSwitchHardwareTraps(
bool enable) {
5229 GetBreakpointSiteList().ForEach([
this, enable](
BreakpointSite *bp_site) {
5232 m_gdb_comm.SendGDBStoppointTypePacket(
5233 eBreakpointHardware, enable, bp_site->GetLoadAddress(),
5234 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5240 size_t wp_count = wps.
GetSize();
5241 for (
size_t i = 0; i < wp_count; ++i) {
5243 if (wp->IsEnabled()) {
5245 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(),
5247 GetInterruptTimeout());
5255 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
5263 switch (GetFollowForkMode()) {
5265 follow_pid = parent_pid;
5266 follow_tid = parent_tid;
5267 detach_pid = child_pid;
5268 detach_tid = child_tid;
5271 follow_pid = child_pid;
5272 follow_tid = child_tid;
5273 detach_pid = parent_pid;
5274 detach_tid = parent_tid;
5279 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5280 LLDB_LOG(log,
"ProcessGDBRemote::DidFork() unable to set pid/tid");
5286 DidForkSwitchSoftwareBreakpoints(
false);
5291 DidForkSwitchHardwareTraps(
false);
5294 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
5295 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
5296 LLDB_LOG(log,
"ProcessGDBRemote::DidFork() unable to reset pid/tid");
5300 LLDB_LOG(log,
"Detaching process {0}", detach_pid);
5301 Status error = m_gdb_comm.Detach(
false, detach_pid);
5303 LLDB_LOG(log,
"ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5304 error.AsCString() ?
error.AsCString() :
"<unknown error>");
5311 DidForkSwitchHardwareTraps(
true);
5317 assert(!m_vfork_in_progress);
5318 m_vfork_in_progress =
true;
5322 DidForkSwitchSoftwareBreakpoints(
false);
5327 switch (GetFollowForkMode()) {
5329 detach_pid = child_pid;
5330 detach_tid = child_tid;
5333 detach_pid = m_gdb_comm.GetCurrentProcessID();
5336 detach_tid = m_thread_ids.front();
5339 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5340 LLDB_LOG(log,
"ProcessGDBRemote::DidFork() unable to set pid/tid");
5345 DidForkSwitchHardwareTraps(
false);
5348 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
5349 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
5350 LLDB_LOG(log,
"ProcessGDBRemote::DidFork() unable to reset pid/tid");
5356 LLDB_LOG(log,
"Detaching process {0}", detach_pid);
5357 Status error = m_gdb_comm.Detach(
false, detach_pid);
5360 "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5361 error.AsCString() ?
error.AsCString() :
"<unknown error>");
5366 void ProcessGDBRemote::DidVForkDone() {
5367 assert(m_vfork_in_progress);
5368 m_vfork_in_progress =
false;
5372 DidForkSwitchSoftwareBreakpoints(
true);
5375 void ProcessGDBRemote::DidExec() {
5379 m_vfork_in_progress =
false;