9#include "lldb/Host/Config.h"
14#include <netinet/in.h>
16#include <sys/socket.h>
21#include <sys/sysctl.h>
87#include "llvm/ADT/ScopeExit.h"
88#include "llvm/ADT/StringMap.h"
89#include "llvm/ADT/StringSwitch.h"
90#include "llvm/Support/FormatAdapters.h"
91#include "llvm/Support/Threading.h"
92#include "llvm/Support/raw_ostream.h"
94#define DEBUGSERVER_BASENAME "debugserver"
112 llvm::consumeError(file.takeError());
116 ((
Process *)p)->DumpPluginHistory(stream);
122#define LLDB_PROPERTIES_processgdbremote
123#include "ProcessGDBRemoteProperties.inc"
126#define LLDB_PROPERTIES_processgdbremote
127#include "ProcessGDBRemotePropertiesEnum.inc"
132 static llvm::StringRef GetSettingName() {
137 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
138 m_collection_sp->Initialize(g_processgdbremote_properties);
141 ~PluginProperties()
override =
default;
143 uint64_t GetPacketTimeout() {
144 const uint32_t idx = ePropertyPacketTimeout;
145 return GetPropertyAtIndexAs<uint64_t>(
146 idx, g_processgdbremote_properties[idx].default_uint_value);
149 bool SetPacketTimeout(uint64_t timeout) {
150 const uint32_t idx = ePropertyPacketTimeout;
154 FileSpec GetTargetDefinitionFile()
const {
155 const uint32_t idx = ePropertyTargetDefinitionFile;
156 return GetPropertyAtIndexAs<FileSpec>(idx, {});
159 bool GetUseSVR4()
const {
160 const uint32_t idx = ePropertyUseSVR4;
161 return GetPropertyAtIndexAs<bool>(
162 idx, g_processgdbremote_properties[idx].default_uint_value != 0);
165 bool GetUseGPacketForReading()
const {
166 const uint32_t idx = ePropertyUseGPacketForReading;
167 return GetPropertyAtIndexAs<bool>(idx,
true);
174 static PluginProperties g_settings;
182#if defined(__APPLE__)
183#define LOW_PORT (IPPORT_RESERVED)
184#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
186#define LOW_PORT (1024u)
187#define HIGH_PORT (49151u)
191 return "GDB Remote protocol based debugging plug-in.";
200 const FileSpec *crash_file_path,
bool can_connect) {
202 if (crash_file_path ==
nullptr)
203 process_sp = std::shared_ptr<ProcessGDBRemote>(
222 bool plugin_specified_by_name) {
223 if (plugin_specified_by_name)
227 Module *exe_module = target_sp->GetExecutableModulePointer();
231 switch (exe_objfile->
GetType()) {
255 :
Process(target_sp, listener_sp),
257 m_async_broadcaster(nullptr,
"lldb.process.gdb-remote.async-broadcaster"),
259 Listener::MakeListener(
"lldb.process.gdb-remote.async-listener")),
260 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
261 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
262 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
263 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
264 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
265 m_waiting_for_attach(false),
266 m_command_sp(), m_breakpoint_pc_offset(0),
268 m_erased_flash_ranges(), m_vfork_in_progress(false) {
270 "async thread should exit");
272 "async thread continue");
274 "async thread did exit");
278 const uint32_t async_event_mask =
284 "ProcessGDBRemote::%s failed to listen for "
285 "m_async_broadcaster events",
289 const uint64_t timeout_seconds =
291 if (timeout_seconds > 0)
317 const FileSpec &target_definition_fspec) {
323 if (module_object_sp) {
326 "gdb-server-target-definition",
error));
328 if (target_definition_sp) {
330 target_definition_sp->GetValueForKey(
"host-info"));
332 if (
auto host_info_dict = target_object->GetAsDictionary()) {
334 host_info_dict->GetValueForKey(
"triple");
335 if (
auto triple_string_value = triple_value->GetAsString()) {
336 std::string triple_string =
337 std::string(triple_string_value->GetValue());
338 ArchSpec host_arch(triple_string.c_str());
347 target_definition_sp->GetValueForKey(
"breakpoint-pc-offset");
348 if (breakpoint_pc_offset_value) {
349 if (
auto breakpoint_pc_int_value =
350 breakpoint_pc_offset_value->GetAsSignedInteger())
355 *target_definition_sp,
GetTarget().GetArchitecture()) > 0) {
364 const llvm::StringRef &comma_separated_register_numbers,
365 std::vector<uint32_t> ®nums,
int base) {
367 for (llvm::StringRef x : llvm::split(comma_separated_register_numbers,
',')) {
369 if (llvm::to_integer(x, reg, base))
370 regnums.push_back(reg);
372 return regnums.size();
385 if (host_packet_timeout > std::chrono::seconds(0)) {
403 if (target_definition_fspec) {
409 target_definition_fspec.
GetPath() +
420 if (remote_process_arch.
IsValid())
421 arch_to_use = remote_process_arch;
423 arch_to_use = remote_host_arch;
426 arch_to_use = target_arch;
432 std::vector<DynamicRegisterInfo::Register> registers;
433 uint32_t reg_num = 0;
437 const int packet_len =
438 ::snprintf(packet,
sizeof(packet),
"qRegisterInfo%x", reg_num);
439 assert(packet_len < (
int)
sizeof(packet));
446 llvm::StringRef name;
447 llvm::StringRef value;
451 if (name.equals(
"name")) {
453 }
else if (name.equals(
"alt-name")) {
455 }
else if (name.equals(
"bitsize")) {
456 if (!value.getAsInteger(0, reg_info.
byte_size))
458 }
else if (name.equals(
"offset")) {
460 }
else if (name.equals(
"encoding")) {
464 }
else if (name.equals(
"format")) {
468 llvm::StringSwitch<Format>(value)
483 }
else if (name.equals(
"set")) {
485 }
else if (name.equals(
"gcc") || name.equals(
"ehframe")) {
487 }
else if (name.equals(
"dwarf")) {
489 }
else if (name.equals(
"generic")) {
491 }
else if (name.equals(
"container-regs")) {
493 }
else if (name.equals(
"invalidate-regs")) {
499 registers.push_back(reg_info);
508 if (registers.empty())
523 bool wait_for_launch) {
568 error.SetErrorStringWithFormat(
569 "Process %" PRIu64
" was reported after connecting to "
570 "'%s', but state was not stopped: %s",
573 error.SetErrorStringWithFormat(
"Process %" PRIu64
574 " was reported after connecting to '%s', "
575 "but no stop reply packet was received",
576 pid, remote_url.str().c_str());
580 "ProcessGDBRemote::%s pid %" PRIu64
581 ": normalizing target architecture initial triple: %s "
582 "(GetTarget().GetArchitecture().IsValid() %s, "
583 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
584 __FUNCTION__,
GetID(),
585 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
600 "ProcessGDBRemote::%s pid %" PRIu64
601 ": normalized target architecture triple: %s",
602 __FUNCTION__,
GetID(),
603 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
620 LLDB_LOGF(log,
"ProcessGDBRemote::%s() entered", __FUNCTION__);
622 uint32_t launch_flags = launch_info.
GetFlags().
Get();
646 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
648 "ProcessGDBRemote::%s provided with STDIO paths via "
649 "launch_info: stdin=%s, stdout=%s, stderr=%s",
651 stdin_file_spec ? stdin_file_spec.GetPath().c_str() :
"<null>",
652 stdout_file_spec ? stdout_file_spec.GetPath().c_str() :
"<null>",
653 stderr_file_spec ? stderr_file_spec.GetPath().c_str() :
"<null>");
656 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
660 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
661 if (stdin_file_spec || disable_stdio) {
676 if (
error.Success()) {
678 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
683 if (!stdin_file_spec)
685 FileSpec::Style::native);
686 if (!stdout_file_spec)
688 FileSpec::Style::native);
689 if (!stderr_file_spec)
691 FileSpec::Style::native);
692 }
else if (platform_sp && platform_sp->IsHost()) {
697 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
701 if (!stdin_file_spec)
702 stdin_file_spec = secondary_name;
704 if (!stdout_file_spec)
705 stdout_file_spec = secondary_name;
707 if (!stderr_file_spec)
708 stderr_file_spec = secondary_name;
712 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
713 "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
716 stdin_file_spec ? stdin_file_spec.GetPath().c_str() :
"<null>",
717 stdout_file_spec ? stdout_file_spec.GetPath().c_str() :
"<null>",
718 stderr_file_spec ? stderr_file_spec.GetPath().c_str() :
"<null>");
722 "ProcessGDBRemote::%s final STDIO paths after all "
723 "adjustments: stdin=%s, stdout=%s, stderr=%s",
725 stdin_file_spec ? stdin_file_spec.GetPath().c_str() :
"<null>",
726 stdout_file_spec ? stdout_file_spec.GetPath().c_str() :
"<null>",
727 stderr_file_spec ? stderr_file_spec.GetPath().c_str() :
"<null>");
731 if (stdout_file_spec)
733 if (stderr_file_spec)
740 GetTarget().GetArchitecture().GetArchitectureName());
743 if (launch_event_data !=
nullptr && *launch_event_data !=
'\0')
756 std::chrono::seconds(10));
764 error.SetErrorStringWithFormatv(
"Cannot launch '{0}': {1}",
766 llvm::fmt_consume(std::move(err)));
773 LLDB_LOGF(log,
"failed to connect to debugserver: %s",
795 if (!disable_stdio) {
801 LLDB_LOGF(log,
"failed to connect to debugserver: %s",
error.AsCString());
811 if (!connect_url.empty()) {
812 LLDB_LOGF(log,
"ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
813 connect_url.str().c_str());
814 std::unique_ptr<ConnectionFileDescriptor> conn_up(
817 const uint32_t max_retry_count = 50;
818 uint32_t retry_count = 0;
827 if (retry_count >= max_retry_count)
830 std::this_thread::sleep_for(std::chrono::milliseconds(100));
837 error.SetErrorString(
"not connected to remote gdb server");
848 error.SetErrorString(
"not connected to remote gdb server");
861 auto handle_cmds = [&] (
const Args &args) ->
void {
865 entry.c_str(), response);
871 handle_cmds(platform_sp->GetExtraStartupCommands());
888 if (remote_process_arch.
IsValid()) {
889 process_arch = remote_process_arch;
890 LLDB_LOG(log,
"gdb-remote had process architecture, using {0} {1}",
896 "gdb-remote did not have process architecture, using gdb-remote "
897 "host architecture {0} {1}",
908 LLDB_LOG(log,
"analyzing target arch, currently {0} {1}",
920 if ((process_arch.
GetMachine() == llvm::Triple::arm ||
921 process_arch.
GetMachine() == llvm::Triple::thumb) &&
922 process_arch.
GetTriple().getVendor() == llvm::Triple::Apple) {
925 "remote process is ARM/Apple, "
926 "setting target arch to {0} {1}",
931 const llvm::Triple &remote_triple = process_arch.
GetTriple();
932 llvm::Triple new_target_triple = target_arch.
GetTriple();
933 if (new_target_triple.getVendorName().size() == 0) {
934 new_target_triple.setVendor(remote_triple.getVendor());
936 if (new_target_triple.getOSName().size() == 0) {
937 new_target_triple.setOS(remote_triple.getOS());
939 if (new_target_triple.getEnvironmentName().size() == 0)
940 new_target_triple.setEnvironment(remote_triple.getEnvironment());
943 ArchSpec new_target_arch = target_arch;
944 new_target_arch.
SetTriple(new_target_triple);
950 "final target arch after adjustments for remote architecture: "
978 if (platform_sp && platform_sp->IsConnected())
990 UUID standalone_uuid;
992 bool standalone_value_is_offset;
994 standalone_value_is_offset)) {
997 if (standalone_uuid.
IsValid()) {
998 const bool force_symbol_search =
true;
999 const bool notify =
true;
1000 const bool set_address_in_target =
true;
1001 const bool allow_memory_image_last_resort =
false;
1003 this,
"", standalone_uuid, standalone_value,
1004 standalone_value_is_offset, force_symbol_search, notify,
1005 set_address_in_target, allow_memory_image_last_resort);
1018 if (bin_addrs.size()) {
1020 const bool value_is_slide =
false;
1021 for (
addr_t addr : bin_addrs) {
1022 const bool notify =
true;
1029 .LoadPlatformBinaryAndSetup(
this, addr, notify))
1032 const bool force_symbol_search =
true;
1033 const bool set_address_in_target =
true;
1034 const bool allow_memory_image_last_resort =
false;
1037 this, llvm::StringRef(), uuid, addr, value_is_slide,
1038 force_symbol_search, notify, set_address_in_target,
1039 allow_memory_image_last_resort);
1054 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1055 offsets->offsets.size();
1059 bool changed =
false;
1060 module_sp->SetLoadAddress(
GetTarget(), offsets->offsets[0],
1079 LLDB_LOGF(log,
"ProcessGDBRemote::%s()", __FUNCTION__);
1085 if (
error.Success()) {
1089 const int packet_len =
1090 ::snprintf(packet,
sizeof(packet),
"vAttach;%" PRIx64, attach_pid);
1107 if (process_name && process_name[0]) {
1109 if (
error.Success()) {
1152llvm::Expected<std::string>
1157llvm::Expected<std::vector<uint8_t>>
1169 process_arch.
Clear();
1186 LLDB_LOGF(log,
"ProcessGDBRemote::Resume()");
1190 if (listener_sp->StartListeningForEvents(
1192 listener_sp->StartListeningForEvents(
1199 bool continue_packet_error =
false;
1201 std::string pid_prefix;
1203 pid_prefix = llvm::formatv(
"p{0:x-}.",
GetID());
1210 continue_packet.
Format(
"vCont;c:{0}-1", pid_prefix);
1218 for (tid_collection::const_iterator
1221 t_pos != t_end; ++t_pos)
1222 continue_packet.
Format(
";c:{0}{1:x-}", pid_prefix, *t_pos);
1224 continue_packet_error =
true;
1229 for (tid_sig_collection::const_iterator
1232 s_pos != s_end; ++s_pos)
1233 continue_packet.
Format(
";C{0:x-2}:{1}{2:x-}", s_pos->second,
1234 pid_prefix, s_pos->first);
1236 continue_packet_error =
true;
1241 for (tid_collection::const_iterator
1244 t_pos != t_end; ++t_pos)
1245 continue_packet.
Format(
";s:{0}{1:x-}", pid_prefix, *t_pos);
1247 continue_packet_error =
true;
1252 for (tid_sig_collection::const_iterator
1255 s_pos != s_end; ++s_pos)
1256 continue_packet.
Format(
";S{0:x-2}:{1}{2:x-}", s_pos->second,
1257 pid_prefix, s_pos->first);
1259 continue_packet_error =
true;
1262 if (continue_packet_error)
1263 continue_packet.
Clear();
1266 continue_packet_error =
true;
1268 if (continue_packet_error) {
1276 if (num_continue_c_tids > 0) {
1277 if (num_continue_c_tids == num_threads) {
1281 continue_packet_error =
false;
1282 }
else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1283 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1287 continue_packet_error =
false;
1291 if (continue_packet_error && num_continue_C_tids > 0) {
1292 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1293 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1294 num_continue_S_tids == 0) {
1297 if (num_continue_C_tids > 1) {
1302 if (num_continue_C_tids > 1) {
1303 continue_packet_error =
false;
1306 continue_packet_error =
true;
1309 if (!continue_packet_error)
1313 continue_packet_error =
false;
1316 if (!continue_packet_error) {
1318 continue_packet.
Printf(
"C%2.2x", continue_signo);
1323 if (continue_packet_error && num_continue_s_tids > 0) {
1324 if (num_continue_s_tids == num_threads) {
1330 continue_packet_error =
false;
1331 }
else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1332 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1336 continue_packet_error =
false;
1340 if (!continue_packet_error && num_continue_S_tids > 0) {
1341 if (num_continue_S_tids == num_threads) {
1344 continue_packet_error =
false;
1345 if (num_continue_S_tids > 1) {
1346 for (
size_t i = 1; i < num_threads; ++i) {
1348 continue_packet_error =
true;
1351 if (!continue_packet_error) {
1354 continue_packet.
Printf(
"S%2.2x", step_signo);
1356 }
else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1357 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1361 continue_packet_error =
false;
1366 if (continue_packet_error) {
1367 error.SetErrorString(
"can't make continue packet for this resume");
1371 error.SetErrorString(
"Trying to resume but the async thread is dead.");
1372 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Trying to resume but the "
1373 "async thread is dead.");
1382 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1383 error.SetErrorString(
"Resume timed out.");
1384 LLDB_LOGF(log,
"ProcessGDBRemote::DoResume: Resume timed out.");
1386 error.SetErrorString(
"Broadcast continue, but the async thread was "
1387 "killed before we got an ack back.");
1389 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1390 "async thread was killed before we got an ack back.");
1406 llvm::StringRef value) {
1412 auto pid_tid = thread_ids.
GetPidTid(pid);
1413 if (pid_tid && pid_tid->first == pid) {
1419 }
while (thread_ids.GetChar() ==
',');
1425 llvm::StringRef value) {
1427 for (llvm::StringRef x : llvm::split(value,
',')) {
1429 if (llvm::to_integer(x,
pc, 16))
1441 if (thread_infos && thread_infos->
GetSize() > 0) {
1465 const std::string &stop_info_str = std::string(stop_info.
GetStringRef());
1468 const size_t thread_pcs_pos = stop_info_str.find(
";thread-pcs:");
1469 if (thread_pcs_pos != std::string::npos) {
1470 const size_t start = thread_pcs_pos + strlen(
";thread-pcs:");
1471 const size_t end = stop_info_str.find(
';', start);
1472 if (end != std::string::npos) {
1473 std::string value = stop_info_str.substr(start, end - start);
1478 const size_t threads_pos = stop_info_str.find(
";threads:");
1479 if (threads_pos != std::string::npos) {
1480 const size_t start = threads_pos + strlen(
";threads:");
1481 const size_t end = stop_info_str.find(
';', start);
1482 if (end != std::string::npos) {
1483 std::string value = stop_info_str.substr(start, end - start);
1491 bool sequence_mutex_unavailable =
false;
1493 if (sequence_mutex_unavailable) {
1508 if (num_thread_ids == 0) {
1514 ThreadList old_thread_list_copy(old_thread_list);
1515 if (num_thread_ids > 0) {
1516 for (
size_t i = 0; i < num_thread_ids; ++i) {
1521 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1522 LLDB_LOGV(log,
"Making new thread: {0} for thread ID: {1:x}.",
1523 thread_sp.get(), thread_sp->GetID());
1525 LLDB_LOGV(log,
"Found old thread: {0} for thread ID: {1:x}.",
1526 thread_sp.get(), thread_sp->GetID());
1536 size_t old_num_thread_ids = old_thread_list_copy.
GetSize(
false);
1537 for (
size_t i = 0; i < old_num_thread_ids; i++) {
1539 if (old_thread_sp) {
1540 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1555 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1568 if (thread_infos_sp) {
1572 const size_t n = thread_infos->
GetSize();
1573 for (
size_t i = 0; i < n; ++i) {
1579 if (tid == thread->
GetID())
1617 uint8_t signo,
const std::string &thread_name,
const std::string &reason,
1618 const std::string &description, uint32_t exc_type,
1619 const std::vector<addr_t> &exc_data,
addr_t thread_dispatch_qaddr,
1620 bool queue_vars_valid,
1622 LazyBool associated_with_dispatch_queue,
addr_t dispatch_queue_t,
1623 std::string &queue_name,
QueueKind queue_kind, uint64_t queue_serial) {
1639 thread_sp = std::make_shared<ThreadGDBRemote>(*
this, tid);
1647 gdb_reg_ctx_sp->InvalidateIfNeeded(
true);
1653 for (
const auto &pair : expedited_register_map) {
1657 reg_value_extractor.
GetHexBytes(buffer_sp->GetData(),
'\xcc');
1658 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1677 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1682 if (queue_vars_valid)
1683 gdb_thread->
SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1684 dispatch_queue_t, associated_with_dispatch_queue);
1695 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(
false);
1697 current_stop_info_sp) {
1698 thread_sp->SetStopInfo(current_stop_info_sp);
1702 if (!thread_sp->StopInfoIsUpToDate()) {
1707 thread_sp = memory_thread_sp;
1709 if (exc_type != 0) {
1710 const size_t exc_data_size = exc_data.size();
1712 thread_sp->SetStopInfo(
1714 *thread_sp, exc_type, exc_data_size,
1715 exc_data_size >= 1 ? exc_data[0] : 0,
1716 exc_data_size >= 2 ? exc_data[1] : 0,
1717 exc_data_size >= 3 ? exc_data[2] : 0));
1719 bool handled =
false;
1720 bool did_exec =
false;
1721 if (!reason.empty()) {
1722 if (reason ==
"trace") {
1723 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1725 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1730 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1731 thread_sp->SetStopInfo(
1733 *thread_sp, bp_site_sp->GetID()));
1735 thread_sp->SetStopInfo(
1738 }
else if (reason ==
"breakpoint") {
1739 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1741 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1750 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1751 thread_sp->SetStopInfo(
1753 *thread_sp, bp_site_sp->GetID()));
1756 thread_sp->SetStopInfo(invalid_stop_info_sp);
1759 }
else if (reason ==
"trap") {
1761 }
else if (reason ==
"watchpoint") {
1793 bool silently_continue =
false;
1802 silently_continue =
true;
1807 wp_sp->SetHardwareIndex(wp_index);
1808 watch_id = wp_sp->GetID();
1812 LLDB_LOGF(log,
"failed to find watchpoint");
1815 *thread_sp, watch_id, silently_continue));
1817 }
else if (reason ==
"exception") {
1819 *thread_sp, description.c_str()));
1821 }
else if (reason ==
"exec") {
1823 thread_sp->SetStopInfo(
1826 }
else if (reason ==
"processor trace") {
1828 *thread_sp, description.c_str()));
1829 }
else if (reason ==
"fork") {
1834 thread_sp->SetStopInfo(
1837 }
else if (reason ==
"vfork") {
1843 *thread_sp, child_pid, child_tid));
1845 }
else if (reason ==
"vforkdone") {
1846 thread_sp->SetStopInfo(
1850 }
else if (!signo) {
1851 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1853 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
pc);
1860 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1862 *thread_sp, bp_site_sp->GetID()));
1867 if (!handled && signo && !did_exec) {
1875 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1884 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1886 thread_sp->GetRegisterContext()->SetPC(
pc);
1887 thread_sp->SetStopInfo(
1889 *thread_sp, bp_site_sp->GetID()));
1892 thread_sp->SetStopInfo(invalid_stop_info_sp);
1900 thread_sp->SetStopInfo(
1904 *thread_sp, signo, description.c_str()));
1909 *thread_sp, signo, description.c_str()));
1912 if (!description.empty()) {
1915 const char *stop_info_desc = stop_info_sp->GetDescription();
1916 if (!stop_info_desc || !stop_info_desc[0])
1917 stop_info_sp->SetDescription(description.c_str());
1920 *thread_sp, description.c_str()));
1930 static constexpr llvm::StringLiteral g_key_tid(
"tid");
1931 static constexpr llvm::StringLiteral g_key_name(
"name");
1932 static constexpr llvm::StringLiteral g_key_reason(
"reason");
1933 static constexpr llvm::StringLiteral g_key_metype(
"metype");
1934 static constexpr llvm::StringLiteral g_key_medata(
"medata");
1935 static constexpr llvm::StringLiteral g_key_qaddr(
"qaddr");
1936 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
1937 "dispatch_queue_t");
1938 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
1939 "associated_with_dispatch_queue");
1940 static constexpr llvm::StringLiteral g_key_queue_name(
"qname");
1941 static constexpr llvm::StringLiteral g_key_queue_kind(
"qkind");
1942 static constexpr llvm::StringLiteral g_key_queue_serial_number(
"qserialnum");
1943 static constexpr llvm::StringLiteral g_key_registers(
"registers");
1944 static constexpr llvm::StringLiteral g_key_memory(
"memory");
1945 static constexpr llvm::StringLiteral g_key_description(
"description");
1946 static constexpr llvm::StringLiteral g_key_signal(
"signal");
1952 std::string thread_name;
1954 std::string description;
1955 uint32_t exc_type = 0;
1956 std::vector<addr_t> exc_data;
1959 bool queue_vars_valid =
false;
1962 std::string queue_name;
1964 uint64_t queue_serial_number = 0;
1969 thread_dict->
ForEach([
this, &tid, &expedited_register_map, &thread_name,
1970 &signo, &reason, &description, &exc_type, &exc_data,
1971 &thread_dispatch_qaddr, &queue_vars_valid,
1972 &associated_with_dispatch_queue, &dispatch_queue_t,
1973 &queue_name, &queue_kind, &queue_serial_number](
1974 llvm::StringRef key,
1976 if (key == g_key_tid) {
1979 }
else if (key == g_key_metype) {
1981 exc_type =
object->GetUnsignedIntegerValue(0);
1982 }
else if (key == g_key_medata) {
1991 }
else if (key == g_key_name) {
1993 }
else if (key == g_key_qaddr) {
1994 thread_dispatch_qaddr =
1996 }
else if (key == g_key_queue_name) {
1997 queue_vars_valid =
true;
1999 }
else if (key == g_key_queue_kind) {
2000 std::string queue_kind_str = std::string(object->
GetStringValue());
2001 if (queue_kind_str ==
"serial") {
2002 queue_vars_valid =
true;
2004 }
else if (queue_kind_str ==
"concurrent") {
2005 queue_vars_valid =
true;
2008 }
else if (key == g_key_queue_serial_number) {
2009 queue_serial_number =
object->GetUnsignedIntegerValue(0);
2010 if (queue_serial_number != 0)
2011 queue_vars_valid =
true;
2012 }
else if (key == g_key_dispatch_queue_t) {
2013 dispatch_queue_t =
object->GetUnsignedIntegerValue(0);
2015 queue_vars_valid =
true;
2016 }
else if (key == g_key_associated_with_dispatch_queue) {
2017 queue_vars_valid =
true;
2018 bool associated =
object->GetBooleanValue();
2023 }
else if (key == g_key_reason) {
2025 }
else if (key == g_key_description) {
2027 }
else if (key == g_key_registers) {
2030 if (registers_dict) {
2032 [&expedited_register_map](llvm::StringRef key,
2035 if (llvm::to_integer(key, reg))
2036 expedited_register_map[reg] =
2041 }
else if (key == g_key_memory) {
2047 if (mem_cache_dict) {
2050 "address", mem_cache_addr)) {
2051 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2052 llvm::StringRef str;
2053 if (mem_cache_dict->GetValueForKeyAsString(
"bytes", str)) {
2054 StringExtractor bytes(str);
2055 bytes.SetFilePos(0);
2057 const size_t byte_size = bytes.GetStringRef().size() / 2;
2058 WritableDataBufferSP data_buffer_sp(
2059 new DataBufferHeap(byte_size, 0));
2060 const size_t bytes_copied =
2061 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2062 if (bytes_copied == byte_size)
2063 m_memory_cache.AddL1CacheData(mem_cache_addr,
2073 }
else if (key == g_key_signal)
2078 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2079 reason, description, exc_type, exc_data,
2080 thread_dispatch_qaddr, queue_vars_valid,
2081 associated_with_dispatch_queue, dispatch_queue_t,
2082 queue_name, queue_kind, queue_serial_number);
2088 const char stop_type = stop_packet.
GetChar();
2089 switch (stop_type) {
2108 const uint8_t signo = stop_packet.
GetHexU8();
2109 llvm::StringRef key;
2110 llvm::StringRef value;
2111 std::string thread_name;
2113 std::string description;
2114 uint32_t exc_type = 0;
2115 std::vector<addr_t> exc_data;
2117 bool queue_vars_valid =
2121 std::string queue_name;
2123 uint64_t queue_serial_number = 0;
2127 if (key.compare(
"metype") == 0) {
2129 value.getAsInteger(16, exc_type);
2130 }
else if (key.compare(
"medata") == 0) {
2133 value.getAsInteger(16, x);
2134 exc_data.push_back(x);
2135 }
else if (key.compare(
"thread") == 0) {
2138 auto pid_tid = thread_id.
GetPidTid(pid);
2140 stop_pid = pid_tid->first;
2141 tid = pid_tid->second;
2144 }
else if (key.compare(
"threads") == 0) {
2145 std::lock_guard<std::recursive_mutex> guard(
2148 }
else if (key.compare(
"thread-pcs") == 0) {
2153 while (!value.empty()) {
2154 llvm::StringRef pc_str;
2155 std::tie(pc_str, value) = value.split(
',');
2156 if (pc_str.getAsInteger(16,
pc))
2160 }
else if (key.compare(
"jstopinfo") == 0) {
2169 }
else if (key.compare(
"hexname") == 0) {
2174 }
else if (key.compare(
"name") == 0) {
2175 thread_name = std::string(value);
2176 }
else if (key.compare(
"qaddr") == 0) {
2177 value.getAsInteger(16, thread_dispatch_qaddr);
2178 }
else if (key.compare(
"dispatch_queue_t") == 0) {
2179 queue_vars_valid =
true;
2180 value.getAsInteger(16, dispatch_queue_t);
2181 }
else if (key.compare(
"qname") == 0) {
2182 queue_vars_valid =
true;
2186 }
else if (key.compare(
"qkind") == 0) {
2187 queue_kind = llvm::StringSwitch<QueueKind>(value)
2192 }
else if (key.compare(
"qserialnum") == 0) {
2193 if (!value.getAsInteger(0, queue_serial_number))
2194 queue_vars_valid =
true;
2195 }
else if (key.compare(
"reason") == 0) {
2196 reason = std::string(value);
2197 }
else if (key.compare(
"description") == 0) {
2201 }
else if (key.compare(
"memory") == 0) {
2215 llvm::StringRef addr_str, bytes_str;
2216 std::tie(addr_str, bytes_str) = value.split(
'=');
2217 if (!addr_str.empty() && !bytes_str.empty()) {
2219 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2224 const size_t bytes_copied =
2226 if (bytes_copied == byte_size)
2230 }
else if (key.compare(
"watch") == 0 || key.compare(
"rwatch") == 0 ||
2231 key.compare(
"awatch") == 0) {
2234 value.getAsInteger(16, wp_addr);
2241 wp_index = wp_sp->GetHardwareIndex();
2246 reason =
"watchpoint";
2248 ostr.
Printf(
"%" PRIu64
" %" PRIu32, wp_addr, wp_index);
2249 description = std::string(ostr.
GetString());
2250 }
else if (key.compare(
"library") == 0) {
2256 }
else if (key.compare(
"fork") == 0 || key.compare(
"vfork") == 0) {
2262 LLDB_LOG(log,
"Invalid PID/TID to fork: {0}", value);
2268 ostr.
Printf(
"%" PRIu64
" %" PRIu64, pid_tid->first, pid_tid->second);
2269 description = std::string(ostr.
GetString());
2270 }
else if (key.compare(
"addressing_bits") == 0) {
2271 uint64_t addressing_bits;
2272 if (!value.getAsInteger(0, addressing_bits)) {
2275 }
else if (key.compare(
"low_mem_addressing_bits") == 0) {
2276 uint64_t addressing_bits;
2277 if (!value.getAsInteger(0, addressing_bits)) {
2280 }
else if (key.compare(
"high_mem_addressing_bits") == 0) {
2281 uint64_t addressing_bits;
2282 if (!value.getAsInteger(0, addressing_bits)) {
2285 }
else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2287 if (!key.getAsInteger(16, reg))
2288 expedited_register_map[reg] = std::string(std::move(value));
2295 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2315 tid, expedited_register_map, signo, thread_name, reason, description,
2316 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2317 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2318 queue_kind, queue_serial_number);
2383 LLDB_LOGF(log,
"ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2387 if (
error.Success())
2389 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2392 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2393 error.AsCString() ?
error.AsCString() :
"<unknown error>");
2396 if (!
error.Success())
2411 LLDB_LOGF(log,
"ProcessGDBRemote::DoDestroy()");
2414 int exit_status = SIGABRT;
2415 std::string exit_string;
2422 exit_status = kill_res.get();
2423#if defined(__APPLE__)
2435 if (platform_sp && platform_sp->IsHost()) {
2438 reap_pid = waitpid(
GetID(), &status, WNOHANG);
2439 LLDB_LOGF(log,
"Reaped pid: %d, status: %d.\n", reap_pid, status);
2443 exit_string.assign(
"killed");
2445 exit_string.assign(llvm::toString(kill_res.takeError()));
2448 exit_string.assign(
"killed or interrupted while attaching.");
2454 exit_string.assign(
"destroying when not connected to debugserver");
2466 const bool did_exec =
2467 response.
GetStringRef().find(
";reason:exec;") != std::string::npos;
2470 LLDB_LOGF(log,
"ProcessGDBRemote::SetLastStopPacket () - detected exec");
2500 LLDB_LOG_ERROR(log, list.takeError(),
"Failed to read module list: {0}.");
2502 addr = list->m_link_map;
2522 const size_t n = thread_infos->
GetSize();
2523 for (
size_t i = 0; i < n; ++i) {
2539 size_t max_memory_size =
2541 if (size > max_memory_size) {
2545 size = max_memory_size;
2550 packet_len = ::snprintf(packet,
sizeof(packet),
"%c%" PRIx64
",%" PRIx64,
2551 binary_memory_read ?
'x' :
'm', (uint64_t)addr,
2553 assert(packet_len + 1 < (
int)
sizeof(packet));
2561 if (binary_memory_read) {
2567 if (data_received_size > size) {
2570 data_received_size = size;
2572 memcpy(buf, response.
GetStringRef().data(), data_received_size);
2573 return data_received_size;
2576 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size),
'\xdd');
2579 error.SetErrorStringWithFormat(
"memory read failed for 0x%" PRIx64, addr);
2581 error.SetErrorStringWithFormat(
2582 "GDB server does not support reading memory");
2584 error.SetErrorStringWithFormat(
2585 "unexpected response to GDB server memory read packet '%s': '%s'",
2588 error.SetErrorStringWithFormat(
"failed to send packet: '%s'", packet);
2597llvm::Expected<std::vector<uint8_t>>
2604 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2605 "Error reading memory tags from remote");
2609 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2610 std::vector<uint8_t> got;
2611 got.reserve(tag_data.size());
2612 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2618 const std::vector<uint8_t> &tags) {
2625 std::vector<ObjectFile::LoadableData> entries) {
2630 std::begin(entries), std::end(entries),
2636 if (
error.Success())
2650 for (
size_t i = 0; i < size; ++i)
2669 status.
SetErrorString(
"Unable to erase flash in multiple regions");
2674 if (blocksize == 0) {
2675 status.
SetErrorString(
"Unable to erase flash because blocksize is 0");
2681 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2682 size += (addr - block_start_addr);
2683 if ((size % blocksize) != 0)
2684 size += (blocksize - size % blocksize);
2726 "unexpected response to GDB server flash erase packet '%s': '%s'",
2755 "unexpected response to GDB server flash done packet: '%s'",
2769 if (size > max_memory_size) {
2773 size = max_memory_size;
2786 error.SetErrorString(
"Writing to flash memory is not allowed");
2794 if (!
error.Success())
2796 packet.
Printf(
"vFlashWrite:%" PRIx64
":", addr);
2799 packet.
Printf(
"M%" PRIx64
",%" PRIx64
":", addr, (uint64_t)size);
2811 error.SetErrorStringWithFormat(
"memory write failed for 0x%" PRIx64,
2814 error.SetErrorStringWithFormat(
2815 "GDB server does not support writing memory");
2817 error.SetErrorStringWithFormat(
2818 "unexpected response to GDB server memory write packet '%s': '%s'",
2821 error.SetErrorStringWithFormat(
"failed to send packet: '%s'",
2828 uint32_t permissions,
2837 return allocated_addr;
2843 if (permissions & lldb::ePermissionsReadable)
2845 if (permissions & lldb::ePermissionsWritable)
2847 if (permissions & lldb::ePermissionsExecutable)
2856 "ProcessGDBRemote::%s no direct stub support for memory "
2857 "allocation, and InferiorCallMmap also failed - is stub "
2858 "missing register context save/restore capability?",
2864 error.SetErrorStringWithFormat(
2865 "unable to allocate %" PRIu64
" bytes of memory with permissions %s",
2869 return allocated_addr;
2891 switch (supported) {
2895 error.SetErrorString(
2896 "tried to deallocate memory without ever allocating memory");
2901 error.SetErrorStringWithFormat(
2902 "unable to deallocate memory at 0x%" PRIx64, addr);
2913 error.SetErrorStringWithFormat(
2914 "unable to deallocate memory at 0x%" PRIx64, addr);
2936 assert(bp_site !=
nullptr);
2947 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2948 ") address = 0x%" PRIx64,
2949 site_id, (uint64_t)addr);
2954 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2955 ") address = 0x%" PRIx64
" -- SUCCESS (already enabled)",
2956 site_id, (uint64_t)addr);
2977 if (error_no == 0) {
2993 if (error_no != UINT8_MAX)
2994 error.SetErrorStringWithFormat(
2995 "error: %d sending the breakpoint request", error_no);
2997 error.SetErrorString(
"error sending the breakpoint request");
3004 LLDB_LOGF(log,
"Software breakpoints are unsupported");
3017 if (error_no == 0) {
3028 if (error_no != UINT8_MAX)
3029 error.SetErrorStringWithFormat(
3030 "error: %d sending the hardware breakpoint request "
3031 "(hardware breakpoint resources might be exhausted or unavailable)",
3034 error.SetErrorString(
"error sending the hardware breakpoint request "
3035 "(hardware breakpoint resources "
3036 "might be exhausted or unavailable)");
3042 LLDB_LOGF(log,
"Hardware breakpoints are unsupported");
3049 error.SetErrorString(
"hardware breakpoints are not supported");
3060 assert(bp_site !=
nullptr);
3065 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3066 ") addr = 0x%8.8" PRIx64,
3067 site_id, (uint64_t)addr);
3082 error.SetErrorToGenericError();
3089 error.SetErrorToGenericError();
3092 if (
error.Success())
3096 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3097 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3098 site_id, (uint64_t)addr);
3102 if (
error.Success())
3103 error.SetErrorToGenericError();
3115 assert((watch_read || watch_write || watch_modify) &&
3116 "watch_read, watch_write, watch_modify cannot all be false.");
3117 if (watch_read && (watch_write || watch_modify))
3119 else if (watch_read)
3131 LLDB_LOGF(log,
"ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
")",
3135 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3136 ") addr = 0x%8.8" PRIx64
": watchpoint already enabled.",
3137 watchID, (uint64_t)addr);
3150 error.SetErrorString(
"sending gdb watchpoint packet failed");
3152 error.SetErrorString(
"watchpoints not supported");
3154 error.SetErrorString(
"Watchpoint argument was NULL.");
3156 if (
error.Success())
3157 error.SetErrorToGenericError();
3171 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3172 ") addr = 0x%8.8" PRIx64,
3173 watchID, (uint64_t)addr);
3177 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3178 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3179 watchID, (uint64_t)addr);
3196 error.SetErrorString(
"sending gdb watchpoint packet failed");
3200 error.SetErrorString(
"Watchpoint argument was NULL.");
3202 if (
error.Success())
3203 error.SetErrorToGenericError();
3215 LLDB_LOGF(log,
"ProcessGDBRemote::DoSignal (signal = %d)", signo);
3218 error.SetErrorStringWithFormat(
"failed to send signal %i", signo);
3229 if (platform_sp && !platform_sp->IsHost())
3230 return Status(
"Lost debug server connection");
3234 const char *error_string =
error.AsCString();
3235 if (error_string ==
nullptr)
3241#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3244#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3246#if defined(FD_CLOEXEC)
3247 int flags = ::fcntl(fd, F_GETFD);
3250 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3259 using namespace std::placeholders;
3264 static FileSpec g_debugserver_file_spec;
3271 const std::weak_ptr<ProcessGDBRemote> this_wp =
3272 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3277#if defined(__APPLE__)
3281 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3283 struct kinfo_proc processInfo;
3284 size_t bufsize =
sizeof(processInfo);
3285 if (sysctl(mib, (
unsigned)(
sizeof(mib)/
sizeof(
int)), &processInfo,
3286 &bufsize, NULL, 0) == 0 && bufsize > 0) {
3287 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3288 FileSpec rosetta_debugserver(
"/Library/Apple/usr/libexec/oah/debugserver");
3294 int communication_fd = -1;
3295#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3299 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3300 error.SetErrorToErrno();
3304 int our_socket = sockets[0];
3305 int gdb_socket = sockets[1];
3306 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3307 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3311 communication_fd = gdb_socket;
3315 nullptr,
GetTarget().GetPlatform().get(), debugserver_launch_info,
3316 nullptr,
nullptr, communication_fd);
3318 if (
error.Success())
3324#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3327 cleanup_our.release();
3329 std::make_unique<ConnectionFileDescriptor>(our_socket,
true));
3337 LLDB_LOGF(log,
"failed to start debugserver process: %s",
3347 error.SetErrorString(
"connection failed");
3354 std::weak_ptr<ProcessGDBRemote> process_wp,
lldb::pid_t debugserver_pid,
3363 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3364 ", signo=%i (0x%x), exit_status=%i)",
3365 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3367 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3368 LLDB_LOGF(log,
"ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3369 static_cast<void *
>(process_sp.get()));
3370 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3376 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3380 const StateType state = process_sp->GetState();
3389 llvm::StringRef signal_name =
3390 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
3392 if (!signal_name.empty())
3393 stream.
Format(format_str, signal_name);
3395 stream.
Format(format_str, signo);
3397 process_sp->SetExitStatus(-1, stream.
GetString());
3413 static llvm::once_flag g_once_flag;
3415 llvm::call_once(g_once_flag, []() {
3424 debugger, PluginProperties::GetSettingName())) {
3425 const bool is_global_setting =
true;
3428 "Properties for the gdb-remote process plug-in.", is_global_setting);
3435 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3442 llvm::Expected<HostThread> async_thread =
3446 if (!async_thread) {
3448 "failed to launch host thread: {0}");
3454 "ProcessGDBRemote::%s () - Called when Async thread was "
3464 LLDB_LOGF(log,
"ProcessGDBRemote::%s ()", __FUNCTION__);
3479 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3485 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread starting...",
3486 __FUNCTION__,
GetID());
3504 "ProcessGDBRemote::%s(pid = %" PRIu64
3505 ") listener.WaitForEvent (NULL, event_sp)...",
3506 __FUNCTION__,
GetID());
3509 const uint32_t event_type = event_sp->GetType();
3512 "ProcessGDBRemote::%s(pid = %" PRIu64
3513 ") Got an event of type: %d...",
3514 __FUNCTION__,
GetID(), event_type);
3516 switch (event_type) {
3521 if (continue_packet) {
3522 const char *continue_cstr =
3523 (
const char *)continue_packet->
GetBytes();
3524 const size_t continue_cstr_len = continue_packet->
GetByteSize();
3526 "ProcessGDBRemote::%s(pid = %" PRIu64
3527 ") got eBroadcastBitAsyncContinue: %s",
3528 __FUNCTION__,
GetID(), continue_cstr);
3530 if (::strstr(continue_cstr,
"vAttach") ==
nullptr)
3537 llvm::StringRef(continue_cstr, continue_cstr_len),
3548 switch (stop_state) {
3561 int exit_status = response.
GetHexU8();
3562 std::string desc_string;
3564 llvm::StringRef desc_str;
3565 llvm::StringRef desc_token;
3567 if (desc_token !=
"description")
3582 if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3585 "System Integrity Protection");
3586 }
else if (::strstr(continue_cstr,
"vAttach") !=
nullptr &&
3606 "ProcessGDBRemote::%s(pid = %" PRIu64
3607 ") got eBroadcastBitAsyncThreadShouldExit...",
3608 __FUNCTION__,
GetID());
3614 "ProcessGDBRemote::%s(pid = %" PRIu64
3615 ") got unknown event 0x%8.8x",
3616 __FUNCTION__,
GetID(), event_type);
3623 "ProcessGDBRemote::%s(pid = %" PRIu64
3624 ") listener.WaitForEvent (NULL, event_sp) => false",
3625 __FUNCTION__,
GetID());
3630 LLDB_LOGF(log,
"ProcessGDBRemote::%s(pid = %" PRIu64
") thread exiting...",
3631 __FUNCTION__,
GetID());
3663 LLDB_LOGF(log,
"Hit New Thread Notification breakpoint.");
3669 LLDB_LOG(log,
"Check if need to update ignored signals");
3683 LLDB_LOG(log,
"Signals' version hasn't changed. version={0}",
3688 auto signals_to_ignore =
3693 "Signals' version changed. old version={0}, new version={1}, "
3694 "signals ignored={2}, update result={3}",
3696 signals_to_ignore.size(),
error);
3698 if (
error.Success())
3708 LLDB_LOGF(log,
"Enabled noticing new thread breakpoint.");
3714 platform_sp->SetThreadCreationBreakpoint(
GetTarget());
3718 log,
"Successfully created new thread notification breakpoint %i",
3723 LLDB_LOGF(log,
"Failed to create new thread notification breakpoint.");
3733 LLDB_LOGF(log,
"Disabling new thread notification breakpoint.");
3754 if (return_value != 0) {
3756 error.SetErrorString(
"Sending events is not supported for this process.");
3758 error.SetErrorStringWithFormat(
"Error sending event data: %d.",
3769 buf = std::make_shared<DataBufferHeap>(response->c_str(),
3770 response->length());
3787 args_dict->GetAsDictionary()->AddIntegerItem(
"thread", tid);
3790 packet <<
"jThreadExtendedInfo:";
3791 args_dict->Dump(packet,
false);
3798 packet << (char)(0x7d ^ 0x20);
3807 if (!response.
Empty()) {
3820 args_dict->GetAsDictionary()->AddIntegerItem(
"image_list_address",
3821 image_list_address);
3822 args_dict->GetAsDictionary()->AddIntegerItem(
"image_count", image_count);
3830 args_dict->GetAsDictionary()->AddBooleanItem(
"fetch_all_solibs",
true);
3836 const std::vector<lldb::addr_t> &load_addresses) {
3840 for (
auto addr : load_addresses)
3841 addresses->AddIntegerItem(addr);
3843 args_dict->GetAsDictionary()->AddItem(
"solib_addresses", addresses);
3856 std::chrono::seconds(10));
3859 packet <<
"jGetLoadedDynamicLibrariesInfos:";
3860 args_dict->Dump(packet,
false);
3867 packet << (char)(0x7d ^ 0x20);
3876 if (!response.
Empty()) {
3898 if (!response.
Empty()) {
3913 packet <<
"jGetSharedCacheInfo:";
3914 args_dict->Dump(packet,
false);
3921 packet << (char)(0x7d ^ 0x20);
3930 if (!response.
Empty()) {
3954 const uint64_t reasonable_largeish_default = 128 * 1024;
3955 const uint64_t conservative_default = 512;
3959 if (stub_max_size !=
UINT64_MAX && stub_max_size != 0) {
3965 if (stub_max_size > reasonable_largeish_default) {
3966 stub_max_size = reasonable_largeish_default;
3972 if (stub_max_size > 70)
3973 stub_max_size -= 32 + 32 + 6;
3979 log->
Warning(
"Packet size is too small. "
3980 "LLDB may face problems while writing memory");
3991 uint64_t user_specified_max) {
3992 if (user_specified_max != 0) {
4020 module_spec = cached->second;
4021 return bool(module_spec);
4025 LLDB_LOGF(log,
"ProcessGDBRemote::%s - failed to get module info for %s:%s",
4026 __FUNCTION__, module_file_spec.
GetPath().c_str(),
4033 module_spec.
Dump(stream);
4034 LLDB_LOGF(log,
"ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4035 __FUNCTION__, module_file_spec.
GetPath().c_str(),
4044 llvm::ArrayRef<FileSpec> module_file_specs,
const llvm::Triple &triple) {
4047 for (
const FileSpec &spec : module_file_specs)
4052 triple.getTriple())] = spec;
4066typedef std::vector<std::string> stringVec;
4068typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4069struct RegisterSetInfo {
4073typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4075struct GdbServerTargetInfo {
4079 RegisterSetMap reg_set_map;
4082static std::vector<RegisterFlags::Field> ParseFlagsFields(
XMLNode flags_node,
4085 const unsigned max_start_bit = size * 8 - 1;
4088 std::vector<RegisterFlags::Field> fields;
4092 std::optional<llvm::StringRef> name;
4093 std::optional<unsigned> start;
4094 std::optional<unsigned> end;
4097 &log](
const llvm::StringRef &attr_name,
4098 const llvm::StringRef &attr_value) {
4101 if (attr_name ==
"name") {
4103 "ProcessGDBRemote::ParseFlags Found field node name \"{0}\"",
4106 }
else if (attr_name ==
"start") {
4107 unsigned parsed_start = 0;
4108 if (llvm::to_integer(attr_value, parsed_start)) {
4109 if (parsed_start > max_start_bit) {
4112 "ProcessGDBRemote::ParseFlags Invalid start {0} in field node, "
4114 parsed_start, max_start_bit);
4116 start = parsed_start;
4119 "ProcessGDBRemote::ParseFlags Invalid start \"{0}\" in "
4123 }
else if (attr_name ==
"end") {
4124 unsigned parsed_end = 0;
4125 if (llvm::to_integer(attr_value, parsed_end))
4126 if (parsed_end > max_start_bit) {
4129 "ProcessGDBRemote::ParseFlags Invalid end {0} in field node, "
4131 parsed_end, max_start_bit);
4137 "ProcessGDBRemote::ParseFlags Invalid end \"{0}\" in field node",
4140 }
else if (attr_name ==
"type") {
4145 "ProcessGDBRemote::ParseFlags Ignoring unknown attribute "
4146 "\"{0}\" in field node",
4153 if (name && start && end) {
4154 if (*start > *end) {
4156 "ProcessGDBRemote::ParseFlags Start {0} > end {1} in field "
4157 "\"{2}\", ignoring",
4158 *start, *end, name->data());
4171 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types) {
4176 [&log, ®isters_flags_types](
const XMLNode &flags_node) ->
bool {
4177 LLDB_LOG(log,
"ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
4180 std::optional<llvm::StringRef>
id;
4181 std::optional<unsigned> size;
4183 [&
id, &size, &log](
const llvm::StringRef &name,
4184 const llvm::StringRef &value) {
4187 }
else if (name ==
"size") {
4188 unsigned parsed_size = 0;
4189 if (llvm::to_integer(value, parsed_size))
4193 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
4199 "ProcessGDBRemote::ParseFlags Ignoring unknown "
4200 "attribute \"{0}\" in flags node",
4208 std::vector<RegisterFlags::Field> fields =
4209 ParseFlagsFields(flags_node, *size);
4210 if (fields.size()) {
4212 std::sort(fields.rbegin(), fields.rend());
4213 std::vector<RegisterFlags::Field>::const_iterator overlap =
4214 std::adjacent_find(fields.begin(), fields.end(),
4217 return lhs.Overlaps(rhs);
4221 if (overlap == fields.end()) {
4222 if (registers_flags_types.contains(*
id)) {
4236 "ProcessGDBRemote::ParseFlags Definition of flags "
4238 "previous definition, using original definition instead.",
4241 registers_flags_types.insert_or_assign(
4242 *
id, std::make_unique<RegisterFlags>(
id->str(), *size,
4243 std::move(fields)));
4247 std::vector<RegisterFlags::Field>::const_iterator next =
4251 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
4252 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
4254 overlap->GetName().c_str(), overlap->GetStart(),
4255 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
4261 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
4262 "\"{0}\" because it contains no fields.",
4272 XMLNode feature_node, GdbServerTargetInfo &target_info,
4273 std::vector<DynamicRegisterInfo::Register> ®isters,
4274 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types) {
4280 ParseFlags(feature_node, registers_flags_types);
4281 for (
const auto &flags : registers_flags_types)
4282 flags.second->log(log);
4286 [&target_info, ®isters, ®isters_flags_types,
4287 log](
const XMLNode ®_node) ->
bool {
4288 std::string gdb_group;
4289 std::string gdb_type;
4291 bool encoding_set =
false;
4292 bool format_set =
false;
4296 &encoding_set, &format_set, ®_info,
4297 log](
const llvm::StringRef &name,
4298 const llvm::StringRef &value) ->
bool {
4299 if (name ==
"name") {
4301 }
else if (name ==
"bitsize") {
4302 if (llvm::to_integer(value, reg_info.
byte_size))
4304 llvm::divideCeil(reg_info.
byte_size, CHAR_BIT);
4305 }
else if (name ==
"type") {
4306 gdb_type = value.str();
4307 }
else if (name ==
"group") {
4308 gdb_group = value.str();
4309 }
else if (name ==
"regnum") {
4311 }
else if (name ==
"offset") {
4313 }
else if (name ==
"altname") {
4315 }
else if (name ==
"encoding") {
4316 encoding_set =
true;
4318 }
else if (name ==
"format") {
4324 llvm::StringSwitch<lldb::Format>(value)
4335 }
else if (name ==
"group_id") {
4337 llvm::to_integer(value, set_id);
4338 RegisterSetMap::const_iterator pos =
4339 target_info.reg_set_map.find(set_id);
4340 if (pos != target_info.reg_set_map.end())
4341 reg_info.
set_name = pos->second.name;
4342 }
else if (name ==
"gcc_regnum" || name ==
"ehframe_regnum") {
4344 }
else if (name ==
"dwarf_regnum") {
4346 }
else if (name ==
"generic") {
4348 }
else if (name ==
"value_regnums") {
4351 }
else if (name ==
"invalidate_regnums") {
4356 "ProcessGDBRemote::ParseRegisters unhandled reg "
4357 "attribute %s = %s",
4358 name.data(), value.data());
4363 if (!gdb_type.empty()) {
4365 llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =
4366 registers_flags_types.find(gdb_type);
4367 if (it != registers_flags_types.end()) {
4368 auto flags_type = it->second.get();
4369 if (reg_info.
byte_size == flags_type->GetSize())
4373 "ProcessGDBRemote::ParseRegisters Size of register "
4374 "flags %s (%d bytes) for "
4375 "register %s does not match the register size (%d "
4376 "bytes). Ignoring this set of flags.",
4377 flags_type->GetID().c_str(), flags_type->GetSize(),
4384 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4385 if (llvm::StringRef(gdb_type).startswith(
"int")) {
4388 }
else if (gdb_type ==
"data_ptr" || gdb_type ==
"code_ptr") {
4391 }
else if (gdb_type ==
"float") {
4394 }
else if (gdb_type ==
"aarch64v" ||
4395 llvm::StringRef(gdb_type).startswith(
"vec") ||
4396 gdb_type ==
"i387_ext" || gdb_type ==
"uint128") {
4404 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4405 "format and encoding for gdb type %s",
4415 if (!gdb_group.empty()) {
4426 "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4429 registers.push_back(reg_info);
4444 ArchSpec &arch_to_use, std::string xml_filename,
4445 std::vector<DynamicRegisterInfo::Register> ®isters) {
4448 if (errorToBool(raw.takeError()))
4453 if (xml_document.
ParseMemory(raw->c_str(), raw->size(),
4454 xml_filename.c_str())) {
4455 GdbServerTargetInfo target_info;
4456 std::vector<XMLNode> feature_nodes;
4462 const XMLNode &node) ->
bool {
4463 llvm::StringRef name = node.
GetName();
4464 if (name ==
"architecture") {
4466 }
else if (name ==
"osabi") {
4468 }
else if (name ==
"xi:include" || name ==
"include") {
4471 target_info.includes.push_back(href);
4472 }
else if (name ==
"feature") {
4473 feature_nodes.push_back(node);
4474 }
else if (name ==
"groups") {
4476 "group", [&target_info](
const XMLNode &node) ->
bool {
4478 RegisterSetInfo set_info;
4481 [&set_id, &set_info](
const llvm::StringRef &name,
4482 const llvm::StringRef &value) ->
bool {
4485 llvm::to_integer(value, set_id);
4492 target_info.reg_set_map[set_id] = set_info;
4505 feature_nodes.push_back(feature_node);
4507 const XMLNode &node) ->
bool {
4508 llvm::StringRef name = node.
GetName();
4509 if (name ==
"xi:include" || name ==
"include") {
4512 target_info.includes.push_back(href);
4526 if (!arch_to_use.
IsValid() && !target_info.arch.empty()) {
4528 arch_to_use.
SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4529 .Case(
"i386:x86-64",
"x86_64")
4530 .Default(target_info.arch) +
4538 for (
auto &feature_node : feature_nodes) {
4539 ParseRegisters(feature_node, target_info, registers,
4543 for (
const auto &include : target_info.includes) {
4555 std::vector<DynamicRegisterInfo::Register> ®isters,
4557 std::map<uint32_t, uint32_t> remote_to_local_map;
4558 uint32_t remote_regnum = 0;
4559 for (
auto it : llvm::enumerate(registers)) {
4567 remote_to_local_map[remote_reg_info.
regnum_remote] = it.index();
4573 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4574 auto lldb_regit = remote_to_local_map.find(process_regnum);
4575 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4579 llvm::transform(remote_reg_info.value_regs,
4580 remote_reg_info.value_regs.begin(), proc_to_lldb);
4581 llvm::transform(remote_reg_info.invalidate_regs,
4582 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4589 abi_sp->AugmentRegisterInfo(registers);
4612 std::vector<DynamicRegisterInfo::Register> registers;
4623 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4624 "XML parsing not available");
4627 LLDB_LOGF(log,
"ProcessGDBRemote::%s", __FUNCTION__);
4636 llvm::Expected<std::string> raw = comm.
ReadExtFeature(
"libraries-svr4",
"");
4638 return raw.takeError();
4641 LLDB_LOGF(log,
"parsing: %s", raw->c_str());
4644 if (!doc.
ParseMemory(raw->c_str(), raw->size(),
"noname.xml"))
4645 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4646 "Error reading noname.xml");
4650 return llvm::createStringError(
4651 llvm::inconvertibleErrorCode(),
4652 "Error finding library-list-svr4 xml element");
4657 if (!main_lm.empty())
4661 "library", [log, &list](
const XMLNode &library) ->
bool {
4666 [&module](
const llvm::StringRef &name,
4667 const llvm::StringRef &value) ->
bool {
4671 else if (name ==
"lm") {
4673 llvm::to_integer(value, uint_value);
4675 }
else if (name ==
"l_addr") {
4678 llvm::to_integer(value, uint_value);
4683 }
else if (name ==
"l_ld") {
4685 llvm::to_integer(value, uint_value);
4695 bool base_is_offset;
4704 "found (link_map:0x%08" PRIx64
", base:0x%08" PRIx64
4705 "[%s], ld:0x%08" PRIx64
", name:'%s')",
4706 lm, base, (base_is_offset ?
"offset" :
"absolute"), ld,
4716 LLDB_LOGF(log,
"found %" PRId32
" modules in total",
4717 (
int)list.
m_list.size());
4721 llvm::Expected<std::string> raw = comm.
ReadExtFeature(
"libraries",
"");
4724 return raw.takeError();
4726 LLDB_LOGF(log,
"parsing: %s", raw->c_str());
4729 if (!doc.
ParseMemory(raw->c_str(), raw->size(),
"noname.xml"))
4730 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4731 "Error reading noname.xml");
4735 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4736 "Error finding library-list xml element");
4740 "library", [log, &list](
const XMLNode &library) ->
bool {
4753 llvm::to_integer(address, address_value);
4761 bool base_is_offset;
4766 LLDB_LOGF(log,
"found (base:0x%08" PRIx64
"[%s], name:'%s')", base,
4767 (base_is_offset ?
"offset" :
"absolute"), name.c_str());
4776 LLDB_LOGF(log,
"found %" PRId32
" modules in total",
4777 (
int)list.
m_list.size());
4780 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4781 "Remote libraries not supported");
4788 bool value_is_offset) {
4803 return module_list.takeError();
4809 std::string mod_name;
4812 bool mod_base_is_offset;
4815 valid &= modInfo.
get_name(mod_name);
4816 valid &= modInfo.
get_base(mod_base);
4829 if (module_sp.get())
4830 new_modules.
Append(module_sp);
4833 if (new_modules.
GetSize() > 0) {
4838 for (
size_t i = 0; i < loaded_modules.
GetSize(); ++i) {
4842 for (
size_t j = 0; j < new_modules.
GetSize(); ++j) {
4851 removed_modules.
Append(loaded_module);
4855 loaded_modules.
Remove(removed_modules);
4875 return llvm::ErrorSuccess();
4884 std::string file_path = file.
GetPath(
false);
4885 if (file_path.empty())
<