blob: 550ec0ea499a5a6365ba093f209467f6e23f2411 [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
Zachary Turner97206d52017-05-12 04:51:55 +0000116bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 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
Zachary Turner97206d52017-05-12 04:51:55 +00001397Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1398 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399
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
Zachary Turner97206d52017-05-12 04:51:55 +00001437Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001439 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 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
Zachary Turner97206d52017-05-12 04:51:55 +00001532Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1533 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001534
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
Zachary Turner97206d52017-05-12 04:51:55 +00001571lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001572 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001573 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001574 if (error.Success())
1575 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1576 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001577}
1578
Zachary Turner97206d52017-05-12 04:51:55 +00001579lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001580GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1581 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001582 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583 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
Zachary Turner97206d52017-05-12 04:51:55 +00002542 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543 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
Zachary Turner97206d52017-05-12 04:51:55 +00002638lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002639 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')
Zachary Turner97206d52017-05-12 04:51:55 +00002664 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002665 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002666 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002667 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2668 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002669 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002670 else if (status_ptr)
2671 *status_ptr = exitcode;
2672 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002673 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002674 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2675 if (signo_ptr)
2676 *signo_ptr = signo;
2677 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002678 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002679 std::string output;
2680 response.GetEscapedBinaryData(output);
2681 if (command_output)
2682 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002683 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002684 }
Zachary Turner97206d52017-05-12 04:51:55 +00002685 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002686}
2687
Zachary Turner97206d52017-05-12 04:51:55 +00002688Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2689 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690 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 Turner97206d52017-05-12 04:51:55 +00002701 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702
2703 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002704 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002705
Zachary Turner97206d52017-05-12 04:51:55 +00002706 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002707}
2708
Zachary Turner97206d52017-05-12 04:51:55 +00002709Status
2710GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2711 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712 std::string path{file_spec.GetPath(false)};
2713 lldb_private::StreamString stream;
2714 stream.PutCString("qPlatform_chmod:");
2715 stream.PutHex32(file_permissions);
2716 stream.PutChar(',');
2717 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002718 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002719 StringExtractorGDBRemote response;
2720
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002721 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002723 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002724
2725 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002726 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727
Zachary Turner97206d52017-05-12 04:51:55 +00002728 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002729}
2730
2731static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002732 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002733 response.SetFilePos(0);
2734 if (response.GetChar() != 'F')
2735 return fail_result;
2736 int32_t result = response.GetS32(-2);
2737 if (result == -2)
2738 return fail_result;
2739 if (response.GetChar() == ',') {
2740 int result_errno = response.GetS32(-2);
2741 if (result_errno != -2)
2742 error.SetError(result_errno, eErrorTypePOSIX);
2743 else
2744 error.SetError(-1, eErrorTypeGeneric);
2745 } else
2746 error.Clear();
2747 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002748}
2749lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002750GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2751 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002752 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002753 std::string path(file_spec.GetPath(false));
2754 lldb_private::StreamString stream;
2755 stream.PutCString("vFile:open:");
2756 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002757 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002758 stream.PutCStringAsRawHex8(path.c_str());
2759 stream.PutChar(',');
2760 stream.PutHex32(flags);
2761 stream.PutChar(',');
2762 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002763 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002764 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765 PacketResult::Success) {
2766 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2767 }
2768 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002769}
2770
Zachary Turner97206d52017-05-12 04:51:55 +00002771bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2772 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 lldb_private::StreamString stream;
2774 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002775 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002776 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 PacketResult::Success) {
2778 return ParseHostIOPacketResponse(response, -1, error) == 0;
2779 }
2780 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002781}
2782
2783// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002784lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2785 const lldb_private::FileSpec &file_spec) {
2786 std::string path(file_spec.GetPath(false));
2787 lldb_private::StreamString stream;
2788 stream.PutCString("vFile:size:");
2789 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002791 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 PacketResult::Success) {
2793 if (response.GetChar() != 'F')
2794 return UINT64_MAX;
2795 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2796 return retcode;
2797 }
2798 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002799}
2800
Zachary Turner97206d52017-05-12 04:51:55 +00002801Status
2802GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2803 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002805 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 lldb_private::StreamString stream;
2807 stream.PutCString("vFile:mode:");
2808 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002810 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811 PacketResult::Success) {
2812 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002813 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002814 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815 } else {
2816 const uint32_t mode = response.GetS32(-1);
2817 if (static_cast<int32_t>(mode) == -1) {
2818 if (response.GetChar() == ',') {
2819 int response_errno = response.GetS32(-1);
2820 if (response_errno > 0)
2821 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2822 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002823 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002824 } else
2825 error.SetErrorToGenericError();
2826 } else {
2827 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2828 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002829 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002831 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002832 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833 }
2834 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002835}
2836
Kate Stoneb9c1b512016-09-06 20:57:50 +00002837uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2838 uint64_t offset, void *dst,
2839 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002840 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 lldb_private::StreamString stream;
2842 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2843 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002844 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002845 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 PacketResult::Success) {
2847 if (response.GetChar() != 'F')
2848 return 0;
2849 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2850 if (retcode == UINT32_MAX)
2851 return retcode;
2852 const char next = (response.Peek() ? *response.Peek() : 0);
2853 if (next == ',')
2854 return 0;
2855 if (next == ';') {
2856 response.GetChar(); // skip the semicolon
2857 std::string buffer;
2858 if (response.GetEscapedBinaryData(buffer)) {
2859 const uint64_t data_to_write =
2860 std::min<uint64_t>(dst_len, buffer.size());
2861 if (data_to_write > 0)
2862 memcpy(dst, &buffer[0], data_to_write);
2863 return data_to_write;
2864 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002865 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 }
2867 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002868}
2869
Kate Stoneb9c1b512016-09-06 20:57:50 +00002870uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2871 uint64_t offset,
2872 const void *src,
2873 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002874 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875 lldb_private::StreamGDBRemote stream;
2876 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2877 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002879 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002880 PacketResult::Success) {
2881 if (response.GetChar() != 'F') {
2882 error.SetErrorStringWithFormat("write file failed");
2883 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002884 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002885 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2886 if (bytes_written == UINT64_MAX) {
2887 error.SetErrorToGenericError();
2888 if (response.GetChar() == ',') {
2889 int response_errno = response.GetS32(-1);
2890 if (response_errno > 0)
2891 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2892 }
2893 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002894 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 return bytes_written;
2896 } else {
2897 error.SetErrorString("failed to send vFile:pwrite packet");
2898 }
2899 return 0;
2900}
2901
Zachary Turner97206d52017-05-12 04:51:55 +00002902Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2903 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002904 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002905 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002906 lldb_private::StreamGDBRemote stream;
2907 stream.PutCString("vFile:symlink:");
2908 // the unix symlink() command reverses its parameters where the dst if first,
2909 // so we follow suit here
2910 stream.PutCStringAsRawHex8(dst_path.c_str());
2911 stream.PutChar(',');
2912 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002914 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002915 PacketResult::Success) {
2916 if (response.GetChar() == 'F') {
2917 uint32_t result = response.GetU32(UINT32_MAX);
2918 if (result != 0) {
2919 error.SetErrorToGenericError();
2920 if (response.GetChar() == ',') {
2921 int response_errno = response.GetS32(-1);
2922 if (response_errno > 0)
2923 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2924 }
2925 }
2926 } else {
2927 // Should have returned with 'F<result>[,<errno>]'
2928 error.SetErrorStringWithFormat("symlink failed");
2929 }
2930 } else {
2931 error.SetErrorString("failed to send vFile:symlink packet");
2932 }
2933 return error;
2934}
2935
Zachary Turner97206d52017-05-12 04:51:55 +00002936Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002937 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002938 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939 lldb_private::StreamGDBRemote stream;
2940 stream.PutCString("vFile:unlink:");
2941 // the unix symlink() command reverses its parameters where the dst if first,
2942 // so we follow suit here
2943 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002944 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002945 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002946 PacketResult::Success) {
2947 if (response.GetChar() == 'F') {
2948 uint32_t result = response.GetU32(UINT32_MAX);
2949 if (result != 0) {
2950 error.SetErrorToGenericError();
2951 if (response.GetChar() == ',') {
2952 int response_errno = response.GetS32(-1);
2953 if (response_errno > 0)
2954 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2955 }
2956 }
2957 } else {
2958 // Should have returned with 'F<result>[,<errno>]'
2959 error.SetErrorStringWithFormat("unlink failed");
2960 }
2961 } else {
2962 error.SetErrorString("failed to send vFile:unlink packet");
2963 }
2964 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002965}
2966
Daniel Maleae0f8f572013-08-26 23:57:52 +00002967// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002968bool GDBRemoteCommunicationClient::GetFileExists(
2969 const lldb_private::FileSpec &file_spec) {
2970 std::string path(file_spec.GetPath(false));
2971 lldb_private::StreamString stream;
2972 stream.PutCString("vFile:exists:");
2973 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002974 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002975 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002976 PacketResult::Success) {
2977 if (response.GetChar() != 'F')
2978 return false;
2979 if (response.GetChar() != ',')
2980 return false;
2981 bool retcode = (response.GetChar() != '0');
2982 return retcode;
2983 }
2984 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002985}
2986
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987bool GDBRemoteCommunicationClient::CalculateMD5(
2988 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
2989 std::string path(file_spec.GetPath(false));
2990 lldb_private::StreamString stream;
2991 stream.PutCString("vFile:MD5:");
2992 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002993 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002994 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 PacketResult::Success) {
2996 if (response.GetChar() != 'F')
2997 return false;
2998 if (response.GetChar() != ',')
2999 return false;
3000 if (response.Peek() && *response.Peek() == 'x')
3001 return false;
3002 low = response.GetHexMaxU64(false, UINT64_MAX);
3003 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003004 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005 }
3006 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003007}
3008
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3010 // Some targets have issues with g/G packets and we need to avoid using them
3011 if (m_avoid_g_packets == eLazyBoolCalculate) {
3012 if (process) {
3013 m_avoid_g_packets = eLazyBoolNo;
3014 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3015 if (arch.IsValid() &&
3016 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3017 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3018 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3019 m_avoid_g_packets = eLazyBoolYes;
3020 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3021 if (gdb_server_version != 0) {
3022 const char *gdb_server_name = GetGDBServerProgramName();
3023 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3024 if (gdb_server_version >= 310)
3025 m_avoid_g_packets = eLazyBoolNo;
3026 }
3027 }
3028 }
3029 }
3030 }
3031 return m_avoid_g_packets == eLazyBoolYes;
3032}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003033
Kate Stoneb9c1b512016-09-06 20:57:50 +00003034DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3035 uint32_t reg) {
3036 StreamString payload;
3037 payload.Printf("p%x", reg);
3038 StringExtractorGDBRemote response;
3039 if (SendThreadSpecificPacketAndWaitForResponse(
3040 tid, std::move(payload), response, false) != PacketResult::Success ||
3041 !response.IsNormalResponse())
3042 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003043
Kate Stoneb9c1b512016-09-06 20:57:50 +00003044 DataBufferSP buffer_sp(
3045 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3046 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3047 return buffer_sp;
3048}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003049
Kate Stoneb9c1b512016-09-06 20:57:50 +00003050DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3051 StreamString payload;
3052 payload.PutChar('g');
3053 StringExtractorGDBRemote response;
3054 if (SendThreadSpecificPacketAndWaitForResponse(
3055 tid, std::move(payload), response, false) != PacketResult::Success ||
3056 !response.IsNormalResponse())
3057 return nullptr;
3058
3059 DataBufferSP buffer_sp(
3060 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3061 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3062 return buffer_sp;
3063}
3064
3065bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3066 uint32_t reg_num,
3067 llvm::ArrayRef<uint8_t> data) {
3068 StreamString payload;
3069 payload.Printf("P%x=", reg_num);
3070 payload.PutBytesAsRawHex8(data.data(), data.size(),
3071 endian::InlHostByteOrder(),
3072 endian::InlHostByteOrder());
3073 StringExtractorGDBRemote response;
3074 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3075 response, false) ==
3076 PacketResult::Success &&
3077 response.IsOKResponse();
3078}
3079
3080bool GDBRemoteCommunicationClient::WriteAllRegisters(
3081 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3082 StreamString payload;
3083 payload.PutChar('G');
3084 payload.PutBytesAsRawHex8(data.data(), data.size(),
3085 endian::InlHostByteOrder(),
3086 endian::InlHostByteOrder());
3087 StringExtractorGDBRemote response;
3088 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3089 response, false) ==
3090 PacketResult::Success &&
3091 response.IsOKResponse();
3092}
3093
3094bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3095 uint32_t &save_id) {
3096 save_id = 0; // Set to invalid save ID
3097 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003098 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099
3100 m_supports_QSaveRegisterState = eLazyBoolYes;
3101 StreamString payload;
3102 payload.PutCString("QSaveRegisterState");
3103 StringExtractorGDBRemote response;
3104 if (SendThreadSpecificPacketAndWaitForResponse(
3105 tid, std::move(payload), response, false) != PacketResult::Success)
3106 return false;
3107
3108 if (response.IsUnsupportedResponse())
3109 m_supports_QSaveRegisterState = eLazyBoolNo;
3110
3111 const uint32_t response_save_id = response.GetU32(0);
3112 if (response_save_id == 0)
3113 return false;
3114
3115 save_id = response_save_id;
3116 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003117}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003118
Kate Stoneb9c1b512016-09-06 20:57:50 +00003119bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3120 uint32_t save_id) {
3121 // We use the "m_supports_QSaveRegisterState" variable here because the
3122 // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3123 // in
3124 // order to be useful
3125 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3126 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003127
Kate Stoneb9c1b512016-09-06 20:57:50 +00003128 StreamString payload;
3129 payload.Printf("QRestoreRegisterState:%u", save_id);
3130 StringExtractorGDBRemote response;
3131 if (SendThreadSpecificPacketAndWaitForResponse(
3132 tid, std::move(payload), response, false) != PacketResult::Success)
3133 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003134
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003136 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003137
3138 if (response.IsUnsupportedResponse())
3139 m_supports_QSaveRegisterState = eLazyBoolNo;
3140 return false;
3141}
3142
3143bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3144 if (!GetSyncThreadStateSupported())
3145 return false;
3146
3147 StreamString packet;
3148 StringExtractorGDBRemote response;
3149 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3150 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3151 GDBRemoteCommunication::PacketResult::Success &&
3152 response.IsOKResponse();
3153}
3154
3155bool GDBRemoteCommunicationClient::GetModuleInfo(
3156 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3157 ModuleSpec &module_spec) {
3158 if (!m_supports_qModuleInfo)
3159 return false;
3160
3161 std::string module_path = module_file_spec.GetPath(false);
3162 if (module_path.empty())
3163 return false;
3164
3165 StreamString packet;
3166 packet.PutCString("qModuleInfo:");
3167 packet.PutCStringAsRawHex8(module_path.c_str());
3168 packet.PutCString(";");
3169 const auto &triple = arch_spec.GetTriple().getTriple();
3170 packet.PutCStringAsRawHex8(triple.c_str());
3171
3172 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003173 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3174 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175 return false;
3176
3177 if (response.IsErrorResponse())
3178 return false;
3179
3180 if (response.IsUnsupportedResponse()) {
3181 m_supports_qModuleInfo = false;
3182 return false;
3183 }
3184
3185 llvm::StringRef name;
3186 llvm::StringRef value;
3187
3188 module_spec.Clear();
3189 module_spec.GetFileSpec() = module_file_spec;
3190
3191 while (response.GetNameColonValue(name, value)) {
3192 if (name == "uuid" || name == "md5") {
3193 StringExtractor extractor(value);
3194 std::string uuid;
3195 extractor.GetHexByteString(uuid);
3196 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3197 } else if (name == "triple") {
3198 StringExtractor extractor(value);
3199 std::string triple;
3200 extractor.GetHexByteString(triple);
3201 module_spec.GetArchitecture().SetTriple(triple.c_str());
3202 } else if (name == "file_offset") {
3203 uint64_t ival = 0;
3204 if (!value.getAsInteger(16, ival))
3205 module_spec.SetObjectOffset(ival);
3206 } else if (name == "file_size") {
3207 uint64_t ival = 0;
3208 if (!value.getAsInteger(16, ival))
3209 module_spec.SetObjectSize(ival);
3210 } else if (name == "file_path") {
3211 StringExtractor extractor(value);
3212 std::string path;
3213 extractor.GetHexByteString(path);
Zachary Turner8c6b5462017-03-06 23:42:44 +00003214 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003215 }
3216 }
3217
3218 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003219}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003220
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003221static llvm::Optional<ModuleSpec>
3222ParseModuleSpec(StructuredData::Dictionary *dict) {
3223 ModuleSpec result;
3224 if (!dict)
3225 return llvm::None;
3226
Zachary Turner28333212017-05-12 05:49:54 +00003227 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003228 uint64_t integer;
3229
3230 if (!dict->GetValueForKeyAsString("uuid", string))
3231 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003232 result.GetUUID().SetFromStringRef(string, string.size());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003233
3234 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3235 return llvm::None;
3236 result.SetObjectOffset(integer);
3237
3238 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3239 return llvm::None;
3240 result.SetObjectSize(integer);
3241
3242 if (!dict->GetValueForKeyAsString("triple", string))
3243 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003244 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003245
3246 if (!dict->GetValueForKeyAsString("file_path", string))
3247 return llvm::None;
Zachary Turner8c6b5462017-03-06 23:42:44 +00003248 result.GetFileSpec() =
3249 FileSpec(string, false, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003250
3251 return result;
3252}
3253
3254llvm::Optional<std::vector<ModuleSpec>>
3255GDBRemoteCommunicationClient::GetModulesInfo(
3256 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3257 if (!m_supports_jModulesInfo)
3258 return llvm::None;
3259
3260 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3261 for (const FileSpec &module_file_spec : module_file_specs) {
3262 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3263 module_array_sp->AppendObject(module_sp);
3264 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003265 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003266 module_sp->SetObject("triple",
3267 std::make_shared<JSONString>(triple.getTriple()));
3268 }
3269 StreamString unescaped_payload;
3270 unescaped_payload.PutCString("jModulesInfo:");
3271 module_array_sp->Write(unescaped_payload);
3272 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003273 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003274 unescaped_payload.GetSize());
3275
Greg Clayton70a9f512017-04-14 17:10:04 +00003276 // Increase the timeout for jModulesInfo since this packet can take longer.
3277 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3278
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003279 StringExtractorGDBRemote response;
3280 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3281 PacketResult::Success ||
3282 response.IsErrorResponse())
3283 return llvm::None;
3284
3285 if (response.IsUnsupportedResponse()) {
3286 m_supports_jModulesInfo = false;
3287 return llvm::None;
3288 }
3289
3290 StructuredData::ObjectSP response_object_sp =
3291 StructuredData::ParseJSON(response.GetStringRef());
3292 if (!response_object_sp)
3293 return llvm::None;
3294
3295 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3296 if (!response_array)
3297 return llvm::None;
3298
3299 std::vector<ModuleSpec> result;
3300 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3301 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3302 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3303 result.push_back(*module_spec);
3304 }
3305
3306 return result;
3307}
3308
Colin Rileyc3c95b22015-04-16 15:51:33 +00003309// query the target remote for extended information using the qXfer packet
3310//
3311// example: object='features', annex='target.xml', out=<xml output>
3312// return: 'true' on success
3313// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003314bool GDBRemoteCommunicationClient::ReadExtFeature(
3315 const lldb_private::ConstString object,
3316 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003317 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003318
Kate Stoneb9c1b512016-09-06 20:57:50 +00003319 std::stringstream output;
3320 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003321
Kate Stoneb9c1b512016-09-06 20:57:50 +00003322 uint64_t size = GetRemoteMaxPacketSize();
3323 if (size == 0)
3324 size = 0x1000;
3325 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3326 int offset = 0;
3327 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003328
Kate Stoneb9c1b512016-09-06 20:57:50 +00003329 // loop until all data has been read
3330 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003331
Kate Stoneb9c1b512016-09-06 20:57:50 +00003332 // send query extended feature packet
3333 std::stringstream packet;
3334 packet << "qXfer:" << object.AsCString("")
3335 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3336 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003337
Kate Stoneb9c1b512016-09-06 20:57:50 +00003338 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003339 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003340
Kate Stoneb9c1b512016-09-06 20:57:50 +00003341 if (res != GDBRemoteCommunication::PacketResult::Success) {
3342 err.SetErrorString("Error sending $qXfer packet");
3343 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003344 }
3345
Kate Stoneb9c1b512016-09-06 20:57:50 +00003346 const std::string &str = chunk.GetStringRef();
3347 if (str.length() == 0) {
3348 // should have some data in chunk
3349 err.SetErrorString("Empty response from $qXfer packet");
3350 return false;
3351 }
3352
3353 // check packet code
3354 switch (str[0]) {
3355 // last chunk
3356 case ('l'):
3357 active = false;
3358 LLVM_FALLTHROUGH;
3359
3360 // more chunks
3361 case ('m'):
3362 if (str.length() > 1)
3363 output << &str[1];
3364 offset += size;
3365 break;
3366
3367 // unknown chunk
3368 default:
3369 err.SetErrorString("Invalid continuation code from $qXfer packet");
3370 return false;
3371 }
3372 }
3373
3374 out = output.str();
3375 err.Success();
3376 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003377}
Greg Clayton0b90be12015-06-23 21:27:50 +00003378
3379// Notify the target that gdb is prepared to serve symbol lookup requests.
3380// packet: "qSymbol::"
3381// reply:
3382// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003383// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3384// encoded).
3385// LLDB may provide the value by sending another qSymbol
3386// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003387// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003388//
3389// Three examples:
3390//
3391// lldb sends: qSymbol::
3392// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003393// Remote gdb stub does not need to know the addresses of any symbols, lldb
3394// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003395// need to ask again in this session.
3396//
3397// lldb sends: qSymbol::
3398// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3399// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3400// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003401// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3402// not know
3403// the address at this time. lldb needs to send qSymbol:: again when it has
3404// more
Jason Molenda50018d32016-01-13 04:08:10 +00003405// solibs loaded.
3406//
3407// lldb sends: qSymbol::
3408// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3409// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3410// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003411// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3412// that it
3413// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3414// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003415// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003416
Kate Stoneb9c1b512016-09-06 20:57:50 +00003417void GDBRemoteCommunicationClient::ServeSymbolLookups(
3418 lldb_private::Process *process) {
3419 // Set to true once we've resolved a symbol to an address for the remote stub.
3420 // If we get an 'OK' response after this, the remote stub doesn't need any
3421 // more
3422 // symbols and we can stop asking.
3423 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003424
Kate Stoneb9c1b512016-09-06 20:57:50 +00003425 // Is this the initial qSymbol:: packet?
3426 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003427
Kate Stoneb9c1b512016-09-06 20:57:50 +00003428 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3429 Lock lock(*this, false);
3430 if (lock) {
3431 StreamString packet;
3432 packet.PutCString("qSymbol::");
3433 StringExtractorGDBRemote response;
3434 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3435 PacketResult::Success) {
3436 if (response.IsOKResponse()) {
3437 if (symbol_response_provided || first_qsymbol_query) {
3438 m_qSymbol_requests_done = true;
3439 }
3440
3441 // We are done serving symbols requests
3442 return;
3443 }
3444 first_qsymbol_query = false;
3445
3446 if (response.IsUnsupportedResponse()) {
3447 // qSymbol is not supported by the current GDB server we are connected
3448 // to
3449 m_supports_qSymbol = false;
3450 return;
3451 } else {
3452 llvm::StringRef response_str(response.GetStringRef());
3453 if (response_str.startswith("qSymbol:")) {
3454 response.SetFilePos(strlen("qSymbol:"));
3455 std::string symbol_name;
3456 if (response.GetHexByteString(symbol_name)) {
3457 if (symbol_name.empty())
3458 return;
3459
3460 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3461 lldb_private::SymbolContextList sc_list;
3462 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3463 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3464 const size_t num_scs = sc_list.GetSize();
3465 for (size_t sc_idx = 0;
3466 sc_idx < num_scs &&
3467 symbol_load_addr == LLDB_INVALID_ADDRESS;
3468 ++sc_idx) {
3469 SymbolContext sc;
3470 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3471 if (sc.symbol) {
3472 switch (sc.symbol->GetType()) {
3473 case eSymbolTypeInvalid:
3474 case eSymbolTypeAbsolute:
3475 case eSymbolTypeUndefined:
3476 case eSymbolTypeSourceFile:
3477 case eSymbolTypeHeaderFile:
3478 case eSymbolTypeObjectFile:
3479 case eSymbolTypeCommonBlock:
3480 case eSymbolTypeBlock:
3481 case eSymbolTypeLocal:
3482 case eSymbolTypeParam:
3483 case eSymbolTypeVariable:
3484 case eSymbolTypeVariableType:
3485 case eSymbolTypeLineEntry:
3486 case eSymbolTypeLineHeader:
3487 case eSymbolTypeScopeBegin:
3488 case eSymbolTypeScopeEnd:
3489 case eSymbolTypeAdditional:
3490 case eSymbolTypeCompiler:
3491 case eSymbolTypeInstrumentation:
3492 case eSymbolTypeTrampoline:
3493 break;
3494
3495 case eSymbolTypeCode:
3496 case eSymbolTypeResolver:
3497 case eSymbolTypeData:
3498 case eSymbolTypeRuntime:
3499 case eSymbolTypeException:
3500 case eSymbolTypeObjCClass:
3501 case eSymbolTypeObjCMetaClass:
3502 case eSymbolTypeObjCIVar:
3503 case eSymbolTypeReExported:
3504 symbol_load_addr =
3505 sc.symbol->GetLoadAddress(&process->GetTarget());
3506 break;
3507 }
Jason Molenda50018d32016-01-13 04:08:10 +00003508 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003509 }
Greg Clayton42b01482015-08-11 22:07:46 +00003510 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003511 }
3512 // This is the normal path where our symbol lookup was successful
3513 // and we want
3514 // to send a packet with the new symbol value and see if another
3515 // lookup needs to be
3516 // done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003517
Kate Stoneb9c1b512016-09-06 20:57:50 +00003518 // Change "packet" to contain the requested symbol value and name
3519 packet.Clear();
3520 packet.PutCString("qSymbol:");
3521 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3522 packet.Printf("%" PRIx64, symbol_load_addr);
3523 symbol_response_provided = true;
3524 } else {
3525 symbol_response_provided = false;
3526 }
3527 packet.PutCString(":");
3528 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3529 continue; // go back to the while loop and send "packet" and wait
3530 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003531 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003532 }
3533 }
3534 }
3535 // If we make it here, the symbol request packet response wasn't valid or
3536 // our symbol lookup failed so we must abort
3537 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003538
Kate Stoneb9c1b512016-09-06 20:57:50 +00003539 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3540 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3541 log->Printf(
3542 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3543 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003544 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003545 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003546}
3547
Kate Stoneb9c1b512016-09-06 20:57:50 +00003548StructuredData::Array *
3549GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3550 if (!m_supported_async_json_packets_is_valid) {
3551 // Query the server for the array of supported asynchronous JSON
3552 // packets.
3553 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003554
Kate Stoneb9c1b512016-09-06 20:57:50 +00003555 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003556
Kate Stoneb9c1b512016-09-06 20:57:50 +00003557 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003558 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003559 const bool send_async = false;
3560 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3561 send_async) == PacketResult::Success) {
3562 m_supported_async_json_packets_sp =
3563 StructuredData::ParseJSON(response.GetStringRef());
3564 if (m_supported_async_json_packets_sp &&
3565 !m_supported_async_json_packets_sp->GetAsArray()) {
3566 // We were returned something other than a JSON array. This
3567 // is invalid. Clear it out.
3568 if (log)
3569 log->Printf("GDBRemoteCommunicationClient::%s(): "
3570 "QSupportedAsyncJSONPackets returned invalid "
3571 "result: %s",
3572 __FUNCTION__, response.GetStringRef().c_str());
3573 m_supported_async_json_packets_sp.reset();
3574 }
3575 } else {
3576 if (log)
3577 log->Printf("GDBRemoteCommunicationClient::%s(): "
3578 "QSupportedAsyncJSONPackets unsupported",
3579 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003581
3582 if (log && m_supported_async_json_packets_sp) {
3583 StreamString stream;
3584 m_supported_async_json_packets_sp->Dump(stream);
3585 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3586 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003587 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003588 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003589 }
3590
3591 return m_supported_async_json_packets_sp
3592 ? m_supported_async_json_packets_sp->GetAsArray()
3593 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003594}
3595
Zachary Turner97206d52017-05-12 04:51:55 +00003596Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003597 llvm::ArrayRef<int32_t> signals) {
3598 // Format packet:
3599 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3600 auto range = llvm::make_range(signals.begin(), signals.end());
3601 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3602
3603 StringExtractorGDBRemote response;
3604 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3605
3606 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003607 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003608
3609 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003610 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003611 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003612 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003613 }
3614}
3615
Zachary Turner97206d52017-05-12 04:51:55 +00003616Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003617 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003618 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003619
3620 if (type_name.GetLength() == 0) {
3621 error.SetErrorString("invalid type_name argument");
3622 return error;
3623 }
3624
3625 // Build command: Configure{type_name}: serialized config
3626 // data.
3627 StreamGDBRemote stream;
3628 stream.PutCString("QConfigure");
3629 stream.PutCString(type_name.AsCString());
3630 stream.PutChar(':');
3631 if (config_sp) {
3632 // Gather the plain-text version of the configuration data.
3633 StreamString unescaped_stream;
3634 config_sp->Dump(unescaped_stream);
3635 unescaped_stream.Flush();
3636
3637 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003638 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003639 unescaped_stream.GetSize());
3640 }
3641 stream.Flush();
3642
3643 // Send the packet.
3644 const bool send_async = false;
3645 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003646 auto result =
3647 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003648 if (result == PacketResult::Success) {
3649 // We failed if the config result comes back other than OK.
3650 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3651 // Okay!
3652 error.Clear();
3653 } else {
3654 error.SetErrorStringWithFormat("configuring StructuredData feature "
3655 "%s failed with error %s",
3656 type_name.AsCString(),
3657 response.GetStringRef().c_str());
3658 }
3659 } else {
3660 // Can we get more data here on the failure?
3661 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3662 "failed when sending packet: "
3663 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003664 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003665 }
3666 return error;
3667}
3668
3669void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3670 GDBRemoteClientBase::OnRunPacketSent(first);
3671 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003672}