blob: 8aa78a4d5ed0be6f5ce69abd4b2edd036a4a728b [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Greg Clayton576d8832011-03-22 04:00:09 +000010#include "GDBRemoteCommunicationClient.h"
11
12// C Includes
Greg Claytone034a042015-05-21 20:52:06 +000013#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000014#include <sys/stat.h>
15
Greg Clayton576d8832011-03-22 04:00:09 +000016// C++ Includes
Greg Claytone034a042015-05-21 20:52:06 +000017#include <numeric>
Kate Stoneb9c1b512016-09-06 20:57:50 +000018#include <sstream>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000019
Greg Clayton576d8832011-03-22 04:00:09 +000020// Other libraries and framework includes
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000021#include "lldb/Core/ModuleSpec.h"
Greg Clayton576d8832011-03-22 04:00:09 +000022#include "lldb/Core/State.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000023#include "lldb/Host/HostInfo.h"
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000024#include "lldb/Interpreter/Args.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000025#include "lldb/Symbol/Symbol.h"
Pavel Labath4cb69922016-07-29 15:41:52 +000026#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000027#include "lldb/Target/Target.h"
Todd Fiala75930012016-08-19 04:21:48 +000028#include "lldb/Target/UnixSignals.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000029#include "lldb/Utility/DataBufferHeap.h"
Pavel Labath2f1fbae2016-09-08 10:07:04 +000030#include "lldb/Utility/JSON.h"
Todd Fiala75930012016-08-19 04:21:48 +000031#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000032#include "lldb/Utility/Log.h"
Zachary Turnerfb1a0a02017-03-06 18:34:25 +000033#include "lldb/Utility/StreamGDBRemote.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000034#include "lldb/Utility/StreamString.h"
Greg Clayton576d8832011-03-22 04:00:09 +000035
36// Project includes
Greg Clayton576d8832011-03-22 04:00:09 +000037#include "ProcessGDBRemote.h"
38#include "ProcessGDBRemoteLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000039#include "Utility/StringExtractorGDBRemote.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000040#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000041
Zachary Turner54695a32016-08-29 19:58:14 +000042#include "llvm/ADT/StringSwitch.h"
43
Kate Stoneb9c1b512016-09-06 20:57:50 +000044#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000045#include <compression.h>
46#endif
47
Greg Clayton576d8832011-03-22 04:00:09 +000048using namespace lldb;
49using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000050using namespace lldb_private::process_gdb_remote;
Pavel Labath1eff73c2016-11-24 10:54:49 +000051using namespace std::chrono;
Greg Clayton576d8832011-03-22 04:00:09 +000052
53//----------------------------------------------------------------------
54// GDBRemoteCommunicationClient constructor
55//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000056GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000057 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000058 m_supports_not_sending_acks(eLazyBoolCalculate),
59 m_supports_thread_suffix(eLazyBoolCalculate),
60 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
61 m_supports_vCont_all(eLazyBoolCalculate),
62 m_supports_vCont_any(eLazyBoolCalculate),
63 m_supports_vCont_c(eLazyBoolCalculate),
64 m_supports_vCont_C(eLazyBoolCalculate),
65 m_supports_vCont_s(eLazyBoolCalculate),
66 m_supports_vCont_S(eLazyBoolCalculate),
67 m_qHostInfo_is_valid(eLazyBoolCalculate),
68 m_curr_pid_is_valid(eLazyBoolCalculate),
69 m_qProcessInfo_is_valid(eLazyBoolCalculate),
70 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
71 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
72 m_supports_memory_region_info(eLazyBoolCalculate),
73 m_supports_watchpoint_support_info(eLazyBoolCalculate),
74 m_supports_detach_stay_stopped(eLazyBoolCalculate),
75 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
76 m_attach_or_wait_reply(eLazyBoolCalculate),
77 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000078 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000079 m_avoid_g_packets(eLazyBoolCalculate),
80 m_supports_QSaveRegisterState(eLazyBoolCalculate),
81 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
82 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
83 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
84 m_supports_qXfer_features_read(eLazyBoolCalculate),
85 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
86 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
87 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000088 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000089 m_supports_QPassSignals(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
91 m_supports_qUserName(true), m_supports_qGroupName(true),
92 m_supports_qThreadStopInfo(true), m_supports_z0(true),
93 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
94 m_supports_z4(true), m_supports_QEnvironment(true),
95 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
96 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
Pavel Labath2f1fbae2016-09-08 10:07:04 +000097 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
98 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000099 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
101 m_os_version_major(UINT32_MAX), m_os_version_minor(UINT32_MAX),
102 m_os_version_update(UINT32_MAX), m_os_build(), m_os_kernel(),
103 m_hostname(), m_gdb_server_name(), m_gdb_server_version(UINT32_MAX),
104 m_default_packet_timeout(0), m_max_packet_size(0),
105 m_qSupported_response(), m_supported_async_json_packets_is_valid(false),
106 m_supported_async_json_packets_sp() {}
Greg Clayton576d8832011-03-22 04:00:09 +0000107
108//----------------------------------------------------------------------
109// Destructor
110//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
112 if (IsConnected())
113 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000114}
115
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116bool GDBRemoteCommunicationClient::HandshakeWithServer(Error *error_ptr) {
117 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000118
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 // Start the read thread after we send the handshake ack since if we
120 // fail to send the handshake ack, there is no reason to continue...
121 if (SendAck()) {
122 // Wait for any responses that might have been queued up in the remote
123 // GDB server and flush them all
124 StringExtractorGDBRemote response;
125 PacketResult packet_result = PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 while (packet_result == PacketResult::Success)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000127 packet_result = ReadPacket(response, milliseconds(10), false);
Ed Maste48f986f2013-12-18 15:31:45 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 // The return value from QueryNoAckModeSupported() is true if the packet
130 // was sent and _any_ response (including UNIMPLEMENTED) was received),
131 // or false if no response was received. This quickly tells us if we have
132 // a live connection to a remote GDB server...
133 if (QueryNoAckModeSupported()) {
134 return true;
135 } else {
136 if (error_ptr)
137 error_ptr->SetErrorString("failed to get reply to handshake packet");
Greg Claytonfb909312013-11-23 01:58:15 +0000138 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 } else {
140 if (error_ptr)
141 error_ptr->SetErrorString("failed to send the handshake ack");
142 }
143 return false;
Greg Clayton1cb64962011-03-24 04:28:38 +0000144}
145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146bool GDBRemoteCommunicationClient::GetEchoSupported() {
147 if (m_supports_qEcho == eLazyBoolCalculate) {
148 GetRemoteQSupported();
149 }
150 return m_supports_qEcho == eLazyBoolYes;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000151}
152
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000153bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
154 if (m_supports_QPassSignals == eLazyBoolCalculate) {
155 GetRemoteQSupported();
156 }
157 return m_supports_QPassSignals == eLazyBoolYes;
158}
159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
161 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
162 GetRemoteQSupported();
163 }
164 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
168 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
169 GetRemoteQSupported();
170 }
171 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
175 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
176 GetRemoteQSupported();
177 }
178 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
182 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
183 GetRemoteQSupported();
184 }
185 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000186}
187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
189 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
190 GetRemoteQSupported();
191 }
192 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
196 if (m_max_packet_size == 0) {
197 GetRemoteQSupported();
198 }
199 return m_max_packet_size;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
203 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
204 m_send_acks = true;
205 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 // This is the first real packet that we'll send in a debug session and it
208 // may take a little
209 // longer than normal to receive a reply. Wait at least 6 seconds for a
210 // reply to this packet.
Jason Molenda36a216e2014-07-24 01:36:24 +0000211
Pavel Labath1eff73c2016-11-24 10:54:49 +0000212 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
Colin Rileyc3c95b22015-04-16 15:51:33 +0000213
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000214 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
216 PacketResult::Success) {
217 if (response.IsOKResponse()) {
218 m_send_acks = false;
219 m_supports_not_sending_acks = eLazyBoolYes;
220 }
221 return true;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000222 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 }
224 return false;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000225}
Greg Clayton576d8832011-03-22 04:00:09 +0000226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
228 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
229 m_supports_threads_in_stop_reply = eLazyBoolNo;
230
231 StringExtractorGDBRemote response;
232 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
233 false) == PacketResult::Success) {
234 if (response.IsOKResponse())
235 m_supports_threads_in_stop_reply = eLazyBoolYes;
Pavel Labath5c95ee42016-08-30 13:56:11 +0000236 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 }
Pavel Labath0faf3732016-08-25 08:34:57 +0000238}
Greg Clayton576d8832011-03-22 04:00:09 +0000239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
241 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
242 m_attach_or_wait_reply = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 StringExtractorGDBRemote response;
245 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
246 false) == PacketResult::Success) {
247 if (response.IsOKResponse())
248 m_attach_or_wait_reply = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000249 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 }
251 if (m_attach_or_wait_reply == eLazyBoolYes)
252 return true;
253 else
Greg Clayton576d8832011-03-22 04:00:09 +0000254 return false;
255}
256
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
258 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
259 m_prepare_for_reg_writing_reply = eLazyBoolNo;
260
261 StringExtractorGDBRemote response;
262 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
263 false) == PacketResult::Success) {
264 if (response.IsOKResponse())
265 m_prepare_for_reg_writing_reply = eLazyBoolYes;
266 }
267 }
268 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
269 return true;
270 else
271 return false;
272}
273
274void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
275 if (did_exec == false) {
276 // Hard reset everything, this is when we first connect to a GDB server
277 m_supports_not_sending_acks = eLazyBoolCalculate;
278 m_supports_thread_suffix = eLazyBoolCalculate;
279 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
280 m_supports_vCont_c = eLazyBoolCalculate;
281 m_supports_vCont_C = eLazyBoolCalculate;
282 m_supports_vCont_s = eLazyBoolCalculate;
283 m_supports_vCont_S = eLazyBoolCalculate;
284 m_supports_p = eLazyBoolCalculate;
285 m_supports_x = eLazyBoolCalculate;
286 m_supports_QSaveRegisterState = eLazyBoolCalculate;
287 m_qHostInfo_is_valid = eLazyBoolCalculate;
288 m_curr_pid_is_valid = eLazyBoolCalculate;
289 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
290 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
291 m_supports_memory_region_info = eLazyBoolCalculate;
292 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
293 m_attach_or_wait_reply = eLazyBoolCalculate;
294 m_avoid_g_packets = eLazyBoolCalculate;
295 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
296 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
297 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
298 m_supports_qXfer_features_read = eLazyBoolCalculate;
299 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
300 m_supports_qProcessInfoPID = true;
301 m_supports_qfProcessInfo = true;
302 m_supports_qUserName = true;
303 m_supports_qGroupName = true;
304 m_supports_qThreadStopInfo = true;
305 m_supports_z0 = true;
306 m_supports_z1 = true;
307 m_supports_z2 = true;
308 m_supports_z3 = true;
309 m_supports_z4 = true;
310 m_supports_QEnvironment = true;
311 m_supports_QEnvironmentHexEncoded = true;
312 m_supports_qSymbol = true;
313 m_qSymbol_requests_done = false;
314 m_supports_qModuleInfo = true;
315 m_host_arch.Clear();
316 m_os_version_major = UINT32_MAX;
317 m_os_version_minor = UINT32_MAX;
318 m_os_version_update = UINT32_MAX;
319 m_os_build.clear();
320 m_os_kernel.clear();
321 m_hostname.clear();
322 m_gdb_server_name.clear();
323 m_gdb_server_version = UINT32_MAX;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000324 m_default_packet_timeout = seconds(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 m_max_packet_size = 0;
326 m_qSupported_response.clear();
327 m_supported_async_json_packets_is_valid = false;
328 m_supported_async_json_packets_sp.reset();
Pavel Labath2f1fbae2016-09-08 10:07:04 +0000329 m_supports_jModulesInfo = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 }
331
332 // These flags should be reset when we first connect to a GDB server
333 // and when our inferior process execs
334 m_qProcessInfo_is_valid = eLazyBoolCalculate;
335 m_process_arch.Clear();
336}
337
338void GDBRemoteCommunicationClient::GetRemoteQSupported() {
339 // Clear out any capabilities we expect to see in the qSupported response
340 m_supports_qXfer_auxv_read = eLazyBoolNo;
341 m_supports_qXfer_libraries_read = eLazyBoolNo;
342 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
343 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
344 m_supports_qXfer_features_read = eLazyBoolNo;
345 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
346 // not, we assume no limit
347
348 // build the qSupported packet
349 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
350 StreamString packet;
351 packet.PutCString("qSupported");
352 for (uint32_t i = 0; i < features.size(); ++i) {
353 packet.PutCString(i == 0 ? ":" : ";");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000354 packet.PutCString(features[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 }
356
357 StringExtractorGDBRemote response;
Zachary Turnerc1564272016-11-16 21:15:24 +0000358 if (SendPacketAndWaitForResponse(packet.GetString(), response,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 /*send_async=*/false) ==
360 PacketResult::Success) {
361 const char *response_cstr = response.GetStringRef().c_str();
362
363 // Hang on to the qSupported packet, so that platforms can do custom
364 // configuration of the transport before attaching/launching the
365 // process.
366 m_qSupported_response = response_cstr;
367
368 if (::strstr(response_cstr, "qXfer:auxv:read+"))
369 m_supports_qXfer_auxv_read = eLazyBoolYes;
370 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
371 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
372 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
373 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
374 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
375 }
376 if (::strstr(response_cstr, "qXfer:libraries:read+"))
377 m_supports_qXfer_libraries_read = eLazyBoolYes;
378 if (::strstr(response_cstr, "qXfer:features:read+"))
379 m_supports_qXfer_features_read = eLazyBoolYes;
380
381 // Look for a list of compressions in the features list e.g.
382 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
383 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
384 if (features_list) {
385 const char *compressions =
386 ::strstr(features_list, "SupportedCompressions=");
387 if (compressions) {
388 std::vector<std::string> supported_compressions;
389 compressions += sizeof("SupportedCompressions=") - 1;
390 const char *end_of_compressions = strchr(compressions, ';');
391 if (end_of_compressions == NULL) {
392 end_of_compressions = strchr(compressions, '\0');
393 }
394 const char *current_compression = compressions;
395 while (current_compression < end_of_compressions) {
396 const char *next_compression_name = strchr(current_compression, ',');
397 const char *end_of_this_word = next_compression_name;
398 if (next_compression_name == NULL ||
399 end_of_compressions < next_compression_name) {
400 end_of_this_word = end_of_compressions;
401 }
402
403 if (end_of_this_word) {
404 if (end_of_this_word == current_compression) {
405 current_compression++;
406 } else {
407 std::string this_compression(
408 current_compression, end_of_this_word - current_compression);
409 supported_compressions.push_back(this_compression);
410 current_compression = end_of_this_word + 1;
411 }
412 } else {
413 supported_compressions.push_back(current_compression);
414 current_compression = end_of_compressions;
415 }
416 }
417
418 if (supported_compressions.size() > 0) {
419 MaybeEnableCompression(supported_compressions);
420 }
421 }
422 }
423
424 if (::strstr(response_cstr, "qEcho"))
425 m_supports_qEcho = eLazyBoolYes;
426 else
427 m_supports_qEcho = eLazyBoolNo;
428
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000429 if (::strstr(response_cstr, "QPassSignals+"))
430 m_supports_QPassSignals = eLazyBoolYes;
431 else
432 m_supports_QPassSignals = eLazyBoolNo;
433
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
435 if (packet_size_str) {
436 StringExtractorGDBRemote packet_response(packet_size_str +
437 strlen("PacketSize="));
438 m_max_packet_size =
439 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
440 if (m_max_packet_size == 0) {
441 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
442 Log *log(
443 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
444 if (log)
445 log->Printf("Garbled PacketSize spec in qSupported response");
446 }
447 }
448 }
449}
450
451bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
452 if (m_supports_thread_suffix == eLazyBoolCalculate) {
453 StringExtractorGDBRemote response;
454 m_supports_thread_suffix = eLazyBoolNo;
455 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
456 false) == PacketResult::Success) {
457 if (response.IsOKResponse())
458 m_supports_thread_suffix = eLazyBoolYes;
459 }
460 }
461 return m_supports_thread_suffix;
462}
463bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
464 if (m_supports_vCont_c == eLazyBoolCalculate) {
465 StringExtractorGDBRemote response;
466 m_supports_vCont_any = eLazyBoolNo;
467 m_supports_vCont_all = eLazyBoolNo;
468 m_supports_vCont_c = eLazyBoolNo;
469 m_supports_vCont_C = eLazyBoolNo;
470 m_supports_vCont_s = eLazyBoolNo;
471 m_supports_vCont_S = eLazyBoolNo;
472 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
473 PacketResult::Success) {
474 const char *response_cstr = response.GetStringRef().c_str();
475 if (::strstr(response_cstr, ";c"))
476 m_supports_vCont_c = eLazyBoolYes;
477
478 if (::strstr(response_cstr, ";C"))
479 m_supports_vCont_C = eLazyBoolYes;
480
481 if (::strstr(response_cstr, ";s"))
482 m_supports_vCont_s = eLazyBoolYes;
483
484 if (::strstr(response_cstr, ";S"))
485 m_supports_vCont_S = eLazyBoolYes;
486
487 if (m_supports_vCont_c == eLazyBoolYes &&
488 m_supports_vCont_C == eLazyBoolYes &&
489 m_supports_vCont_s == eLazyBoolYes &&
490 m_supports_vCont_S == eLazyBoolYes) {
491 m_supports_vCont_all = eLazyBoolYes;
492 }
493
494 if (m_supports_vCont_c == eLazyBoolYes ||
495 m_supports_vCont_C == eLazyBoolYes ||
496 m_supports_vCont_s == eLazyBoolYes ||
497 m_supports_vCont_S == eLazyBoolYes) {
498 m_supports_vCont_any = eLazyBoolYes;
499 }
500 }
501 }
502
503 switch (flavor) {
504 case 'a':
505 return m_supports_vCont_any;
506 case 'A':
507 return m_supports_vCont_all;
508 case 'c':
509 return m_supports_vCont_c;
510 case 'C':
511 return m_supports_vCont_C;
512 case 's':
513 return m_supports_vCont_s;
514 case 'S':
515 return m_supports_vCont_S;
516 default:
517 break;
518 }
519 return false;
520}
521
Pavel Labath4b6f9592016-08-18 08:30:03 +0000522GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
524 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
525 bool send_async) {
526 Lock lock(*this, send_async);
527 if (!lock) {
528 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
529 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
530 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
531 "for %s packet.",
Zachary Turnerc1564272016-11-16 21:15:24 +0000532 __FUNCTION__, payload.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533 return PacketResult::ErrorNoSequenceLock;
534 }
Pavel Labath5c95ee42016-08-30 13:56:11 +0000535
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 if (GetThreadSuffixSupported())
537 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
538 else {
539 if (!SetCurrentThread(tid))
540 return PacketResult::ErrorSendFailed;
541 }
Pavel Labath4b6f9592016-08-18 08:30:03 +0000542
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000544}
545
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000546// Check if the target supports 'p' packet. It sends out a 'p'
547// packet and checks the response. A normal packet will tell us
548// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000549//
550// Takes a valid thread ID because p needs to apply to a thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
552 if (m_supports_p == eLazyBoolCalculate) {
553 m_supports_p = eLazyBoolNo;
554 StreamString payload;
555 payload.PutCString("p0");
556 StringExtractorGDBRemote response;
557 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
558 response, false) ==
559 PacketResult::Success &&
560 response.IsNormalResponse()) {
561 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000562 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 }
564 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000565}
Greg Clayton576d8832011-03-22 04:00:09 +0000566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
568 // Get information on all threads at one using the "jThreadsInfo" packet
569 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 if (m_supports_jThreadsInfo) {
572 StringExtractorGDBRemote response;
573 response.SetResponseValidatorToJSON();
574 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
575 PacketResult::Success) {
576 if (response.IsUnsupportedResponse()) {
577 m_supports_jThreadsInfo = false;
578 } else if (!response.Empty()) {
579 object_sp = StructuredData::ParseJSON(response.GetStringRef());
580 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
583 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000584}
585
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
587 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
588 StringExtractorGDBRemote response;
589 m_supports_jThreadExtendedInfo = eLazyBoolNo;
590 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
591 PacketResult::Success) {
592 if (response.IsOKResponse()) {
593 m_supports_jThreadExtendedInfo = eLazyBoolYes;
594 }
Jason Molenda705b1802014-06-13 02:37:02 +0000595 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 }
597 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000598}
599
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
601 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
602 StringExtractorGDBRemote response;
603 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
604 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
605 response,
606 false) == PacketResult::Success) {
607 if (response.IsOKResponse()) {
608 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
609 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000610 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 }
612 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000613}
614
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
616 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
617 StringExtractorGDBRemote response;
618 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
619 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
620 PacketResult::Success) {
621 if (response.IsOKResponse()) {
622 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
623 }
Jason Molenda37397352016-07-22 00:17:55 +0000624 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 }
626 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000627}
628
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629bool GDBRemoteCommunicationClient::GetxPacketSupported() {
630 if (m_supports_x == eLazyBoolCalculate) {
631 StringExtractorGDBRemote response;
632 m_supports_x = eLazyBoolNo;
633 char packet[256];
634 snprintf(packet, sizeof(packet), "x0,0");
635 if (SendPacketAndWaitForResponse(packet, response, false) ==
636 PacketResult::Success) {
637 if (response.IsOKResponse())
638 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000639 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640 }
641 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000642}
643
Greg Clayton3dedae12013-12-06 21:45:27 +0000644GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
646 const char *payload_prefix, std::string &response_string) {
647 Lock lock(*this, false);
648 if (!lock) {
649 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
650 GDBR_LOG_PACKETS));
651 if (log)
652 log->Printf("error: failed to get packet sequence mutex, not sending "
653 "packets with prefix '%s'",
654 payload_prefix);
655 return PacketResult::ErrorNoSequenceLock;
656 }
657
658 response_string = "";
659 std::string payload_prefix_str(payload_prefix);
660 unsigned int response_size = 0x1000;
661 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
662 response_size = GetRemoteMaxPacketSize();
663 }
664
665 for (unsigned int offset = 0; true; offset += response_size) {
666 StringExtractorGDBRemote this_response;
667 // Construct payload
668 char sizeDescriptor[128];
669 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
670 response_size);
671 PacketResult result = SendPacketAndWaitForResponseNoLock(
672 payload_prefix_str + sizeDescriptor, this_response);
673 if (result != PacketResult::Success)
674 return result;
675
676 const std::string &this_string = this_response.GetStringRef();
677
678 // Check for m or l as first character; l seems to mean this is the last
679 // chunk
680 char first_char = *this_string.c_str();
681 if (first_char != 'm' && first_char != 'l') {
682 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000683 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684 // Concatenate the result so far (skipping 'm' or 'l')
685 response_string.append(this_string, 1, std::string::npos);
686 if (first_char == 'l')
687 // We're done
688 return PacketResult::Success;
689 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000690}
691
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
693 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
694 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000695
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 // First try to retrieve the pid via the qProcessInfo request.
697 GetCurrentProcessInfo(allow_lazy);
698 if (m_curr_pid_is_valid == eLazyBoolYes) {
699 // We really got it.
700 return m_curr_pid;
701 } else {
702 // If we don't get a response for qProcessInfo, check if $qC gives us a
703 // result.
704 // $qC only returns a real process id on older debugserver and lldb-platform
705 // stubs.
706 // The gdb remote protocol documents $qC as returning the thread id, which
707 // newer
708 // debugserver and lldb-gdbserver stubs return correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000709 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000710 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 PacketResult::Success) {
712 if (response.GetChar() == 'Q') {
713 if (response.GetChar() == 'C') {
714 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
715 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
716 m_curr_pid_is_valid = eLazyBoolYes;
717 return m_curr_pid;
718 }
Greg Clayton576d8832011-03-22 04:00:09 +0000719 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720 }
Greg Clayton576d8832011-03-22 04:00:09 +0000721 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722
723 // If we don't get a response for $qC, check if $qfThreadID gives us a
724 // result.
725 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
726 std::vector<lldb::tid_t> thread_ids;
727 bool sequence_mutex_unavailable;
728 size_t size;
729 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
730 if (size && sequence_mutex_unavailable == false) {
731 m_curr_pid = thread_ids.front();
732 m_curr_pid_is_valid = eLazyBoolYes;
733 return m_curr_pid;
734 }
Greg Clayton576d8832011-03-22 04:00:09 +0000735 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 }
737
738 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000739}
740
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
742 error_str.clear();
743 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000744 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
745 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 if (response.IsOKResponse())
747 return true;
748 if (response.GetChar() == 'E') {
749 // A string the describes what failed when launching...
750 error_str = response.GetStringRef().substr(1);
751 } else {
752 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000753 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 } else {
755 error_str.assign("timed out waiting for app to launch");
756 }
757 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000758}
759
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760int GDBRemoteCommunicationClient::SendArgumentsPacket(
761 const ProcessLaunchInfo &launch_info) {
762 // Since we don't get the send argv0 separate from the executable path, we
763 // need to
764 // make sure to use the actual executable path found in the launch_info...
765 std::vector<const char *> argv;
766 FileSpec exe_file = launch_info.GetExecutableFile();
767 std::string exe_path;
768 const char *arg = NULL;
769 const Args &launch_args = launch_info.GetArguments();
770 if (exe_file)
771 exe_path = exe_file.GetPath(false);
772 else {
773 arg = launch_args.GetArgumentAtIndex(0);
774 if (arg)
775 exe_path = arg;
776 }
777 if (!exe_path.empty()) {
778 argv.push_back(exe_path.c_str());
779 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
780 ++i) {
781 if (arg)
782 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000783 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 }
785 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000786 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 packet.PutChar('A');
788 for (size_t i = 0, n = argv.size(); i < n; ++i) {
789 arg = argv[i];
790 const int arg_len = strlen(arg);
791 if (i > 0)
792 packet.PutChar(',');
793 packet.Printf("%i,%i,", arg_len * 2, (int)i);
794 packet.PutBytesAsRawHex8(arg, arg_len);
795 }
796
Vince Harrone0be4252015-02-06 18:32:57 +0000797 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000798 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
799 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000801 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 uint8_t error = response.GetError();
803 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000804 return error;
805 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 }
807 return -1;
808}
Johnny Chen64637202012-05-23 21:09:52 +0000809
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810int GDBRemoteCommunicationClient::SendEnvironmentPacket(
811 char const *name_equal_value) {
812 if (name_equal_value && name_equal_value[0]) {
813 StreamString packet;
814 bool send_hex_encoding = false;
815 for (const char *p = name_equal_value;
816 *p != '\0' && send_hex_encoding == false; ++p) {
817 if (isprint(*p)) {
818 switch (*p) {
819 case '$':
820 case '#':
821 case '*':
822 case '}':
823 send_hex_encoding = true;
824 break;
825 default:
826 break;
Johnny Chen64637202012-05-23 21:09:52 +0000827 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 } else {
829 // We have non printable characters, lets hex encode this...
830 send_hex_encoding = true;
831 }
Johnny Chen64637202012-05-23 21:09:52 +0000832 }
833
Greg Claytonfbb76342013-11-20 21:07:01 +0000834 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 if (send_hex_encoding) {
836 if (m_supports_QEnvironmentHexEncoded) {
837 packet.PutCString("QEnvironmentHexEncoded:");
838 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000839 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
840 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 if (response.IsOKResponse())
842 return 0;
843 uint8_t error = response.GetError();
844 if (error)
845 return error;
846 if (response.IsUnsupportedResponse())
847 m_supports_QEnvironmentHexEncoded = false;
848 }
849 }
850
851 } else if (m_supports_QEnvironment) {
852 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000853 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
854 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 if (response.IsOKResponse())
856 return 0;
857 uint8_t error = response.GetError();
858 if (error)
859 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000860 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000861 m_supports_QEnvironment = false;
862 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000863 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 }
865 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000866}
867
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
869 if (arch && arch[0]) {
870 StreamString packet;
871 packet.Printf("QLaunchArch:%s", arch);
872 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000873 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
874 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000875 if (response.IsOKResponse())
876 return 0;
877 uint8_t error = response.GetError();
878 if (error)
879 return error;
880 }
881 }
882 return -1;
883}
Chaoren Lind3173f32015-05-29 19:52:29 +0000884
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
886 char const *data, bool *was_supported) {
887 if (data && *data != '\0') {
888 StreamString packet;
889 packet.Printf("QSetProcessEvent:%s", data);
890 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000891 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
892 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 if (response.IsOKResponse()) {
894 if (was_supported)
895 *was_supported = true;
896 return 0;
897 } else if (response.IsUnsupportedResponse()) {
898 if (was_supported)
899 *was_supported = false;
900 return -1;
901 } else {
902 uint8_t error = response.GetError();
903 if (was_supported)
904 *was_supported = true;
905 if (error)
906 return error;
907 }
908 }
909 }
910 return -1;
911}
912
913bool GDBRemoteCommunicationClient::GetOSVersion(uint32_t &major,
914 uint32_t &minor,
915 uint32_t &update) {
916 if (GetHostInfo()) {
917 if (m_os_version_major != UINT32_MAX) {
918 major = m_os_version_major;
919 minor = m_os_version_minor;
920 update = m_os_version_update;
921 return true;
922 }
923 }
924 return false;
925}
926
927bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
928 if (GetHostInfo()) {
929 if (!m_os_build.empty()) {
930 s = m_os_build;
931 return true;
932 }
933 }
934 s.clear();
935 return false;
936}
937
938bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
939 if (GetHostInfo()) {
940 if (!m_os_kernel.empty()) {
941 s = m_os_kernel;
942 return true;
943 }
944 }
945 s.clear();
946 return false;
947}
948
949bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
950 if (GetHostInfo()) {
951 if (!m_hostname.empty()) {
952 s = m_hostname;
953 return true;
954 }
955 }
956 s.clear();
957 return false;
958}
959
960ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
961 if (GetHostInfo())
962 return m_host_arch;
963 return ArchSpec();
964}
965
966const lldb_private::ArchSpec &
967GDBRemoteCommunicationClient::GetProcessArchitecture() {
968 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
969 GetCurrentProcessInfo();
970 return m_process_arch;
971}
972
973bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
974 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
975 m_gdb_server_name.clear();
976 m_gdb_server_version = 0;
977 m_qGDBServerVersion_is_valid = eLazyBoolNo;
978
979 StringExtractorGDBRemote response;
980 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
981 PacketResult::Success) {
982 if (response.IsNormalResponse()) {
983 llvm::StringRef name, value;
984 bool success = false;
985 while (response.GetNameColonValue(name, value)) {
986 if (name.equals("name")) {
987 success = true;
988 m_gdb_server_name = value;
989 } else if (name.equals("version")) {
990 llvm::StringRef major, minor;
991 std::tie(major, minor) = value.split('.');
992 if (!major.getAsInteger(0, m_gdb_server_version))
993 success = true;
994 }
Greg Clayton576d8832011-03-22 04:00:09 +0000995 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 if (success)
997 m_qGDBServerVersion_is_valid = eLazyBoolYes;
998 }
Greg Clayton576d8832011-03-22 04:00:09 +0000999 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 }
1001 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001002}
1003
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004void GDBRemoteCommunicationClient::MaybeEnableCompression(
1005 std::vector<std::string> supported_compressions) {
1006 CompressionType avail_type = CompressionType::None;
1007 std::string avail_name;
1008
1009#if defined(HAVE_LIBCOMPRESSION)
1010 // libcompression is weak linked so test if compression_decode_buffer() is
1011 // available
1012 if (compression_decode_buffer != NULL &&
1013 avail_type == CompressionType::None) {
1014 for (auto compression : supported_compressions) {
1015 if (compression == "lzfse") {
1016 avail_type = CompressionType::LZFSE;
1017 avail_name = compression;
1018 break;
1019 }
1020 }
1021 }
1022#endif
1023
1024#if defined(HAVE_LIBCOMPRESSION)
1025 // libcompression is weak linked so test if compression_decode_buffer() is
1026 // available
1027 if (compression_decode_buffer != NULL &&
1028 avail_type == CompressionType::None) {
1029 for (auto compression : supported_compressions) {
1030 if (compression == "zlib-deflate") {
1031 avail_type = CompressionType::ZlibDeflate;
1032 avail_name = compression;
1033 break;
1034 }
1035 }
1036 }
1037#endif
1038
1039#if defined(HAVE_LIBZ)
1040 if (avail_type == CompressionType::None) {
1041 for (auto compression : supported_compressions) {
1042 if (compression == "zlib-deflate") {
1043 avail_type = CompressionType::ZlibDeflate;
1044 avail_name = compression;
1045 break;
1046 }
1047 }
1048 }
1049#endif
1050
1051#if defined(HAVE_LIBCOMPRESSION)
1052 // libcompression is weak linked so test if compression_decode_buffer() is
1053 // available
1054 if (compression_decode_buffer != NULL &&
1055 avail_type == CompressionType::None) {
1056 for (auto compression : supported_compressions) {
1057 if (compression == "lz4") {
1058 avail_type = CompressionType::LZ4;
1059 avail_name = compression;
1060 break;
1061 }
1062 }
1063 }
1064#endif
1065
1066#if defined(HAVE_LIBCOMPRESSION)
1067 // libcompression is weak linked so test if compression_decode_buffer() is
1068 // available
1069 if (compression_decode_buffer != NULL &&
1070 avail_type == CompressionType::None) {
1071 for (auto compression : supported_compressions) {
1072 if (compression == "lzma") {
1073 avail_type = CompressionType::LZMA;
1074 avail_name = compression;
1075 break;
1076 }
1077 }
1078 }
1079#endif
1080
1081 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001082 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001084 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 PacketResult::Success)
1086 return;
1087
1088 if (response.IsOKResponse()) {
1089 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001090 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001091 }
Greg Clayton576d8832011-03-22 04:00:09 +00001092}
Greg Clayton32e0a752011-03-30 18:16:51 +00001093
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1095 if (GetGDBServerVersion()) {
1096 if (!m_gdb_server_name.empty())
1097 return m_gdb_server_name.c_str();
1098 }
1099 return NULL;
1100}
1101
1102uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1103 if (GetGDBServerVersion())
1104 return m_gdb_server_version;
1105 return 0;
1106}
1107
1108bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1109 StringExtractorGDBRemote response;
1110 if (SendPacketAndWaitForResponse("qC", response, false) !=
1111 PacketResult::Success)
1112 return false;
1113
1114 if (!response.IsNormalResponse())
1115 return false;
1116
1117 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1118 tid = response.GetHexMaxU32(true, -1);
1119
1120 return true;
1121}
1122
1123bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1124 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1125
1126 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1127 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001128 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1130 PacketResult::Success) {
1131 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001132 llvm::StringRef name;
1133 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001134 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1135 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 std::string arch_name;
1137 std::string os_name;
1138 std::string vendor_name;
1139 std::string triple;
1140 std::string distribution_id;
1141 uint32_t pointer_byte_size = 0;
1142 ByteOrder byte_order = eByteOrderInvalid;
1143 uint32_t num_keys_decoded = 0;
1144 while (response.GetNameColonValue(name, value)) {
1145 if (name.equals("cputype")) {
1146 // exception type in big endian hex
1147 if (!value.getAsInteger(0, cpu))
1148 ++num_keys_decoded;
1149 } else if (name.equals("cpusubtype")) {
1150 // exception count in big endian hex
1151 if (!value.getAsInteger(0, sub))
1152 ++num_keys_decoded;
1153 } else if (name.equals("arch")) {
1154 arch_name = value;
1155 ++num_keys_decoded;
1156 } else if (name.equals("triple")) {
1157 StringExtractor extractor(value);
1158 extractor.GetHexByteString(triple);
1159 ++num_keys_decoded;
1160 } else if (name.equals("distribution_id")) {
1161 StringExtractor extractor(value);
1162 extractor.GetHexByteString(distribution_id);
1163 ++num_keys_decoded;
1164 } else if (name.equals("os_build")) {
1165 StringExtractor extractor(value);
1166 extractor.GetHexByteString(m_os_build);
1167 ++num_keys_decoded;
1168 } else if (name.equals("hostname")) {
1169 StringExtractor extractor(value);
1170 extractor.GetHexByteString(m_hostname);
1171 ++num_keys_decoded;
1172 } else if (name.equals("os_kernel")) {
1173 StringExtractor extractor(value);
1174 extractor.GetHexByteString(m_os_kernel);
1175 ++num_keys_decoded;
1176 } else if (name.equals("ostype")) {
1177 os_name = value;
1178 ++num_keys_decoded;
1179 } else if (name.equals("vendor")) {
1180 vendor_name = value;
1181 ++num_keys_decoded;
1182 } else if (name.equals("endian")) {
1183 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1184 .Case("little", eByteOrderLittle)
1185 .Case("big", eByteOrderBig)
1186 .Case("pdp", eByteOrderPDP)
1187 .Default(eByteOrderInvalid);
1188 if (byte_order != eByteOrderInvalid)
1189 ++num_keys_decoded;
1190 } else if (name.equals("ptrsize")) {
1191 if (!value.getAsInteger(0, pointer_byte_size))
1192 ++num_keys_decoded;
1193 } else if (name.equals("os_version") ||
1194 name.equals(
1195 "version")) // Older debugserver binaries used the
1196 // "version" key instead of
1197 // "os_version"...
1198 {
Zachary Turner6fa7681b2016-09-17 02:00:02 +00001199 Args::StringToVersion(value, m_os_version_major, m_os_version_minor,
1200 m_os_version_update);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 if (m_os_version_major != UINT32_MAX)
1202 ++num_keys_decoded;
1203 } else if (name.equals("watchpoint_exceptions_received")) {
1204 m_watchpoints_trigger_after_instruction =
1205 llvm::StringSwitch<LazyBool>(value)
1206 .Case("before", eLazyBoolNo)
1207 .Case("after", eLazyBoolYes)
1208 .Default(eLazyBoolCalculate);
1209 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1210 ++num_keys_decoded;
1211 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001212 uint32_t timeout_seconds;
1213 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001214 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 SetPacketTimeout(m_default_packet_timeout);
1216 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001217 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 }
Jason Molenda89c37492014-01-27 22:23:20 +00001219 }
1220
Kate Stoneb9c1b512016-09-06 20:57:50 +00001221 if (num_keys_decoded > 0)
1222 m_qHostInfo_is_valid = eLazyBoolYes;
1223
1224 if (triple.empty()) {
1225 if (arch_name.empty()) {
1226 if (cpu != LLDB_INVALID_CPUTYPE) {
1227 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1228 if (pointer_byte_size) {
1229 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1230 }
1231 if (byte_order != eByteOrderInvalid) {
1232 assert(byte_order == m_host_arch.GetByteOrder());
1233 }
1234
1235 if (!vendor_name.empty())
1236 m_host_arch.GetTriple().setVendorName(
1237 llvm::StringRef(vendor_name));
1238 if (!os_name.empty())
1239 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001240 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001242 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001243 triple += arch_name;
1244 if (!vendor_name.empty() || !os_name.empty()) {
1245 triple += '-';
1246 if (vendor_name.empty())
1247 triple += "unknown";
1248 else
1249 triple += vendor_name;
1250 triple += '-';
1251 if (os_name.empty())
1252 triple += "unknown";
1253 else
1254 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001255 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001257
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 llvm::Triple &host_triple = m_host_arch.GetTriple();
1259 if (host_triple.getVendor() == llvm::Triple::Apple &&
1260 host_triple.getOS() == llvm::Triple::Darwin) {
1261 switch (m_host_arch.GetMachine()) {
1262 case llvm::Triple::aarch64:
1263 case llvm::Triple::arm:
1264 case llvm::Triple::thumb:
1265 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001266 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001267 default:
1268 host_triple.setOS(llvm::Triple::MacOSX);
1269 break;
1270 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001271 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 if (pointer_byte_size) {
1273 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1274 }
1275 if (byte_order != eByteOrderInvalid) {
1276 assert(byte_order == m_host_arch.GetByteOrder());
1277 }
1278 }
1279 } else {
1280 m_host_arch.SetTriple(triple.c_str());
1281 if (pointer_byte_size) {
1282 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1283 }
1284 if (byte_order != eByteOrderInvalid) {
1285 assert(byte_order == m_host_arch.GetByteOrder());
1286 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001287
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288 if (log)
1289 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1290 "architecture as %s, triple as %s from triple text %s",
1291 __FUNCTION__, m_host_arch.GetArchitectureName()
1292 ? m_host_arch.GetArchitectureName()
1293 : "<null-arch-name>",
1294 m_host_arch.GetTriple().getTriple().c_str(),
1295 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001296 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297 if (!distribution_id.empty())
1298 m_host_arch.SetDistributionId(distribution_id.c_str());
1299 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001300 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 }
1302 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001303}
Greg Clayton37a0a242012-04-11 00:24:49 +00001304
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305int GDBRemoteCommunicationClient::SendAttach(
1306 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1307 if (pid != LLDB_INVALID_PROCESS_ID) {
1308 char packet[64];
1309 const int packet_len =
1310 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001311 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001313 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314 PacketResult::Success) {
1315 if (response.IsErrorResponse())
1316 return response.GetError();
1317 return 0;
1318 }
1319 }
1320 return -1;
1321}
1322
1323int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1324 size_t data_len) {
1325 StreamString packet;
1326 packet.PutCString("I");
1327 packet.PutBytesAsRawHex8(data, data_len);
1328 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001329 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1330 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331 return 0;
1332 }
1333 return response.GetError();
1334}
1335
1336const lldb_private::ArchSpec &
1337GDBRemoteCommunicationClient::GetHostArchitecture() {
1338 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1339 GetHostInfo();
1340 return m_host_arch;
1341}
1342
Pavel Labath1eff73c2016-11-24 10:54:49 +00001343seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1345 GetHostInfo();
1346 return m_default_packet_timeout;
1347}
1348
1349addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1350 uint32_t permissions) {
1351 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1352 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1353 char packet[64];
1354 const int packet_len = ::snprintf(
1355 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1356 permissions & lldb::ePermissionsReadable ? "r" : "",
1357 permissions & lldb::ePermissionsWritable ? "w" : "",
1358 permissions & lldb::ePermissionsExecutable ? "x" : "");
1359 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001360 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001361 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001362 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001363 PacketResult::Success) {
1364 if (response.IsUnsupportedResponse())
1365 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1366 else if (!response.IsErrorResponse())
1367 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1368 } else {
1369 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1370 }
1371 }
1372 return LLDB_INVALID_ADDRESS;
1373}
1374
1375bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1376 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1377 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1378 char packet[64];
1379 const int packet_len =
1380 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1381 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001382 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001383 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001384 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385 PacketResult::Success) {
1386 if (response.IsUnsupportedResponse())
1387 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1388 else if (response.IsOKResponse())
1389 return true;
1390 } else {
1391 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1392 }
1393 }
1394 return false;
1395}
1396
1397Error GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1398 Error error;
1399
1400 if (keep_stopped) {
1401 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1402 char packet[64];
1403 const int packet_len =
1404 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1405 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001406 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001407 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001408 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409 PacketResult::Success &&
1410 response.IsOKResponse()) {
1411 m_supports_detach_stay_stopped = eLazyBoolYes;
1412 } else {
1413 m_supports_detach_stay_stopped = eLazyBoolNo;
1414 }
1415 }
1416
1417 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1418 error.SetErrorString("Stays stopped not supported by this target.");
1419 return error;
1420 } else {
1421 StringExtractorGDBRemote response;
1422 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001423 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424 if (packet_result != PacketResult::Success)
1425 error.SetErrorString("Sending extended disconnect packet failed.");
1426 }
1427 } else {
1428 StringExtractorGDBRemote response;
1429 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001430 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001431 if (packet_result != PacketResult::Success)
1432 error.SetErrorString("Sending disconnect packet failed.");
1433 }
1434 return error;
1435}
1436
1437Error GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1438 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1439 Error error;
1440 region_info.Clear();
1441
1442 if (m_supports_memory_region_info != eLazyBoolNo) {
1443 m_supports_memory_region_info = eLazyBoolYes;
1444 char packet[64];
1445 const int packet_len = ::snprintf(
1446 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1447 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001448 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001450 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 PacketResult::Success) {
1452 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 }
1527 if (error.Fail())
1528 region_info.Clear();
1529 return error;
1530}
1531
1532Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1533 Error error;
1534
1535 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1536 num = m_num_supported_hardware_watchpoints;
1537 return error;
1538 }
1539
1540 // Set num to 0 first.
1541 num = 0;
1542 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1543 char packet[64];
1544 const int packet_len =
1545 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1546 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001547 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001548 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001549 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001550 PacketResult::Success) {
1551 m_supports_watchpoint_support_info = eLazyBoolYes;
1552 llvm::StringRef name;
1553 llvm::StringRef value;
1554 while (response.GetNameColonValue(name, value)) {
1555 if (name.equals("num")) {
1556 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1557 num = m_num_supported_hardware_watchpoints;
1558 }
1559 }
1560 } else {
1561 m_supports_watchpoint_support_info = eLazyBoolNo;
1562 }
1563 }
1564
1565 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1566 error.SetErrorString("qWatchpointSupportInfo is not supported");
1567 }
1568 return error;
1569}
1570
1571lldb_private::Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1572 uint32_t &num, bool &after, const ArchSpec &arch) {
1573 Error error(GetWatchpointSupportInfo(num));
1574 if (error.Success())
1575 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1576 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001577}
1578
Daniel Maleae0f8f572013-08-26 23:57:52 +00001579lldb_private::Error
Kate Stoneb9c1b512016-09-06 20:57:50 +00001580GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1581 bool &after, const ArchSpec &arch) {
1582 Error error;
1583 llvm::Triple::ArchType atype = arch.GetMachine();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001584
Kate Stoneb9c1b512016-09-06 20:57:50 +00001585 // we assume watchpoints will happen after running the relevant opcode
1586 // and we only want to override this behavior if we have explicitly
1587 // received a qHostInfo telling us otherwise
1588 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1589 // On targets like MIPS, watchpoint exceptions are always generated
1590 // before the instruction is executed. The connected target may not
1591 // support qHostInfo or qWatchpointSupportInfo packets.
1592 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1593 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1594 after = false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001595 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001596 after = true;
1597 } else {
1598 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1599 // if it is not calculated before.
1600 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1601 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1602 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1603 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1604
1605 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1606 }
1607 return error;
1608}
1609
1610int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1611 if (file_spec) {
1612 std::string path{file_spec.GetPath(false)};
1613 StreamString packet;
1614 packet.PutCString("QSetSTDIN:");
1615 packet.PutCStringAsRawHex8(path.c_str());
1616
1617 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001618 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1619 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620 if (response.IsOKResponse())
1621 return 0;
1622 uint8_t error = response.GetError();
1623 if (error)
1624 return error;
1625 }
1626 }
1627 return -1;
1628}
1629
1630int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1631 if (file_spec) {
1632 std::string path{file_spec.GetPath(false)};
1633 StreamString packet;
1634 packet.PutCString("QSetSTDOUT:");
1635 packet.PutCStringAsRawHex8(path.c_str());
1636
1637 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001638 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1639 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001640 if (response.IsOKResponse())
1641 return 0;
1642 uint8_t error = response.GetError();
1643 if (error)
1644 return error;
1645 }
1646 }
1647 return -1;
1648}
1649
1650int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1651 if (file_spec) {
1652 std::string path{file_spec.GetPath(false)};
1653 StreamString packet;
1654 packet.PutCString("QSetSTDERR:");
1655 packet.PutCStringAsRawHex8(path.c_str());
1656
1657 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001658 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1659 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660 if (response.IsOKResponse())
1661 return 0;
1662 uint8_t error = response.GetError();
1663 if (error)
1664 return error;
1665 }
1666 }
1667 return -1;
1668}
1669
1670bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1671 StringExtractorGDBRemote response;
1672 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1673 PacketResult::Success) {
1674 if (response.IsUnsupportedResponse())
1675 return false;
1676 if (response.IsErrorResponse())
1677 return false;
1678 std::string cwd;
1679 response.GetHexByteString(cwd);
Zachary Turner8c6b5462017-03-06 23:42:44 +00001680 working_dir.SetFile(cwd, false, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681 return !cwd.empty();
1682 }
1683 return false;
1684}
1685
1686int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1687 if (working_dir) {
1688 std::string path{working_dir.GetPath(false)};
1689 StreamString packet;
1690 packet.PutCString("QSetWorkingDir:");
1691 packet.PutCStringAsRawHex8(path.c_str());
1692
1693 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001694 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1695 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696 if (response.IsOKResponse())
1697 return 0;
1698 uint8_t error = response.GetError();
1699 if (error)
1700 return error;
1701 }
1702 }
1703 return -1;
1704}
1705
1706int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1707 char packet[32];
1708 const int packet_len =
1709 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1710 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001711 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001712 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001713 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001714 PacketResult::Success) {
1715 if (response.IsOKResponse())
1716 return 0;
1717 uint8_t error = response.GetError();
1718 if (error)
1719 return error;
1720 }
1721 return -1;
1722}
1723
1724int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1725 char packet[32];
1726 const int packet_len = ::snprintf(packet, sizeof(packet),
1727 "QSetDetachOnError:%i", enable ? 1 : 0);
1728 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001729 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001731 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 PacketResult::Success) {
1733 if (response.IsOKResponse())
1734 return 0;
1735 uint8_t error = response.GetError();
1736 if (error)
1737 return error;
1738 }
1739 return -1;
1740}
1741
1742bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1743 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1744 if (response.IsNormalResponse()) {
1745 llvm::StringRef name;
1746 llvm::StringRef value;
1747 StringExtractor extractor;
1748
1749 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1750 uint32_t sub = 0;
1751 std::string vendor;
1752 std::string os_type;
1753
1754 while (response.GetNameColonValue(name, value)) {
1755 if (name.equals("pid")) {
1756 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1757 value.getAsInteger(0, pid);
1758 process_info.SetProcessID(pid);
1759 } else if (name.equals("ppid")) {
1760 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1761 value.getAsInteger(0, pid);
1762 process_info.SetParentProcessID(pid);
1763 } else if (name.equals("uid")) {
1764 uint32_t uid = UINT32_MAX;
1765 value.getAsInteger(0, uid);
1766 process_info.SetUserID(uid);
1767 } else if (name.equals("euid")) {
1768 uint32_t uid = UINT32_MAX;
1769 value.getAsInteger(0, uid);
1770 process_info.SetEffectiveGroupID(uid);
1771 } else if (name.equals("gid")) {
1772 uint32_t gid = UINT32_MAX;
1773 value.getAsInteger(0, gid);
1774 process_info.SetGroupID(gid);
1775 } else if (name.equals("egid")) {
1776 uint32_t gid = UINT32_MAX;
1777 value.getAsInteger(0, gid);
1778 process_info.SetEffectiveGroupID(gid);
1779 } else if (name.equals("triple")) {
1780 StringExtractor extractor(value);
1781 std::string triple;
1782 extractor.GetHexByteString(triple);
1783 process_info.GetArchitecture().SetTriple(triple.c_str());
1784 } else if (name.equals("name")) {
1785 StringExtractor extractor(value);
1786 // The process name from ASCII hex bytes since we can't
1787 // control the characters in a process name
1788 std::string name;
1789 extractor.GetHexByteString(name);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001790 process_info.GetExecutableFile().SetFile(name, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001791 } else if (name.equals("cputype")) {
1792 value.getAsInteger(0, cpu);
1793 } else if (name.equals("cpusubtype")) {
1794 value.getAsInteger(0, sub);
1795 } else if (name.equals("vendor")) {
1796 vendor = value;
1797 } else if (name.equals("ostype")) {
1798 os_type = value;
1799 }
1800 }
1801
1802 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1803 if (vendor == "apple") {
1804 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1805 sub);
1806 process_info.GetArchitecture().GetTriple().setVendorName(
1807 llvm::StringRef(vendor));
1808 process_info.GetArchitecture().GetTriple().setOSName(
1809 llvm::StringRef(os_type));
1810 }
1811 }
1812
1813 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1814 return true;
1815 }
1816 return false;
1817}
1818
1819bool GDBRemoteCommunicationClient::GetProcessInfo(
1820 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1821 process_info.Clear();
1822
1823 if (m_supports_qProcessInfoPID) {
1824 char packet[32];
1825 const int packet_len =
1826 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1827 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001828 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001829 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001830 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001831 PacketResult::Success) {
1832 return DecodeProcessInfoResponse(response, process_info);
1833 } else {
1834 m_supports_qProcessInfoPID = false;
1835 return false;
1836 }
1837 }
1838 return false;
1839}
1840
1841bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1842 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1843 GDBR_LOG_PACKETS));
1844
1845 if (allow_lazy) {
1846 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1847 return true;
1848 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1849 return false;
1850 }
1851
1852 GetHostInfo();
1853
1854 StringExtractorGDBRemote response;
1855 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1856 PacketResult::Success) {
1857 if (response.IsNormalResponse()) {
1858 llvm::StringRef name;
1859 llvm::StringRef value;
1860 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1861 uint32_t sub = 0;
1862 std::string arch_name;
1863 std::string os_name;
1864 std::string vendor_name;
1865 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001866 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001867 uint32_t pointer_byte_size = 0;
1868 StringExtractor extractor;
1869 ByteOrder byte_order = eByteOrderInvalid;
1870 uint32_t num_keys_decoded = 0;
1871 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1872 while (response.GetNameColonValue(name, value)) {
1873 if (name.equals("cputype")) {
1874 if (!value.getAsInteger(16, cpu))
1875 ++num_keys_decoded;
1876 } else if (name.equals("cpusubtype")) {
1877 if (!value.getAsInteger(16, sub))
1878 ++num_keys_decoded;
1879 } else if (name.equals("triple")) {
1880 StringExtractor extractor(value);
1881 extractor.GetHexByteString(triple);
1882 ++num_keys_decoded;
1883 } else if (name.equals("ostype")) {
1884 os_name = value;
1885 ++num_keys_decoded;
1886 } else if (name.equals("vendor")) {
1887 vendor_name = value;
1888 ++num_keys_decoded;
1889 } else if (name.equals("endian")) {
1890 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1891 .Case("little", eByteOrderLittle)
1892 .Case("big", eByteOrderBig)
1893 .Case("pdp", eByteOrderPDP)
1894 .Default(eByteOrderInvalid);
1895 if (byte_order != eByteOrderInvalid)
1896 ++num_keys_decoded;
1897 } else if (name.equals("ptrsize")) {
1898 if (!value.getAsInteger(16, pointer_byte_size))
1899 ++num_keys_decoded;
1900 } else if (name.equals("pid")) {
1901 if (!value.getAsInteger(16, pid))
1902 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001903 } else if (name.equals("elf_abi")) {
1904 elf_abi = value;
1905 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001906 }
1907 }
1908 if (num_keys_decoded > 0)
1909 m_qProcessInfo_is_valid = eLazyBoolYes;
1910 if (pid != LLDB_INVALID_PROCESS_ID) {
1911 m_curr_pid_is_valid = eLazyBoolYes;
1912 m_curr_pid = pid;
1913 }
1914
1915 // Set the ArchSpec from the triple if we have it.
1916 if (!triple.empty()) {
1917 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00001918 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919 if (pointer_byte_size) {
1920 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1921 }
1922 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
1923 !vendor_name.empty()) {
1924 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
1925
1926 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00001927 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001928 switch (triple.getObjectFormat()) {
1929 case llvm::Triple::MachO:
1930 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1931 break;
1932 case llvm::Triple::ELF:
1933 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
1934 break;
1935 case llvm::Triple::COFF:
1936 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
1937 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00001938 case llvm::Triple::Wasm:
1939 if (log)
1940 log->Printf("error: not supported target architecture");
1941 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001942 case llvm::Triple::UnknownObjectFormat:
1943 if (log)
1944 log->Printf("error: failed to determine target architecture");
1945 return false;
1946 }
1947
1948 if (pointer_byte_size) {
1949 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1950 }
1951 if (byte_order != eByteOrderInvalid) {
1952 assert(byte_order == m_process_arch.GetByteOrder());
1953 }
1954 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1955 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1956 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1957 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1958 }
1959 return true;
1960 }
1961 } else {
1962 m_qProcessInfo_is_valid = eLazyBoolNo;
1963 }
1964
1965 return false;
1966}
1967
1968uint32_t GDBRemoteCommunicationClient::FindProcesses(
1969 const ProcessInstanceInfoMatch &match_info,
1970 ProcessInstanceInfoList &process_infos) {
1971 process_infos.Clear();
1972
1973 if (m_supports_qfProcessInfo) {
1974 StreamString packet;
1975 packet.PutCString("qfProcessInfo");
1976 if (!match_info.MatchAllProcesses()) {
1977 packet.PutChar(':');
1978 const char *name = match_info.GetProcessInfo().GetName();
1979 bool has_name_match = false;
1980 if (name && name[0]) {
1981 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00001982 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001983 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00001984 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001985 has_name_match = false;
1986 break;
1987
Pavel Labathc4a33952017-02-20 11:35:33 +00001988 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001989 packet.PutCString("name_match:equals;");
1990 break;
1991
Pavel Labathc4a33952017-02-20 11:35:33 +00001992 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001993 packet.PutCString("name_match:contains;");
1994 break;
1995
Pavel Labathc4a33952017-02-20 11:35:33 +00001996 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001997 packet.PutCString("name_match:starts_with;");
1998 break;
1999
Pavel Labathc4a33952017-02-20 11:35:33 +00002000 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002001 packet.PutCString("name_match:ends_with;");
2002 break;
2003
Pavel Labathc4a33952017-02-20 11:35:33 +00002004 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002005 packet.PutCString("name_match:regex;");
2006 break;
2007 }
2008 if (has_name_match) {
2009 packet.PutCString("name:");
2010 packet.PutBytesAsRawHex8(name, ::strlen(name));
2011 packet.PutChar(';');
2012 }
2013 }
2014
2015 if (match_info.GetProcessInfo().ProcessIDIsValid())
2016 packet.Printf("pid:%" PRIu64 ";",
2017 match_info.GetProcessInfo().GetProcessID());
2018 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2019 packet.Printf("parent_pid:%" PRIu64 ";",
2020 match_info.GetProcessInfo().GetParentProcessID());
2021 if (match_info.GetProcessInfo().UserIDIsValid())
2022 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2023 if (match_info.GetProcessInfo().GroupIDIsValid())
2024 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2025 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2026 packet.Printf("euid:%u;",
2027 match_info.GetProcessInfo().GetEffectiveUserID());
2028 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2029 packet.Printf("egid:%u;",
2030 match_info.GetProcessInfo().GetEffectiveGroupID());
2031 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2032 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2033 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2034 const ArchSpec &match_arch =
2035 match_info.GetProcessInfo().GetArchitecture();
2036 const llvm::Triple &triple = match_arch.GetTriple();
2037 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002038 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002039 packet.PutChar(';');
2040 }
2041 }
2042 StringExtractorGDBRemote response;
2043 // Increase timeout as the first qfProcessInfo packet takes a long time
2044 // on Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002045 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002046 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2047 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002048 do {
2049 ProcessInstanceInfo process_info;
2050 if (!DecodeProcessInfoResponse(response, process_info))
2051 break;
2052 process_infos.Append(process_info);
2053 response.GetStringRef().clear();
2054 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002055 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2056 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002057 } else {
2058 m_supports_qfProcessInfo = false;
2059 return 0;
2060 }
2061 }
2062 return process_infos.GetSize();
2063}
2064
2065bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2066 std::string &name) {
2067 if (m_supports_qUserName) {
2068 char packet[32];
2069 const int packet_len =
2070 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2071 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002072 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002073 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002074 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002075 PacketResult::Success) {
2076 if (response.IsNormalResponse()) {
2077 // Make sure we parsed the right number of characters. The response is
2078 // the hex encoded user name and should make up the entire packet.
2079 // If there are any non-hex ASCII bytes, the length won't match below..
2080 if (response.GetHexByteString(name) * 2 ==
2081 response.GetStringRef().size())
2082 return true;
2083 }
2084 } else {
2085 m_supports_qUserName = false;
2086 return false;
2087 }
2088 }
2089 return false;
2090}
2091
2092bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2093 std::string &name) {
2094 if (m_supports_qGroupName) {
2095 char packet[32];
2096 const int packet_len =
2097 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2098 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002099 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002101 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002102 PacketResult::Success) {
2103 if (response.IsNormalResponse()) {
2104 // Make sure we parsed the right number of characters. The response is
2105 // the hex encoded group name and should make up the entire packet.
2106 // If there are any non-hex ASCII bytes, the length won't match below..
2107 if (response.GetHexByteString(name) * 2 ==
2108 response.GetStringRef().size())
2109 return true;
2110 }
2111 } else {
2112 m_supports_qGroupName = false;
2113 return false;
2114 }
2115 }
2116 return false;
2117}
2118
2119bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2120 // Form non-stop packet request
2121 char packet[32];
2122 const int packet_len =
2123 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2124 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002125 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126
2127 StringExtractorGDBRemote response;
2128 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002129 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002130 PacketResult::Success)
2131 if (response.IsOKResponse())
2132 return true;
2133
2134 // Failed or not supported
2135 return false;
2136}
2137
2138static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2139 uint32_t recv_size) {
2140 packet.Clear();
2141 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2142 uint32_t bytes_left = send_size;
2143 while (bytes_left > 0) {
2144 if (bytes_left >= 26) {
2145 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2146 bytes_left -= 26;
2147 } else {
2148 packet.Printf("%*.*s;", bytes_left, bytes_left,
2149 "abcdefghijklmnopqrstuvwxyz");
2150 bytes_left = 0;
2151 }
2152 }
2153}
2154
Pavel Labath1eff73c2016-11-24 10:54:49 +00002155duration<float>
2156calculate_standard_deviation(const std::vector<duration<float>> &v) {
2157 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002158 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2159 Dur mean = sum / v.size();
2160 float accum = 0;
2161 for (auto d : v) {
2162 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002163 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002164 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002165
Pavel Labath3aa04912016-10-31 17:19:42 +00002166 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167}
2168
2169void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2170 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002171 uint32_t max_recv,
2172 uint64_t recv_amount,
2173 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002175 if (SendSpeedTestPacket(0, 0)) {
2176 StreamString packet;
2177 if (json)
2178 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2179 "\"results\" : [",
2180 num_packets);
2181 else
2182 strm.Printf("Testing sending %u packets of various sizes:\n",
2183 num_packets);
2184 strm.Flush();
2185
2186 uint32_t result_idx = 0;
2187 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002188 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189
2190 for (send_size = 0; send_size <= max_send;
2191 send_size ? send_size *= 2 : send_size = 4) {
2192 for (uint32_t recv_size = 0; recv_size <= max_recv;
2193 recv_size ? recv_size *= 2 : recv_size = 4) {
2194 MakeSpeedTestPacket(packet, send_size, recv_size);
2195
2196 packet_times.clear();
2197 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002198 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002199 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002200 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002201 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002202 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002203 const auto packet_end_time = steady_clock::now();
2204 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002206 const auto end_time = steady_clock::now();
2207 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208
2209 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002210 ((float)num_packets) / duration<float>(total_time).count();
2211 auto average_per_packet = total_time / num_packets;
2212 const duration<float> standard_deviation =
2213 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002215 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2216 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2217 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002218 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002219 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 ++result_idx;
2221 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002222 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2223 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2224 "standard deviation of {5,10:ms+f6}\n",
2225 send_size, recv_size, duration<float>(total_time),
2226 packets_per_second, duration<float>(average_per_packet),
2227 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228 }
2229 strm.Flush();
2230 }
2231 }
2232
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002233 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 if (json)
2235 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2236 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002237 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 else
2239 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2240 "packet sizes:\n",
2241 k_recv_amount_mb);
2242 strm.Flush();
2243 send_size = 0;
2244 result_idx = 0;
2245 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2246 MakeSpeedTestPacket(packet, send_size, recv_size);
2247
2248 // If we have a receive size, test how long it takes to receive 4MB of
2249 // data
2250 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002251 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002252 uint32_t bytes_read = 0;
2253 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002254 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002255 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002256 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 bytes_read += recv_size;
2258 ++packet_count;
2259 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002260 const auto end_time = steady_clock::now();
2261 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002262 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002263 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002264 (1024.0 * 1024.0);
2265 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002266 ((float)packet_count) / duration<float>(total_time).count();
2267 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002268
2269 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002270 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2271 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002272 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002273 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002274 ++result_idx;
2275 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002276 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2277 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2278 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002279 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002280 duration<float>(total_time), mb_second,
2281 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282 }
2283 strm.Flush();
2284 }
2285 }
2286 if (json)
2287 strm.Printf("\n ]\n }\n}\n");
2288 else
2289 strm.EOL();
2290 }
2291}
2292
2293bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2294 uint32_t recv_size) {
2295 StreamString packet;
2296 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2297 uint32_t bytes_left = send_size;
2298 while (bytes_left > 0) {
2299 if (bytes_left >= 26) {
2300 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2301 bytes_left -= 26;
2302 } else {
2303 packet.Printf("%*.*s;", bytes_left, bytes_left,
2304 "abcdefghijklmnopqrstuvwxyz");
2305 bytes_left = 0;
2306 }
2307 }
2308
2309 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002310 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2311 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002312}
2313
2314bool GDBRemoteCommunicationClient::LaunchGDBServer(
2315 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2316 std::string &socket_name) {
2317 pid = LLDB_INVALID_PROCESS_ID;
2318 port = 0;
2319 socket_name.clear();
2320
2321 StringExtractorGDBRemote response;
2322 StreamString stream;
2323 stream.PutCString("qLaunchGDBServer;");
2324 std::string hostname;
2325 if (remote_accept_hostname && remote_accept_hostname[0])
2326 hostname = remote_accept_hostname;
2327 else {
2328 if (HostInfo::GetHostname(hostname)) {
2329 // Make the GDB server we launch only accept connections from this host
2330 stream.Printf("host:%s;", hostname.c_str());
2331 } else {
2332 // Make the GDB server we launch accept connections from any host since we
2333 // can't figure out the hostname
2334 stream.Printf("host:*;");
2335 }
2336 }
2337 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002338 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002339
2340 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2341 PacketResult::Success) {
2342 llvm::StringRef name;
2343 llvm::StringRef value;
2344 while (response.GetNameColonValue(name, value)) {
2345 if (name.equals("port"))
2346 value.getAsInteger(0, port);
2347 else if (name.equals("pid"))
2348 value.getAsInteger(0, pid);
2349 else if (name.compare("socket_name") == 0) {
2350 StringExtractor extractor(value);
2351 extractor.GetHexByteString(socket_name);
2352 }
2353 }
2354 return true;
2355 }
2356 return false;
2357}
2358
2359size_t GDBRemoteCommunicationClient::QueryGDBServer(
2360 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2361 connection_urls.clear();
2362
2363 StringExtractorGDBRemote response;
2364 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2365 PacketResult::Success)
2366 return 0;
2367
2368 StructuredData::ObjectSP data =
2369 StructuredData::ParseJSON(response.GetStringRef());
2370 if (!data)
2371 return 0;
2372
2373 StructuredData::Array *array = data->GetAsArray();
2374 if (!array)
2375 return 0;
2376
2377 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2378 StructuredData::Dictionary *element = nullptr;
2379 if (!array->GetItemAtIndexAsDictionary(i, element))
2380 continue;
2381
2382 uint16_t port = 0;
2383 if (StructuredData::ObjectSP port_osp =
2384 element->GetValueForKey(llvm::StringRef("port")))
2385 port = port_osp->GetIntegerValue(0);
2386
2387 std::string socket_name;
2388 if (StructuredData::ObjectSP socket_name_osp =
2389 element->GetValueForKey(llvm::StringRef("socket_name")))
2390 socket_name = socket_name_osp->GetStringValue();
2391
2392 if (port != 0 || !socket_name.empty())
2393 connection_urls.emplace_back(port, socket_name);
2394 }
2395 return connection_urls.size();
2396}
2397
2398bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2399 StreamString stream;
2400 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401
2402 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002403 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002404 PacketResult::Success) {
2405 if (response.IsOKResponse())
2406 return true;
2407 }
2408 return false;
2409}
2410
2411bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2412 if (m_curr_tid == tid)
2413 return true;
2414
2415 char packet[32];
2416 int packet_len;
2417 if (tid == UINT64_MAX)
2418 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2419 else
2420 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2421 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002422 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002423 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002424 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002425 PacketResult::Success) {
2426 if (response.IsOKResponse()) {
2427 m_curr_tid = tid;
2428 return true;
2429 }
2430
2431 /*
2432 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2433 * Hg packet.
2434 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2435 * which can
2436 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2437 */
2438 if (response.IsUnsupportedResponse() && IsConnected()) {
2439 m_curr_tid = 1;
2440 return true;
2441 }
2442 }
2443 return false;
2444}
2445
2446bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2447 if (m_curr_tid_run == tid)
2448 return true;
2449
2450 char packet[32];
2451 int packet_len;
2452 if (tid == UINT64_MAX)
2453 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2454 else
2455 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2456
2457 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002458 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002459 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002460 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002461 PacketResult::Success) {
2462 if (response.IsOKResponse()) {
2463 m_curr_tid_run = tid;
2464 return true;
2465 }
2466
2467 /*
2468 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2469 * Hc packet.
2470 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2471 * which can
2472 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2473 */
2474 if (response.IsUnsupportedResponse() && IsConnected()) {
2475 m_curr_tid_run = 1;
2476 return true;
2477 }
2478 }
2479 return false;
2480}
2481
2482bool GDBRemoteCommunicationClient::GetStopReply(
2483 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002484 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002485 PacketResult::Success)
2486 return response.IsNormalResponse();
2487 return false;
2488}
2489
2490bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2491 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2492 if (m_supports_qThreadStopInfo) {
2493 char packet[256];
2494 int packet_len =
2495 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2496 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002497 UNUSED_IF_ASSERT_DISABLED(packet_len);
2498 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002499 PacketResult::Success) {
2500 if (response.IsUnsupportedResponse())
2501 m_supports_qThreadStopInfo = false;
2502 else if (response.IsNormalResponse())
2503 return true;
2504 else
2505 return false;
2506 } else {
2507 m_supports_qThreadStopInfo = false;
2508 }
2509 }
2510 return false;
2511}
2512
2513uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2514 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2515 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2516 if (log)
2517 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2518 __FUNCTION__, insert ? "add" : "remove", addr);
2519
2520 // Check if the stub is known not to support this breakpoint type
2521 if (!SupportsGDBStoppointPacket(type))
2522 return UINT8_MAX;
2523 // Construct the breakpoint packet
2524 char packet[64];
2525 const int packet_len =
2526 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2527 insert ? 'Z' : 'z', type, addr, length);
2528 // Check we haven't overwritten the end of the packet buffer
2529 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002530 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002531 StringExtractorGDBRemote response;
2532 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2533 // or "" (unsupported)
2534 response.SetResponseValidatorToOKErrorNotSupported();
2535 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002536 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537 PacketResult::Success) {
2538 // Receive and OK packet when the breakpoint successfully placed
2539 if (response.IsOKResponse())
2540 return 0;
2541
2542 // Error while setting breakpoint, send back specific error
2543 if (response.IsErrorResponse())
2544 return response.GetError();
2545
2546 // Empty packet informs us that breakpoint is not supported
2547 if (response.IsUnsupportedResponse()) {
2548 // Disable this breakpoint type since it is unsupported
2549 switch (type) {
2550 case eBreakpointSoftware:
2551 m_supports_z0 = false;
2552 break;
2553 case eBreakpointHardware:
2554 m_supports_z1 = false;
2555 break;
2556 case eWatchpointWrite:
2557 m_supports_z2 = false;
2558 break;
2559 case eWatchpointRead:
2560 m_supports_z3 = false;
2561 break;
2562 case eWatchpointReadWrite:
2563 m_supports_z4 = false;
2564 break;
2565 case eStoppointInvalid:
2566 return UINT8_MAX;
2567 }
2568 }
2569 }
2570 // Signal generic failure
2571 return UINT8_MAX;
2572}
2573
2574size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2575 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2576 thread_ids.clear();
2577
2578 Lock lock(*this, false);
2579 if (lock) {
2580 sequence_mutex_unavailable = false;
2581 StringExtractorGDBRemote response;
2582
2583 PacketResult packet_result;
2584 for (packet_result =
2585 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2586 packet_result == PacketResult::Success && response.IsNormalResponse();
2587 packet_result =
2588 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2589 char ch = response.GetChar();
2590 if (ch == 'l')
2591 break;
2592 if (ch == 'm') {
2593 do {
2594 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2595
2596 if (tid != LLDB_INVALID_THREAD_ID) {
2597 thread_ids.push_back(tid);
2598 }
2599 ch = response.GetChar(); // Skip the command separator
2600 } while (ch == ','); // Make sure we got a comma separator
2601 }
2602 }
2603
2604 /*
2605 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2606 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2607 * could
2608 * be as simple as 'S05'. There is no packet which can give us pid and/or
2609 * tid.
2610 * Assume pid=tid=1 in such cases.
2611 */
2612 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 &&
2613 IsConnected()) {
2614 thread_ids.push_back(1);
2615 }
2616 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002617#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002618 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2619 GDBR_LOG_PACKETS));
2620 if (log)
2621 log->Printf("error: failed to get packet sequence mutex, not sending "
2622 "packet 'qfThreadInfo'");
2623#endif
2624 sequence_mutex_unavailable = true;
2625 }
2626 return thread_ids.size();
2627}
2628
2629lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2630 StringExtractorGDBRemote response;
2631 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2632 PacketResult::Success ||
2633 !response.IsNormalResponse())
2634 return LLDB_INVALID_ADDRESS;
2635 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2636}
2637
2638lldb_private::Error GDBRemoteCommunicationClient::RunShellCommand(
2639 const char *command, // Shouldn't be NULL
2640 const FileSpec &
2641 working_dir, // Pass empty FileSpec to use the current working directory
2642 int *status_ptr, // Pass NULL if you don't want the process exit status
2643 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2644 // process to exit
2645 std::string
2646 *command_output, // Pass NULL if you don't want the command output
2647 uint32_t
2648 timeout_sec) // Timeout in seconds to wait for shell program to finish
2649{
2650 lldb_private::StreamString stream;
2651 stream.PutCString("qPlatform_shell:");
2652 stream.PutBytesAsRawHex8(command, strlen(command));
2653 stream.PutChar(',');
2654 stream.PutHex32(timeout_sec);
2655 if (working_dir) {
2656 std::string path{working_dir.GetPath(false)};
2657 stream.PutChar(',');
2658 stream.PutCStringAsRawHex8(path.c_str());
2659 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002660 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002661 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002662 PacketResult::Success) {
2663 if (response.GetChar() != 'F')
2664 return Error("malformed reply");
2665 if (response.GetChar() != ',')
2666 return Error("malformed reply");
2667 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2668 if (exitcode == UINT32_MAX)
2669 return Error("unable to run remote process");
2670 else if (status_ptr)
2671 *status_ptr = exitcode;
2672 if (response.GetChar() != ',')
2673 return Error("malformed reply");
2674 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2675 if (signo_ptr)
2676 *signo_ptr = signo;
2677 if (response.GetChar() != ',')
2678 return Error("malformed reply");
2679 std::string output;
2680 response.GetEscapedBinaryData(output);
2681 if (command_output)
2682 command_output->assign(output);
Mehdi Aminic1edf562016-11-11 04:29:25 +00002683 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002684 }
2685 return Error("unable to send packet");
2686}
2687
2688Error GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2689 uint32_t file_permissions) {
2690 std::string path{file_spec.GetPath(false)};
2691 lldb_private::StreamString stream;
2692 stream.PutCString("qPlatform_mkdir:");
2693 stream.PutHex32(file_permissions);
2694 stream.PutChar(',');
2695 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002696 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697 StringExtractorGDBRemote response;
2698
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002699 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002700 PacketResult::Success)
Zachary Turnerc1564272016-11-16 21:15:24 +00002701 return Error("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702
2703 if (response.GetChar() != 'F')
Zachary Turnerc1564272016-11-16 21:15:24 +00002704 return Error("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002705
2706 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2707}
2708
2709Error GDBRemoteCommunicationClient::SetFilePermissions(
2710 const FileSpec &file_spec, uint32_t file_permissions) {
2711 std::string path{file_spec.GetPath(false)};
2712 lldb_private::StreamString stream;
2713 stream.PutCString("qPlatform_chmod:");
2714 stream.PutHex32(file_permissions);
2715 stream.PutChar(',');
2716 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002717 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 StringExtractorGDBRemote response;
2719
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002720 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721 PacketResult::Success)
Zachary Turnerc1564272016-11-16 21:15:24 +00002722 return Error("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723
2724 if (response.GetChar() != 'F')
Zachary Turnerc1564272016-11-16 21:15:24 +00002725 return Error("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726
2727 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2728}
2729
2730static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2731 uint64_t fail_result, Error &error) {
2732 response.SetFilePos(0);
2733 if (response.GetChar() != 'F')
2734 return fail_result;
2735 int32_t result = response.GetS32(-2);
2736 if (result == -2)
2737 return fail_result;
2738 if (response.GetChar() == ',') {
2739 int result_errno = response.GetS32(-2);
2740 if (result_errno != -2)
2741 error.SetError(result_errno, eErrorTypePOSIX);
2742 else
2743 error.SetError(-1, eErrorTypeGeneric);
2744 } else
2745 error.Clear();
2746 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002747}
2748lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2750 uint32_t flags, mode_t mode,
2751 Error &error) {
2752 std::string path(file_spec.GetPath(false));
2753 lldb_private::StreamString stream;
2754 stream.PutCString("vFile:open:");
2755 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002756 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 stream.PutCStringAsRawHex8(path.c_str());
2758 stream.PutChar(',');
2759 stream.PutHex32(flags);
2760 stream.PutChar(',');
2761 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002763 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 PacketResult::Success) {
2765 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2766 }
2767 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002768}
2769
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, Error &error) {
2771 lldb_private::StreamString stream;
2772 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002774 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002775 PacketResult::Success) {
2776 return ParseHostIOPacketResponse(response, -1, error) == 0;
2777 }
2778 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002779}
2780
2781// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2783 const lldb_private::FileSpec &file_spec) {
2784 std::string path(file_spec.GetPath(false));
2785 lldb_private::StreamString stream;
2786 stream.PutCString("vFile:size:");
2787 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002788 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002789 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 PacketResult::Success) {
2791 if (response.GetChar() != 'F')
2792 return UINT64_MAX;
2793 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2794 return retcode;
2795 }
2796 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002797}
2798
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799Error GDBRemoteCommunicationClient::GetFilePermissions(
2800 const FileSpec &file_spec, uint32_t &file_permissions) {
2801 std::string path{file_spec.GetPath(false)};
2802 Error error;
2803 lldb_private::StreamString stream;
2804 stream.PutCString("vFile:mode:");
2805 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002807 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808 PacketResult::Success) {
2809 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002810 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002811 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 } else {
2813 const uint32_t mode = response.GetS32(-1);
2814 if (static_cast<int32_t>(mode) == -1) {
2815 if (response.GetChar() == ',') {
2816 int response_errno = response.GetS32(-1);
2817 if (response_errno > 0)
2818 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2819 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002820 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 } else
2822 error.SetErrorToGenericError();
2823 } else {
2824 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2825 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002826 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002827 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002828 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002829 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 }
2831 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002832}
2833
Kate Stoneb9c1b512016-09-06 20:57:50 +00002834uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2835 uint64_t offset, void *dst,
2836 uint64_t dst_len,
2837 Error &error) {
2838 lldb_private::StreamString stream;
2839 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2840 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002842 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 PacketResult::Success) {
2844 if (response.GetChar() != 'F')
2845 return 0;
2846 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2847 if (retcode == UINT32_MAX)
2848 return retcode;
2849 const char next = (response.Peek() ? *response.Peek() : 0);
2850 if (next == ',')
2851 return 0;
2852 if (next == ';') {
2853 response.GetChar(); // skip the semicolon
2854 std::string buffer;
2855 if (response.GetEscapedBinaryData(buffer)) {
2856 const uint64_t data_to_write =
2857 std::min<uint64_t>(dst_len, buffer.size());
2858 if (data_to_write > 0)
2859 memcpy(dst, &buffer[0], data_to_write);
2860 return data_to_write;
2861 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002862 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863 }
2864 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002865}
2866
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2868 uint64_t offset,
2869 const void *src,
2870 uint64_t src_len,
2871 Error &error) {
2872 lldb_private::StreamGDBRemote stream;
2873 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2874 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002876 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002877 PacketResult::Success) {
2878 if (response.GetChar() != 'F') {
2879 error.SetErrorStringWithFormat("write file failed");
2880 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002881 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002882 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2883 if (bytes_written == UINT64_MAX) {
2884 error.SetErrorToGenericError();
2885 if (response.GetChar() == ',') {
2886 int response_errno = response.GetS32(-1);
2887 if (response_errno > 0)
2888 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2889 }
2890 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002891 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002892 return bytes_written;
2893 } else {
2894 error.SetErrorString("failed to send vFile:pwrite packet");
2895 }
2896 return 0;
2897}
2898
2899Error GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2900 const FileSpec &dst) {
2901 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
2902 Error error;
2903 lldb_private::StreamGDBRemote stream;
2904 stream.PutCString("vFile:symlink:");
2905 // the unix symlink() command reverses its parameters where the dst if first,
2906 // so we follow suit here
2907 stream.PutCStringAsRawHex8(dst_path.c_str());
2908 stream.PutChar(',');
2909 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002911 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 PacketResult::Success) {
2913 if (response.GetChar() == 'F') {
2914 uint32_t result = response.GetU32(UINT32_MAX);
2915 if (result != 0) {
2916 error.SetErrorToGenericError();
2917 if (response.GetChar() == ',') {
2918 int response_errno = response.GetS32(-1);
2919 if (response_errno > 0)
2920 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2921 }
2922 }
2923 } else {
2924 // Should have returned with 'F<result>[,<errno>]'
2925 error.SetErrorStringWithFormat("symlink failed");
2926 }
2927 } else {
2928 error.SetErrorString("failed to send vFile:symlink packet");
2929 }
2930 return error;
2931}
2932
2933Error GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
2934 std::string path{file_spec.GetPath(false)};
2935 Error error;
2936 lldb_private::StreamGDBRemote stream;
2937 stream.PutCString("vFile:unlink:");
2938 // the unix symlink() command reverses its parameters where the dst if first,
2939 // so we follow suit here
2940 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002941 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002942 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002943 PacketResult::Success) {
2944 if (response.GetChar() == 'F') {
2945 uint32_t result = response.GetU32(UINT32_MAX);
2946 if (result != 0) {
2947 error.SetErrorToGenericError();
2948 if (response.GetChar() == ',') {
2949 int response_errno = response.GetS32(-1);
2950 if (response_errno > 0)
2951 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2952 }
2953 }
2954 } else {
2955 // Should have returned with 'F<result>[,<errno>]'
2956 error.SetErrorStringWithFormat("unlink failed");
2957 }
2958 } else {
2959 error.SetErrorString("failed to send vFile:unlink packet");
2960 }
2961 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002962}
2963
Daniel Maleae0f8f572013-08-26 23:57:52 +00002964// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002965bool GDBRemoteCommunicationClient::GetFileExists(
2966 const lldb_private::FileSpec &file_spec) {
2967 std::string path(file_spec.GetPath(false));
2968 lldb_private::StreamString stream;
2969 stream.PutCString("vFile:exists:");
2970 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002971 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002972 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 PacketResult::Success) {
2974 if (response.GetChar() != 'F')
2975 return false;
2976 if (response.GetChar() != ',')
2977 return false;
2978 bool retcode = (response.GetChar() != '0');
2979 return retcode;
2980 }
2981 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002982}
2983
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984bool GDBRemoteCommunicationClient::CalculateMD5(
2985 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
2986 std::string path(file_spec.GetPath(false));
2987 lldb_private::StreamString stream;
2988 stream.PutCString("vFile:MD5:");
2989 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002990 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002991 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 PacketResult::Success) {
2993 if (response.GetChar() != 'F')
2994 return false;
2995 if (response.GetChar() != ',')
2996 return false;
2997 if (response.Peek() && *response.Peek() == 'x')
2998 return false;
2999 low = response.GetHexMaxU64(false, UINT64_MAX);
3000 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003001 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002 }
3003 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003004}
3005
Kate Stoneb9c1b512016-09-06 20:57:50 +00003006bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3007 // Some targets have issues with g/G packets and we need to avoid using them
3008 if (m_avoid_g_packets == eLazyBoolCalculate) {
3009 if (process) {
3010 m_avoid_g_packets = eLazyBoolNo;
3011 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3012 if (arch.IsValid() &&
3013 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3014 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3015 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3016 m_avoid_g_packets = eLazyBoolYes;
3017 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3018 if (gdb_server_version != 0) {
3019 const char *gdb_server_name = GetGDBServerProgramName();
3020 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3021 if (gdb_server_version >= 310)
3022 m_avoid_g_packets = eLazyBoolNo;
3023 }
3024 }
3025 }
3026 }
3027 }
3028 return m_avoid_g_packets == eLazyBoolYes;
3029}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003030
Kate Stoneb9c1b512016-09-06 20:57:50 +00003031DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3032 uint32_t reg) {
3033 StreamString payload;
3034 payload.Printf("p%x", reg);
3035 StringExtractorGDBRemote response;
3036 if (SendThreadSpecificPacketAndWaitForResponse(
3037 tid, std::move(payload), response, false) != PacketResult::Success ||
3038 !response.IsNormalResponse())
3039 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003040
Kate Stoneb9c1b512016-09-06 20:57:50 +00003041 DataBufferSP buffer_sp(
3042 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3043 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3044 return buffer_sp;
3045}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003046
Kate Stoneb9c1b512016-09-06 20:57:50 +00003047DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3048 StreamString payload;
3049 payload.PutChar('g');
3050 StringExtractorGDBRemote response;
3051 if (SendThreadSpecificPacketAndWaitForResponse(
3052 tid, std::move(payload), response, false) != PacketResult::Success ||
3053 !response.IsNormalResponse())
3054 return nullptr;
3055
3056 DataBufferSP buffer_sp(
3057 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3058 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3059 return buffer_sp;
3060}
3061
3062bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3063 uint32_t reg_num,
3064 llvm::ArrayRef<uint8_t> data) {
3065 StreamString payload;
3066 payload.Printf("P%x=", reg_num);
3067 payload.PutBytesAsRawHex8(data.data(), data.size(),
3068 endian::InlHostByteOrder(),
3069 endian::InlHostByteOrder());
3070 StringExtractorGDBRemote response;
3071 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3072 response, false) ==
3073 PacketResult::Success &&
3074 response.IsOKResponse();
3075}
3076
3077bool GDBRemoteCommunicationClient::WriteAllRegisters(
3078 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3079 StreamString payload;
3080 payload.PutChar('G');
3081 payload.PutBytesAsRawHex8(data.data(), data.size(),
3082 endian::InlHostByteOrder(),
3083 endian::InlHostByteOrder());
3084 StringExtractorGDBRemote response;
3085 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3086 response, false) ==
3087 PacketResult::Success &&
3088 response.IsOKResponse();
3089}
3090
3091bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3092 uint32_t &save_id) {
3093 save_id = 0; // Set to invalid save ID
3094 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003095 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096
3097 m_supports_QSaveRegisterState = eLazyBoolYes;
3098 StreamString payload;
3099 payload.PutCString("QSaveRegisterState");
3100 StringExtractorGDBRemote response;
3101 if (SendThreadSpecificPacketAndWaitForResponse(
3102 tid, std::move(payload), response, false) != PacketResult::Success)
3103 return false;
3104
3105 if (response.IsUnsupportedResponse())
3106 m_supports_QSaveRegisterState = eLazyBoolNo;
3107
3108 const uint32_t response_save_id = response.GetU32(0);
3109 if (response_save_id == 0)
3110 return false;
3111
3112 save_id = response_save_id;
3113 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003114}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003115
Kate Stoneb9c1b512016-09-06 20:57:50 +00003116bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3117 uint32_t save_id) {
3118 // We use the "m_supports_QSaveRegisterState" variable here because the
3119 // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3120 // in
3121 // order to be useful
3122 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3123 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003124
Kate Stoneb9c1b512016-09-06 20:57:50 +00003125 StreamString payload;
3126 payload.Printf("QRestoreRegisterState:%u", save_id);
3127 StringExtractorGDBRemote response;
3128 if (SendThreadSpecificPacketAndWaitForResponse(
3129 tid, std::move(payload), response, false) != PacketResult::Success)
3130 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003131
Kate Stoneb9c1b512016-09-06 20:57:50 +00003132 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003133 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134
3135 if (response.IsUnsupportedResponse())
3136 m_supports_QSaveRegisterState = eLazyBoolNo;
3137 return false;
3138}
3139
3140bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3141 if (!GetSyncThreadStateSupported())
3142 return false;
3143
3144 StreamString packet;
3145 StringExtractorGDBRemote response;
3146 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3147 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3148 GDBRemoteCommunication::PacketResult::Success &&
3149 response.IsOKResponse();
3150}
3151
3152bool GDBRemoteCommunicationClient::GetModuleInfo(
3153 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3154 ModuleSpec &module_spec) {
3155 if (!m_supports_qModuleInfo)
3156 return false;
3157
3158 std::string module_path = module_file_spec.GetPath(false);
3159 if (module_path.empty())
3160 return false;
3161
3162 StreamString packet;
3163 packet.PutCString("qModuleInfo:");
3164 packet.PutCStringAsRawHex8(module_path.c_str());
3165 packet.PutCString(";");
3166 const auto &triple = arch_spec.GetTriple().getTriple();
3167 packet.PutCStringAsRawHex8(triple.c_str());
3168
3169 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003170 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3171 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003172 return false;
3173
3174 if (response.IsErrorResponse())
3175 return false;
3176
3177 if (response.IsUnsupportedResponse()) {
3178 m_supports_qModuleInfo = false;
3179 return false;
3180 }
3181
3182 llvm::StringRef name;
3183 llvm::StringRef value;
3184
3185 module_spec.Clear();
3186 module_spec.GetFileSpec() = module_file_spec;
3187
3188 while (response.GetNameColonValue(name, value)) {
3189 if (name == "uuid" || name == "md5") {
3190 StringExtractor extractor(value);
3191 std::string uuid;
3192 extractor.GetHexByteString(uuid);
3193 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3194 } else if (name == "triple") {
3195 StringExtractor extractor(value);
3196 std::string triple;
3197 extractor.GetHexByteString(triple);
3198 module_spec.GetArchitecture().SetTriple(triple.c_str());
3199 } else if (name == "file_offset") {
3200 uint64_t ival = 0;
3201 if (!value.getAsInteger(16, ival))
3202 module_spec.SetObjectOffset(ival);
3203 } else if (name == "file_size") {
3204 uint64_t ival = 0;
3205 if (!value.getAsInteger(16, ival))
3206 module_spec.SetObjectSize(ival);
3207 } else if (name == "file_path") {
3208 StringExtractor extractor(value);
3209 std::string path;
3210 extractor.GetHexByteString(path);
Zachary Turner8c6b5462017-03-06 23:42:44 +00003211 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003212 }
3213 }
3214
3215 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003216}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003217
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003218static llvm::Optional<ModuleSpec>
3219ParseModuleSpec(StructuredData::Dictionary *dict) {
3220 ModuleSpec result;
3221 if (!dict)
3222 return llvm::None;
3223
3224 std::string string;
3225 uint64_t integer;
3226
3227 if (!dict->GetValueForKeyAsString("uuid", string))
3228 return llvm::None;
3229 result.GetUUID().SetFromCString(string.c_str(), string.size());
3230
3231 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3232 return llvm::None;
3233 result.SetObjectOffset(integer);
3234
3235 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3236 return llvm::None;
3237 result.SetObjectSize(integer);
3238
3239 if (!dict->GetValueForKeyAsString("triple", string))
3240 return llvm::None;
3241 result.GetArchitecture().SetTriple(string.c_str());
3242
3243 if (!dict->GetValueForKeyAsString("file_path", string))
3244 return llvm::None;
Zachary Turner8c6b5462017-03-06 23:42:44 +00003245 result.GetFileSpec() =
3246 FileSpec(string, false, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003247
3248 return result;
3249}
3250
3251llvm::Optional<std::vector<ModuleSpec>>
3252GDBRemoteCommunicationClient::GetModulesInfo(
3253 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3254 if (!m_supports_jModulesInfo)
3255 return llvm::None;
3256
3257 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3258 for (const FileSpec &module_file_spec : module_file_specs) {
3259 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3260 module_array_sp->AppendObject(module_sp);
3261 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003262 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003263 module_sp->SetObject("triple",
3264 std::make_shared<JSONString>(triple.getTriple()));
3265 }
3266 StreamString unescaped_payload;
3267 unescaped_payload.PutCString("jModulesInfo:");
3268 module_array_sp->Write(unescaped_payload);
3269 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003270 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003271 unescaped_payload.GetSize());
3272
3273 StringExtractorGDBRemote response;
3274 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3275 PacketResult::Success ||
3276 response.IsErrorResponse())
3277 return llvm::None;
3278
3279 if (response.IsUnsupportedResponse()) {
3280 m_supports_jModulesInfo = false;
3281 return llvm::None;
3282 }
3283
3284 StructuredData::ObjectSP response_object_sp =
3285 StructuredData::ParseJSON(response.GetStringRef());
3286 if (!response_object_sp)
3287 return llvm::None;
3288
3289 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3290 if (!response_array)
3291 return llvm::None;
3292
3293 std::vector<ModuleSpec> result;
3294 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3295 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3296 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3297 result.push_back(*module_spec);
3298 }
3299
3300 return result;
3301}
3302
Colin Rileyc3c95b22015-04-16 15:51:33 +00003303// query the target remote for extended information using the qXfer packet
3304//
3305// example: object='features', annex='target.xml', out=<xml output>
3306// return: 'true' on success
3307// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003308bool GDBRemoteCommunicationClient::ReadExtFeature(
3309 const lldb_private::ConstString object,
3310 const lldb_private::ConstString annex, std::string &out,
3311 lldb_private::Error &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003312
Kate Stoneb9c1b512016-09-06 20:57:50 +00003313 std::stringstream output;
3314 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003315
Kate Stoneb9c1b512016-09-06 20:57:50 +00003316 uint64_t size = GetRemoteMaxPacketSize();
3317 if (size == 0)
3318 size = 0x1000;
3319 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3320 int offset = 0;
3321 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003322
Kate Stoneb9c1b512016-09-06 20:57:50 +00003323 // loop until all data has been read
3324 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003325
Kate Stoneb9c1b512016-09-06 20:57:50 +00003326 // send query extended feature packet
3327 std::stringstream packet;
3328 packet << "qXfer:" << object.AsCString("")
3329 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3330 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003331
Kate Stoneb9c1b512016-09-06 20:57:50 +00003332 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003333 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003334
Kate Stoneb9c1b512016-09-06 20:57:50 +00003335 if (res != GDBRemoteCommunication::PacketResult::Success) {
3336 err.SetErrorString("Error sending $qXfer packet");
3337 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003338 }
3339
Kate Stoneb9c1b512016-09-06 20:57:50 +00003340 const std::string &str = chunk.GetStringRef();
3341 if (str.length() == 0) {
3342 // should have some data in chunk
3343 err.SetErrorString("Empty response from $qXfer packet");
3344 return false;
3345 }
3346
3347 // check packet code
3348 switch (str[0]) {
3349 // last chunk
3350 case ('l'):
3351 active = false;
3352 LLVM_FALLTHROUGH;
3353
3354 // more chunks
3355 case ('m'):
3356 if (str.length() > 1)
3357 output << &str[1];
3358 offset += size;
3359 break;
3360
3361 // unknown chunk
3362 default:
3363 err.SetErrorString("Invalid continuation code from $qXfer packet");
3364 return false;
3365 }
3366 }
3367
3368 out = output.str();
3369 err.Success();
3370 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003371}
Greg Clayton0b90be12015-06-23 21:27:50 +00003372
3373// Notify the target that gdb is prepared to serve symbol lookup requests.
3374// packet: "qSymbol::"
3375// reply:
3376// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003377// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3378// encoded).
3379// LLDB may provide the value by sending another qSymbol
3380// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003381// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003382//
3383// Three examples:
3384//
3385// lldb sends: qSymbol::
3386// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003387// Remote gdb stub does not need to know the addresses of any symbols, lldb
3388// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003389// need to ask again in this session.
3390//
3391// lldb sends: qSymbol::
3392// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3393// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3394// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003395// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3396// not know
3397// the address at this time. lldb needs to send qSymbol:: again when it has
3398// more
Jason Molenda50018d32016-01-13 04:08:10 +00003399// solibs loaded.
3400//
3401// lldb sends: qSymbol::
3402// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3403// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3404// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003405// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3406// that it
3407// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3408// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003409// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003410
Kate Stoneb9c1b512016-09-06 20:57:50 +00003411void GDBRemoteCommunicationClient::ServeSymbolLookups(
3412 lldb_private::Process *process) {
3413 // Set to true once we've resolved a symbol to an address for the remote stub.
3414 // If we get an 'OK' response after this, the remote stub doesn't need any
3415 // more
3416 // symbols and we can stop asking.
3417 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003418
Kate Stoneb9c1b512016-09-06 20:57:50 +00003419 // Is this the initial qSymbol:: packet?
3420 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003421
Kate Stoneb9c1b512016-09-06 20:57:50 +00003422 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3423 Lock lock(*this, false);
3424 if (lock) {
3425 StreamString packet;
3426 packet.PutCString("qSymbol::");
3427 StringExtractorGDBRemote response;
3428 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3429 PacketResult::Success) {
3430 if (response.IsOKResponse()) {
3431 if (symbol_response_provided || first_qsymbol_query) {
3432 m_qSymbol_requests_done = true;
3433 }
3434
3435 // We are done serving symbols requests
3436 return;
3437 }
3438 first_qsymbol_query = false;
3439
3440 if (response.IsUnsupportedResponse()) {
3441 // qSymbol is not supported by the current GDB server we are connected
3442 // to
3443 m_supports_qSymbol = false;
3444 return;
3445 } else {
3446 llvm::StringRef response_str(response.GetStringRef());
3447 if (response_str.startswith("qSymbol:")) {
3448 response.SetFilePos(strlen("qSymbol:"));
3449 std::string symbol_name;
3450 if (response.GetHexByteString(symbol_name)) {
3451 if (symbol_name.empty())
3452 return;
3453
3454 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3455 lldb_private::SymbolContextList sc_list;
3456 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3457 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3458 const size_t num_scs = sc_list.GetSize();
3459 for (size_t sc_idx = 0;
3460 sc_idx < num_scs &&
3461 symbol_load_addr == LLDB_INVALID_ADDRESS;
3462 ++sc_idx) {
3463 SymbolContext sc;
3464 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3465 if (sc.symbol) {
3466 switch (sc.symbol->GetType()) {
3467 case eSymbolTypeInvalid:
3468 case eSymbolTypeAbsolute:
3469 case eSymbolTypeUndefined:
3470 case eSymbolTypeSourceFile:
3471 case eSymbolTypeHeaderFile:
3472 case eSymbolTypeObjectFile:
3473 case eSymbolTypeCommonBlock:
3474 case eSymbolTypeBlock:
3475 case eSymbolTypeLocal:
3476 case eSymbolTypeParam:
3477 case eSymbolTypeVariable:
3478 case eSymbolTypeVariableType:
3479 case eSymbolTypeLineEntry:
3480 case eSymbolTypeLineHeader:
3481 case eSymbolTypeScopeBegin:
3482 case eSymbolTypeScopeEnd:
3483 case eSymbolTypeAdditional:
3484 case eSymbolTypeCompiler:
3485 case eSymbolTypeInstrumentation:
3486 case eSymbolTypeTrampoline:
3487 break;
3488
3489 case eSymbolTypeCode:
3490 case eSymbolTypeResolver:
3491 case eSymbolTypeData:
3492 case eSymbolTypeRuntime:
3493 case eSymbolTypeException:
3494 case eSymbolTypeObjCClass:
3495 case eSymbolTypeObjCMetaClass:
3496 case eSymbolTypeObjCIVar:
3497 case eSymbolTypeReExported:
3498 symbol_load_addr =
3499 sc.symbol->GetLoadAddress(&process->GetTarget());
3500 break;
3501 }
Jason Molenda50018d32016-01-13 04:08:10 +00003502 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003503 }
Greg Clayton42b01482015-08-11 22:07:46 +00003504 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003505 }
3506 // This is the normal path where our symbol lookup was successful
3507 // and we want
3508 // to send a packet with the new symbol value and see if another
3509 // lookup needs to be
3510 // done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003511
Kate Stoneb9c1b512016-09-06 20:57:50 +00003512 // Change "packet" to contain the requested symbol value and name
3513 packet.Clear();
3514 packet.PutCString("qSymbol:");
3515 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3516 packet.Printf("%" PRIx64, symbol_load_addr);
3517 symbol_response_provided = true;
3518 } else {
3519 symbol_response_provided = false;
3520 }
3521 packet.PutCString(":");
3522 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3523 continue; // go back to the while loop and send "packet" and wait
3524 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003525 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003526 }
3527 }
3528 }
3529 // If we make it here, the symbol request packet response wasn't valid or
3530 // our symbol lookup failed so we must abort
3531 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003532
Kate Stoneb9c1b512016-09-06 20:57:50 +00003533 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3534 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3535 log->Printf(
3536 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3537 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003538 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003539 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003540}
3541
Kate Stoneb9c1b512016-09-06 20:57:50 +00003542StructuredData::Array *
3543GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3544 if (!m_supported_async_json_packets_is_valid) {
3545 // Query the server for the array of supported asynchronous JSON
3546 // packets.
3547 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003548
Kate Stoneb9c1b512016-09-06 20:57:50 +00003549 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003550
Kate Stoneb9c1b512016-09-06 20:57:50 +00003551 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003552 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003553 const bool send_async = false;
3554 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3555 send_async) == PacketResult::Success) {
3556 m_supported_async_json_packets_sp =
3557 StructuredData::ParseJSON(response.GetStringRef());
3558 if (m_supported_async_json_packets_sp &&
3559 !m_supported_async_json_packets_sp->GetAsArray()) {
3560 // We were returned something other than a JSON array. This
3561 // is invalid. Clear it out.
3562 if (log)
3563 log->Printf("GDBRemoteCommunicationClient::%s(): "
3564 "QSupportedAsyncJSONPackets returned invalid "
3565 "result: %s",
3566 __FUNCTION__, response.GetStringRef().c_str());
3567 m_supported_async_json_packets_sp.reset();
3568 }
3569 } else {
3570 if (log)
3571 log->Printf("GDBRemoteCommunicationClient::%s(): "
3572 "QSupportedAsyncJSONPackets unsupported",
3573 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003574 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003575
3576 if (log && m_supported_async_json_packets_sp) {
3577 StreamString stream;
3578 m_supported_async_json_packets_sp->Dump(stream);
3579 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3580 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003581 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003582 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003583 }
3584
3585 return m_supported_async_json_packets_sp
3586 ? m_supported_async_json_packets_sp->GetAsArray()
3587 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003588}
3589
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003590Error GDBRemoteCommunicationClient::SendSignalsToIgnore(
3591 llvm::ArrayRef<int32_t> signals) {
3592 // Format packet:
3593 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3594 auto range = llvm::make_range(signals.begin(), signals.end());
3595 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3596
3597 StringExtractorGDBRemote response;
3598 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3599
3600 if (send_status != GDBRemoteCommunication::PacketResult::Success)
3601 return Error("Sending QPassSignals packet failed");
3602
3603 if (response.IsOKResponse()) {
3604 return Error();
3605 } else {
3606 return Error("Unknown error happened during sending QPassSignals packet.");
3607 }
3608}
3609
Kate Stoneb9c1b512016-09-06 20:57:50 +00003610Error GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3611 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
3612 Error error;
3613
3614 if (type_name.GetLength() == 0) {
3615 error.SetErrorString("invalid type_name argument");
3616 return error;
3617 }
3618
3619 // Build command: Configure{type_name}: serialized config
3620 // data.
3621 StreamGDBRemote stream;
3622 stream.PutCString("QConfigure");
3623 stream.PutCString(type_name.AsCString());
3624 stream.PutChar(':');
3625 if (config_sp) {
3626 // Gather the plain-text version of the configuration data.
3627 StreamString unescaped_stream;
3628 config_sp->Dump(unescaped_stream);
3629 unescaped_stream.Flush();
3630
3631 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003632 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003633 unescaped_stream.GetSize());
3634 }
3635 stream.Flush();
3636
3637 // Send the packet.
3638 const bool send_async = false;
3639 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003640 auto result =
3641 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003642 if (result == PacketResult::Success) {
3643 // We failed if the config result comes back other than OK.
3644 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3645 // Okay!
3646 error.Clear();
3647 } else {
3648 error.SetErrorStringWithFormat("configuring StructuredData feature "
3649 "%s failed with error %s",
3650 type_name.AsCString(),
3651 response.GetStringRef().c_str());
3652 }
3653 } else {
3654 // Can we get more data here on the failure?
3655 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3656 "failed when sending packet: "
3657 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003658 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003659 }
3660 return error;
3661}
3662
3663void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3664 GDBRemoteClientBase::OnRunPacketSent(first);
3665 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003666}