blob: c6b792e70fcb9bd5a52a33d29fe838366d7bf3e2 [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Greg Clayton576d8832011-03-22 04:00:09 +00006//
7//===----------------------------------------------------------------------===//
8
Greg Clayton576d8832011-03-22 04:00:09 +00009#include "GDBRemoteCommunicationClient.h"
10
Greg Claytone034a042015-05-21 20:52:06 +000011#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000012#include <sys/stat.h>
13
Greg Claytone034a042015-05-21 20:52:06 +000014#include <numeric>
Kate Stoneb9c1b512016-09-06 20:57:50 +000015#include <sstream>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000016
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000017#include "lldb/Core/ModuleSpec.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000018#include "lldb/Host/HostInfo.h"
Pavel Labath16064d32018-03-20 11:56:24 +000019#include "lldb/Host/XML.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000020#include "lldb/Symbol/Symbol.h"
Pavel Labath4cb69922016-07-29 15:41:52 +000021#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000022#include "lldb/Target/Target.h"
Todd Fiala75930012016-08-19 04:21:48 +000023#include "lldb/Target/UnixSignals.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000024#include "lldb/Utility/Args.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000025#include "lldb/Utility/DataBufferHeap.h"
Pavel Labath2f1fbae2016-09-08 10:07:04 +000026#include "lldb/Utility/JSON.h"
Todd Fiala75930012016-08-19 04:21:48 +000027#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000028#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000029#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000030#include "lldb/Utility/StreamString.h"
Greg Clayton576d8832011-03-22 04:00:09 +000031
Greg Clayton576d8832011-03-22 04:00:09 +000032#include "ProcessGDBRemote.h"
33#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000034#include "lldb/Host/Config.h"
Pavel Labath9af71b32018-03-20 16:14:00 +000035#include "lldb/Utility/StringExtractorGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000036
Zachary Turner54695a32016-08-29 19:58:14 +000037#include "llvm/ADT/StringSwitch.h"
38
Jason Molenda4a793c82018-12-18 23:02:50 +000039#if defined(__APPLE__)
Jason Molendaaa107ca2019-04-03 01:16:54 +000040#ifndef HAVE_LIBCOMPRESSION
Jason Molenda4a793c82018-12-18 23:02:50 +000041#define HAVE_LIBCOMPRESSION
Jason Molendaaa107ca2019-04-03 01:16:54 +000042#endif
Jason Molenda91ffe0a2015-06-18 21:46:06 +000043#include <compression.h>
44#endif
45
Greg Clayton576d8832011-03-22 04:00:09 +000046using namespace lldb;
47using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000048using namespace lldb_private::process_gdb_remote;
Pavel Labath1eff73c2016-11-24 10:54:49 +000049using namespace std::chrono;
Greg Clayton576d8832011-03-22 04:00:09 +000050
Greg Clayton576d8832011-03-22 04:00:09 +000051// GDBRemoteCommunicationClient constructor
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000052GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000053 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000054 m_supports_not_sending_acks(eLazyBoolCalculate),
55 m_supports_thread_suffix(eLazyBoolCalculate),
56 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
57 m_supports_vCont_all(eLazyBoolCalculate),
58 m_supports_vCont_any(eLazyBoolCalculate),
59 m_supports_vCont_c(eLazyBoolCalculate),
60 m_supports_vCont_C(eLazyBoolCalculate),
61 m_supports_vCont_s(eLazyBoolCalculate),
62 m_supports_vCont_S(eLazyBoolCalculate),
63 m_qHostInfo_is_valid(eLazyBoolCalculate),
64 m_curr_pid_is_valid(eLazyBoolCalculate),
65 m_qProcessInfo_is_valid(eLazyBoolCalculate),
66 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
67 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
68 m_supports_memory_region_info(eLazyBoolCalculate),
69 m_supports_watchpoint_support_info(eLazyBoolCalculate),
70 m_supports_detach_stay_stopped(eLazyBoolCalculate),
71 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
72 m_attach_or_wait_reply(eLazyBoolCalculate),
73 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000074 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000075 m_avoid_g_packets(eLazyBoolCalculate),
76 m_supports_QSaveRegisterState(eLazyBoolCalculate),
77 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
78 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
79 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
80 m_supports_qXfer_features_read(eLazyBoolCalculate),
Pavel Labath16064d32018-03-20 11:56:24 +000081 m_supports_qXfer_memory_map_read(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000082 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
83 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
84 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000085 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000086 m_supports_QPassSignals(eLazyBoolCalculate),
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +000087 m_supports_error_string_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
89 m_supports_qUserName(true), m_supports_qGroupName(true),
90 m_supports_qThreadStopInfo(true), m_supports_z0(true),
91 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
92 m_supports_z4(true), m_supports_QEnvironment(true),
93 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
94 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
Pavel Labath2f1fbae2016-09-08 10:07:04 +000095 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
96 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000097 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
Kate Stoneb9c1b512016-09-06 20:57:50 +000098 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
Pavel Labath2272c482018-06-18 15:02:23 +000099 m_os_build(), m_os_kernel(), m_hostname(), m_gdb_server_name(),
100 m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0),
101 m_max_packet_size(0), m_qSupported_response(),
102 m_supported_async_json_packets_is_valid(false),
Pavel Labath16064d32018-03-20 11:56:24 +0000103 m_supported_async_json_packets_sp(), m_qXfer_memory_map(),
104 m_qXfer_memory_map_loaded(false) {}
Greg Clayton576d8832011-03-22 04:00:09 +0000105
Greg Clayton576d8832011-03-22 04:00:09 +0000106// Destructor
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
108 if (IsConnected())
109 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000110}
111
Zachary Turner97206d52017-05-12 04:51:55 +0000112bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000114
Adrian Prantl05097242018-04-30 16:49:04 +0000115 // Start the read thread after we send the handshake ack since if we fail to
116 // send the handshake ack, there is no reason to continue...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 if (SendAck()) {
118 // Wait for any responses that might have been queued up in the remote
119 // GDB server and flush them all
120 StringExtractorGDBRemote response;
121 PacketResult packet_result = PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 while (packet_result == PacketResult::Success)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000123 packet_result = ReadPacket(response, milliseconds(10), false);
Ed Maste48f986f2013-12-18 15:31:45 +0000124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 // The return value from QueryNoAckModeSupported() is true if the packet
Adrian Prantl05097242018-04-30 16:49:04 +0000126 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
127 // false if no response was received. This quickly tells us if we have a
128 // live connection to a remote GDB server...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 if (QueryNoAckModeSupported()) {
130 return true;
131 } else {
132 if (error_ptr)
133 error_ptr->SetErrorString("failed to get reply to handshake packet");
Greg Claytonfb909312013-11-23 01:58:15 +0000134 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 } else {
136 if (error_ptr)
137 error_ptr->SetErrorString("failed to send the handshake ack");
138 }
139 return false;
Greg Clayton1cb64962011-03-24 04:28:38 +0000140}
141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142bool GDBRemoteCommunicationClient::GetEchoSupported() {
143 if (m_supports_qEcho == eLazyBoolCalculate) {
144 GetRemoteQSupported();
145 }
146 return m_supports_qEcho == eLazyBoolYes;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000147}
148
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000149bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
150 if (m_supports_QPassSignals == eLazyBoolCalculate) {
151 GetRemoteQSupported();
152 }
153 return m_supports_QPassSignals == eLazyBoolYes;
154}
155
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
157 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
158 GetRemoteQSupported();
159 }
160 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000161}
162
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
164 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
165 GetRemoteQSupported();
166 }
167 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000168}
169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
171 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
172 GetRemoteQSupported();
173 }
174 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000175}
176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
178 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
179 GetRemoteQSupported();
180 }
181 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000182}
183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
185 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
186 GetRemoteQSupported();
187 }
188 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000189}
190
Pavel Labath16064d32018-03-20 11:56:24 +0000191bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() {
192 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) {
193 GetRemoteQSupported();
194 }
195 return m_supports_qXfer_memory_map_read == eLazyBoolYes;
196}
197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
199 if (m_max_packet_size == 0) {
200 GetRemoteQSupported();
201 }
202 return m_max_packet_size;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000203}
204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
206 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
207 m_send_acks = true;
208 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000209
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210 // This is the first real packet that we'll send in a debug session and it
Adrian Prantl05097242018-04-30 16:49:04 +0000211 // may take a little longer than normal to receive a reply. Wait at least
212 // 6 seconds for a reply to this packet.
Jason Molenda36a216e2014-07-24 01:36:24 +0000213
Pavel Labath1eff73c2016-11-24 10:54:49 +0000214 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
Colin Rileyc3c95b22015-04-16 15:51:33 +0000215
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000216 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
218 PacketResult::Success) {
219 if (response.IsOKResponse()) {
220 m_send_acks = false;
221 m_supports_not_sending_acks = eLazyBoolYes;
222 }
223 return true;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000224 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225 }
226 return false;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000227}
Greg Clayton576d8832011-03-22 04:00:09 +0000228
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
230 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
231 m_supports_threads_in_stop_reply = eLazyBoolNo;
232
233 StringExtractorGDBRemote response;
234 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
235 false) == PacketResult::Success) {
236 if (response.IsOKResponse())
237 m_supports_threads_in_stop_reply = eLazyBoolYes;
Pavel Labath5c95ee42016-08-30 13:56:11 +0000238 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 }
Pavel Labath0faf3732016-08-25 08:34:57 +0000240}
Greg Clayton576d8832011-03-22 04:00:09 +0000241
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
243 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
244 m_attach_or_wait_reply = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +0000245
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246 StringExtractorGDBRemote response;
247 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
248 false) == PacketResult::Success) {
249 if (response.IsOKResponse())
250 m_attach_or_wait_reply = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000251 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000253 return m_attach_or_wait_reply == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000254}
255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
257 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
258 m_prepare_for_reg_writing_reply = eLazyBoolNo;
259
260 StringExtractorGDBRemote response;
261 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
262 false) == PacketResult::Success) {
263 if (response.IsOKResponse())
264 m_prepare_for_reg_writing_reply = eLazyBoolYes;
265 }
266 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000267 return m_prepare_for_reg_writing_reply == eLazyBoolYes;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268}
269
270void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000271 if (!did_exec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 // Hard reset everything, this is when we first connect to a GDB server
273 m_supports_not_sending_acks = eLazyBoolCalculate;
274 m_supports_thread_suffix = eLazyBoolCalculate;
275 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
276 m_supports_vCont_c = eLazyBoolCalculate;
277 m_supports_vCont_C = eLazyBoolCalculate;
278 m_supports_vCont_s = eLazyBoolCalculate;
279 m_supports_vCont_S = eLazyBoolCalculate;
280 m_supports_p = eLazyBoolCalculate;
281 m_supports_x = eLazyBoolCalculate;
282 m_supports_QSaveRegisterState = eLazyBoolCalculate;
283 m_qHostInfo_is_valid = eLazyBoolCalculate;
284 m_curr_pid_is_valid = eLazyBoolCalculate;
285 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
286 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
287 m_supports_memory_region_info = eLazyBoolCalculate;
288 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
289 m_attach_or_wait_reply = eLazyBoolCalculate;
290 m_avoid_g_packets = eLazyBoolCalculate;
291 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
292 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
293 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
294 m_supports_qXfer_features_read = eLazyBoolCalculate;
Pavel Labath16064d32018-03-20 11:56:24 +0000295 m_supports_qXfer_memory_map_read = eLazyBoolCalculate;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
297 m_supports_qProcessInfoPID = true;
298 m_supports_qfProcessInfo = true;
299 m_supports_qUserName = true;
300 m_supports_qGroupName = true;
301 m_supports_qThreadStopInfo = true;
302 m_supports_z0 = true;
303 m_supports_z1 = true;
304 m_supports_z2 = true;
305 m_supports_z3 = true;
306 m_supports_z4 = true;
307 m_supports_QEnvironment = true;
308 m_supports_QEnvironmentHexEncoded = true;
309 m_supports_qSymbol = true;
310 m_qSymbol_requests_done = false;
311 m_supports_qModuleInfo = true;
312 m_host_arch.Clear();
Pavel Labath2272c482018-06-18 15:02:23 +0000313 m_os_version = llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314 m_os_build.clear();
315 m_os_kernel.clear();
316 m_hostname.clear();
317 m_gdb_server_name.clear();
318 m_gdb_server_version = UINT32_MAX;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000319 m_default_packet_timeout = seconds(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 m_max_packet_size = 0;
321 m_qSupported_response.clear();
322 m_supported_async_json_packets_is_valid = false;
323 m_supported_async_json_packets_sp.reset();
Pavel Labath2f1fbae2016-09-08 10:07:04 +0000324 m_supports_jModulesInfo = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 }
326
Adrian Prantl05097242018-04-30 16:49:04 +0000327 // These flags should be reset when we first connect to a GDB server and when
328 // our inferior process execs
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 m_qProcessInfo_is_valid = eLazyBoolCalculate;
330 m_process_arch.Clear();
331}
332
333void GDBRemoteCommunicationClient::GetRemoteQSupported() {
334 // Clear out any capabilities we expect to see in the qSupported response
335 m_supports_qXfer_auxv_read = eLazyBoolNo;
336 m_supports_qXfer_libraries_read = eLazyBoolNo;
337 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
338 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
339 m_supports_qXfer_features_read = eLazyBoolNo;
Pavel Labath16064d32018-03-20 11:56:24 +0000340 m_supports_qXfer_memory_map_read = eLazyBoolNo;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
342 // not, we assume no limit
343
344 // build the qSupported packet
345 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
346 StreamString packet;
347 packet.PutCString("qSupported");
348 for (uint32_t i = 0; i < features.size(); ++i) {
349 packet.PutCString(i == 0 ? ":" : ";");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000350 packet.PutCString(features[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 }
352
353 StringExtractorGDBRemote response;
Zachary Turnerc1564272016-11-16 21:15:24 +0000354 if (SendPacketAndWaitForResponse(packet.GetString(), response,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 /*send_async=*/false) ==
356 PacketResult::Success) {
357 const char *response_cstr = response.GetStringRef().c_str();
358
359 // Hang on to the qSupported packet, so that platforms can do custom
Adrian Prantl05097242018-04-30 16:49:04 +0000360 // configuration of the transport before attaching/launching the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 m_qSupported_response = response_cstr;
362
363 if (::strstr(response_cstr, "qXfer:auxv:read+"))
364 m_supports_qXfer_auxv_read = eLazyBoolYes;
365 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
366 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
367 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
368 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
369 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
370 }
371 if (::strstr(response_cstr, "qXfer:libraries:read+"))
372 m_supports_qXfer_libraries_read = eLazyBoolYes;
373 if (::strstr(response_cstr, "qXfer:features:read+"))
374 m_supports_qXfer_features_read = eLazyBoolYes;
Pavel Labath16064d32018-03-20 11:56:24 +0000375 if (::strstr(response_cstr, "qXfer:memory-map:read+"))
376 m_supports_qXfer_memory_map_read = eLazyBoolYes;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377
378 // Look for a list of compressions in the features list e.g.
Adrian Prantl05097242018-04-30 16:49:04 +0000379 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
380 // deflate,lzma
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
382 if (features_list) {
383 const char *compressions =
384 ::strstr(features_list, "SupportedCompressions=");
385 if (compressions) {
386 std::vector<std::string> supported_compressions;
387 compressions += sizeof("SupportedCompressions=") - 1;
388 const char *end_of_compressions = strchr(compressions, ';');
389 if (end_of_compressions == NULL) {
390 end_of_compressions = strchr(compressions, '\0');
391 }
392 const char *current_compression = compressions;
393 while (current_compression < end_of_compressions) {
394 const char *next_compression_name = strchr(current_compression, ',');
395 const char *end_of_this_word = next_compression_name;
396 if (next_compression_name == NULL ||
397 end_of_compressions < next_compression_name) {
398 end_of_this_word = end_of_compressions;
399 }
400
401 if (end_of_this_word) {
402 if (end_of_this_word == current_compression) {
403 current_compression++;
404 } else {
405 std::string this_compression(
406 current_compression, end_of_this_word - current_compression);
407 supported_compressions.push_back(this_compression);
408 current_compression = end_of_this_word + 1;
409 }
410 } else {
411 supported_compressions.push_back(current_compression);
412 current_compression = end_of_compressions;
413 }
414 }
415
416 if (supported_compressions.size() > 0) {
417 MaybeEnableCompression(supported_compressions);
418 }
419 }
420 }
421
422 if (::strstr(response_cstr, "qEcho"))
423 m_supports_qEcho = eLazyBoolYes;
424 else
425 m_supports_qEcho = eLazyBoolNo;
426
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000427 if (::strstr(response_cstr, "QPassSignals+"))
428 m_supports_QPassSignals = eLazyBoolYes;
429 else
430 m_supports_QPassSignals = eLazyBoolNo;
431
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
433 if (packet_size_str) {
434 StringExtractorGDBRemote packet_response(packet_size_str +
435 strlen("PacketSize="));
436 m_max_packet_size =
437 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
438 if (m_max_packet_size == 0) {
439 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
440 Log *log(
441 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
442 if (log)
443 log->Printf("Garbled PacketSize spec in qSupported response");
444 }
445 }
446 }
447}
448
449bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
450 if (m_supports_thread_suffix == eLazyBoolCalculate) {
451 StringExtractorGDBRemote response;
452 m_supports_thread_suffix = eLazyBoolNo;
453 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
454 false) == PacketResult::Success) {
455 if (response.IsOKResponse())
456 m_supports_thread_suffix = eLazyBoolYes;
457 }
458 }
459 return m_supports_thread_suffix;
460}
461bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
462 if (m_supports_vCont_c == eLazyBoolCalculate) {
463 StringExtractorGDBRemote response;
464 m_supports_vCont_any = eLazyBoolNo;
465 m_supports_vCont_all = eLazyBoolNo;
466 m_supports_vCont_c = eLazyBoolNo;
467 m_supports_vCont_C = eLazyBoolNo;
468 m_supports_vCont_s = eLazyBoolNo;
469 m_supports_vCont_S = eLazyBoolNo;
470 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
471 PacketResult::Success) {
472 const char *response_cstr = response.GetStringRef().c_str();
473 if (::strstr(response_cstr, ";c"))
474 m_supports_vCont_c = eLazyBoolYes;
475
476 if (::strstr(response_cstr, ";C"))
477 m_supports_vCont_C = eLazyBoolYes;
478
479 if (::strstr(response_cstr, ";s"))
480 m_supports_vCont_s = eLazyBoolYes;
481
482 if (::strstr(response_cstr, ";S"))
483 m_supports_vCont_S = eLazyBoolYes;
484
485 if (m_supports_vCont_c == eLazyBoolYes &&
486 m_supports_vCont_C == eLazyBoolYes &&
487 m_supports_vCont_s == eLazyBoolYes &&
488 m_supports_vCont_S == eLazyBoolYes) {
489 m_supports_vCont_all = eLazyBoolYes;
490 }
491
492 if (m_supports_vCont_c == eLazyBoolYes ||
493 m_supports_vCont_C == eLazyBoolYes ||
494 m_supports_vCont_s == eLazyBoolYes ||
495 m_supports_vCont_S == eLazyBoolYes) {
496 m_supports_vCont_any = eLazyBoolYes;
497 }
498 }
499 }
500
501 switch (flavor) {
502 case 'a':
503 return m_supports_vCont_any;
504 case 'A':
505 return m_supports_vCont_all;
506 case 'c':
507 return m_supports_vCont_c;
508 case 'C':
509 return m_supports_vCont_C;
510 case 's':
511 return m_supports_vCont_s;
512 case 'S':
513 return m_supports_vCont_S;
514 default:
515 break;
516 }
517 return false;
518}
519
Pavel Labath4b6f9592016-08-18 08:30:03 +0000520GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
522 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
523 bool send_async) {
524 Lock lock(*this, send_async);
525 if (!lock) {
526 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
527 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
528 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
529 "for %s packet.",
Zachary Turnerc1564272016-11-16 21:15:24 +0000530 __FUNCTION__, payload.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 return PacketResult::ErrorNoSequenceLock;
532 }
Pavel Labath5c95ee42016-08-30 13:56:11 +0000533
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 if (GetThreadSuffixSupported())
535 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
536 else {
537 if (!SetCurrentThread(tid))
538 return PacketResult::ErrorSendFailed;
539 }
Pavel Labath4b6f9592016-08-18 08:30:03 +0000540
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000542}
543
Adrian Prantl05097242018-04-30 16:49:04 +0000544// Check if the target supports 'p' packet. It sends out a 'p' packet and
545// checks the response. A normal packet will tell us that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000546//
547// Takes a valid thread ID because p needs to apply to a thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
549 if (m_supports_p == eLazyBoolCalculate) {
550 m_supports_p = eLazyBoolNo;
551 StreamString payload;
552 payload.PutCString("p0");
553 StringExtractorGDBRemote response;
554 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
555 response, false) ==
556 PacketResult::Success &&
557 response.IsNormalResponse()) {
558 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000559 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 }
561 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000562}
Greg Clayton576d8832011-03-22 04:00:09 +0000563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
565 // Get information on all threads at one using the "jThreadsInfo" packet
566 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000567
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 if (m_supports_jThreadsInfo) {
569 StringExtractorGDBRemote response;
570 response.SetResponseValidatorToJSON();
571 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
572 PacketResult::Success) {
573 if (response.IsUnsupportedResponse()) {
574 m_supports_jThreadsInfo = false;
575 } else if (!response.Empty()) {
576 object_sp = StructuredData::ParseJSON(response.GetStringRef());
577 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 }
580 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000581}
582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
584 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
585 StringExtractorGDBRemote response;
586 m_supports_jThreadExtendedInfo = eLazyBoolNo;
587 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
588 PacketResult::Success) {
589 if (response.IsOKResponse()) {
590 m_supports_jThreadExtendedInfo = eLazyBoolYes;
591 }
Jason Molenda705b1802014-06-13 02:37:02 +0000592 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593 }
594 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000595}
596
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000597void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
598 if (m_supports_error_string_reply == eLazyBoolCalculate) {
599 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +0000600 // We try to enable error strings in remote packets but if we fail, we just
601 // work in the older way.
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000602 m_supports_error_string_reply = eLazyBoolNo;
603 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
604 PacketResult::Success) {
605 if (response.IsOKResponse()) {
606 m_supports_error_string_reply = eLazyBoolYes;
607 }
608 }
609 }
610}
611
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
613 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
614 StringExtractorGDBRemote response;
615 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
616 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
617 response,
618 false) == PacketResult::Success) {
619 if (response.IsOKResponse()) {
620 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
621 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000622 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 }
624 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000625}
626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
628 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
629 StringExtractorGDBRemote response;
630 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
631 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
632 PacketResult::Success) {
633 if (response.IsOKResponse()) {
634 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
635 }
Jason Molenda37397352016-07-22 00:17:55 +0000636 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 }
638 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000639}
640
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641bool GDBRemoteCommunicationClient::GetxPacketSupported() {
642 if (m_supports_x == eLazyBoolCalculate) {
643 StringExtractorGDBRemote response;
644 m_supports_x = eLazyBoolNo;
645 char packet[256];
646 snprintf(packet, sizeof(packet), "x0,0");
647 if (SendPacketAndWaitForResponse(packet, response, false) ==
648 PacketResult::Success) {
649 if (response.IsOKResponse())
650 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000651 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652 }
653 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000654}
655
Greg Clayton3dedae12013-12-06 21:45:27 +0000656GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
658 const char *payload_prefix, std::string &response_string) {
659 Lock lock(*this, false);
660 if (!lock) {
661 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
662 GDBR_LOG_PACKETS));
663 if (log)
664 log->Printf("error: failed to get packet sequence mutex, not sending "
665 "packets with prefix '%s'",
666 payload_prefix);
667 return PacketResult::ErrorNoSequenceLock;
668 }
669
670 response_string = "";
671 std::string payload_prefix_str(payload_prefix);
672 unsigned int response_size = 0x1000;
673 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
674 response_size = GetRemoteMaxPacketSize();
675 }
676
677 for (unsigned int offset = 0; true; offset += response_size) {
678 StringExtractorGDBRemote this_response;
679 // Construct payload
680 char sizeDescriptor[128];
681 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
682 response_size);
683 PacketResult result = SendPacketAndWaitForResponseNoLock(
684 payload_prefix_str + sizeDescriptor, this_response);
685 if (result != PacketResult::Success)
686 return result;
687
688 const std::string &this_string = this_response.GetStringRef();
689
690 // Check for m or l as first character; l seems to mean this is the last
691 // chunk
692 char first_char = *this_string.c_str();
693 if (first_char != 'm' && first_char != 'l') {
694 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 // Concatenate the result so far (skipping 'm' or 'l')
697 response_string.append(this_string, 1, std::string::npos);
698 if (first_char == 'l')
699 // We're done
700 return PacketResult::Success;
701 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000702}
703
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
705 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
706 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000707
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 // First try to retrieve the pid via the qProcessInfo request.
709 GetCurrentProcessInfo(allow_lazy);
710 if (m_curr_pid_is_valid == eLazyBoolYes) {
711 // We really got it.
712 return m_curr_pid;
713 } else {
714 // If we don't get a response for qProcessInfo, check if $qC gives us a
Adrian Prantl05097242018-04-30 16:49:04 +0000715 // result. $qC only returns a real process id on older debugserver and
716 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
717 // the thread id, which newer debugserver and lldb-gdbserver stubs return
718 // correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000719 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000720 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 PacketResult::Success) {
722 if (response.GetChar() == 'Q') {
723 if (response.GetChar() == 'C') {
724 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
725 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
726 m_curr_pid_is_valid = eLazyBoolYes;
727 return m_curr_pid;
728 }
Greg Clayton576d8832011-03-22 04:00:09 +0000729 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 }
Greg Clayton576d8832011-03-22 04:00:09 +0000731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732
733 // If we don't get a response for $qC, check if $qfThreadID gives us a
734 // result.
735 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
736 std::vector<lldb::tid_t> thread_ids;
737 bool sequence_mutex_unavailable;
738 size_t size;
739 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000740 if (size && !sequence_mutex_unavailable) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 m_curr_pid = thread_ids.front();
742 m_curr_pid_is_valid = eLazyBoolYes;
743 return m_curr_pid;
744 }
Greg Clayton576d8832011-03-22 04:00:09 +0000745 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 }
747
748 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000749}
750
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
752 error_str.clear();
753 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000754 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
755 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 if (response.IsOKResponse())
757 return true;
758 if (response.GetChar() == 'E') {
759 // A string the describes what failed when launching...
760 error_str = response.GetStringRef().substr(1);
761 } else {
762 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000763 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 } else {
765 error_str.assign("timed out waiting for app to launch");
766 }
767 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000768}
769
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770int GDBRemoteCommunicationClient::SendArgumentsPacket(
771 const ProcessLaunchInfo &launch_info) {
772 // Since we don't get the send argv0 separate from the executable path, we
Adrian Prantl05097242018-04-30 16:49:04 +0000773 // need to make sure to use the actual executable path found in the
774 // launch_info...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 std::vector<const char *> argv;
776 FileSpec exe_file = launch_info.GetExecutableFile();
777 std::string exe_path;
778 const char *arg = NULL;
779 const Args &launch_args = launch_info.GetArguments();
780 if (exe_file)
781 exe_path = exe_file.GetPath(false);
782 else {
783 arg = launch_args.GetArgumentAtIndex(0);
784 if (arg)
785 exe_path = arg;
786 }
787 if (!exe_path.empty()) {
788 argv.push_back(exe_path.c_str());
789 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
790 ++i) {
791 if (arg)
792 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000793 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 }
795 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000796 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 packet.PutChar('A');
798 for (size_t i = 0, n = argv.size(); i < n; ++i) {
799 arg = argv[i];
800 const int arg_len = strlen(arg);
801 if (i > 0)
802 packet.PutChar(',');
803 packet.Printf("%i,%i,", arg_len * 2, (int)i);
804 packet.PutBytesAsRawHex8(arg, arg_len);
805 }
806
Vince Harrone0be4252015-02-06 18:32:57 +0000807 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000808 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
809 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000811 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 uint8_t error = response.GetError();
813 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000814 return error;
815 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 }
817 return -1;
818}
Johnny Chen64637202012-05-23 21:09:52 +0000819
Pavel Labath62930e52018-01-10 11:57:31 +0000820int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
821 for (const auto &KV : env) {
822 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
823 if (r != 0)
824 return r;
825 }
826 return 0;
827}
828
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829int GDBRemoteCommunicationClient::SendEnvironmentPacket(
830 char const *name_equal_value) {
831 if (name_equal_value && name_equal_value[0]) {
832 StreamString packet;
833 bool send_hex_encoding = false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000834 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
835 ++p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836 if (isprint(*p)) {
837 switch (*p) {
838 case '$':
839 case '#':
840 case '*':
841 case '}':
842 send_hex_encoding = true;
843 break;
844 default:
845 break;
Johnny Chen64637202012-05-23 21:09:52 +0000846 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 } else {
848 // We have non printable characters, lets hex encode this...
849 send_hex_encoding = true;
850 }
Johnny Chen64637202012-05-23 21:09:52 +0000851 }
852
Greg Claytonfbb76342013-11-20 21:07:01 +0000853 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 if (send_hex_encoding) {
855 if (m_supports_QEnvironmentHexEncoded) {
856 packet.PutCString("QEnvironmentHexEncoded:");
857 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000858 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
859 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 if (response.IsOKResponse())
861 return 0;
862 uint8_t error = response.GetError();
863 if (error)
864 return error;
865 if (response.IsUnsupportedResponse())
866 m_supports_QEnvironmentHexEncoded = false;
867 }
868 }
869
870 } else if (m_supports_QEnvironment) {
871 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000872 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
873 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874 if (response.IsOKResponse())
875 return 0;
876 uint8_t error = response.GetError();
877 if (error)
878 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000879 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 m_supports_QEnvironment = false;
881 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000882 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 }
884 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000885}
886
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
888 if (arch && arch[0]) {
889 StreamString packet;
890 packet.Printf("QLaunchArch:%s", arch);
891 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000892 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
893 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 if (response.IsOKResponse())
895 return 0;
896 uint8_t error = response.GetError();
897 if (error)
898 return error;
899 }
900 }
901 return -1;
902}
Chaoren Lind3173f32015-05-29 19:52:29 +0000903
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
905 char const *data, bool *was_supported) {
906 if (data && *data != '\0') {
907 StreamString packet;
908 packet.Printf("QSetProcessEvent:%s", data);
909 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000910 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
911 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 if (response.IsOKResponse()) {
913 if (was_supported)
914 *was_supported = true;
915 return 0;
916 } else if (response.IsUnsupportedResponse()) {
917 if (was_supported)
918 *was_supported = false;
919 return -1;
920 } else {
921 uint8_t error = response.GetError();
922 if (was_supported)
923 *was_supported = true;
924 if (error)
925 return error;
926 }
927 }
928 }
929 return -1;
930}
931
Pavel Labath2272c482018-06-18 15:02:23 +0000932llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() {
933 GetHostInfo();
934 return m_os_version;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935}
936
937bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
938 if (GetHostInfo()) {
939 if (!m_os_build.empty()) {
940 s = m_os_build;
941 return true;
942 }
943 }
944 s.clear();
945 return false;
946}
947
948bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
949 if (GetHostInfo()) {
950 if (!m_os_kernel.empty()) {
951 s = m_os_kernel;
952 return true;
953 }
954 }
955 s.clear();
956 return false;
957}
958
959bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
960 if (GetHostInfo()) {
961 if (!m_hostname.empty()) {
962 s = m_hostname;
963 return true;
964 }
965 }
966 s.clear();
967 return false;
968}
969
970ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
971 if (GetHostInfo())
972 return m_host_arch;
973 return ArchSpec();
974}
975
976const lldb_private::ArchSpec &
977GDBRemoteCommunicationClient::GetProcessArchitecture() {
978 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
979 GetCurrentProcessInfo();
980 return m_process_arch;
981}
982
983bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
984 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
985 m_gdb_server_name.clear();
986 m_gdb_server_version = 0;
987 m_qGDBServerVersion_is_valid = eLazyBoolNo;
988
989 StringExtractorGDBRemote response;
990 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
991 PacketResult::Success) {
992 if (response.IsNormalResponse()) {
993 llvm::StringRef name, value;
994 bool success = false;
995 while (response.GetNameColonValue(name, value)) {
996 if (name.equals("name")) {
997 success = true;
998 m_gdb_server_name = value;
999 } else if (name.equals("version")) {
1000 llvm::StringRef major, minor;
1001 std::tie(major, minor) = value.split('.');
1002 if (!major.getAsInteger(0, m_gdb_server_version))
1003 success = true;
1004 }
Greg Clayton576d8832011-03-22 04:00:09 +00001005 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 if (success)
1007 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1008 }
Greg Clayton576d8832011-03-22 04:00:09 +00001009 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 }
1011 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001012}
1013
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014void GDBRemoteCommunicationClient::MaybeEnableCompression(
1015 std::vector<std::string> supported_compressions) {
1016 CompressionType avail_type = CompressionType::None;
1017 std::string avail_name;
1018
1019#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001020 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 for (auto compression : supported_compressions) {
1022 if (compression == "lzfse") {
1023 avail_type = CompressionType::LZFSE;
1024 avail_name = compression;
1025 break;
1026 }
1027 }
1028 }
1029#endif
1030
1031#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001032 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 for (auto compression : supported_compressions) {
1034 if (compression == "zlib-deflate") {
1035 avail_type = CompressionType::ZlibDeflate;
1036 avail_name = compression;
1037 break;
1038 }
1039 }
1040 }
1041#endif
1042
1043#if defined(HAVE_LIBZ)
1044 if (avail_type == CompressionType::None) {
1045 for (auto compression : supported_compressions) {
1046 if (compression == "zlib-deflate") {
1047 avail_type = CompressionType::ZlibDeflate;
1048 avail_name = compression;
1049 break;
1050 }
1051 }
1052 }
1053#endif
1054
1055#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001056 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 for (auto compression : supported_compressions) {
1058 if (compression == "lz4") {
1059 avail_type = CompressionType::LZ4;
1060 avail_name = compression;
1061 break;
1062 }
1063 }
1064 }
1065#endif
1066
1067#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001068 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001069 for (auto compression : supported_compressions) {
1070 if (compression == "lzma") {
1071 avail_type = CompressionType::LZMA;
1072 avail_name = compression;
1073 break;
1074 }
1075 }
1076 }
1077#endif
1078
1079 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001080 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001082 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 PacketResult::Success)
1084 return;
1085
1086 if (response.IsOKResponse()) {
1087 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001088 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089 }
Greg Clayton576d8832011-03-22 04:00:09 +00001090}
Greg Clayton32e0a752011-03-30 18:16:51 +00001091
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1093 if (GetGDBServerVersion()) {
1094 if (!m_gdb_server_name.empty())
1095 return m_gdb_server_name.c_str();
1096 }
1097 return NULL;
1098}
1099
1100uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1101 if (GetGDBServerVersion())
1102 return m_gdb_server_version;
1103 return 0;
1104}
1105
1106bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1107 StringExtractorGDBRemote response;
1108 if (SendPacketAndWaitForResponse("qC", response, false) !=
1109 PacketResult::Success)
1110 return false;
1111
1112 if (!response.IsNormalResponse())
1113 return false;
1114
1115 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1116 tid = response.GetHexMaxU32(true, -1);
1117
1118 return true;
1119}
1120
1121bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1122 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1123
1124 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
Pavel Labathe7ec0832018-08-31 05:34:03 +00001125 // host info computation can require DNS traffic and shelling out to external processes.
1126 // Increase the timeout to account for that.
1127 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001129 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1131 PacketResult::Success) {
1132 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001133 llvm::StringRef name;
1134 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001135 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1136 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001137 std::string arch_name;
1138 std::string os_name;
1139 std::string vendor_name;
1140 std::string triple;
1141 std::string distribution_id;
1142 uint32_t pointer_byte_size = 0;
1143 ByteOrder byte_order = eByteOrderInvalid;
1144 uint32_t num_keys_decoded = 0;
1145 while (response.GetNameColonValue(name, value)) {
1146 if (name.equals("cputype")) {
1147 // exception type in big endian hex
1148 if (!value.getAsInteger(0, cpu))
1149 ++num_keys_decoded;
1150 } else if (name.equals("cpusubtype")) {
1151 // exception count in big endian hex
1152 if (!value.getAsInteger(0, sub))
1153 ++num_keys_decoded;
1154 } else if (name.equals("arch")) {
1155 arch_name = value;
1156 ++num_keys_decoded;
1157 } else if (name.equals("triple")) {
1158 StringExtractor extractor(value);
1159 extractor.GetHexByteString(triple);
1160 ++num_keys_decoded;
1161 } else if (name.equals("distribution_id")) {
1162 StringExtractor extractor(value);
1163 extractor.GetHexByteString(distribution_id);
1164 ++num_keys_decoded;
1165 } else if (name.equals("os_build")) {
1166 StringExtractor extractor(value);
1167 extractor.GetHexByteString(m_os_build);
1168 ++num_keys_decoded;
1169 } else if (name.equals("hostname")) {
1170 StringExtractor extractor(value);
1171 extractor.GetHexByteString(m_hostname);
1172 ++num_keys_decoded;
1173 } else if (name.equals("os_kernel")) {
1174 StringExtractor extractor(value);
1175 extractor.GetHexByteString(m_os_kernel);
1176 ++num_keys_decoded;
1177 } else if (name.equals("ostype")) {
1178 os_name = value;
1179 ++num_keys_decoded;
1180 } else if (name.equals("vendor")) {
1181 vendor_name = value;
1182 ++num_keys_decoded;
1183 } else if (name.equals("endian")) {
1184 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1185 .Case("little", eByteOrderLittle)
1186 .Case("big", eByteOrderBig)
1187 .Case("pdp", eByteOrderPDP)
1188 .Default(eByteOrderInvalid);
1189 if (byte_order != eByteOrderInvalid)
1190 ++num_keys_decoded;
1191 } else if (name.equals("ptrsize")) {
1192 if (!value.getAsInteger(0, pointer_byte_size))
1193 ++num_keys_decoded;
1194 } else if (name.equals("os_version") ||
1195 name.equals(
1196 "version")) // Older debugserver binaries used the
1197 // "version" key instead of
1198 // "os_version"...
1199 {
Pavel Labath2272c482018-06-18 15:02:23 +00001200 if (!m_os_version.tryParse(value))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 ++num_keys_decoded;
1202 } else if (name.equals("watchpoint_exceptions_received")) {
1203 m_watchpoints_trigger_after_instruction =
1204 llvm::StringSwitch<LazyBool>(value)
1205 .Case("before", eLazyBoolNo)
1206 .Case("after", eLazyBoolYes)
1207 .Default(eLazyBoolCalculate);
1208 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1209 ++num_keys_decoded;
1210 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001211 uint32_t timeout_seconds;
1212 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001213 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 SetPacketTimeout(m_default_packet_timeout);
1215 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001216 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 }
Jason Molenda89c37492014-01-27 22:23:20 +00001218 }
1219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 if (num_keys_decoded > 0)
1221 m_qHostInfo_is_valid = eLazyBoolYes;
1222
1223 if (triple.empty()) {
1224 if (arch_name.empty()) {
1225 if (cpu != LLDB_INVALID_CPUTYPE) {
1226 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1227 if (pointer_byte_size) {
1228 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1229 }
1230 if (byte_order != eByteOrderInvalid) {
1231 assert(byte_order == m_host_arch.GetByteOrder());
1232 }
1233
1234 if (!vendor_name.empty())
1235 m_host_arch.GetTriple().setVendorName(
1236 llvm::StringRef(vendor_name));
1237 if (!os_name.empty())
1238 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001239 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001241 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 triple += arch_name;
1243 if (!vendor_name.empty() || !os_name.empty()) {
1244 triple += '-';
1245 if (vendor_name.empty())
1246 triple += "unknown";
1247 else
1248 triple += vendor_name;
1249 triple += '-';
1250 if (os_name.empty())
1251 triple += "unknown";
1252 else
1253 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001254 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001256
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 llvm::Triple &host_triple = m_host_arch.GetTriple();
1258 if (host_triple.getVendor() == llvm::Triple::Apple &&
1259 host_triple.getOS() == llvm::Triple::Darwin) {
1260 switch (m_host_arch.GetMachine()) {
1261 case llvm::Triple::aarch64:
1262 case llvm::Triple::arm:
1263 case llvm::Triple::thumb:
1264 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001265 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 default:
1267 host_triple.setOS(llvm::Triple::MacOSX);
1268 break;
1269 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001270 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 if (pointer_byte_size) {
1272 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1273 }
1274 if (byte_order != eByteOrderInvalid) {
1275 assert(byte_order == m_host_arch.GetByteOrder());
1276 }
1277 }
1278 } else {
1279 m_host_arch.SetTriple(triple.c_str());
1280 if (pointer_byte_size) {
1281 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1282 }
1283 if (byte_order != eByteOrderInvalid) {
1284 assert(byte_order == m_host_arch.GetByteOrder());
1285 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001286
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 if (log)
1288 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1289 "architecture as %s, triple as %s from triple text %s",
1290 __FUNCTION__, m_host_arch.GetArchitectureName()
1291 ? m_host_arch.GetArchitectureName()
1292 : "<null-arch-name>",
1293 m_host_arch.GetTriple().getTriple().c_str(),
1294 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001295 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 if (!distribution_id.empty())
1297 m_host_arch.SetDistributionId(distribution_id.c_str());
1298 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001299 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 }
1301 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001302}
Greg Clayton37a0a242012-04-11 00:24:49 +00001303
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304int GDBRemoteCommunicationClient::SendAttach(
1305 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1306 if (pid != LLDB_INVALID_PROCESS_ID) {
1307 char packet[64];
1308 const int packet_len =
1309 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001310 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001311 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001312 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 PacketResult::Success) {
1314 if (response.IsErrorResponse())
1315 return response.GetError();
1316 return 0;
1317 }
1318 }
1319 return -1;
1320}
1321
1322int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1323 size_t data_len) {
1324 StreamString packet;
1325 packet.PutCString("I");
1326 packet.PutBytesAsRawHex8(data, data_len);
1327 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001328 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1329 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 return 0;
1331 }
1332 return response.GetError();
1333}
1334
1335const lldb_private::ArchSpec &
1336GDBRemoteCommunicationClient::GetHostArchitecture() {
1337 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1338 GetHostInfo();
1339 return m_host_arch;
1340}
1341
Pavel Labath1eff73c2016-11-24 10:54:49 +00001342seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1344 GetHostInfo();
1345 return m_default_packet_timeout;
1346}
1347
1348addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1349 uint32_t permissions) {
1350 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1351 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1352 char packet[64];
1353 const int packet_len = ::snprintf(
1354 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1355 permissions & lldb::ePermissionsReadable ? "r" : "",
1356 permissions & lldb::ePermissionsWritable ? "w" : "",
1357 permissions & lldb::ePermissionsExecutable ? "x" : "");
1358 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001359 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001360 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001361 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 PacketResult::Success) {
1363 if (response.IsUnsupportedResponse())
1364 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1365 else if (!response.IsErrorResponse())
1366 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1367 } else {
1368 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1369 }
1370 }
1371 return LLDB_INVALID_ADDRESS;
1372}
1373
1374bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1375 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1376 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1377 char packet[64];
1378 const int packet_len =
1379 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1380 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001381 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001383 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384 PacketResult::Success) {
1385 if (response.IsUnsupportedResponse())
1386 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1387 else if (response.IsOKResponse())
1388 return true;
1389 } else {
1390 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1391 }
1392 }
1393 return false;
1394}
1395
Zachary Turner97206d52017-05-12 04:51:55 +00001396Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1397 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398
1399 if (keep_stopped) {
1400 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1401 char packet[64];
1402 const int packet_len =
1403 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1404 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001405 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001407 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001408 PacketResult::Success &&
1409 response.IsOKResponse()) {
1410 m_supports_detach_stay_stopped = eLazyBoolYes;
1411 } else {
1412 m_supports_detach_stay_stopped = eLazyBoolNo;
1413 }
1414 }
1415
1416 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1417 error.SetErrorString("Stays stopped not supported by this target.");
1418 return error;
1419 } else {
1420 StringExtractorGDBRemote response;
1421 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001422 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001423 if (packet_result != PacketResult::Success)
1424 error.SetErrorString("Sending extended disconnect packet failed.");
1425 }
1426 } else {
1427 StringExtractorGDBRemote response;
1428 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001429 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 if (packet_result != PacketResult::Success)
1431 error.SetErrorString("Sending disconnect packet failed.");
1432 }
1433 return error;
1434}
1435
Zachary Turner97206d52017-05-12 04:51:55 +00001436Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001438 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 region_info.Clear();
1440
1441 if (m_supports_memory_region_info != eLazyBoolNo) {
1442 m_supports_memory_region_info = eLazyBoolYes;
1443 char packet[64];
1444 const int packet_len = ::snprintf(
1445 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1446 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001447 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001449 if (SendPacketAndWaitForResponse(packet, response, false) ==
Pavel Labath16064d32018-03-20 11:56:24 +00001450 PacketResult::Success &&
1451 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 llvm::StringRef name;
1453 llvm::StringRef value;
1454 addr_t addr_value = LLDB_INVALID_ADDRESS;
1455 bool success = true;
1456 bool saw_permissions = false;
1457 while (success && response.GetNameColonValue(name, value)) {
1458 if (name.equals("start")) {
1459 if (!value.getAsInteger(16, addr_value))
1460 region_info.GetRange().SetRangeBase(addr_value);
1461 } else if (name.equals("size")) {
1462 if (!value.getAsInteger(16, addr_value))
1463 region_info.GetRange().SetByteSize(addr_value);
1464 } else if (name.equals("permissions") &&
1465 region_info.GetRange().IsValid()) {
1466 saw_permissions = true;
1467 if (region_info.GetRange().Contains(addr)) {
1468 if (value.find('r') != llvm::StringRef::npos)
1469 region_info.SetReadable(MemoryRegionInfo::eYes);
1470 else
1471 region_info.SetReadable(MemoryRegionInfo::eNo);
1472
1473 if (value.find('w') != llvm::StringRef::npos)
1474 region_info.SetWritable(MemoryRegionInfo::eYes);
1475 else
1476 region_info.SetWritable(MemoryRegionInfo::eNo);
1477
1478 if (value.find('x') != llvm::StringRef::npos)
1479 region_info.SetExecutable(MemoryRegionInfo::eYes);
1480 else
1481 region_info.SetExecutable(MemoryRegionInfo::eNo);
1482
1483 region_info.SetMapped(MemoryRegionInfo::eYes);
1484 } else {
1485 // The reported region does not contain this address -- we're
1486 // looking at an unmapped page
1487 region_info.SetReadable(MemoryRegionInfo::eNo);
1488 region_info.SetWritable(MemoryRegionInfo::eNo);
1489 region_info.SetExecutable(MemoryRegionInfo::eNo);
1490 region_info.SetMapped(MemoryRegionInfo::eNo);
1491 }
1492 } else if (name.equals("name")) {
1493 StringExtractorGDBRemote name_extractor(value);
1494 std::string name;
1495 name_extractor.GetHexByteString(name);
1496 region_info.SetName(name.c_str());
1497 } else if (name.equals("error")) {
1498 StringExtractorGDBRemote error_extractor(value);
1499 std::string error_string;
1500 // Now convert the HEX bytes into a string value
1501 error_extractor.GetHexByteString(error_string);
1502 error.SetErrorString(error_string.c_str());
1503 }
1504 }
1505
Stephane Sezer48d14272017-03-31 18:00:48 +00001506 if (region_info.GetRange().IsValid()) {
1507 // We got a valid address range back but no permissions -- which means
1508 // this is an unmapped page
1509 if (!saw_permissions) {
1510 region_info.SetReadable(MemoryRegionInfo::eNo);
1511 region_info.SetWritable(MemoryRegionInfo::eNo);
1512 region_info.SetExecutable(MemoryRegionInfo::eNo);
1513 region_info.SetMapped(MemoryRegionInfo::eNo);
1514 }
1515 } else {
1516 // We got an invalid address range back
1517 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001518 }
1519 } else {
1520 m_supports_memory_region_info = eLazyBoolNo;
1521 }
1522 }
1523
1524 if (m_supports_memory_region_info == eLazyBoolNo) {
1525 error.SetErrorString("qMemoryRegionInfo is not supported");
1526 }
Pavel Labath16064d32018-03-20 11:56:24 +00001527
1528 // Try qXfer:memory-map:read to get region information not included in
1529 // qMemoryRegionInfo
1530 MemoryRegionInfo qXfer_region_info;
1531 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1532
1533 if (error.Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001534 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1535 // the qXfer result as a fallback
Pavel Labath16064d32018-03-20 11:56:24 +00001536 if (qXfer_error.Success()) {
1537 region_info = qXfer_region_info;
1538 error.Clear();
1539 } else {
1540 region_info.Clear();
1541 }
1542 } else if (qXfer_error.Success()) {
1543 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
Adrian Prantl05097242018-04-30 16:49:04 +00001544 // both regions are the same range, update the result to include the flash-
1545 // memory information that is specific to the qXfer result.
Pavel Labath16064d32018-03-20 11:56:24 +00001546 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1547 region_info.SetFlash(qXfer_region_info.GetFlash());
1548 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1549 }
1550 }
1551 return error;
1552}
1553
1554Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1555 lldb::addr_t addr, MemoryRegionInfo &region) {
1556 Status error = LoadQXferMemoryMap();
1557 if (!error.Success())
1558 return error;
1559 for (const auto &map_region : m_qXfer_memory_map) {
1560 if (map_region.GetRange().Contains(addr)) {
1561 region = map_region;
1562 return error;
1563 }
1564 }
1565 error.SetErrorString("Region not found");
1566 return error;
1567}
1568
1569Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1570
1571 Status error;
1572
1573 if (m_qXfer_memory_map_loaded)
1574 // Already loaded, return success
1575 return error;
1576
1577 if (!XMLDocument::XMLEnabled()) {
1578 error.SetErrorString("XML is not supported");
1579 return error;
1580 }
1581
1582 if (!GetQXferMemoryMapReadSupported()) {
1583 error.SetErrorString("Memory map is not supported");
1584 return error;
1585 }
1586
1587 std::string xml;
1588 lldb_private::Status lldberr;
1589 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1590 lldberr)) {
1591 error.SetErrorString("Failed to read memory map");
1592 return error;
1593 }
1594
1595 XMLDocument xml_document;
1596
1597 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1598 error.SetErrorString("Failed to parse memory map xml");
1599 return error;
1600 }
1601
1602 XMLNode map_node = xml_document.GetRootElement("memory-map");
1603 if (!map_node) {
1604 error.SetErrorString("Invalid root node in memory map xml");
1605 return error;
1606 }
1607
1608 m_qXfer_memory_map.clear();
1609
1610 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1611 if (!memory_node.IsElement())
1612 return true;
1613 if (memory_node.GetName() != "memory")
1614 return true;
1615 auto type = memory_node.GetAttributeValue("type", "");
1616 uint64_t start;
1617 uint64_t length;
1618 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1619 return true;
1620 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1621 return true;
1622 MemoryRegionInfo region;
1623 region.GetRange().SetRangeBase(start);
1624 region.GetRange().SetByteSize(length);
1625 if (type == "rom") {
1626 region.SetReadable(MemoryRegionInfo::eYes);
1627 this->m_qXfer_memory_map.push_back(region);
1628 } else if (type == "ram") {
1629 region.SetReadable(MemoryRegionInfo::eYes);
1630 region.SetWritable(MemoryRegionInfo::eYes);
1631 this->m_qXfer_memory_map.push_back(region);
1632 } else if (type == "flash") {
1633 region.SetFlash(MemoryRegionInfo::eYes);
1634 memory_node.ForEachChildElement(
1635 [&region](const XMLNode &prop_node) -> bool {
1636 if (!prop_node.IsElement())
1637 return true;
1638 if (prop_node.GetName() != "property")
1639 return true;
1640 auto propname = prop_node.GetAttributeValue("name", "");
1641 if (propname == "blocksize") {
1642 uint64_t blocksize;
1643 if (prop_node.GetElementTextAsUnsigned(blocksize))
1644 region.SetBlocksize(blocksize);
1645 }
1646 return true;
1647 });
1648 this->m_qXfer_memory_map.push_back(region);
1649 }
1650 return true;
1651 });
1652
1653 m_qXfer_memory_map_loaded = true;
1654
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 return error;
1656}
1657
Zachary Turner97206d52017-05-12 04:51:55 +00001658Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1659 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660
1661 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1662 num = m_num_supported_hardware_watchpoints;
1663 return error;
1664 }
1665
1666 // Set num to 0 first.
1667 num = 0;
1668 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1669 char packet[64];
1670 const int packet_len =
1671 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1672 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001673 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001674 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001675 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676 PacketResult::Success) {
1677 m_supports_watchpoint_support_info = eLazyBoolYes;
1678 llvm::StringRef name;
1679 llvm::StringRef value;
Jason Molendac0e793d2018-11-09 22:33:26 +00001680 bool found_num_field = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681 while (response.GetNameColonValue(name, value)) {
1682 if (name.equals("num")) {
1683 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1684 num = m_num_supported_hardware_watchpoints;
Jason Molendac0e793d2018-11-09 22:33:26 +00001685 found_num_field = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001686 }
1687 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001688 if (!found_num_field) {
Jason Molendac0e793d2018-11-09 22:33:26 +00001689 m_supports_watchpoint_support_info = eLazyBoolNo;
1690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 } else {
1692 m_supports_watchpoint_support_info = eLazyBoolNo;
1693 }
1694 }
1695
1696 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1697 error.SetErrorString("qWatchpointSupportInfo is not supported");
1698 }
1699 return error;
1700}
1701
Zachary Turner97206d52017-05-12 04:51:55 +00001702lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001704 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001705 if (error.Success())
1706 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1707 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001708}
1709
Zachary Turner97206d52017-05-12 04:51:55 +00001710lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1712 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001713 Status error;
Fangrui Song2f677ab2019-05-16 09:07:33 +00001714 llvm::Triple triple = arch.GetTriple();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001715
Adrian Prantl05097242018-04-30 16:49:04 +00001716 // we assume watchpoints will happen after running the relevant opcode and we
1717 // only want to override this behavior if we have explicitly received a
1718 // qHostInfo telling us otherwise
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719 if (m_qHostInfo_is_valid != eLazyBoolYes) {
Fangrui Song2f677ab2019-05-16 09:07:33 +00001720 // On targets like MIPS and ppc64, watchpoint exceptions are always
Adrian Prantl05097242018-04-30 16:49:04 +00001721 // generated before the instruction is executed. The connected target may
1722 // not support qHostInfo or qWatchpointSupportInfo packets.
Fangrui Song2f677ab2019-05-16 09:07:33 +00001723 after = !(triple.isMIPS() || triple.isPPC64());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001724 } else {
Fangrui Song2f677ab2019-05-16 09:07:33 +00001725 // For MIPS and ppc64, set m_watchpoints_trigger_after_instruction to
Pavel Labathc51ad482017-10-27 17:02:32 +00001726 // eLazyBoolNo if it is not calculated before.
Fangrui Songddb93b62019-05-16 08:37:32 +00001727 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
Fangrui Song2f677ab2019-05-16 09:07:33 +00001728 (triple.isMIPS() || triple.isPPC64()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1730
1731 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1732 }
1733 return error;
1734}
1735
1736int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1737 if (file_spec) {
1738 std::string path{file_spec.GetPath(false)};
1739 StreamString packet;
1740 packet.PutCString("QSetSTDIN:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001741 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742
1743 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001744 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1745 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746 if (response.IsOKResponse())
1747 return 0;
1748 uint8_t error = response.GetError();
1749 if (error)
1750 return error;
1751 }
1752 }
1753 return -1;
1754}
1755
1756int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1757 if (file_spec) {
1758 std::string path{file_spec.GetPath(false)};
1759 StreamString packet;
1760 packet.PutCString("QSetSTDOUT:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001761 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001762
1763 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001764 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1765 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766 if (response.IsOKResponse())
1767 return 0;
1768 uint8_t error = response.GetError();
1769 if (error)
1770 return error;
1771 }
1772 }
1773 return -1;
1774}
1775
1776int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1777 if (file_spec) {
1778 std::string path{file_spec.GetPath(false)};
1779 StreamString packet;
1780 packet.PutCString("QSetSTDERR:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001781 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001782
1783 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001784 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1785 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786 if (response.IsOKResponse())
1787 return 0;
1788 uint8_t error = response.GetError();
1789 if (error)
1790 return error;
1791 }
1792 }
1793 return -1;
1794}
1795
1796bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1797 StringExtractorGDBRemote response;
1798 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1799 PacketResult::Success) {
1800 if (response.IsUnsupportedResponse())
1801 return false;
1802 if (response.IsErrorResponse())
1803 return false;
1804 std::string cwd;
1805 response.GetHexByteString(cwd);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001806 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807 return !cwd.empty();
1808 }
1809 return false;
1810}
1811
1812int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1813 if (working_dir) {
1814 std::string path{working_dir.GetPath(false)};
1815 StreamString packet;
1816 packet.PutCString("QSetWorkingDir:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001817 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001818
1819 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001820 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1821 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001822 if (response.IsOKResponse())
1823 return 0;
1824 uint8_t error = response.GetError();
1825 if (error)
1826 return error;
1827 }
1828 }
1829 return -1;
1830}
1831
1832int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1833 char packet[32];
1834 const int packet_len =
1835 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1836 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001837 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001838 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001839 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001840 PacketResult::Success) {
1841 if (response.IsOKResponse())
1842 return 0;
1843 uint8_t error = response.GetError();
1844 if (error)
1845 return error;
1846 }
1847 return -1;
1848}
1849
1850int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1851 char packet[32];
1852 const int packet_len = ::snprintf(packet, sizeof(packet),
1853 "QSetDetachOnError:%i", enable ? 1 : 0);
1854 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001855 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001856 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001857 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001858 PacketResult::Success) {
1859 if (response.IsOKResponse())
1860 return 0;
1861 uint8_t error = response.GetError();
1862 if (error)
1863 return error;
1864 }
1865 return -1;
1866}
1867
1868bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1869 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1870 if (response.IsNormalResponse()) {
1871 llvm::StringRef name;
1872 llvm::StringRef value;
1873 StringExtractor extractor;
1874
1875 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1876 uint32_t sub = 0;
1877 std::string vendor;
1878 std::string os_type;
1879
1880 while (response.GetNameColonValue(name, value)) {
1881 if (name.equals("pid")) {
1882 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1883 value.getAsInteger(0, pid);
1884 process_info.SetProcessID(pid);
1885 } else if (name.equals("ppid")) {
1886 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1887 value.getAsInteger(0, pid);
1888 process_info.SetParentProcessID(pid);
1889 } else if (name.equals("uid")) {
1890 uint32_t uid = UINT32_MAX;
1891 value.getAsInteger(0, uid);
1892 process_info.SetUserID(uid);
1893 } else if (name.equals("euid")) {
1894 uint32_t uid = UINT32_MAX;
1895 value.getAsInteger(0, uid);
1896 process_info.SetEffectiveGroupID(uid);
1897 } else if (name.equals("gid")) {
1898 uint32_t gid = UINT32_MAX;
1899 value.getAsInteger(0, gid);
1900 process_info.SetGroupID(gid);
1901 } else if (name.equals("egid")) {
1902 uint32_t gid = UINT32_MAX;
1903 value.getAsInteger(0, gid);
1904 process_info.SetEffectiveGroupID(gid);
1905 } else if (name.equals("triple")) {
1906 StringExtractor extractor(value);
1907 std::string triple;
1908 extractor.GetHexByteString(triple);
1909 process_info.GetArchitecture().SetTriple(triple.c_str());
1910 } else if (name.equals("name")) {
1911 StringExtractor extractor(value);
Adrian Prantl05097242018-04-30 16:49:04 +00001912 // The process name from ASCII hex bytes since we can't control the
1913 // characters in a process name
Kate Stoneb9c1b512016-09-06 20:57:50 +00001914 std::string name;
1915 extractor.GetHexByteString(name);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001916 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001917 } else if (name.equals("cputype")) {
1918 value.getAsInteger(0, cpu);
1919 } else if (name.equals("cpusubtype")) {
1920 value.getAsInteger(0, sub);
1921 } else if (name.equals("vendor")) {
1922 vendor = value;
1923 } else if (name.equals("ostype")) {
1924 os_type = value;
1925 }
1926 }
1927
1928 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1929 if (vendor == "apple") {
1930 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1931 sub);
1932 process_info.GetArchitecture().GetTriple().setVendorName(
1933 llvm::StringRef(vendor));
1934 process_info.GetArchitecture().GetTriple().setOSName(
1935 llvm::StringRef(os_type));
1936 }
1937 }
1938
1939 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1940 return true;
1941 }
1942 return false;
1943}
1944
1945bool GDBRemoteCommunicationClient::GetProcessInfo(
1946 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1947 process_info.Clear();
1948
1949 if (m_supports_qProcessInfoPID) {
1950 char packet[32];
1951 const int packet_len =
1952 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1953 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001954 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001956 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001957 PacketResult::Success) {
1958 return DecodeProcessInfoResponse(response, process_info);
1959 } else {
1960 m_supports_qProcessInfoPID = false;
1961 return false;
1962 }
1963 }
1964 return false;
1965}
1966
1967bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1968 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1969 GDBR_LOG_PACKETS));
1970
1971 if (allow_lazy) {
1972 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1973 return true;
1974 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1975 return false;
1976 }
1977
1978 GetHostInfo();
1979
1980 StringExtractorGDBRemote response;
1981 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1982 PacketResult::Success) {
1983 if (response.IsNormalResponse()) {
1984 llvm::StringRef name;
1985 llvm::StringRef value;
1986 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1987 uint32_t sub = 0;
1988 std::string arch_name;
1989 std::string os_name;
1990 std::string vendor_name;
1991 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001992 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001993 uint32_t pointer_byte_size = 0;
1994 StringExtractor extractor;
1995 ByteOrder byte_order = eByteOrderInvalid;
1996 uint32_t num_keys_decoded = 0;
1997 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1998 while (response.GetNameColonValue(name, value)) {
1999 if (name.equals("cputype")) {
2000 if (!value.getAsInteger(16, cpu))
2001 ++num_keys_decoded;
2002 } else if (name.equals("cpusubtype")) {
2003 if (!value.getAsInteger(16, sub))
2004 ++num_keys_decoded;
2005 } else if (name.equals("triple")) {
2006 StringExtractor extractor(value);
2007 extractor.GetHexByteString(triple);
2008 ++num_keys_decoded;
2009 } else if (name.equals("ostype")) {
2010 os_name = value;
2011 ++num_keys_decoded;
2012 } else if (name.equals("vendor")) {
2013 vendor_name = value;
2014 ++num_keys_decoded;
2015 } else if (name.equals("endian")) {
2016 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2017 .Case("little", eByteOrderLittle)
2018 .Case("big", eByteOrderBig)
2019 .Case("pdp", eByteOrderPDP)
2020 .Default(eByteOrderInvalid);
2021 if (byte_order != eByteOrderInvalid)
2022 ++num_keys_decoded;
2023 } else if (name.equals("ptrsize")) {
2024 if (!value.getAsInteger(16, pointer_byte_size))
2025 ++num_keys_decoded;
2026 } else if (name.equals("pid")) {
2027 if (!value.getAsInteger(16, pid))
2028 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002029 } else if (name.equals("elf_abi")) {
2030 elf_abi = value;
2031 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002032 }
2033 }
2034 if (num_keys_decoded > 0)
2035 m_qProcessInfo_is_valid = eLazyBoolYes;
2036 if (pid != LLDB_INVALID_PROCESS_ID) {
2037 m_curr_pid_is_valid = eLazyBoolYes;
2038 m_curr_pid = pid;
2039 }
2040
2041 // Set the ArchSpec from the triple if we have it.
2042 if (!triple.empty()) {
2043 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00002044 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002045 if (pointer_byte_size) {
2046 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2047 }
2048 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2049 !vendor_name.empty()) {
2050 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2051
2052 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00002053 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Jason Liua03ae732019-03-12 22:01:10 +00002054 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002055 switch (triple.getObjectFormat()) {
2056 case llvm::Triple::MachO:
2057 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2058 break;
2059 case llvm::Triple::ELF:
2060 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2061 break;
2062 case llvm::Triple::COFF:
2063 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2064 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00002065 case llvm::Triple::Wasm:
Jason Liua03ae732019-03-12 22:01:10 +00002066 case llvm::Triple::XCOFF:
Pavel Labath4f19fce22017-02-17 13:39:50 +00002067 if (log)
2068 log->Printf("error: not supported target architecture");
2069 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002070 case llvm::Triple::UnknownObjectFormat:
2071 if (log)
2072 log->Printf("error: failed to determine target architecture");
2073 return false;
2074 }
2075
2076 if (pointer_byte_size) {
2077 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2078 }
2079 if (byte_order != eByteOrderInvalid) {
2080 assert(byte_order == m_process_arch.GetByteOrder());
2081 }
2082 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2083 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2084 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2085 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2086 }
2087 return true;
2088 }
2089 } else {
2090 m_qProcessInfo_is_valid = eLazyBoolNo;
2091 }
2092
2093 return false;
2094}
2095
2096uint32_t GDBRemoteCommunicationClient::FindProcesses(
2097 const ProcessInstanceInfoMatch &match_info,
2098 ProcessInstanceInfoList &process_infos) {
2099 process_infos.Clear();
2100
2101 if (m_supports_qfProcessInfo) {
2102 StreamString packet;
2103 packet.PutCString("qfProcessInfo");
2104 if (!match_info.MatchAllProcesses()) {
2105 packet.PutChar(':');
2106 const char *name = match_info.GetProcessInfo().GetName();
2107 bool has_name_match = false;
2108 if (name && name[0]) {
2109 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00002110 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002111 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00002112 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002113 has_name_match = false;
2114 break;
2115
Pavel Labathc4a33952017-02-20 11:35:33 +00002116 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002117 packet.PutCString("name_match:equals;");
2118 break;
2119
Pavel Labathc4a33952017-02-20 11:35:33 +00002120 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002121 packet.PutCString("name_match:contains;");
2122 break;
2123
Pavel Labathc4a33952017-02-20 11:35:33 +00002124 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002125 packet.PutCString("name_match:starts_with;");
2126 break;
2127
Pavel Labathc4a33952017-02-20 11:35:33 +00002128 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002129 packet.PutCString("name_match:ends_with;");
2130 break;
2131
Pavel Labathc4a33952017-02-20 11:35:33 +00002132 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002133 packet.PutCString("name_match:regex;");
2134 break;
2135 }
2136 if (has_name_match) {
2137 packet.PutCString("name:");
2138 packet.PutBytesAsRawHex8(name, ::strlen(name));
2139 packet.PutChar(';');
2140 }
2141 }
2142
2143 if (match_info.GetProcessInfo().ProcessIDIsValid())
2144 packet.Printf("pid:%" PRIu64 ";",
2145 match_info.GetProcessInfo().GetProcessID());
2146 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2147 packet.Printf("parent_pid:%" PRIu64 ";",
2148 match_info.GetProcessInfo().GetParentProcessID());
2149 if (match_info.GetProcessInfo().UserIDIsValid())
2150 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2151 if (match_info.GetProcessInfo().GroupIDIsValid())
2152 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2153 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2154 packet.Printf("euid:%u;",
2155 match_info.GetProcessInfo().GetEffectiveUserID());
2156 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2157 packet.Printf("egid:%u;",
2158 match_info.GetProcessInfo().GetEffectiveGroupID());
2159 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2160 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2161 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2162 const ArchSpec &match_arch =
2163 match_info.GetProcessInfo().GetArchitecture();
2164 const llvm::Triple &triple = match_arch.GetTriple();
2165 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002166 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167 packet.PutChar(';');
2168 }
2169 }
2170 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +00002171 // Increase timeout as the first qfProcessInfo packet takes a long time on
2172 // Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002173 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002174 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2175 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176 do {
2177 ProcessInstanceInfo process_info;
2178 if (!DecodeProcessInfoResponse(response, process_info))
2179 break;
2180 process_infos.Append(process_info);
2181 response.GetStringRef().clear();
2182 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002183 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2184 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002185 } else {
2186 m_supports_qfProcessInfo = false;
2187 return 0;
2188 }
2189 }
2190 return process_infos.GetSize();
2191}
2192
2193bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2194 std::string &name) {
2195 if (m_supports_qUserName) {
2196 char packet[32];
2197 const int packet_len =
2198 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2199 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002200 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002201 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002202 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002203 PacketResult::Success) {
2204 if (response.IsNormalResponse()) {
2205 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002206 // the hex encoded user name and should make up the entire packet. If
2207 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208 if (response.GetHexByteString(name) * 2 ==
2209 response.GetStringRef().size())
2210 return true;
2211 }
2212 } else {
2213 m_supports_qUserName = false;
2214 return false;
2215 }
2216 }
2217 return false;
2218}
2219
2220bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2221 std::string &name) {
2222 if (m_supports_qGroupName) {
2223 char packet[32];
2224 const int packet_len =
2225 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2226 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002227 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002229 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002230 PacketResult::Success) {
2231 if (response.IsNormalResponse()) {
2232 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002233 // the hex encoded group name and should make up the entire packet. If
2234 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 if (response.GetHexByteString(name) * 2 ==
2236 response.GetStringRef().size())
2237 return true;
2238 }
2239 } else {
2240 m_supports_qGroupName = false;
2241 return false;
2242 }
2243 }
2244 return false;
2245}
2246
2247bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2248 // Form non-stop packet request
2249 char packet[32];
2250 const int packet_len =
2251 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2252 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002253 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002254
2255 StringExtractorGDBRemote response;
2256 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002257 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258 PacketResult::Success)
2259 if (response.IsOKResponse())
2260 return true;
2261
2262 // Failed or not supported
2263 return false;
2264}
2265
2266static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2267 uint32_t recv_size) {
2268 packet.Clear();
2269 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2270 uint32_t bytes_left = send_size;
2271 while (bytes_left > 0) {
2272 if (bytes_left >= 26) {
2273 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2274 bytes_left -= 26;
2275 } else {
2276 packet.Printf("%*.*s;", bytes_left, bytes_left,
2277 "abcdefghijklmnopqrstuvwxyz");
2278 bytes_left = 0;
2279 }
2280 }
2281}
2282
Pavel Labath1eff73c2016-11-24 10:54:49 +00002283duration<float>
2284calculate_standard_deviation(const std::vector<duration<float>> &v) {
2285 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002286 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2287 Dur mean = sum / v.size();
2288 float accum = 0;
2289 for (auto d : v) {
2290 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002291 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002292 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293
Pavel Labath3aa04912016-10-31 17:19:42 +00002294 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002295}
2296
2297void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2298 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002299 uint32_t max_recv,
2300 uint64_t recv_amount,
2301 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002303 if (SendSpeedTestPacket(0, 0)) {
2304 StreamString packet;
2305 if (json)
2306 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2307 "\"results\" : [",
2308 num_packets);
2309 else
2310 strm.Printf("Testing sending %u packets of various sizes:\n",
2311 num_packets);
2312 strm.Flush();
2313
2314 uint32_t result_idx = 0;
2315 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002316 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002317
2318 for (send_size = 0; send_size <= max_send;
2319 send_size ? send_size *= 2 : send_size = 4) {
2320 for (uint32_t recv_size = 0; recv_size <= max_recv;
2321 recv_size ? recv_size *= 2 : recv_size = 4) {
2322 MakeSpeedTestPacket(packet, send_size, recv_size);
2323
2324 packet_times.clear();
2325 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002326 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002327 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002328 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002330 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002331 const auto packet_end_time = steady_clock::now();
2332 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002333 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002334 const auto end_time = steady_clock::now();
2335 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002336
2337 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002338 ((float)num_packets) / duration<float>(total_time).count();
2339 auto average_per_packet = total_time / num_packets;
2340 const duration<float> standard_deviation =
2341 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002342 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002343 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2344 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2345 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002346 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002347 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348 ++result_idx;
2349 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002350 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2351 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2352 "standard deviation of {5,10:ms+f6}\n",
2353 send_size, recv_size, duration<float>(total_time),
2354 packets_per_second, duration<float>(average_per_packet),
2355 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002356 }
2357 strm.Flush();
2358 }
2359 }
2360
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002361 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362 if (json)
2363 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2364 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002365 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366 else
2367 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2368 "packet sizes:\n",
2369 k_recv_amount_mb);
2370 strm.Flush();
2371 send_size = 0;
2372 result_idx = 0;
2373 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2374 MakeSpeedTestPacket(packet, send_size, recv_size);
2375
2376 // If we have a receive size, test how long it takes to receive 4MB of
2377 // data
2378 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002379 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002380 uint32_t bytes_read = 0;
2381 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002382 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002383 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002384 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002385 bytes_read += recv_size;
2386 ++packet_count;
2387 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002388 const auto end_time = steady_clock::now();
2389 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002390 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002391 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392 (1024.0 * 1024.0);
2393 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002394 ((float)packet_count) / duration<float>(total_time).count();
2395 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396
2397 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002398 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2399 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002400 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002401 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 ++result_idx;
2403 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002404 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2405 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2406 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002408 duration<float>(total_time), mb_second,
2409 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 }
2411 strm.Flush();
2412 }
2413 }
2414 if (json)
2415 strm.Printf("\n ]\n }\n}\n");
2416 else
2417 strm.EOL();
2418 }
2419}
2420
2421bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2422 uint32_t recv_size) {
2423 StreamString packet;
2424 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2425 uint32_t bytes_left = send_size;
2426 while (bytes_left > 0) {
2427 if (bytes_left >= 26) {
2428 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2429 bytes_left -= 26;
2430 } else {
2431 packet.Printf("%*.*s;", bytes_left, bytes_left,
2432 "abcdefghijklmnopqrstuvwxyz");
2433 bytes_left = 0;
2434 }
2435 }
2436
2437 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002438 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2439 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002440}
2441
2442bool GDBRemoteCommunicationClient::LaunchGDBServer(
2443 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2444 std::string &socket_name) {
2445 pid = LLDB_INVALID_PROCESS_ID;
2446 port = 0;
2447 socket_name.clear();
2448
2449 StringExtractorGDBRemote response;
2450 StreamString stream;
2451 stream.PutCString("qLaunchGDBServer;");
2452 std::string hostname;
2453 if (remote_accept_hostname && remote_accept_hostname[0])
2454 hostname = remote_accept_hostname;
2455 else {
2456 if (HostInfo::GetHostname(hostname)) {
2457 // Make the GDB server we launch only accept connections from this host
2458 stream.Printf("host:%s;", hostname.c_str());
2459 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002460 // Make the GDB server we launch accept connections from any host since
2461 // we can't figure out the hostname
Kate Stoneb9c1b512016-09-06 20:57:50 +00002462 stream.Printf("host:*;");
2463 }
2464 }
2465 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002466 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467
2468 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2469 PacketResult::Success) {
2470 llvm::StringRef name;
2471 llvm::StringRef value;
2472 while (response.GetNameColonValue(name, value)) {
2473 if (name.equals("port"))
2474 value.getAsInteger(0, port);
2475 else if (name.equals("pid"))
2476 value.getAsInteger(0, pid);
2477 else if (name.compare("socket_name") == 0) {
2478 StringExtractor extractor(value);
2479 extractor.GetHexByteString(socket_name);
2480 }
2481 }
2482 return true;
2483 }
2484 return false;
2485}
2486
2487size_t GDBRemoteCommunicationClient::QueryGDBServer(
2488 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2489 connection_urls.clear();
2490
2491 StringExtractorGDBRemote response;
2492 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2493 PacketResult::Success)
2494 return 0;
2495
2496 StructuredData::ObjectSP data =
2497 StructuredData::ParseJSON(response.GetStringRef());
2498 if (!data)
2499 return 0;
2500
2501 StructuredData::Array *array = data->GetAsArray();
2502 if (!array)
2503 return 0;
2504
2505 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2506 StructuredData::Dictionary *element = nullptr;
2507 if (!array->GetItemAtIndexAsDictionary(i, element))
2508 continue;
2509
2510 uint16_t port = 0;
2511 if (StructuredData::ObjectSP port_osp =
2512 element->GetValueForKey(llvm::StringRef("port")))
2513 port = port_osp->GetIntegerValue(0);
2514
2515 std::string socket_name;
2516 if (StructuredData::ObjectSP socket_name_osp =
2517 element->GetValueForKey(llvm::StringRef("socket_name")))
2518 socket_name = socket_name_osp->GetStringValue();
2519
2520 if (port != 0 || !socket_name.empty())
2521 connection_urls.emplace_back(port, socket_name);
2522 }
2523 return connection_urls.size();
2524}
2525
2526bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2527 StreamString stream;
2528 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002529
2530 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002531 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002532 PacketResult::Success) {
2533 if (response.IsOKResponse())
2534 return true;
2535 }
2536 return false;
2537}
2538
2539bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2540 if (m_curr_tid == tid)
2541 return true;
2542
2543 char packet[32];
2544 int packet_len;
2545 if (tid == UINT64_MAX)
2546 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2547 else
2548 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2549 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002550 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002551 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002552 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002553 PacketResult::Success) {
2554 if (response.IsOKResponse()) {
2555 m_curr_tid = tid;
2556 return true;
2557 }
2558
2559 /*
2560 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2561 * Hg packet.
2562 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2563 * which can
2564 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2565 */
2566 if (response.IsUnsupportedResponse() && IsConnected()) {
2567 m_curr_tid = 1;
2568 return true;
2569 }
2570 }
2571 return false;
2572}
2573
2574bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2575 if (m_curr_tid_run == tid)
2576 return true;
2577
2578 char packet[32];
2579 int packet_len;
2580 if (tid == UINT64_MAX)
2581 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2582 else
2583 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2584
2585 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002586 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002587 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002588 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002589 PacketResult::Success) {
2590 if (response.IsOKResponse()) {
2591 m_curr_tid_run = tid;
2592 return true;
2593 }
2594
2595 /*
2596 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2597 * Hc packet.
2598 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2599 * which can
2600 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2601 */
2602 if (response.IsUnsupportedResponse() && IsConnected()) {
2603 m_curr_tid_run = 1;
2604 return true;
2605 }
2606 }
2607 return false;
2608}
2609
2610bool GDBRemoteCommunicationClient::GetStopReply(
2611 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002612 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002613 PacketResult::Success)
2614 return response.IsNormalResponse();
2615 return false;
2616}
2617
2618bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2619 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2620 if (m_supports_qThreadStopInfo) {
2621 char packet[256];
2622 int packet_len =
2623 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2624 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002625 UNUSED_IF_ASSERT_DISABLED(packet_len);
2626 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002627 PacketResult::Success) {
2628 if (response.IsUnsupportedResponse())
2629 m_supports_qThreadStopInfo = false;
2630 else if (response.IsNormalResponse())
2631 return true;
2632 else
2633 return false;
2634 } else {
2635 m_supports_qThreadStopInfo = false;
2636 }
2637 }
2638 return false;
2639}
2640
2641uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2642 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2643 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2644 if (log)
2645 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2646 __FUNCTION__, insert ? "add" : "remove", addr);
2647
2648 // Check if the stub is known not to support this breakpoint type
2649 if (!SupportsGDBStoppointPacket(type))
2650 return UINT8_MAX;
2651 // Construct the breakpoint packet
2652 char packet[64];
2653 const int packet_len =
2654 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2655 insert ? 'Z' : 'z', type, addr, length);
2656 // Check we haven't overwritten the end of the packet buffer
2657 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002658 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002659 StringExtractorGDBRemote response;
2660 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2661 // or "" (unsupported)
2662 response.SetResponseValidatorToOKErrorNotSupported();
2663 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002664 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002665 PacketResult::Success) {
2666 // Receive and OK packet when the breakpoint successfully placed
2667 if (response.IsOKResponse())
2668 return 0;
2669
Zachary Turner97206d52017-05-12 04:51:55 +00002670 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002671 if (response.IsErrorResponse())
2672 return response.GetError();
2673
2674 // Empty packet informs us that breakpoint is not supported
2675 if (response.IsUnsupportedResponse()) {
2676 // Disable this breakpoint type since it is unsupported
2677 switch (type) {
2678 case eBreakpointSoftware:
2679 m_supports_z0 = false;
2680 break;
2681 case eBreakpointHardware:
2682 m_supports_z1 = false;
2683 break;
2684 case eWatchpointWrite:
2685 m_supports_z2 = false;
2686 break;
2687 case eWatchpointRead:
2688 m_supports_z3 = false;
2689 break;
2690 case eWatchpointReadWrite:
2691 m_supports_z4 = false;
2692 break;
2693 case eStoppointInvalid:
2694 return UINT8_MAX;
2695 }
2696 }
2697 }
2698 // Signal generic failure
2699 return UINT8_MAX;
2700}
2701
2702size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2703 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2704 thread_ids.clear();
2705
2706 Lock lock(*this, false);
2707 if (lock) {
2708 sequence_mutex_unavailable = false;
2709 StringExtractorGDBRemote response;
2710
2711 PacketResult packet_result;
2712 for (packet_result =
2713 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2714 packet_result == PacketResult::Success && response.IsNormalResponse();
2715 packet_result =
2716 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2717 char ch = response.GetChar();
2718 if (ch == 'l')
2719 break;
2720 if (ch == 'm') {
2721 do {
2722 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2723
2724 if (tid != LLDB_INVALID_THREAD_ID) {
2725 thread_ids.push_back(tid);
2726 }
2727 ch = response.GetChar(); // Skip the command separator
2728 } while (ch == ','); // Make sure we got a comma separator
2729 }
2730 }
2731
2732 /*
2733 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2734 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2735 * could
2736 * be as simple as 'S05'. There is no packet which can give us pid and/or
2737 * tid.
2738 * Assume pid=tid=1 in such cases.
2739 */
Tamas Berghammer1492cb82017-09-18 10:24:48 +00002740 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2741 thread_ids.size() == 0 && IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742 thread_ids.push_back(1);
2743 }
2744 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002745#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002746 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2747 GDBR_LOG_PACKETS));
2748 if (log)
2749 log->Printf("error: failed to get packet sequence mutex, not sending "
2750 "packet 'qfThreadInfo'");
2751#endif
2752 sequence_mutex_unavailable = true;
2753 }
2754 return thread_ids.size();
2755}
2756
2757lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2758 StringExtractorGDBRemote response;
2759 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2760 PacketResult::Success ||
2761 !response.IsNormalResponse())
2762 return LLDB_INVALID_ADDRESS;
2763 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2764}
2765
Zachary Turner97206d52017-05-12 04:51:55 +00002766lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002767 const char *command, // Shouldn't be NULL
2768 const FileSpec &
2769 working_dir, // Pass empty FileSpec to use the current working directory
2770 int *status_ptr, // Pass NULL if you don't want the process exit status
2771 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2772 // process to exit
2773 std::string
2774 *command_output, // Pass NULL if you don't want the command output
Pavel Labath19dd1a02018-05-10 10:46:03 +00002775 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 lldb_private::StreamString stream;
2777 stream.PutCString("qPlatform_shell:");
2778 stream.PutBytesAsRawHex8(command, strlen(command));
2779 stream.PutChar(',');
Pavel Labath19dd1a02018-05-10 10:46:03 +00002780 uint32_t timeout_sec = UINT32_MAX;
2781 if (timeout) {
2782 // TODO: Use chrono version of std::ceil once c++17 is available.
2783 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2784 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002785 stream.PutHex32(timeout_sec);
2786 if (working_dir) {
2787 std::string path{working_dir.GetPath(false)};
2788 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002789 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002792 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002793 PacketResult::Success) {
2794 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002795 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002796 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002797 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002798 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2799 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002800 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 else if (status_ptr)
2802 *status_ptr = exitcode;
2803 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002804 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2806 if (signo_ptr)
2807 *signo_ptr = signo;
2808 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002809 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810 std::string output;
2811 response.GetEscapedBinaryData(output);
2812 if (command_output)
2813 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002814 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815 }
Zachary Turner97206d52017-05-12 04:51:55 +00002816 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817}
2818
Zachary Turner97206d52017-05-12 04:51:55 +00002819Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2820 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 std::string path{file_spec.GetPath(false)};
2822 lldb_private::StreamString stream;
2823 stream.PutCString("qPlatform_mkdir:");
2824 stream.PutHex32(file_permissions);
2825 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002826 stream.PutStringAsRawHex8(path);
Zachary Turnerc1564272016-11-16 21:15:24 +00002827 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 StringExtractorGDBRemote response;
2829
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002830 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002831 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002832 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833
2834 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002835 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836
Zachary Turner97206d52017-05-12 04:51:55 +00002837 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838}
2839
Zachary Turner97206d52017-05-12 04:51:55 +00002840Status
2841GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2842 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 std::string path{file_spec.GetPath(false)};
2844 lldb_private::StreamString stream;
2845 stream.PutCString("qPlatform_chmod:");
2846 stream.PutHex32(file_permissions);
2847 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002848 stream.PutStringAsRawHex8(path);
Zachary Turnerc1564272016-11-16 21:15:24 +00002849 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 StringExtractorGDBRemote response;
2851
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002852 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002853 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002854 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855
2856 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002857 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858
Zachary Turner97206d52017-05-12 04:51:55 +00002859 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002860}
2861
2862static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002863 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864 response.SetFilePos(0);
2865 if (response.GetChar() != 'F')
2866 return fail_result;
2867 int32_t result = response.GetS32(-2);
2868 if (result == -2)
2869 return fail_result;
2870 if (response.GetChar() == ',') {
2871 int result_errno = response.GetS32(-2);
2872 if (result_errno != -2)
2873 error.SetError(result_errno, eErrorTypePOSIX);
2874 else
2875 error.SetError(-1, eErrorTypeGeneric);
2876 } else
2877 error.Clear();
2878 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002879}
2880lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002881GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2882 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002883 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002884 std::string path(file_spec.GetPath(false));
2885 lldb_private::StreamString stream;
2886 stream.PutCString("vFile:open:");
2887 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002888 return UINT64_MAX;
Pavel Labath7f815a92019-02-12 14:28:55 +00002889 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 stream.PutChar(',');
2891 stream.PutHex32(flags);
2892 stream.PutChar(',');
2893 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002895 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002896 PacketResult::Success) {
2897 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2898 }
2899 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002900}
2901
Zachary Turner97206d52017-05-12 04:51:55 +00002902bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2903 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002904 lldb_private::StreamString stream;
2905 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002906 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002907 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002908 PacketResult::Success) {
2909 return ParseHostIOPacketResponse(response, -1, error) == 0;
2910 }
2911 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002912}
2913
2914// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002915lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2916 const lldb_private::FileSpec &file_spec) {
2917 std::string path(file_spec.GetPath(false));
2918 lldb_private::StreamString stream;
2919 stream.PutCString("vFile:size:");
Pavel Labath7f815a92019-02-12 14:28:55 +00002920 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002922 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002923 PacketResult::Success) {
2924 if (response.GetChar() != 'F')
2925 return UINT64_MAX;
2926 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2927 return retcode;
2928 }
2929 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002930}
2931
Zachary Turner97206d52017-05-12 04:51:55 +00002932Status
2933GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2934 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002935 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002936 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002937 lldb_private::StreamString stream;
2938 stream.PutCString("vFile:mode:");
Pavel Labath7f815a92019-02-12 14:28:55 +00002939 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002940 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002941 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002942 PacketResult::Success) {
2943 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002944 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002945 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002946 } else {
2947 const uint32_t mode = response.GetS32(-1);
2948 if (static_cast<int32_t>(mode) == -1) {
2949 if (response.GetChar() == ',') {
2950 int response_errno = response.GetS32(-1);
2951 if (response_errno > 0)
2952 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2953 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002954 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002955 } else
2956 error.SetErrorToGenericError();
2957 } else {
2958 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2959 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002960 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002961 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002962 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002963 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 }
2965 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002966}
2967
Kate Stoneb9c1b512016-09-06 20:57:50 +00002968uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2969 uint64_t offset, void *dst,
2970 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002971 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002972 lldb_private::StreamString stream;
2973 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2974 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002976 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002977 PacketResult::Success) {
2978 if (response.GetChar() != 'F')
2979 return 0;
2980 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2981 if (retcode == UINT32_MAX)
2982 return retcode;
2983 const char next = (response.Peek() ? *response.Peek() : 0);
2984 if (next == ',')
2985 return 0;
2986 if (next == ';') {
2987 response.GetChar(); // skip the semicolon
2988 std::string buffer;
2989 if (response.GetEscapedBinaryData(buffer)) {
2990 const uint64_t data_to_write =
2991 std::min<uint64_t>(dst_len, buffer.size());
2992 if (data_to_write > 0)
2993 memcpy(dst, &buffer[0], data_to_write);
2994 return data_to_write;
2995 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002996 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002997 }
2998 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002999}
3000
Kate Stoneb9c1b512016-09-06 20:57:50 +00003001uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3002 uint64_t offset,
3003 const void *src,
3004 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003005 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003006 lldb_private::StreamGDBRemote stream;
3007 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3008 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003010 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003011 PacketResult::Success) {
3012 if (response.GetChar() != 'F') {
3013 error.SetErrorStringWithFormat("write file failed");
3014 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003015 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003016 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3017 if (bytes_written == UINT64_MAX) {
3018 error.SetErrorToGenericError();
3019 if (response.GetChar() == ',') {
3020 int response_errno = response.GetS32(-1);
3021 if (response_errno > 0)
3022 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3023 }
3024 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003025 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 return bytes_written;
3027 } else {
3028 error.SetErrorString("failed to send vFile:pwrite packet");
3029 }
3030 return 0;
3031}
3032
Zachary Turner97206d52017-05-12 04:51:55 +00003033Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3034 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003035 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003036 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 lldb_private::StreamGDBRemote stream;
3038 stream.PutCString("vFile:symlink:");
3039 // the unix symlink() command reverses its parameters where the dst if first,
3040 // so we follow suit here
Pavel Labath7f815a92019-02-12 14:28:55 +00003041 stream.PutStringAsRawHex8(dst_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00003043 stream.PutStringAsRawHex8(src_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003044 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003045 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046 PacketResult::Success) {
3047 if (response.GetChar() == 'F') {
3048 uint32_t result = response.GetU32(UINT32_MAX);
3049 if (result != 0) {
3050 error.SetErrorToGenericError();
3051 if (response.GetChar() == ',') {
3052 int response_errno = response.GetS32(-1);
3053 if (response_errno > 0)
3054 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3055 }
3056 }
3057 } else {
3058 // Should have returned with 'F<result>[,<errno>]'
3059 error.SetErrorStringWithFormat("symlink failed");
3060 }
3061 } else {
3062 error.SetErrorString("failed to send vFile:symlink packet");
3063 }
3064 return error;
3065}
3066
Zachary Turner97206d52017-05-12 04:51:55 +00003067Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003069 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003070 lldb_private::StreamGDBRemote stream;
3071 stream.PutCString("vFile:unlink:");
3072 // the unix symlink() command reverses its parameters where the dst if first,
3073 // so we follow suit here
Pavel Labath7f815a92019-02-12 14:28:55 +00003074 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003075 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003076 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003077 PacketResult::Success) {
3078 if (response.GetChar() == 'F') {
3079 uint32_t result = response.GetU32(UINT32_MAX);
3080 if (result != 0) {
3081 error.SetErrorToGenericError();
3082 if (response.GetChar() == ',') {
3083 int response_errno = response.GetS32(-1);
3084 if (response_errno > 0)
3085 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3086 }
3087 }
3088 } else {
3089 // Should have returned with 'F<result>[,<errno>]'
3090 error.SetErrorStringWithFormat("unlink failed");
3091 }
3092 } else {
3093 error.SetErrorString("failed to send vFile:unlink packet");
3094 }
3095 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00003096}
3097
Daniel Maleae0f8f572013-08-26 23:57:52 +00003098// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099bool GDBRemoteCommunicationClient::GetFileExists(
3100 const lldb_private::FileSpec &file_spec) {
3101 std::string path(file_spec.GetPath(false));
3102 lldb_private::StreamString stream;
3103 stream.PutCString("vFile:exists:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003104 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003105 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003106 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003107 PacketResult::Success) {
3108 if (response.GetChar() != 'F')
3109 return false;
3110 if (response.GetChar() != ',')
3111 return false;
3112 bool retcode = (response.GetChar() != '0');
3113 return retcode;
3114 }
3115 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003116}
3117
Kate Stoneb9c1b512016-09-06 20:57:50 +00003118bool GDBRemoteCommunicationClient::CalculateMD5(
3119 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3120 std::string path(file_spec.GetPath(false));
3121 lldb_private::StreamString stream;
3122 stream.PutCString("vFile:MD5:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003123 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003125 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003126 PacketResult::Success) {
3127 if (response.GetChar() != 'F')
3128 return false;
3129 if (response.GetChar() != ',')
3130 return false;
3131 if (response.Peek() && *response.Peek() == 'x')
3132 return false;
3133 low = response.GetHexMaxU64(false, UINT64_MAX);
3134 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003135 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003136 }
3137 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003138}
3139
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3141 // Some targets have issues with g/G packets and we need to avoid using them
3142 if (m_avoid_g_packets == eLazyBoolCalculate) {
3143 if (process) {
3144 m_avoid_g_packets = eLazyBoolNo;
3145 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3146 if (arch.IsValid() &&
3147 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3148 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3149 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3150 m_avoid_g_packets = eLazyBoolYes;
3151 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3152 if (gdb_server_version != 0) {
3153 const char *gdb_server_name = GetGDBServerProgramName();
3154 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3155 if (gdb_server_version >= 310)
3156 m_avoid_g_packets = eLazyBoolNo;
3157 }
3158 }
3159 }
3160 }
3161 }
3162 return m_avoid_g_packets == eLazyBoolYes;
3163}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003164
Kate Stoneb9c1b512016-09-06 20:57:50 +00003165DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3166 uint32_t reg) {
3167 StreamString payload;
3168 payload.Printf("p%x", reg);
3169 StringExtractorGDBRemote response;
3170 if (SendThreadSpecificPacketAndWaitForResponse(
3171 tid, std::move(payload), response, false) != PacketResult::Success ||
3172 !response.IsNormalResponse())
3173 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003174
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175 DataBufferSP buffer_sp(
3176 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3177 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3178 return buffer_sp;
3179}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003180
Kate Stoneb9c1b512016-09-06 20:57:50 +00003181DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3182 StreamString payload;
3183 payload.PutChar('g');
3184 StringExtractorGDBRemote response;
3185 if (SendThreadSpecificPacketAndWaitForResponse(
3186 tid, std::move(payload), response, false) != PacketResult::Success ||
3187 !response.IsNormalResponse())
3188 return nullptr;
3189
3190 DataBufferSP buffer_sp(
3191 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3192 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3193 return buffer_sp;
3194}
3195
3196bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3197 uint32_t reg_num,
3198 llvm::ArrayRef<uint8_t> data) {
3199 StreamString payload;
3200 payload.Printf("P%x=", reg_num);
3201 payload.PutBytesAsRawHex8(data.data(), data.size(),
3202 endian::InlHostByteOrder(),
3203 endian::InlHostByteOrder());
3204 StringExtractorGDBRemote response;
3205 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3206 response, false) ==
3207 PacketResult::Success &&
3208 response.IsOKResponse();
3209}
3210
3211bool GDBRemoteCommunicationClient::WriteAllRegisters(
3212 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3213 StreamString payload;
3214 payload.PutChar('G');
3215 payload.PutBytesAsRawHex8(data.data(), data.size(),
3216 endian::InlHostByteOrder(),
3217 endian::InlHostByteOrder());
3218 StringExtractorGDBRemote response;
3219 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3220 response, false) ==
3221 PacketResult::Success &&
3222 response.IsOKResponse();
3223}
3224
3225bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3226 uint32_t &save_id) {
3227 save_id = 0; // Set to invalid save ID
3228 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003229 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230
3231 m_supports_QSaveRegisterState = eLazyBoolYes;
3232 StreamString payload;
3233 payload.PutCString("QSaveRegisterState");
3234 StringExtractorGDBRemote response;
3235 if (SendThreadSpecificPacketAndWaitForResponse(
3236 tid, std::move(payload), response, false) != PacketResult::Success)
3237 return false;
3238
3239 if (response.IsUnsupportedResponse())
3240 m_supports_QSaveRegisterState = eLazyBoolNo;
3241
3242 const uint32_t response_save_id = response.GetU32(0);
3243 if (response_save_id == 0)
3244 return false;
3245
3246 save_id = response_save_id;
3247 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003248}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003249
Kate Stoneb9c1b512016-09-06 20:57:50 +00003250bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3251 uint32_t save_id) {
3252 // We use the "m_supports_QSaveRegisterState" variable here because the
Adrian Prantl05097242018-04-30 16:49:04 +00003253 // QSaveRegisterState and QRestoreRegisterState packets must both be
3254 // supported in order to be useful
Kate Stoneb9c1b512016-09-06 20:57:50 +00003255 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3256 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003257
Kate Stoneb9c1b512016-09-06 20:57:50 +00003258 StreamString payload;
3259 payload.Printf("QRestoreRegisterState:%u", save_id);
3260 StringExtractorGDBRemote response;
3261 if (SendThreadSpecificPacketAndWaitForResponse(
3262 tid, std::move(payload), response, false) != PacketResult::Success)
3263 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003264
Kate Stoneb9c1b512016-09-06 20:57:50 +00003265 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003266 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003267
3268 if (response.IsUnsupportedResponse())
3269 m_supports_QSaveRegisterState = eLazyBoolNo;
3270 return false;
3271}
3272
3273bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3274 if (!GetSyncThreadStateSupported())
3275 return false;
3276
3277 StreamString packet;
3278 StringExtractorGDBRemote response;
3279 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3280 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3281 GDBRemoteCommunication::PacketResult::Success &&
3282 response.IsOKResponse();
3283}
3284
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003285lldb::user_id_t
3286GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3287 Status &error) {
3288 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3289 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3290
3291 StreamGDBRemote escaped_packet;
3292 escaped_packet.PutCString("jTraceStart:");
3293
3294 StructuredData::Dictionary json_packet;
3295 json_packet.AddIntegerItem("type", options.getType());
3296 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3297 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3298
3299 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3300 json_packet.AddIntegerItem("threadid", options.getThreadID());
3301
3302 StructuredData::DictionarySP custom_params = options.getTraceParams();
3303 if (custom_params)
3304 json_packet.AddItem("params", custom_params);
3305
3306 StreamString json_string;
3307 json_packet.Dump(json_string, false);
3308 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3309
3310 StringExtractorGDBRemote response;
3311 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3312 true) ==
3313 GDBRemoteCommunication::PacketResult::Success) {
3314 if (!response.IsNormalResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003315 error = response.GetStatus();
3316 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003317 } else {
3318 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3319 }
3320 } else {
3321 LLDB_LOG(log, "failed to send packet");
3322 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3323 escaped_packet.GetData());
3324 }
3325 return ret_uid;
3326}
3327
3328Status
3329GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3330 lldb::tid_t thread_id) {
3331 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3332 StringExtractorGDBRemote response;
3333 Status error;
3334
3335 StructuredData::Dictionary json_packet;
3336 StreamGDBRemote escaped_packet;
3337 StreamString json_string;
3338 escaped_packet.PutCString("jTraceStop:");
3339
3340 json_packet.AddIntegerItem("traceid", uid);
3341
3342 if (thread_id != LLDB_INVALID_THREAD_ID)
3343 json_packet.AddIntegerItem("threadid", thread_id);
3344
3345 json_packet.Dump(json_string, false);
3346
3347 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3348
3349 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3350 true) ==
3351 GDBRemoteCommunication::PacketResult::Success) {
3352 if (!response.IsOKResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003353 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003354 LLDB_LOG(log, "stop tracing failed");
3355 }
3356 } else {
3357 LLDB_LOG(log, "failed to send packet");
3358 error.SetErrorStringWithFormat(
3359 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3360 response.GetError());
3361 }
3362 return error;
3363}
3364
3365Status GDBRemoteCommunicationClient::SendGetDataPacket(
3366 lldb::user_id_t uid, lldb::tid_t thread_id,
3367 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003368
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003369 StreamGDBRemote escaped_packet;
3370 escaped_packet.PutCString("jTraceBufferRead:");
3371 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3372}
3373
3374Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3375 lldb::user_id_t uid, lldb::tid_t thread_id,
3376 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003377
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003378 StreamGDBRemote escaped_packet;
3379 escaped_packet.PutCString("jTraceMetaRead:");
3380 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3381}
3382
3383Status
3384GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3385 TraceOptions &options) {
3386 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3387 StringExtractorGDBRemote response;
3388 Status error;
3389
3390 StreamString json_string;
3391 StreamGDBRemote escaped_packet;
3392 escaped_packet.PutCString("jTraceConfigRead:");
3393
3394 StructuredData::Dictionary json_packet;
3395 json_packet.AddIntegerItem("traceid", uid);
3396
3397 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3398 json_packet.AddIntegerItem("threadid", options.getThreadID());
3399
3400 json_packet.Dump(json_string, false);
3401 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3402
3403 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3404 true) ==
3405 GDBRemoteCommunication::PacketResult::Success) {
3406 if (response.IsNormalResponse()) {
3407 uint64_t type = std::numeric_limits<uint64_t>::max();
3408 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3409 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3410
3411 auto json_object = StructuredData::ParseJSON(response.Peek());
3412
3413 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003414 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003415 error.SetErrorString("Invalid Configuration obtained");
3416 return error;
3417 }
3418
3419 auto json_dict = json_object->GetAsDictionary();
3420
3421 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3422 metabuffersize);
3423 options.setMetaDataBufferSize(metabuffersize);
3424
3425 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3426 options.setTraceBufferSize(buffersize);
3427
3428 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3429 options.setType(static_cast<lldb::TraceType>(type));
3430
3431 StructuredData::ObjectSP custom_params_sp =
3432 json_dict->GetValueForKey("params");
3433 if (custom_params_sp) {
3434 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003435 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003436 error.SetErrorString("Invalid Configuration obtained");
3437 return error;
3438 } else
3439 options.setTraceParams(
3440 static_pointer_cast<StructuredData::Dictionary>(
3441 custom_params_sp));
3442 }
3443 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003444 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003445 }
3446 } else {
3447 LLDB_LOG(log, "failed to send packet");
3448 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3449 escaped_packet.GetData());
3450 }
3451 return error;
3452}
3453
3454Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3455 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3456 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3457 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3458 Status error;
3459
3460 StructuredData::Dictionary json_packet;
3461
3462 json_packet.AddIntegerItem("traceid", uid);
3463 json_packet.AddIntegerItem("offset", offset);
3464 json_packet.AddIntegerItem("buffersize", buffer.size());
3465
3466 if (thread_id != LLDB_INVALID_THREAD_ID)
3467 json_packet.AddIntegerItem("threadid", thread_id);
3468
3469 StreamString json_string;
3470 json_packet.Dump(json_string, false);
3471
3472 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3473 StringExtractorGDBRemote response;
3474 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3475 GDBRemoteCommunication::PacketResult::Success) {
3476 if (response.IsNormalResponse()) {
3477 size_t filled_size = response.GetHexBytesAvail(buffer);
3478 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3479 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003480 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003481 buffer = buffer.slice(buffer.size());
3482 }
3483 } else {
3484 LLDB_LOG(log, "failed to send packet");
3485 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3486 packet.GetData());
3487 buffer = buffer.slice(buffer.size());
3488 }
3489 return error;
3490}
3491
Kate Stoneb9c1b512016-09-06 20:57:50 +00003492bool GDBRemoteCommunicationClient::GetModuleInfo(
3493 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3494 ModuleSpec &module_spec) {
3495 if (!m_supports_qModuleInfo)
3496 return false;
3497
3498 std::string module_path = module_file_spec.GetPath(false);
3499 if (module_path.empty())
3500 return false;
3501
3502 StreamString packet;
3503 packet.PutCString("qModuleInfo:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003504 packet.PutStringAsRawHex8(module_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003505 packet.PutCString(";");
3506 const auto &triple = arch_spec.GetTriple().getTriple();
Pavel Labath7f815a92019-02-12 14:28:55 +00003507 packet.PutStringAsRawHex8(triple);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003508
3509 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003510 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3511 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003512 return false;
3513
3514 if (response.IsErrorResponse())
3515 return false;
3516
3517 if (response.IsUnsupportedResponse()) {
3518 m_supports_qModuleInfo = false;
3519 return false;
3520 }
3521
3522 llvm::StringRef name;
3523 llvm::StringRef value;
3524
3525 module_spec.Clear();
3526 module_spec.GetFileSpec() = module_file_spec;
3527
3528 while (response.GetNameColonValue(name, value)) {
3529 if (name == "uuid" || name == "md5") {
3530 StringExtractor extractor(value);
3531 std::string uuid;
3532 extractor.GetHexByteString(uuid);
Pavel Labatha174bcb2018-06-21 15:24:39 +00003533 module_spec.GetUUID().SetFromStringRef(uuid, uuid.size() / 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003534 } else if (name == "triple") {
3535 StringExtractor extractor(value);
3536 std::string triple;
3537 extractor.GetHexByteString(triple);
3538 module_spec.GetArchitecture().SetTriple(triple.c_str());
3539 } else if (name == "file_offset") {
3540 uint64_t ival = 0;
3541 if (!value.getAsInteger(16, ival))
3542 module_spec.SetObjectOffset(ival);
3543 } else if (name == "file_size") {
3544 uint64_t ival = 0;
3545 if (!value.getAsInteger(16, ival))
3546 module_spec.SetObjectSize(ival);
3547 } else if (name == "file_path") {
3548 StringExtractor extractor(value);
3549 std::string path;
3550 extractor.GetHexByteString(path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003551 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003552 }
3553 }
3554
3555 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003556}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003557
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003558static llvm::Optional<ModuleSpec>
3559ParseModuleSpec(StructuredData::Dictionary *dict) {
3560 ModuleSpec result;
3561 if (!dict)
3562 return llvm::None;
3563
Zachary Turner28333212017-05-12 05:49:54 +00003564 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003565 uint64_t integer;
3566
3567 if (!dict->GetValueForKeyAsString("uuid", string))
3568 return llvm::None;
Pavel Labath8c92c892017-12-18 14:31:44 +00003569 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3570 string.size())
3571 return llvm::None;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003572
3573 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3574 return llvm::None;
3575 result.SetObjectOffset(integer);
3576
3577 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3578 return llvm::None;
3579 result.SetObjectSize(integer);
3580
3581 if (!dict->GetValueForKeyAsString("triple", string))
3582 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003583 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003584
3585 if (!dict->GetValueForKeyAsString("file_path", string))
3586 return llvm::None;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003587 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003588
3589 return result;
3590}
3591
3592llvm::Optional<std::vector<ModuleSpec>>
3593GDBRemoteCommunicationClient::GetModulesInfo(
3594 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3595 if (!m_supports_jModulesInfo)
3596 return llvm::None;
3597
3598 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3599 for (const FileSpec &module_file_spec : module_file_specs) {
3600 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3601 module_array_sp->AppendObject(module_sp);
3602 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003603 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003604 module_sp->SetObject("triple",
3605 std::make_shared<JSONString>(triple.getTriple()));
3606 }
3607 StreamString unescaped_payload;
3608 unescaped_payload.PutCString("jModulesInfo:");
3609 module_array_sp->Write(unescaped_payload);
3610 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003611 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003612 unescaped_payload.GetSize());
3613
Greg Clayton70a9f512017-04-14 17:10:04 +00003614 // Increase the timeout for jModulesInfo since this packet can take longer.
3615 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3616
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003617 StringExtractorGDBRemote response;
3618 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3619 PacketResult::Success ||
3620 response.IsErrorResponse())
3621 return llvm::None;
3622
3623 if (response.IsUnsupportedResponse()) {
3624 m_supports_jModulesInfo = false;
3625 return llvm::None;
3626 }
3627
3628 StructuredData::ObjectSP response_object_sp =
3629 StructuredData::ParseJSON(response.GetStringRef());
3630 if (!response_object_sp)
3631 return llvm::None;
3632
3633 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3634 if (!response_array)
3635 return llvm::None;
3636
3637 std::vector<ModuleSpec> result;
3638 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3639 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3640 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3641 result.push_back(*module_spec);
3642 }
3643
3644 return result;
3645}
3646
Colin Rileyc3c95b22015-04-16 15:51:33 +00003647// query the target remote for extended information using the qXfer packet
3648//
Adrian Prantl05097242018-04-30 16:49:04 +00003649// example: object='features', annex='target.xml', out=<xml output> return:
3650// 'true' on success
Colin Rileyc3c95b22015-04-16 15:51:33 +00003651// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003652bool GDBRemoteCommunicationClient::ReadExtFeature(
3653 const lldb_private::ConstString object,
3654 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003655 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003656
Kate Stoneb9c1b512016-09-06 20:57:50 +00003657 std::stringstream output;
3658 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003659
Kate Stoneb9c1b512016-09-06 20:57:50 +00003660 uint64_t size = GetRemoteMaxPacketSize();
3661 if (size == 0)
3662 size = 0x1000;
3663 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3664 int offset = 0;
3665 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003666
Kate Stoneb9c1b512016-09-06 20:57:50 +00003667 // loop until all data has been read
3668 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003669
Kate Stoneb9c1b512016-09-06 20:57:50 +00003670 // send query extended feature packet
3671 std::stringstream packet;
3672 packet << "qXfer:" << object.AsCString("")
3673 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3674 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003675
Kate Stoneb9c1b512016-09-06 20:57:50 +00003676 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003677 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003678
Kate Stoneb9c1b512016-09-06 20:57:50 +00003679 if (res != GDBRemoteCommunication::PacketResult::Success) {
3680 err.SetErrorString("Error sending $qXfer packet");
3681 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003682 }
3683
Kate Stoneb9c1b512016-09-06 20:57:50 +00003684 const std::string &str = chunk.GetStringRef();
3685 if (str.length() == 0) {
3686 // should have some data in chunk
3687 err.SetErrorString("Empty response from $qXfer packet");
3688 return false;
3689 }
3690
3691 // check packet code
3692 switch (str[0]) {
3693 // last chunk
3694 case ('l'):
3695 active = false;
3696 LLVM_FALLTHROUGH;
3697
3698 // more chunks
3699 case ('m'):
3700 if (str.length() > 1)
3701 output << &str[1];
3702 offset += size;
3703 break;
3704
3705 // unknown chunk
3706 default:
3707 err.SetErrorString("Invalid continuation code from $qXfer packet");
3708 return false;
3709 }
3710 }
3711
3712 out = output.str();
3713 err.Success();
3714 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003715}
Greg Clayton0b90be12015-06-23 21:27:50 +00003716
3717// Notify the target that gdb is prepared to serve symbol lookup requests.
3718// packet: "qSymbol::"
3719// reply:
3720// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003721// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3722// encoded).
3723// LLDB may provide the value by sending another qSymbol
3724// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003725// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003726//
3727// Three examples:
3728//
3729// lldb sends: qSymbol::
3730// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003731// Remote gdb stub does not need to know the addresses of any symbols, lldb
3732// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003733// need to ask again in this session.
3734//
3735// lldb sends: qSymbol::
3736// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3737// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3738// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003739// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3740// not know
3741// the address at this time. lldb needs to send qSymbol:: again when it has
3742// more
Jason Molenda50018d32016-01-13 04:08:10 +00003743// solibs loaded.
3744//
3745// lldb sends: qSymbol::
3746// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3747// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3748// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003749// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3750// that it
3751// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3752// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003753// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003754
Kate Stoneb9c1b512016-09-06 20:57:50 +00003755void GDBRemoteCommunicationClient::ServeSymbolLookups(
3756 lldb_private::Process *process) {
Adrian Prantl05097242018-04-30 16:49:04 +00003757 // Set to true once we've resolved a symbol to an address for the remote
3758 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3759 // any more symbols and we can stop asking.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003760 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003761
Kate Stoneb9c1b512016-09-06 20:57:50 +00003762 // Is this the initial qSymbol:: packet?
3763 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003764
Jonas Devliegherea6682a42018-12-15 00:15:33 +00003765 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003766 Lock lock(*this, false);
3767 if (lock) {
3768 StreamString packet;
3769 packet.PutCString("qSymbol::");
3770 StringExtractorGDBRemote response;
3771 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3772 PacketResult::Success) {
3773 if (response.IsOKResponse()) {
3774 if (symbol_response_provided || first_qsymbol_query) {
3775 m_qSymbol_requests_done = true;
3776 }
3777
3778 // We are done serving symbols requests
3779 return;
3780 }
3781 first_qsymbol_query = false;
3782
3783 if (response.IsUnsupportedResponse()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003784 // qSymbol is not supported by the current GDB server we are
3785 // connected to
Kate Stoneb9c1b512016-09-06 20:57:50 +00003786 m_supports_qSymbol = false;
3787 return;
3788 } else {
3789 llvm::StringRef response_str(response.GetStringRef());
3790 if (response_str.startswith("qSymbol:")) {
3791 response.SetFilePos(strlen("qSymbol:"));
3792 std::string symbol_name;
3793 if (response.GetHexByteString(symbol_name)) {
3794 if (symbol_name.empty())
3795 return;
3796
3797 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3798 lldb_private::SymbolContextList sc_list;
3799 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3800 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3801 const size_t num_scs = sc_list.GetSize();
3802 for (size_t sc_idx = 0;
3803 sc_idx < num_scs &&
3804 symbol_load_addr == LLDB_INVALID_ADDRESS;
3805 ++sc_idx) {
3806 SymbolContext sc;
3807 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3808 if (sc.symbol) {
3809 switch (sc.symbol->GetType()) {
3810 case eSymbolTypeInvalid:
3811 case eSymbolTypeAbsolute:
3812 case eSymbolTypeUndefined:
3813 case eSymbolTypeSourceFile:
3814 case eSymbolTypeHeaderFile:
3815 case eSymbolTypeObjectFile:
3816 case eSymbolTypeCommonBlock:
3817 case eSymbolTypeBlock:
3818 case eSymbolTypeLocal:
3819 case eSymbolTypeParam:
3820 case eSymbolTypeVariable:
3821 case eSymbolTypeVariableType:
3822 case eSymbolTypeLineEntry:
3823 case eSymbolTypeLineHeader:
3824 case eSymbolTypeScopeBegin:
3825 case eSymbolTypeScopeEnd:
3826 case eSymbolTypeAdditional:
3827 case eSymbolTypeCompiler:
3828 case eSymbolTypeInstrumentation:
3829 case eSymbolTypeTrampoline:
3830 break;
3831
3832 case eSymbolTypeCode:
3833 case eSymbolTypeResolver:
3834 case eSymbolTypeData:
3835 case eSymbolTypeRuntime:
3836 case eSymbolTypeException:
3837 case eSymbolTypeObjCClass:
3838 case eSymbolTypeObjCMetaClass:
3839 case eSymbolTypeObjCIVar:
3840 case eSymbolTypeReExported:
3841 symbol_load_addr =
3842 sc.symbol->GetLoadAddress(&process->GetTarget());
3843 break;
3844 }
Jason Molenda50018d32016-01-13 04:08:10 +00003845 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003846 }
Greg Clayton42b01482015-08-11 22:07:46 +00003847 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003848 }
3849 // This is the normal path where our symbol lookup was successful
Adrian Prantl05097242018-04-30 16:49:04 +00003850 // and we want to send a packet with the new symbol value and see
3851 // if another lookup needs to be done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003852
Kate Stoneb9c1b512016-09-06 20:57:50 +00003853 // Change "packet" to contain the requested symbol value and name
3854 packet.Clear();
3855 packet.PutCString("qSymbol:");
3856 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3857 packet.Printf("%" PRIx64, symbol_load_addr);
3858 symbol_response_provided = true;
3859 } else {
3860 symbol_response_provided = false;
3861 }
3862 packet.PutCString(":");
3863 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3864 continue; // go back to the while loop and send "packet" and wait
3865 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003866 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003867 }
3868 }
3869 }
3870 // If we make it here, the symbol request packet response wasn't valid or
3871 // our symbol lookup failed so we must abort
3872 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003873
Kate Stoneb9c1b512016-09-06 20:57:50 +00003874 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3875 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3876 log->Printf(
3877 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3878 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003879 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003880 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003881}
3882
Kate Stoneb9c1b512016-09-06 20:57:50 +00003883StructuredData::Array *
3884GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3885 if (!m_supported_async_json_packets_is_valid) {
Adrian Prantl05097242018-04-30 16:49:04 +00003886 // Query the server for the array of supported asynchronous JSON packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003887 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003888
Kate Stoneb9c1b512016-09-06 20:57:50 +00003889 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003890
Kate Stoneb9c1b512016-09-06 20:57:50 +00003891 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003892 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003893 const bool send_async = false;
3894 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3895 send_async) == PacketResult::Success) {
3896 m_supported_async_json_packets_sp =
3897 StructuredData::ParseJSON(response.GetStringRef());
3898 if (m_supported_async_json_packets_sp &&
3899 !m_supported_async_json_packets_sp->GetAsArray()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003900 // We were returned something other than a JSON array. This is
3901 // invalid. Clear it out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003902 if (log)
3903 log->Printf("GDBRemoteCommunicationClient::%s(): "
3904 "QSupportedAsyncJSONPackets returned invalid "
3905 "result: %s",
3906 __FUNCTION__, response.GetStringRef().c_str());
3907 m_supported_async_json_packets_sp.reset();
3908 }
3909 } else {
3910 if (log)
3911 log->Printf("GDBRemoteCommunicationClient::%s(): "
3912 "QSupportedAsyncJSONPackets unsupported",
3913 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003914 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003915
3916 if (log && m_supported_async_json_packets_sp) {
3917 StreamString stream;
3918 m_supported_async_json_packets_sp->Dump(stream);
3919 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3920 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003921 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003922 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003923 }
3924
3925 return m_supported_async_json_packets_sp
3926 ? m_supported_async_json_packets_sp->GetAsArray()
3927 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003928}
3929
Zachary Turner97206d52017-05-12 04:51:55 +00003930Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003931 llvm::ArrayRef<int32_t> signals) {
3932 // Format packet:
3933 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3934 auto range = llvm::make_range(signals.begin(), signals.end());
3935 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3936
3937 StringExtractorGDBRemote response;
3938 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3939
3940 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003941 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003942
3943 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003944 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003945 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003946 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003947 }
3948}
3949
Zachary Turner97206d52017-05-12 04:51:55 +00003950Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003951 ConstString type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003952 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003953
3954 if (type_name.GetLength() == 0) {
3955 error.SetErrorString("invalid type_name argument");
3956 return error;
3957 }
3958
Adrian Prantl05097242018-04-30 16:49:04 +00003959 // Build command: Configure{type_name}: serialized config data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003960 StreamGDBRemote stream;
3961 stream.PutCString("QConfigure");
3962 stream.PutCString(type_name.AsCString());
3963 stream.PutChar(':');
3964 if (config_sp) {
3965 // Gather the plain-text version of the configuration data.
3966 StreamString unescaped_stream;
3967 config_sp->Dump(unescaped_stream);
3968 unescaped_stream.Flush();
3969
3970 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003971 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003972 unescaped_stream.GetSize());
3973 }
3974 stream.Flush();
3975
3976 // Send the packet.
3977 const bool send_async = false;
3978 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003979 auto result =
3980 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003981 if (result == PacketResult::Success) {
3982 // We failed if the config result comes back other than OK.
3983 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3984 // Okay!
3985 error.Clear();
3986 } else {
3987 error.SetErrorStringWithFormat("configuring StructuredData feature "
3988 "%s failed with error %s",
3989 type_name.AsCString(),
3990 response.GetStringRef().c_str());
3991 }
3992 } else {
3993 // Can we get more data here on the failure?
3994 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3995 "failed when sending packet: "
3996 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003997 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003998 }
3999 return error;
4000}
4001
4002void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4003 GDBRemoteClientBase::OnRunPacketSent(first);
4004 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004005}