9#include "lldb/Host/Config.h"
14#include <netinet/in.h>
16#include <sys/socket.h>
21#include <sys/sysctl.h>
86#include "llvm/ADT/ScopeExit.h"
87#include "llvm/ADT/StringSwitch.h"
88#include "llvm/Support/FormatAdapters.h"
89#include "llvm/Support/Threading.h"
90#include "llvm/Support/raw_ostream.h"
92#define DEBUGSERVER_BASENAME "debugserver"
110 llvm::consumeError(file.takeError());
120#define LLDB_PROPERTIES_processgdbremote
121#include "ProcessGDBRemoteProperties.inc"
124#define LLDB_PROPERTIES_processgdbremote
125#include "ProcessGDBRemotePropertiesEnum.inc"
135 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
136 m_collection_sp->Initialize(g_processgdbremote_properties);
139 ~PluginProperties()
override =
default;
141 uint64_t GetPacketTimeout() {
142 const uint32_t idx = ePropertyPacketTimeout;
143 return m_collection_sp->GetPropertyAtIndexAsUInt64(
144 nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
147 bool SetPacketTimeout(uint64_t timeout) {
148 const uint32_t idx = ePropertyPacketTimeout;
149 return m_collection_sp->SetPropertyAtIndexAsUInt64(
nullptr, idx, timeout);
152 FileSpec GetTargetDefinitionFile()
const {
153 const uint32_t idx = ePropertyTargetDefinitionFile;
154 return m_collection_sp->GetPropertyAtIndexAsFileSpec(
nullptr, idx);
157 bool GetUseSVR4()
const {
158 const uint32_t idx = ePropertyUseSVR4;
159 return m_collection_sp->GetPropertyAtIndexAsBoolean(
161 g_processgdbremote_properties[idx].default_uint_value != 0);
164 bool GetUseGPacketForReading()
const {
165 const uint32_t idx = ePropertyUseGPacketForReading;
166 return m_collection_sp->GetPropertyAtIndexAsBoolean(
nullptr, idx,
true);
173 static PluginProperties g_settings;
181#if defined(__APPLE__)
182#define LOW_PORT (IPPORT_RESERVED)
183#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
185#define LOW_PORT (1024u)
186#define HIGH_PORT (49151u)
190 return "GDB Remote protocol based debugging plug-in.";
198 lldb::TargetSP target_sp, ListenerSP listener_sp,
199 const FileSpec *crash_file_path,
bool can_connect) {
200 lldb::ProcessSP process_sp;
201 if (crash_file_path ==
nullptr)
202 process_sp = std::shared_ptr<ProcessGDBRemote>(
216 bool plugin_specified_by_name) {
217 if (plugin_specified_by_name)
221 Module *exe_module = target_sp->GetExecutableModulePointer();
225 switch (exe_objfile->
GetType()) {
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");
278 "ProcessGDBRemote::%s failed to listen for "
279 "m_async_broadcaster events",
283 const uint64_t timeout_seconds =
285 if (timeout_seconds > 0)
311 const FileSpec &target_definition_fspec) {
317 if (module_object_sp) {
320 "gdb-server-target-definition",
error));
322 if (target_definition_sp) {
324 target_definition_sp->GetValueForKey(
"host-info"));
326 if (
auto host_info_dict = target_object->GetAsDictionary()) {
328 host_info_dict->GetValueForKey(
"triple");
329 if (
auto triple_string_value = triple_value->GetAsString()) {
330 std::string triple_string =
331 std::string(triple_string_value->GetValue());
332 ArchSpec host_arch(triple_string.c_str());
341 target_definition_sp->GetValueForKey(
"breakpoint-pc-offset");
342 if (breakpoint_pc_offset_value) {
343 if (
auto breakpoint_pc_int_value =
344 breakpoint_pc_offset_value->GetAsInteger())
349 *target_definition_sp,
GetTarget().GetArchitecture()) > 0) {
358 const llvm::StringRef &comma_separated_register_numbers,
359 std::vector<uint32_t> ®nums,
int base) {
361 for (llvm::StringRef x : llvm::split(comma_separated_register_numbers,
',')) {
363 if (llvm::to_integer(x, reg, base))
364 regnums.push_back(reg);
366 return regnums.size();
379 if (host_packet_timeout > std::chrono::seconds(0)) {
397 if (target_definition_fspec) {
403 target_definition_fspec.
GetPath() +
414 if (remote_process_arch.
IsValid())
415 arch_to_use = remote_process_arch;
417 arch_to_use = remote_host_arch;
420 arch_to_use = target_arch;
426 std::vector<DynamicRegisterInfo::Register> registers;
431 const int packet_len =
432 ::snprintf(packet,
sizeof(packet),
"qRegisterInfo%x", reg_num);
433 assert(packet_len < (
int)
sizeof(packet));
440 llvm::StringRef name;
441 llvm::StringRef value;
445 if (name.equals(
"name")) {
447 }
else if (name.equals(
"alt-name")) {
449 }
else if (name.equals(
"bitsize")) {
450 if (!value.getAsInteger(0, reg_info.
byte_size))
452 }
else if (name.equals(
"offset")) {
454 }
else if (name.equals(
"encoding")) {
458 }
else if (name.equals(
"format")) {
462 llvm::StringSwitch<Format>(value)
477 }
else if (name.equals(
"set")) {
479 }
else if (name.equals(
"gcc") || name.equals(
"ehframe")) {
481 }
else if (name.equals(
"dwarf")) {
483 }
else if (name.equals(
"generic")) {
485 }
else if (name.equals(
"container-regs")) {
487 }
else if (name.equals(
"invalidate-regs")) {
493 registers.push_back(reg_info);
502 if (registers.empty())
517 bool wait_for_launch) {
562 error.SetErrorStringWithFormat(
563 "Process %" PRIu64
" was reported after connecting to "
564 "'%s', but state was not stopped: %s",
567 error.SetErrorStringWithFormat(
"Process %" PRIu64
568 " was reported after connecting to '%s', "
569 "but no stop reply packet was received",
570 pid, remote_url.str().c_str());
574 "ProcessGDBRemote::%s pid %" PRIu64
575 ": normalizing target architecture initial triple: %s "
576 "(GetTarget().GetArchitecture().IsValid() %s, "
577 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
578 __FUNCTION__,
GetID(),
579 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
594 "ProcessGDBRemote::%s pid %" PRIu64
595 ": normalized target architecture triple: %s",
596 __FUNCTION__,
GetID(),
597 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
614 LLDB_LOGF(log,
"ProcessGDBRemote::%s() entered", __FUNCTION__);
640 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
642 "ProcessGDBRemote::%s provided with STDIO paths via "
643 "launch_info: stdin=%s, stdout=%s, stderr=%s",
645 stdin_file_spec ? stdin_file_spec.GetPath().c_str() :
"<null>",
646 stdout_file_spec ? stdout_file_spec.GetPath().c_str() :
"<null>",
647 stderr_file_spec ? stderr_file_spec.GetPath().c_str() :
"<null>");
650 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
654 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
655 if (stdin_file_spec || disable_stdio) {
670 if (
error.Success()) {
672 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
674 PlatformSP platform_sp(
GetTarget().GetPlatform());
677 if (!stdin_file_spec)
679 FileSpec::Style::native);
680 if (!stdout_file_spec)
682 FileSpec::Style::native);
683 if (!stderr_file_spec)
685 FileSpec::Style::native);
686 }
else if (platform_sp && platform_sp->IsHost()) {
691 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
695 if (!stdin_file_spec)
696 stdin_file_spec = secondary_name;
698 if (!stdout_file_spec)
699 stdout_file_spec = secondary_name;
701 if (!stderr_file_spec)
702 stderr_file_spec = secondary_name;
706 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
707 "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
710 stdin_file_spec ? stdin_file_spec.GetPath().c_str() :
"<null>",
711 stdout_file_spec ? stdout_file_spec.GetPath().c_str() :
"<null>",
712 stderr_file_spec ? stderr_file_spec.GetPath().c_str() :
"<null>");
716 "ProcessGDBRemote::%s final STDIO paths after all "
717 "adjustments: stdin=%s, stdout=%s, stderr=%s",
719 stdin_file_spec ? stdin_file_spec.GetPath().c_str() :
"<null>",
720 stdout_file_spec ? stdout_file_spec.GetPath().c_str() :
"<null>",
721 stderr_file_spec ? stderr_file_spec.GetPath().c_str() :
"<null>");
725 if (stdout_file_spec)
727 if (stderr_file_spec)
734 GetTarget().GetArchitecture().GetArchitectureName());
737 if (launch_event_data !=
nullptr && *launch_event_data !=
'\0')
750 std::chrono::seconds(10));
758 error.SetErrorStringWithFormatv(
"Cannot launch '{0}': {1}",
760 llvm::fmt_consume(std::move(err)));
767 LLDB_LOGF(log,
"failed to connect to debugserver: %s",
789 if (!disable_stdio) {
795 LLDB_LOGF(log,
"failed to connect to debugserver: %s",
error.AsCString());
805 if (!connect_url.empty()) {
806 LLDB_LOGF(log,
"ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
807 connect_url.str().c_str());
808 std::unique_ptr<ConnectionFileDescriptor> conn_up(
811 const uint32_t max_retry_count = 50;
821 if (retry_count >= max_retry_count)
824 std::this_thread::sleep_for(std::chrono::milliseconds(100));
831 error.SetErrorString(
"not connected to remote gdb server");
842 error.SetErrorString(
"not connected to remote gdb server");
855 auto handle_cmds = [&] (
const Args &args) ->
void {
859 entry.c_str(), response);
865 handle_cmds(platform_sp->GetExtraStartupCommands());
882 if (remote_process_arch.
IsValid()) {
883 process_arch = remote_process_arch;
884 LLDB_LOG(log,
"gdb-remote had process architecture, using {0} {1}",
890 "gdb-remote did not have process architecture, using gdb-remote "
891 "host architecture {0} {1}",
897 lldb::addr_t address_mask = ~((1ULL << addressable_bits) - 1);
905 LLDB_LOG(log,
"analyzing target arch, currently {0} {1}",
917 if ((process_arch.
GetMachine() == llvm::Triple::arm ||
918 process_arch.
GetMachine() == llvm::Triple::thumb) &&
919 process_arch.
GetTriple().getVendor() == llvm::Triple::Apple) {
922 "remote process is ARM/Apple, "
923 "setting target arch to {0} {1}",
928 const llvm::Triple &remote_triple = process_arch.
GetTriple();
929 llvm::Triple new_target_triple = target_arch.
GetTriple();
930 if (new_target_triple.getVendorName().size() == 0) {
931 new_target_triple.setVendor(remote_triple.getVendor());
933 if (new_target_triple.getOSName().size() == 0) {
934 new_target_triple.setOS(remote_triple.getOS());
936 if (new_target_triple.getEnvironmentName().size() == 0)
937 new_target_triple.setEnvironment(remote_triple.getEnvironment());
940 ArchSpec new_target_arch = target_arch;
941 new_target_arch.
SetTriple(new_target_triple);
947 "final target arch after adjustments for remote architecture: "
975 if (platform_sp && platform_sp->IsConnected())
987 UUID standalone_uuid;
989 bool standalone_value_is_offset;
991 standalone_value_is_offset)) {
994 if (standalone_uuid.
IsValid()) {
995 const bool force_symbol_search =
true;
996 const bool notify =
true;
998 this,
"", standalone_uuid, standalone_value,
999 standalone_value_is_offset, force_symbol_search, notify);
1012 if (bin_addrs.size()) {
1014 const bool value_is_slide =
false;
1015 for (
addr_t addr : bin_addrs) {
1016 const bool notify =
true;
1023 .LoadPlatformBinaryAndSetup(
this, addr, notify))
1026 const bool force_symbol_search =
true;
1029 addr, value_is_slide,
1030 force_symbol_search, notify);
1045 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1046 offsets->offsets.size();
1050 bool changed =
false;
1051 module_sp->SetLoadAddress(
GetTarget(), offsets->offsets[0],
1070 LLDB_LOGF(log,
"ProcessGDBRemote::%s()", __FUNCTION__);
1076 if (
error.Success()) {
1080 const int packet_len =
1081 ::snprintf(packet,
sizeof(packet),
"vAttach;%" PRIx64, attach_pid);
1098 if (process_name && process_name[0]) {
1100 if (
error.Success()) {
1143llvm::Expected<std::string>
1148llvm::Expected<std::vector<uint8_t>>
1160 process_arch.
Clear();
1177 LLDB_LOGF(log,
"ProcessGDBRemote::Resume()");
1179 ListenerSP listener_sp(
1181 if (listener_sp->StartListeningForEvents(
1183 listener_sp->StartListeningForEvents(
1190 bool continue_packet_error =
false;
1192 std::string pid_prefix;
1194 pid_prefix = llvm::formatv(
"p{0:x-}.",
GetID());
1201 continue_packet.
Format(
"vCont;c:{0}-1", pid_prefix);
1209 for (tid_collection::const_iterator
1212 t_pos != t_end; ++t_pos)
1213 continue_packet.
Format(
";c:{0}{1:x-}", pid_prefix, *t_pos);
1215 continue_packet_error =
true;
1220 for (tid_sig_collection::const_iterator
1223 s_pos != s_end; ++s_pos)
1224 continue_packet.
Format(
";C{0:x-2}:{1}{2:x-}", s_pos->second,
1225 pid_prefix, s_pos->first);
1227 continue_packet_error =
true;
1232 for (tid_collection::const_iterator
1235 t_pos != t_end; ++t_pos)
1236 continue_packet.
Format(
";s:{0}{1:x-}", pid_prefix, *t_pos);
1238 continue_packet_error =
true;
1243 for (tid_sig_collection::const_iterator
1246 s_pos != s_end; ++s_pos)
1247 continue_packet.
Format(
";S{0:x-2}:{1}{2:x-}", s_pos->second,
1248 pid_prefix, s_pos->first);
1250 continue_packet_error =
true;
1253 if (continue_packet_error)
1254 continue_packet.
Clear();
1257 continue_packet_error =
true;
1259 if (continue_packet_error) {
1267 if (num_continue_c_tids > 0) {
1268 if (num_continue_c_tids == num_threads) {
1272 continue_packet_error =
false;
1273 }
else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1274 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1278 continue_packet_error =
false;
1282 if (continue_packet_error && num_continue_C_tids > 0) {
1283 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1284 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1285 num_continue_S_tids == 0) {
1288 if (num_continue_C_tids > 1) {
1293 if (num_continue_C_tids > 1) {
1294 continue_packet_error =
false;
1297 continue_packet_error =
true;
1300 if (!continue_packet_error)
1304 continue_packet_error =
false;
1307 if (!continue_packet_error) {
1309 continue_packet.
Printf(
"C%2.2x", continue_signo);
1314 if (continue_packet_error && num_continue_s_tids > 0) {
1315 if (num_continue_s_tids == num_threads) {
1321 continue_packet_error =
false;
1322 }
else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1323 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1327 continue_packet_error =
false;
1331 if (!continue_packet_error && num_continue_S_tids > 0) {
1332 if (num_continue_S_tids == num_threads) {
1335 continue_packet_error =
false;
1336 if (num_continue_S_tids > 1) {
1337 for (
size_t i = 1; i < num_threads; ++i) {
1339 continue_packet_error =
true;
1342 if (!continue_packet_error) {
1345 continue_packet.
Printf(
"S%2.2x", step_signo);
1347 }
else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1348 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1352 continue_packet_error =
false;
1357 if (continue_packet_error) {
1358 error.SetErrorString(
"can't make continue packet for this resume");
1362 error.SetErrorString(
"Trying to resume but the async thread is dead.");
1363 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Trying to resume but the "
1364 "async thread is dead.");
1373 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1374 error.SetErrorString(
"Resume timed out.");
1375 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Resume timed out.");
1377 error.SetErrorString(
"Broadcast continue, but the async thread was "
1378 "killed before we got an ack back.");
1380 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1381 "async thread was killed before we got an ack back.");
1397 llvm::StringRef value) {
1403 auto pid_tid = thread_ids.
GetPidTid(pid);
1404 if (pid_tid && pid_tid->first == pid) {
1410 }
while (thread_ids.GetChar() ==
',');
1416 llvm::StringRef value) {
1418 for (llvm::StringRef x : llvm::split(value,
',')) {
1420 if (llvm::to_integer(x,
pc, 16))
1432 if (thread_infos && thread_infos->
GetSize() > 0) {
1456 const std::string &stop_info_str = std::string(stop_info.
GetStringRef());
1459 const size_t thread_pcs_pos = stop_info_str.find(
";thread-pcs:");
1460 if (thread_pcs_pos != std::string::npos) {
1461 const size_t start = thread_pcs_pos + strlen(
";thread-pcs:");
1462 const size_t end = stop_info_str.find(
';', start);
1463 if (end != std::string::npos) {
1464 std::string value = stop_info_str.substr(start, end - start);
1469 const size_t threads_pos = stop_info_str.find(
";threads:");
1470 if (threads_pos != std::string::npos) {
1471 const size_t start = threads_pos + strlen(
";threads:");
1472 const size_t end = stop_info_str.find(
';', start);
1473 if (end != std::string::npos) {
1474 std::string value = stop_info_str.substr(start, end - start);
1482 bool sequence_mutex_unavailable =
false;
1484 if (sequence_mutex_unavailable) {
1499 if (num_thread_ids == 0) {
1505 ThreadList old_thread_list_copy(old_thread_list);
1506 if (num_thread_ids > 0) {
1507 for (
size_t i = 0; i < num_thread_ids; ++i) {
1512 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1513 LLDB_LOGV(log,
"Making new thread: {0} for thread ID: {1:x}.",
1514 thread_sp.get(), thread_sp->GetID());
1516 LLDB_LOGV(log,
"Found old thread: {0} for thread ID: {1:x}.",
1517 thread_sp.get(), thread_sp->GetID());
1527 size_t old_num_thread_ids = old_thread_list_copy.
GetSize(
false);
1528 for (
size_t i = 0; i < old_num_thread_ids; i++) {
1530 if (old_thread_sp) {
1531 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1544 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1546 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1559 if (thread_infos_sp) {
1563 const size_t n = thread_infos->
GetSize();
1564 for (
size_t i = 0; i < n; ++i) {
1570 if (tid == thread->
GetID())
1608 uint8_t signo,
const std::string &thread_name,
const std::string &reason,
1609 const std::string &description,
uint32_t exc_type,
1610 const std::vector<addr_t> &exc_data,
addr_t thread_dispatch_qaddr,
1611 bool queue_vars_valid,
1613 LazyBool associated_with_dispatch_queue,
addr_t dispatch_queue_t,
1614 std::string &queue_name,
QueueKind queue_kind, uint64_t queue_serial) {
1630 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1638 gdb_reg_ctx_sp->InvalidateIfNeeded(
true);
1644 for (
const auto &pair : expedited_register_map) {
1646 WritableDataBufferSP buffer_sp(
1648 reg_value_extractor.
GetHexBytes(buffer_sp->GetData(),
'\xcc');
1649 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1667 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1672 if (queue_vars_valid)
1673 gdb_thread->
SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1674 dispatch_queue_t, associated_with_dispatch_queue);
1685 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(
false);
1687 current_stop_info_sp) {
1688 thread_sp->SetStopInfo(current_stop_info_sp);
1692 if (!thread_sp->StopInfoIsUpToDate()) {
1693 thread_sp->SetStopInfo(StopInfoSP());
1697 thread_sp = memory_thread_sp;
1699 if (exc_type != 0) {
1700 const size_t exc_data_size = exc_data.size();
1702 thread_sp->SetStopInfo(
1704 *thread_sp, exc_type, exc_data_size,
1705 exc_data_size >= 1 ? exc_data[0] : 0,
1706 exc_data_size >= 2 ? exc_data[1] : 0,
1707 exc_data_size >= 3 ? exc_data[2] : 0));
1709 bool handled =
false;
1710 bool did_exec =
false;
1711 if (!reason.empty()) {
1712 if (reason ==
"trace") {
1713 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1714 lldb::BreakpointSiteSP bp_site_sp =
1715 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1720 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1721 thread_sp->SetStopInfo(
1723 *thread_sp, bp_site_sp->GetID()));
1725 thread_sp->SetStopInfo(
1728 }
else if (reason ==
"breakpoint") {
1729 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1730 lldb::BreakpointSiteSP bp_site_sp =
1731 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1740 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1741 thread_sp->SetStopInfo(
1743 *thread_sp, bp_site_sp->GetID()));
1745 StopInfoSP invalid_stop_info_sp;
1746 thread_sp->SetStopInfo(invalid_stop_info_sp);
1749 }
else if (reason ==
"trap") {
1751 }
else if (reason ==
"watchpoint") {
1769 wp_sp->SetHardwareIndex(wp_index);
1770 watch_id = wp_sp->GetID();
1775 LLDB_LOGF(log,
"failed to find watchpoint");
1778 *thread_sp, watch_id, wp_hit_addr));
1780 }
else if (reason ==
"exception") {
1782 *thread_sp, description.c_str()));
1784 }
else if (reason ==
"exec") {
1786 thread_sp->SetStopInfo(
1789 }
else if (reason ==
"processor trace") {
1791 *thread_sp, description.c_str()));
1792 }
else if (reason ==
"fork") {
1797 thread_sp->SetStopInfo(
1800 }
else if (reason ==
"vfork") {
1806 *thread_sp, child_pid, child_tid));
1808 }
else if (reason ==
"vforkdone") {
1809 thread_sp->SetStopInfo(
1813 }
else if (!signo) {
1814 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1815 lldb::BreakpointSiteSP bp_site_sp =
1816 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
pc);
1823 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1825 *thread_sp, bp_site_sp->GetID()));
1830 if (!handled && signo && !did_exec) {
1837 lldb::BreakpointSiteSP bp_site_sp =
1838 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1847 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1849 thread_sp->GetRegisterContext()->SetPC(
pc);
1850 thread_sp->SetStopInfo(
1852 *thread_sp, bp_site_sp->GetID()));
1854 StopInfoSP invalid_stop_info_sp;
1855 thread_sp->SetStopInfo(invalid_stop_info_sp);
1863 thread_sp->SetStopInfo(
1867 *thread_sp, signo, description.c_str()));
1872 *thread_sp, signo, description.c_str()));
1875 if (!description.empty()) {
1876 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1878 const char *stop_info_desc = stop_info_sp->GetDescription();
1879 if (!stop_info_desc || !stop_info_desc[0])
1880 stop_info_sp->SetDescription(description.c_str());
1883 *thread_sp, description.c_str()));
1899 static ConstString g_key_dispatch_queue_t(
"dispatch_queue_t");
1900 static ConstString g_key_associated_with_dispatch_queue(
1901 "associated_with_dispatch_queue");
1904 static ConstString g_key_queue_serial_number(
"qserialnum");
1909 static ConstString g_key_description(
"description");
1916 std::string thread_name;
1918 std::string description;
1920 std::vector<addr_t> exc_data;
1923 bool queue_vars_valid =
false;
1926 std::string queue_name;
1928 uint64_t queue_serial_number = 0;
1933 thread_dict->
ForEach([
this, &tid, &expedited_register_map, &thread_name,
1934 &signo, &reason, &description, &exc_type, &exc_data,
1935 &thread_dispatch_qaddr, &queue_vars_valid,
1936 &associated_with_dispatch_queue, &dispatch_queue_t,
1937 &queue_name, &queue_kind, &queue_serial_number](
1940 if (key == g_key_tid) {
1943 }
else if (key == g_key_metype) {
1945 exc_type =
object->GetIntegerValue(0);
1946 }
else if (key == g_key_medata) {
1955 }
else if (key == g_key_name) {
1957 }
else if (key == g_key_qaddr) {
1959 }
else if (key == g_key_queue_name) {
1960 queue_vars_valid =
true;
1962 }
else if (key == g_key_queue_kind) {
1963 std::string queue_kind_str = std::string(object->
GetStringValue());
1964 if (queue_kind_str ==
"serial") {
1965 queue_vars_valid =
true;
1967 }
else if (queue_kind_str ==
"concurrent") {
1968 queue_vars_valid =
true;
1971 }
else if (key == g_key_queue_serial_number) {
1972 queue_serial_number =
object->GetIntegerValue(0);
1973 if (queue_serial_number != 0)
1974 queue_vars_valid =
true;
1975 }
else if (key == g_key_dispatch_queue_t) {
1976 dispatch_queue_t =
object->GetIntegerValue(0);
1978 queue_vars_valid =
true;
1979 }
else if (key == g_key_associated_with_dispatch_queue) {
1980 queue_vars_valid =
true;
1981 bool associated =
object->GetBooleanValue();
1986 }
else if (key == g_key_reason) {
1988 }
else if (key == g_key_description) {
1990 }
else if (key == g_key_registers) {
1993 if (registers_dict) {
1998 if (llvm::to_integer(key.
AsCString(), reg))
1999 expedited_register_map[reg] =
2004 }
else if (key == g_key_memory) {
2010 if (mem_cache_dict) {
2013 "address", mem_cache_addr)) {
2014 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2015 llvm::StringRef str;
2016 if (mem_cache_dict->GetValueForKeyAsString(
"bytes", str)) {
2017 StringExtractor bytes(str);
2018 bytes.SetFilePos(0);
2020 const size_t byte_size = bytes.GetStringRef().size() / 2;
2021 WritableDataBufferSP data_buffer_sp(
2022 new DataBufferHeap(byte_size, 0));
2023 const size_t bytes_copied =
2024 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2025 if (bytes_copied == byte_size)
2026 m_memory_cache.AddL1CacheData(mem_cache_addr,
2036 }
else if (key == g_key_signal)
2041 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2042 reason, description, exc_type, exc_data,
2043 thread_dispatch_qaddr, queue_vars_valid,
2044 associated_with_dispatch_queue, dispatch_queue_t,
2045 queue_name, queue_kind, queue_serial_number);
2051 const char stop_type = stop_packet.
GetChar();
2052 switch (stop_type) {
2071 const uint8_t signo = stop_packet.
GetHexU8();
2072 llvm::StringRef key;
2073 llvm::StringRef value;
2074 std::string thread_name;
2076 std::string description;
2078 std::vector<addr_t> exc_data;
2080 bool queue_vars_valid =
2084 std::string queue_name;
2086 uint64_t queue_serial_number = 0;
2089 if (key.compare(
"metype") == 0) {
2091 value.getAsInteger(16, exc_type);
2092 }
else if (key.compare(
"medata") == 0) {
2095 value.getAsInteger(16, x);
2096 exc_data.push_back(x);
2097 }
else if (key.compare(
"thread") == 0) {
2100 auto pid_tid = thread_id.
GetPidTid(pid);
2102 stop_pid = pid_tid->first;
2103 tid = pid_tid->second;
2106 }
else if (key.compare(
"threads") == 0) {
2107 std::lock_guard<std::recursive_mutex> guard(
2110 }
else if (key.compare(
"thread-pcs") == 0) {
2115 while (!value.empty()) {
2116 llvm::StringRef pc_str;
2117 std::tie(pc_str, value) = value.split(
',');
2118 if (pc_str.getAsInteger(16,
pc))
2122 }
else if (key.compare(
"jstopinfo") == 0) {
2131 }
else if (key.compare(
"hexname") == 0) {
2136 }
else if (key.compare(
"name") == 0) {
2137 thread_name = std::string(value);
2138 }
else if (key.compare(
"qaddr") == 0) {
2139 value.getAsInteger(16, thread_dispatch_qaddr);
2140 }
else if (key.compare(
"dispatch_queue_t") == 0) {
2141 queue_vars_valid =
true;
2142 value.getAsInteger(16, dispatch_queue_t);
2143 }
else if (key.compare(
"qname") == 0) {
2144 queue_vars_valid =
true;
2148 }
else if (key.compare(
"qkind") == 0) {
2149 queue_kind = llvm::StringSwitch<QueueKind>(value)
2154 }
else if (key.compare(
"qserialnum") == 0) {
2155 if (!value.getAsInteger(0, queue_serial_number))
2156 queue_vars_valid =
true;
2157 }
else if (key.compare(
"reason") == 0) {
2158 reason = std::string(value);
2159 }
else if (key.compare(
"description") == 0) {
2163 }
else if (key.compare(
"memory") == 0) {
2177 llvm::StringRef addr_str, bytes_str;
2178 std::tie(addr_str, bytes_str) = value.split(
'=');
2179 if (!addr_str.empty() && !bytes_str.empty()) {
2181 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2184 WritableDataBufferSP data_buffer_sp(
2186 const size_t bytes_copied =
2188 if (bytes_copied == byte_size)
2192 }
else if (key.compare(
"watch") == 0 || key.compare(
"rwatch") == 0 ||
2193 key.compare(
"awatch") == 0) {
2196 value.getAsInteger(16, wp_addr);
2198 WatchpointSP wp_sp =
2203 wp_index = wp_sp->GetHardwareIndex();
2205 reason =
"watchpoint";
2207 ostr.
Printf(
"%" PRIu64
" %" PRIu32, wp_addr, wp_index);
2208 description = std::string(ostr.
GetString());
2209 }
else if (key.compare(
"library") == 0) {
2215 }
else if (key.compare(
"fork") == 0 || key.compare(
"vfork") == 0) {
2221 LLDB_LOG(log,
"Invalid PID/TID to fork: {0}", value);
2227 ostr.
Printf(
"%" PRIu64
" %" PRIu64, pid_tid->first, pid_tid->second);
2228 description = std::string(ostr.
GetString());
2229 }
else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2231 if (!key.getAsInteger(16, reg))
2232 expedited_register_map[reg] = std::string(std::move(value));
2239 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2257 tid, expedited_register_map, signo, thread_name, reason, description,
2258 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2259 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2260 queue_kind, queue_serial_number);
2325 LLDB_LOGF(log,
"ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2329 if (
error.Success())
2331 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2334 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2335 error.AsCString() ?
error.AsCString() :
"<unknown error>");
2338 if (!
error.Success())
2353 LLDB_LOGF(log,
"ProcessGDBRemote::DoDestroy()");
2356 int exit_status = SIGABRT;
2357 std::string exit_string;
2364 exit_status = kill_res.get();
2365#if defined(__APPLE__)
2376 PlatformSP platform_sp(
GetTarget().GetPlatform());
2377 if (platform_sp && platform_sp->IsHost()) {
2380 reap_pid = waitpid(
GetID(), &status, WNOHANG);
2381 LLDB_LOGF(log,
"Reaped pid: %d, status: %d.\n", reap_pid, status);
2385 exit_string.assign(
"killed");
2387 exit_string.assign(llvm::toString(kill_res.takeError()));
2390 exit_string.assign(
"killed or interrupted while attaching.");
2396 exit_string.assign(
"destroying when not connected to debugserver");
2408 const bool did_exec =
2409 response.
GetStringRef().find(
";reason:exec;") != std::string::npos;
2412 LLDB_LOGF(log,
"ProcessGDBRemote::SetLastStopPacket () - detected exec");
2442 LLDB_LOG_ERROR(log, list.takeError(),
"Failed to read module list: {0}.");
2444 addr = list->m_link_map;
2464 const size_t n = thread_infos->
GetSize();
2465 for (
size_t i = 0; i < n; ++i) {
2481 size_t max_memory_size =
2483 if (size > max_memory_size) {
2487 size = max_memory_size;
2492 packet_len = ::snprintf(packet,
sizeof(packet),
"%c%" PRIx64
",%" PRIx64,
2493 binary_memory_read ?
'x' :
'm', (uint64_t)addr,
2495 assert(packet_len + 1 < (
int)
sizeof(packet));
2503 if (binary_memory_read) {
2509 if (data_received_size > size) {
2512 data_received_size = size;
2514 memcpy(buf, response.
GetStringRef().data(), data_received_size);
2515 return data_received_size;
2518 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size),
'\xdd');
2521 error.SetErrorStringWithFormat(
"memory read failed for 0x%" PRIx64, addr);
2523 error.SetErrorStringWithFormat(
2524 "GDB server does not support reading memory");
2526 error.SetErrorStringWithFormat(
2527 "unexpected response to GDB server memory read packet '%s': '%s'",
2530 error.SetErrorStringWithFormat(
"failed to send packet: '%s'", packet);
2539llvm::Expected<std::vector<uint8_t>>
2546 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2547 "Error reading memory tags from remote");
2551 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2552 std::vector<uint8_t> got;
2553 got.reserve(tag_data.size());
2554 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2560 const std::vector<uint8_t> &tags) {
2567 std::vector<ObjectFile::LoadableData> entries) {
2572 std::begin(entries), std::end(entries),
2578 if (
error.Success())
2592 for (
size_t i = 0; i < size; ++i)
2611 status.
SetErrorString(
"Unable to erase flash in multiple regions");
2616 if (blocksize == 0) {
2617 status.
SetErrorString(
"Unable to erase flash because blocksize is 0");
2623 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2624 size += (addr - block_start_addr);
2625 if ((size % blocksize) != 0)
2626 size += (blocksize - size % blocksize);
2668 "unexpected response to GDB server flash erase packet '%s': '%s'",
2697 "unexpected response to GDB server flash done packet: '%s'",
2711 if (size > max_memory_size) {
2715 size = max_memory_size;
2728 error.SetErrorString(
"Writing to flash memory is not allowed");
2736 if (!
error.Success())
2738 packet.
Printf(
"vFlashWrite:%" PRIx64
":", addr);
2741 packet.
Printf(
"M%" PRIx64
",%" PRIx64
":", addr, (uint64_t)size);
2753 error.SetErrorStringWithFormat(
"memory write failed for 0x%" PRIx64,
2756 error.SetErrorStringWithFormat(
2757 "GDB server does not support writing memory");
2759 error.SetErrorStringWithFormat(
2760 "unexpected response to GDB server memory write packet '%s': '%s'",
2763 error.SetErrorStringWithFormat(
"failed to send packet: '%s'",
2779 return allocated_addr;
2785 if (permissions & lldb::ePermissionsReadable)
2787 if (permissions & lldb::ePermissionsWritable)
2789 if (permissions & lldb::ePermissionsExecutable)
2798 "ProcessGDBRemote::%s no direct stub support for memory "
2799 "allocation, and InferiorCallMmap also failed - is stub "
2800 "missing register context save/restore capability?",
2806 error.SetErrorStringWithFormat(
2807 "unable to allocate %" PRIu64
" bytes of memory with permissions %s",
2811 return allocated_addr;
2833 switch (supported) {
2837 error.SetErrorString(
2838 "tried to deallocate memory without ever allocating memory");
2843 error.SetErrorStringWithFormat(
2844 "unable to deallocate memory at 0x%" PRIx64, addr);
2855 error.SetErrorStringWithFormat(
2856 "unable to deallocate memory at 0x%" PRIx64, addr);
2878 assert(bp_site !=
nullptr);
2889 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2890 ") address = 0x%" PRIx64,
2891 site_id, (uint64_t)addr);
2896 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2897 ") address = 0x%" PRIx64
" -- SUCCESS (already enabled)",
2898 site_id, (uint64_t)addr);
2919 if (error_no == 0) {
2935 if (error_no != UINT8_MAX)
2936 error.SetErrorStringWithFormat(
2937 "error: %d sending the breakpoint request", error_no);
2939 error.SetErrorString(
"error sending the breakpoint request");
2946 LLDB_LOGF(log,
"Software breakpoints are unsupported");
2959 if (error_no == 0) {
2970 if (error_no != UINT8_MAX)
2971 error.SetErrorStringWithFormat(
2972 "error: %d sending the hardware breakpoint request "
2973 "(hardware breakpoint resources might be exhausted or unavailable)",
2976 error.SetErrorString(
"error sending the hardware breakpoint request "
2977 "(hardware breakpoint resources "
2978 "might be exhausted or unavailable)");
2984 LLDB_LOGF(log,
"Hardware breakpoints are unsupported");
2991 error.SetErrorString(
"hardware breakpoints are not supported");
3002 assert(bp_site !=
nullptr);
3007 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3008 ") addr = 0x%8.8" PRIx64,
3009 site_id, (uint64_t)addr);
3024 error.SetErrorToGenericError();
3031 error.SetErrorToGenericError();
3034 if (
error.Success())
3038 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3039 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3040 site_id, (uint64_t)addr);
3044 if (
error.Success())
3045 error.SetErrorToGenericError();
3056 assert(watch_read || watch_write);
3057 if (watch_read && watch_write)
3059 else if (watch_read)
3071 LLDB_LOGF(log,
"ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
")",
3075 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3076 ") addr = 0x%8.8" PRIx64
": watchpoint already enabled.",
3077 watchID, (uint64_t)addr);
3090 error.SetErrorString(
"sending gdb watchpoint packet failed");
3092 error.SetErrorString(
"watchpoints not supported");
3094 error.SetErrorString(
"Watchpoint argument was NULL.");
3096 if (
error.Success())
3097 error.SetErrorToGenericError();
3111 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3112 ") addr = 0x%8.8" PRIx64,
3113 watchID, (uint64_t)addr);
3117 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3118 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3119 watchID, (uint64_t)addr);
3136 error.SetErrorString(
"sending gdb watchpoint packet failed");
3140 error.SetErrorString(
"Watchpoint argument was NULL.");
3142 if (
error.Success())
3143 error.SetErrorToGenericError();
3155 LLDB_LOGF(log,
"ProcessGDBRemote::DoSignal (signal = %d)", signo);
3158 error.SetErrorStringWithFormat(
"failed to send signal %i", signo);
3168 PlatformSP platform_sp(
GetTarget().GetPlatform());
3169 if (platform_sp && !platform_sp->IsHost())
3170 return Status(
"Lost debug server connection");
3174 const char *error_string =
error.AsCString();
3175 if (error_string ==
nullptr)
3181#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3184#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3186#if defined(FD_CLOEXEC)
3187 int flags = ::fcntl(fd, F_GETFD);
3190 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3199 using namespace std::placeholders;
3204 static FileSpec g_debugserver_file_spec;
3211 const std::weak_ptr<ProcessGDBRemote> this_wp =
3212 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3217#if defined(__APPLE__)
3221 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3223 struct kinfo_proc processInfo;
3224 size_t bufsize =
sizeof(processInfo);
3225 if (sysctl(mib, (
unsigned)(
sizeof(mib)/
sizeof(
int)), &processInfo,
3226 &bufsize, NULL, 0) == 0 && bufsize > 0) {
3227 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3228 FileSpec rosetta_debugserver(
"/Library/Apple/usr/libexec/oah/debugserver");
3234 int communication_fd = -1;
3235#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3239 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3240 error.SetErrorToErrno();
3244 int our_socket = sockets[0];
3245 int gdb_socket = sockets[1];
3246 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3247 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3251 communication_fd = gdb_socket;
3255 nullptr,
GetTarget().GetPlatform().get(), debugserver_launch_info,
3256 nullptr,
nullptr, communication_fd);
3258 if (
error.Success())
3264#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3267 cleanup_our.release();
3269 std::make_unique<ConnectionFileDescriptor>(our_socket,
true));
3277 LLDB_LOGF(log,
"failed to start debugserver process: %s",
3287 error.SetErrorString(
"connection failed");
3294 std::weak_ptr<ProcessGDBRemote> process_wp,
lldb::pid_t debugserver_pid,
3303 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3304 ", signo=%i (0x%x), exit_status=%i)",
3305 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3307 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3308 LLDB_LOGF(log,
"ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3309 static_cast<void *
>(process_sp.get()));
3310 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3316 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3320 const StateType state = process_sp->GetState();
3324 char error_str[1024];
3326 const char *signal_cstr =
3327 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3329 ::snprintf(error_str,
sizeof(error_str),
3332 ::snprintf(error_str,
sizeof(error_str),
3335 ::snprintf(error_str,
sizeof(error_str),
3340 process_sp->SetExitStatus(-1, error_str);
3356 static llvm::once_flag g_once_flag;
3358 llvm::call_once(g_once_flag, []() {
3367 debugger, PluginProperties::GetSettingName())) {
3368 const bool is_global_setting =
true;
3371 ConstString(
"Properties for the gdb-remote process plug-in."),
3379 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3386 llvm::Expected<HostThread> async_thread =
3390 if (!async_thread) {
3392 "failed to launch host thread: {}");
3398 "ProcessGDBRemote::%s () - Called when Async thread was "
3408 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3423 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3429 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread starting...",
3430 __FUNCTION__,
GetID());
3448 "ProcessGDBRemote::%s(pid = %" PRIu64
3449 ") listener.WaitForEvent (NULL, event_sp)...",
3450 __FUNCTION__,
GetID());
3453 const uint32_t event_type = event_sp->GetType();
3456 "ProcessGDBRemote::%s(pid = %" PRIu64
3457 ") Got an event of type: %d...",
3458 __FUNCTION__,
GetID(), event_type);
3460 switch (event_type) {
3465 if (continue_packet) {
3466 const char *continue_cstr =
3467 (
const char *)continue_packet->
GetBytes();
3468 const size_t continue_cstr_len = continue_packet->
GetByteSize();
3470 "ProcessGDBRemote::%s(pid = %" PRIu64
3471 ") got eBroadcastBitAsyncContinue: %s",
3472 __FUNCTION__,
GetID(), continue_cstr);
3474 if (::strstr(continue_cstr,
"vAttach") ==
nullptr)
3481 llvm::StringRef(continue_cstr, continue_cstr_len),
3492 switch (stop_state) {
3505 int exit_status = response.
GetHexU8();
3506 std::string desc_string;
3508 llvm::StringRef desc_str;
3509 llvm::StringRef desc_token;
3511 if (desc_token !=
"description")
3526 if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3529 "System Integrity Protection");
3530 }
else if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3550 "ProcessGDBRemote::%s(pid = %" PRIu64
3551 ") got eBroadcastBitAsyncThreadShouldExit...",
3552 __FUNCTION__,
GetID());
3558 "ProcessGDBRemote::%s(pid = %" PRIu64
3559 ") got unknown event 0x%8.8x",
3560 __FUNCTION__,
GetID(), event_type);
3567 "ProcessGDBRemote::%s(pid = %" PRIu64
3568 ") listener.WaitForEvent (NULL, event_sp) => false",
3569 __FUNCTION__,
GetID());
3574 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread exiting...",
3575 __FUNCTION__,
GetID());
3607 LLDB_LOGF(log,
"Hit New Thread Notification breakpoint.");
3613 LLDB_LOG(log,
"Check if need to update ignored signals");
3627 LLDB_LOG(log,
"Signals' version hasn't changed. version={0}",
3632 auto signals_to_ignore =
3637 "Signals' version changed. old version={0}, new version={1}, "
3638 "signals ignored={2}, update result={3}",
3640 signals_to_ignore.size(),
error);
3642 if (
error.Success())
3652 LLDB_LOGF(log,
"Enabled noticing new thread breakpoint.");
3655 PlatformSP platform_sp(
GetTarget().GetPlatform());
3658 platform_sp->SetThreadCreationBreakpoint(
GetTarget());
3662 log,
"Successfully created new thread notification breakpoint %i",
3667 LLDB_LOGF(log,
"Failed to create new thread notification breakpoint.");
3677 LLDB_LOGF(log,
"Disabling new thread notification breakpoint.");
3698 if (return_value != 0) {
3700 error.SetErrorString(
"Sending events is not supported for this process.");
3702 error.SetErrorStringWithFormat(
"Error sending event data: %d.",
3713 buf = std::make_shared<DataBufferHeap>(response->c_str(),
3714 response->length());
3731 args_dict->GetAsDictionary()->AddIntegerItem(
"thread", tid);
3734 packet <<
"jThreadExtendedInfo:";
3735 args_dict->Dump(packet,
false);
3742 packet << (char)(0x7d ^ 0x20);
3751 if (!response.
Empty()) {
3765 args_dict->GetAsDictionary()->AddIntegerItem(
"image_list_address",
3766 image_list_address);
3767 args_dict->GetAsDictionary()->AddIntegerItem(
"image_count", image_count);
3775 args_dict->GetAsDictionary()->AddBooleanItem(
"fetch_all_solibs",
true);
3781 const std::vector<lldb::addr_t> &load_addresses) {
3785 for (
auto addr : load_addresses) {
3787 addresses->AddItem(addr_sp);
3790 args_dict->GetAsDictionary()->AddItem(
"solib_addresses", addresses);
3803 std::chrono::seconds(10));
3806 packet <<
"jGetLoadedDynamicLibrariesInfos:";
3807 args_dict->Dump(packet,
false);
3814 packet << (char)(0x7d ^ 0x20);
3823 if (!response.
Empty()) {
3846 if (!response.
Empty()) {
3862 packet <<
"jGetSharedCacheInfo:";
3863 args_dict->Dump(packet,
false);
3870 packet << (char)(0x7d ^ 0x20);
3879 if (!response.
Empty()) {
3904 const uint64_t reasonable_largeish_default = 128 * 1024;
3905 const uint64_t conservative_default = 512;
3909 if (stub_max_size !=
UINT64_MAX && stub_max_size != 0) {
3915 if (stub_max_size > reasonable_largeish_default) {
3916 stub_max_size = reasonable_largeish_default;
3922 if (stub_max_size > 70)
3923 stub_max_size -= 32 + 32 + 6;
3929 log->
Warning(
"Packet size is too small. "
3930 "LLDB may face problems while writing memory");
3941 uint64_t user_specified_max) {
3942 if (user_specified_max != 0) {
3970 module_spec = cached->second;
3971 return bool(module_spec);
3975 LLDB_LOGF(log,
"ProcessGDBRemote::%s - failed to get module info for %s:%s",
3976 __FUNCTION__, module_file_spec.
GetPath().c_str(),
3983 module_spec.
Dump(stream);
3984 LLDB_LOGF(log,
"ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
3985 __FUNCTION__, module_file_spec.
GetPath().c_str(),
3994 llvm::ArrayRef<FileSpec> module_file_specs,
const llvm::Triple &triple) {
3997 for (
const FileSpec &spec : module_file_specs)
4002 triple.getTriple())] = spec;
4016typedef std::vector<std::string> stringVec;
4018typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4019struct RegisterSetInfo {
4023typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4025struct GdbServerTargetInfo {
4029 RegisterSetMap reg_set_map;
4032bool ParseRegisters(
XMLNode feature_node, GdbServerTargetInfo &target_info,
4033 std::vector<DynamicRegisterInfo::Register> ®isters) {
4040 "reg", [&target_info, ®isters, log](
const XMLNode ®_node) ->
bool {
4041 std::string gdb_group;
4042 std::string gdb_type;
4044 bool encoding_set =
false;
4045 bool format_set =
false;
4049 &encoding_set, &format_set, ®_info,
4050 log](
const llvm::StringRef &name,
4051 const llvm::StringRef &value) ->
bool {
4052 if (name ==
"name") {
4054 }
else if (name ==
"bitsize") {
4055 if (llvm::to_integer(value, reg_info.
byte_size))
4057 llvm::divideCeil(reg_info.
byte_size, CHAR_BIT);
4058 }
else if (name ==
"type") {
4059 gdb_type = value.str();
4060 }
else if (name ==
"group") {
4061 gdb_group = value.str();
4062 }
else if (name ==
"regnum") {
4064 }
else if (name ==
"offset") {
4066 }
else if (name ==
"altname") {
4068 }
else if (name ==
"encoding") {
4069 encoding_set =
true;
4071 }
else if (name ==
"format") {
4077 llvm::StringSwitch<lldb::Format>(value)
4088 }
else if (name ==
"group_id") {
4090 llvm::to_integer(value, set_id);
4091 RegisterSetMap::const_iterator pos =
4092 target_info.reg_set_map.find(set_id);
4093 if (pos != target_info.reg_set_map.end())
4094 reg_info.
set_name = pos->second.name;
4095 }
else if (name ==
"gcc_regnum" || name ==
"ehframe_regnum") {
4097 }
else if (name ==
"dwarf_regnum") {
4099 }
else if (name ==
"generic") {
4101 }
else if (name ==
"value_regnums") {
4104 }
else if (name ==
"invalidate_regnums") {
4109 "ProcessGDBRemote::ParseRegisters unhandled reg "
4110 "attribute %s = %s",
4111 name.data(), value.data());
4116 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4117 if (llvm::StringRef(gdb_type).startswith(
"int")) {
4120 }
else if (gdb_type ==
"data_ptr" || gdb_type ==
"code_ptr") {
4123 }
else if (gdb_type ==
"float") {
4126 }
else if (gdb_type ==
"aarch64v" ||
4127 llvm::StringRef(gdb_type).startswith(
"vec") ||
4128 gdb_type ==
"i387_ext" || gdb_type ==
"uint128") {
4136 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4137 "format and encoding for gdb type %s",
4146 if (!gdb_group.empty()) {
4157 "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4160 registers.push_back(reg_info);
4175 ArchSpec &arch_to_use, std::string xml_filename,
4176 std::vector<DynamicRegisterInfo::Register> ®isters) {
4179 if (errorToBool(raw.takeError()))
4184 if (xml_document.
ParseMemory(raw->c_str(), raw->size(),
4185 xml_filename.c_str())) {
4186 GdbServerTargetInfo target_info;
4187 std::vector<XMLNode> feature_nodes;
4193 const XMLNode &node) ->
bool {
4194 llvm::StringRef name = node.
GetName();
4195 if (name ==
"architecture") {
4197 }
else if (name ==
"osabi") {
4199 }
else if (name ==
"xi:include" || name ==
"include") {
4202 target_info.includes.push_back(href);
4203 }
else if (name ==
"feature") {
4204 feature_nodes.push_back(node);
4205 }
else if (name ==
"groups") {
4207 "group", [&target_info](
const XMLNode &node) ->
bool {
4209 RegisterSetInfo set_info;
4212 [&set_id, &set_info](
const llvm::StringRef &name,
4213 const llvm::StringRef &value) ->
bool {
4216 llvm::to_integer(value, set_id);
4223 target_info.reg_set_map[set_id] = set_info;
4236 feature_nodes.push_back(feature_node);
4238 const XMLNode &node) ->
bool {
4239 llvm::StringRef name = node.
GetName();
4240 if (name ==
"xi:include" || name ==
"include") {
4243 target_info.includes.push_back(href);
4257 if (!arch_to_use.
IsValid() && !target_info.arch.empty()) {
4259 arch_to_use.
SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4260 .Case(
"i386:x86-64",
"x86_64")
4261 .Default(target_info.arch) +
4269 for (
auto &feature_node : feature_nodes) {
4270 ParseRegisters(feature_node, target_info,
4274 for (
const auto &include : target_info.includes) {
4286 std::vector<DynamicRegisterInfo::Register> ®isters,
4288 std::map<uint32_t, uint32_t> remote_to_local_map;
4290 for (
auto it : llvm::enumerate(registers)) {
4298 remote_to_local_map[remote_reg_info.
regnum_remote] = it.index();
4304 auto proc_to_lldb = [&remote_to_local_map](
uint32_t process_regnum) {
4305 auto lldb_regit = remote_to_local_map.find(process_regnum);
4306 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4310 llvm::transform(remote_reg_info.value_regs,
4311 remote_reg_info.value_regs.begin(), proc_to_lldb);
4312 llvm::transform(remote_reg_info.invalidate_regs,
4313 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4320 abi_sp->AugmentRegisterInfo(registers);
4336 std::vector<DynamicRegisterInfo::Register> registers;
4347 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4348 "XML parsing not available");
4351 LLDB_LOGF(log,
"ProcessGDBRemote::%s", __FUNCTION__);
4360 llvm::Expected<std::string> raw = comm.
ReadExtFeature(
"libraries-svr4",
"");
4362 return raw.takeError();
4365 LLDB_LOGF(log,
"parsing: %s", raw->c_str());
4368 if (!doc.
ParseMemory(raw->c_str(), raw->size(),
"noname.xml"))
4369 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4370 "Error reading noname.xml");
4374 return llvm::createStringError(
4375 llvm::inconvertibleErrorCode(),
4376 "Error finding library-list-svr4 xml element");
4381 if (!main_lm.empty())
4385 "library", [log, &list](
const XMLNode &library) ->
bool {
4390 [&module](
const llvm::StringRef &name,
4391 const llvm::StringRef &value) ->
bool {
4395 else if (name ==
"lm") {
4397 llvm::to_integer(value, uint_value);
4399 }
else if (name ==
"l_addr") {
4402 llvm::to_integer(value, uint_value);
4407 }
else if (name ==
"l_ld") {
4409 llvm::to_integer(value, uint_value);
4419 bool base_is_offset;
4428 "found (link_map:0x%08" PRIx64
", base:0x%08" PRIx64
4429 "[%s], ld:0x%08" PRIx64
", name:'%s')",
4430 lm, base, (base_is_offset ?
"offset" :
"absolute"), ld,
4440 LLDB_LOGF(log,
"found %" PRId32
" modules in total",
4441 (
int)list.
m_list.size());
4445 llvm::Expected<std::string> raw = comm.
ReadExtFeature(
"libraries",
"");
4448 return raw.takeError();
4450 LLDB_LOGF(log,
"parsing: %s", raw->c_str());
4453 if (!doc.
ParseMemory(raw->c_str(), raw->size(),
"noname.xml"))
4454 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4455 "Error reading noname.xml");
4459 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4460 "Error finding library-list xml element");
4464 "library", [log, &list](
const XMLNode &library) ->
bool {
4477 llvm::to_integer(address, address_value);
4485 bool base_is_offset;
4490 LLDB_LOGF(log,
"found (base:0x%08" PRIx64
"[%s], name:'%s')", base,
4491 (base_is_offset ?
"offset" :
"absolute"), name.c_str());
4500 LLDB_LOGF(log,
"found %" PRId32
" modules in total",
4501 (
int)list.
m_list.size());
4504 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4505 "Remote libraries not supported");
4512 bool value_is_offset) {
4527 return module_list.takeError();
4533 std::string mod_name;
4536 bool mod_base_is_offset;
4539 valid &= modInfo.
get_name(mod_name);
4540 valid &= modInfo.
get_base(mod_base);
4550 lldb::ModuleSP module_sp =
4553 if (module_sp.get())
4554 new_modules.
Append(module_sp);
4557 if (new_modules.
GetSize() > 0) {
4562 for (
size_t i = 0; i < loaded_modules.
GetSize(); ++i) {
4566 for (
size_t j = 0; j < new_modules.
GetSize(); ++j) {
4575 removed_modules.
Append(loaded_module);
4579 loaded_modules.
Remove(removed_modules);
4582 new_modules.
ForEach([&target](
const lldb::ModuleSP module_sp) ->
bool {
4590 lldb::ModuleSP module_copy_sp = module_sp;
4599 return llvm::ErrorSuccess();
4608 std::string file_path = file.
GetPath(
false);
4609 if (file_path.empty())
4610 return Status(
"Empty file name specified");
4619 return Status(
"Sending qFileLoadAddress packet failed");
4630 "Fetching file load address from remote server returned an error");
4640 "Unknown error happened during sending the load address packet");
4661 std::string input = data.str();
4668 size_t found, pos = 0, len = input.length();
4669 while ((found = input.find(
end_delimiter, pos)) != std::string::npos) {
4671 input.substr(pos, found).c_str());
4672 std::string profile_data =
4687 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4689 llvm::raw_string_ostream output_stream(output);
4690 llvm::StringRef name, value;
4694 if (name.compare(
"thread_used_id") == 0) {
4696 uint64_t thread_id = threadIDHexExtractor.
GetHexMaxU64(
false, 0);
4698 bool has_used_usec =
false;
4700 llvm::StringRef usec_name, usec_value;
4703 if (usec_name.equals(
"thread_used_usec")) {
4704 has_used_usec =
true;
4705 usec_value.getAsInteger(0, curr_used_usec);
4709 profileDataExtractor.
SetFilePos(input_file_pos);
4713 if (has_used_usec) {
4715 std::map<uint64_t, uint32_t>::iterator iterator =
4721 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4723 bool good_first_time =
4724 (prev_used_usec == 0) && (real_used_usec > 250000);
4725 bool good_subsequent_time =
4726 (prev_used_usec > 0) &&
4729 if (good_first_time || good_subsequent_time) {
4733 output_stream << name <<
":";
4735 output_stream << index_id <<
";";
4737 output_stream << usec_name <<
":" << usec_value <<
";";
4740 llvm::StringRef local_name, local_value;
4746 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4749 output_stream << name <<
":" << value <<
";";
4752 output_stream << name <<
":" << value <<
";";
4758 return output_stream.str();
4787 return llvm::createStringError(
4788 llvm::inconvertibleErrorCode(),
4789 llvm::formatv(
"qSaveCore returned an error"));
4794 for (
auto x : llvm::split(response.
GetStringRef(),
';')) {
4795 if (x.consume_front(
"core-path:"))
4801 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4802 "qSaveCore returned no core path");
4805 FileSpec remote_core{llvm::StringRef(path)};
4811 platform.
Unlink(remote_core);
4813 return error.ToError();
4819 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4820 "Unable to send qSaveCore");
4833 "GDBRemoteCommunicationClientBase::%s() received $J packet "
4834 "but was not a StructuredData packet: packet starts with "
4848 json_sp->Dump(json_str,
true);
4851 "ProcessGDBRemote::%s() "
4852 "received Async StructuredData packet: %s",
4853 __FUNCTION__, json_str.
GetData());
4856 "ProcessGDBRemote::%s"
4857 "() received StructuredData packet:"
4867 if (structured_data_sp)