blob: 319fa6543238f172627f83fd6a748c2861f89428 [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 Labath16064d32018-03-20 11:56:24 +000024#include "lldb/Host/XML.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"
Pavel Labath145d95c2018-04-17 18:53:35 +000029#include "lldb/Utility/Args.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000030#include "lldb/Utility/DataBufferHeap.h"
Pavel Labath2f1fbae2016-09-08 10:07:04 +000031#include "lldb/Utility/JSON.h"
Todd Fiala75930012016-08-19 04:21:48 +000032#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000033#include "lldb/Utility/Log.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"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000039#include "lldb/Host/Config.h"
Pavel Labath9af71b32018-03-20 16:14:00 +000040#include "lldb/Utility/StringExtractorGDBRemote.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),
Pavel Labath16064d32018-03-20 11:56:24 +000085 m_supports_qXfer_memory_map_read(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000086 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
87 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
88 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000089 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000090 m_supports_QPassSignals(eLazyBoolCalculate),
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +000091 m_supports_error_string_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
93 m_supports_qUserName(true), m_supports_qGroupName(true),
94 m_supports_qThreadStopInfo(true), m_supports_z0(true),
95 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
96 m_supports_z4(true), m_supports_QEnvironment(true),
97 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
98 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
Pavel Labath2f1fbae2016-09-08 10:07:04 +000099 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
100 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000101 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
Pavel Labath2272c482018-06-18 15:02:23 +0000103 m_os_build(), m_os_kernel(), m_hostname(), m_gdb_server_name(),
104 m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0),
105 m_max_packet_size(0), m_qSupported_response(),
106 m_supported_async_json_packets_is_valid(false),
Pavel Labath16064d32018-03-20 11:56:24 +0000107 m_supported_async_json_packets_sp(), m_qXfer_memory_map(),
108 m_qXfer_memory_map_loaded(false) {}
Greg Clayton576d8832011-03-22 04:00:09 +0000109
110//----------------------------------------------------------------------
111// Destructor
112//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
114 if (IsConnected())
115 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000116}
117
Zachary Turner97206d52017-05-12 04:51:55 +0000118bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000120
Adrian Prantl05097242018-04-30 16:49:04 +0000121 // Start the read thread after we send the handshake ack since if we fail to
122 // send the handshake ack, there is no reason to continue...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123 if (SendAck()) {
124 // Wait for any responses that might have been queued up in the remote
125 // GDB server and flush them all
126 StringExtractorGDBRemote response;
127 PacketResult packet_result = PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 while (packet_result == PacketResult::Success)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000129 packet_result = ReadPacket(response, milliseconds(10), false);
Ed Maste48f986f2013-12-18 15:31:45 +0000130
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 // The return value from QueryNoAckModeSupported() is true if the packet
Adrian Prantl05097242018-04-30 16:49:04 +0000132 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
133 // false if no response was received. This quickly tells us if we have a
134 // live connection to a remote GDB server...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 if (QueryNoAckModeSupported()) {
136 return true;
137 } else {
138 if (error_ptr)
139 error_ptr->SetErrorString("failed to get reply to handshake packet");
Greg Claytonfb909312013-11-23 01:58:15 +0000140 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 } else {
142 if (error_ptr)
143 error_ptr->SetErrorString("failed to send the handshake ack");
144 }
145 return false;
Greg Clayton1cb64962011-03-24 04:28:38 +0000146}
147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148bool GDBRemoteCommunicationClient::GetEchoSupported() {
149 if (m_supports_qEcho == eLazyBoolCalculate) {
150 GetRemoteQSupported();
151 }
152 return m_supports_qEcho == eLazyBoolYes;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000153}
154
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000155bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
156 if (m_supports_QPassSignals == eLazyBoolCalculate) {
157 GetRemoteQSupported();
158 }
159 return m_supports_QPassSignals == eLazyBoolYes;
160}
161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
163 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
164 GetRemoteQSupported();
165 }
166 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000167}
168
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
170 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
171 GetRemoteQSupported();
172 }
173 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000174}
175
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
177 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
178 GetRemoteQSupported();
179 }
180 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000181}
182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
184 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
185 GetRemoteQSupported();
186 }
187 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000188}
189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
191 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
192 GetRemoteQSupported();
193 }
194 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000195}
196
Pavel Labath16064d32018-03-20 11:56:24 +0000197bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() {
198 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) {
199 GetRemoteQSupported();
200 }
201 return m_supports_qXfer_memory_map_read == eLazyBoolYes;
202}
203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
205 if (m_max_packet_size == 0) {
206 GetRemoteQSupported();
207 }
208 return m_max_packet_size;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000209}
210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
212 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
213 m_send_acks = true;
214 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000215
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216 // This is the first real packet that we'll send in a debug session and it
Adrian Prantl05097242018-04-30 16:49:04 +0000217 // may take a little longer than normal to receive a reply. Wait at least
218 // 6 seconds for a reply to this packet.
Jason Molenda36a216e2014-07-24 01:36:24 +0000219
Pavel Labath1eff73c2016-11-24 10:54:49 +0000220 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
Colin Rileyc3c95b22015-04-16 15:51:33 +0000221
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000222 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
224 PacketResult::Success) {
225 if (response.IsOKResponse()) {
226 m_send_acks = false;
227 m_supports_not_sending_acks = eLazyBoolYes;
228 }
229 return true;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000230 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231 }
232 return false;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000233}
Greg Clayton576d8832011-03-22 04:00:09 +0000234
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
236 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
237 m_supports_threads_in_stop_reply = eLazyBoolNo;
238
239 StringExtractorGDBRemote response;
240 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
241 false) == PacketResult::Success) {
242 if (response.IsOKResponse())
243 m_supports_threads_in_stop_reply = eLazyBoolYes;
Pavel Labath5c95ee42016-08-30 13:56:11 +0000244 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 }
Pavel Labath0faf3732016-08-25 08:34:57 +0000246}
Greg Clayton576d8832011-03-22 04:00:09 +0000247
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
249 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
250 m_attach_or_wait_reply = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +0000251
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 StringExtractorGDBRemote response;
253 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
254 false) == PacketResult::Success) {
255 if (response.IsOKResponse())
256 m_attach_or_wait_reply = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000257 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258 }
259 if (m_attach_or_wait_reply == eLazyBoolYes)
260 return true;
261 else
Greg Clayton576d8832011-03-22 04:00:09 +0000262 return false;
263}
264
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
266 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
267 m_prepare_for_reg_writing_reply = eLazyBoolNo;
268
269 StringExtractorGDBRemote response;
270 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
271 false) == PacketResult::Success) {
272 if (response.IsOKResponse())
273 m_prepare_for_reg_writing_reply = eLazyBoolYes;
274 }
275 }
276 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
277 return true;
278 else
279 return false;
280}
281
282void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
283 if (did_exec == false) {
284 // Hard reset everything, this is when we first connect to a GDB server
285 m_supports_not_sending_acks = eLazyBoolCalculate;
286 m_supports_thread_suffix = eLazyBoolCalculate;
287 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
288 m_supports_vCont_c = eLazyBoolCalculate;
289 m_supports_vCont_C = eLazyBoolCalculate;
290 m_supports_vCont_s = eLazyBoolCalculate;
291 m_supports_vCont_S = eLazyBoolCalculate;
292 m_supports_p = eLazyBoolCalculate;
293 m_supports_x = eLazyBoolCalculate;
294 m_supports_QSaveRegisterState = eLazyBoolCalculate;
295 m_qHostInfo_is_valid = eLazyBoolCalculate;
296 m_curr_pid_is_valid = eLazyBoolCalculate;
297 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
298 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
299 m_supports_memory_region_info = eLazyBoolCalculate;
300 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
301 m_attach_or_wait_reply = eLazyBoolCalculate;
302 m_avoid_g_packets = eLazyBoolCalculate;
303 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
304 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
305 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
306 m_supports_qXfer_features_read = eLazyBoolCalculate;
Pavel Labath16064d32018-03-20 11:56:24 +0000307 m_supports_qXfer_memory_map_read = eLazyBoolCalculate;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
309 m_supports_qProcessInfoPID = true;
310 m_supports_qfProcessInfo = true;
311 m_supports_qUserName = true;
312 m_supports_qGroupName = true;
313 m_supports_qThreadStopInfo = true;
314 m_supports_z0 = true;
315 m_supports_z1 = true;
316 m_supports_z2 = true;
317 m_supports_z3 = true;
318 m_supports_z4 = true;
319 m_supports_QEnvironment = true;
320 m_supports_QEnvironmentHexEncoded = true;
321 m_supports_qSymbol = true;
322 m_qSymbol_requests_done = false;
323 m_supports_qModuleInfo = true;
324 m_host_arch.Clear();
Pavel Labath2272c482018-06-18 15:02:23 +0000325 m_os_version = llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 m_os_build.clear();
327 m_os_kernel.clear();
328 m_hostname.clear();
329 m_gdb_server_name.clear();
330 m_gdb_server_version = UINT32_MAX;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000331 m_default_packet_timeout = seconds(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 m_max_packet_size = 0;
333 m_qSupported_response.clear();
334 m_supported_async_json_packets_is_valid = false;
335 m_supported_async_json_packets_sp.reset();
Pavel Labath2f1fbae2016-09-08 10:07:04 +0000336 m_supports_jModulesInfo = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 }
338
Adrian Prantl05097242018-04-30 16:49:04 +0000339 // These flags should be reset when we first connect to a GDB server and when
340 // our inferior process execs
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 m_qProcessInfo_is_valid = eLazyBoolCalculate;
342 m_process_arch.Clear();
343}
344
345void GDBRemoteCommunicationClient::GetRemoteQSupported() {
346 // Clear out any capabilities we expect to see in the qSupported response
347 m_supports_qXfer_auxv_read = eLazyBoolNo;
348 m_supports_qXfer_libraries_read = eLazyBoolNo;
349 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
350 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
351 m_supports_qXfer_features_read = eLazyBoolNo;
Pavel Labath16064d32018-03-20 11:56:24 +0000352 m_supports_qXfer_memory_map_read = eLazyBoolNo;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
354 // not, we assume no limit
355
356 // build the qSupported packet
357 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
358 StreamString packet;
359 packet.PutCString("qSupported");
360 for (uint32_t i = 0; i < features.size(); ++i) {
361 packet.PutCString(i == 0 ? ":" : ";");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000362 packet.PutCString(features[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 }
364
365 StringExtractorGDBRemote response;
Zachary Turnerc1564272016-11-16 21:15:24 +0000366 if (SendPacketAndWaitForResponse(packet.GetString(), response,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 /*send_async=*/false) ==
368 PacketResult::Success) {
369 const char *response_cstr = response.GetStringRef().c_str();
370
371 // Hang on to the qSupported packet, so that platforms can do custom
Adrian Prantl05097242018-04-30 16:49:04 +0000372 // configuration of the transport before attaching/launching the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 m_qSupported_response = response_cstr;
374
375 if (::strstr(response_cstr, "qXfer:auxv:read+"))
376 m_supports_qXfer_auxv_read = eLazyBoolYes;
377 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
378 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
379 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
380 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
381 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
382 }
383 if (::strstr(response_cstr, "qXfer:libraries:read+"))
384 m_supports_qXfer_libraries_read = eLazyBoolYes;
385 if (::strstr(response_cstr, "qXfer:features:read+"))
386 m_supports_qXfer_features_read = eLazyBoolYes;
Pavel Labath16064d32018-03-20 11:56:24 +0000387 if (::strstr(response_cstr, "qXfer:memory-map:read+"))
388 m_supports_qXfer_memory_map_read = eLazyBoolYes;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389
390 // Look for a list of compressions in the features list e.g.
Adrian Prantl05097242018-04-30 16:49:04 +0000391 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
392 // deflate,lzma
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
394 if (features_list) {
395 const char *compressions =
396 ::strstr(features_list, "SupportedCompressions=");
397 if (compressions) {
398 std::vector<std::string> supported_compressions;
399 compressions += sizeof("SupportedCompressions=") - 1;
400 const char *end_of_compressions = strchr(compressions, ';');
401 if (end_of_compressions == NULL) {
402 end_of_compressions = strchr(compressions, '\0');
403 }
404 const char *current_compression = compressions;
405 while (current_compression < end_of_compressions) {
406 const char *next_compression_name = strchr(current_compression, ',');
407 const char *end_of_this_word = next_compression_name;
408 if (next_compression_name == NULL ||
409 end_of_compressions < next_compression_name) {
410 end_of_this_word = end_of_compressions;
411 }
412
413 if (end_of_this_word) {
414 if (end_of_this_word == current_compression) {
415 current_compression++;
416 } else {
417 std::string this_compression(
418 current_compression, end_of_this_word - current_compression);
419 supported_compressions.push_back(this_compression);
420 current_compression = end_of_this_word + 1;
421 }
422 } else {
423 supported_compressions.push_back(current_compression);
424 current_compression = end_of_compressions;
425 }
426 }
427
428 if (supported_compressions.size() > 0) {
429 MaybeEnableCompression(supported_compressions);
430 }
431 }
432 }
433
434 if (::strstr(response_cstr, "qEcho"))
435 m_supports_qEcho = eLazyBoolYes;
436 else
437 m_supports_qEcho = eLazyBoolNo;
438
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000439 if (::strstr(response_cstr, "QPassSignals+"))
440 m_supports_QPassSignals = eLazyBoolYes;
441 else
442 m_supports_QPassSignals = eLazyBoolNo;
443
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
445 if (packet_size_str) {
446 StringExtractorGDBRemote packet_response(packet_size_str +
447 strlen("PacketSize="));
448 m_max_packet_size =
449 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
450 if (m_max_packet_size == 0) {
451 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
452 Log *log(
453 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
454 if (log)
455 log->Printf("Garbled PacketSize spec in qSupported response");
456 }
457 }
458 }
459}
460
461bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
462 if (m_supports_thread_suffix == eLazyBoolCalculate) {
463 StringExtractorGDBRemote response;
464 m_supports_thread_suffix = eLazyBoolNo;
465 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
466 false) == PacketResult::Success) {
467 if (response.IsOKResponse())
468 m_supports_thread_suffix = eLazyBoolYes;
469 }
470 }
471 return m_supports_thread_suffix;
472}
473bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
474 if (m_supports_vCont_c == eLazyBoolCalculate) {
475 StringExtractorGDBRemote response;
476 m_supports_vCont_any = eLazyBoolNo;
477 m_supports_vCont_all = eLazyBoolNo;
478 m_supports_vCont_c = eLazyBoolNo;
479 m_supports_vCont_C = eLazyBoolNo;
480 m_supports_vCont_s = eLazyBoolNo;
481 m_supports_vCont_S = eLazyBoolNo;
482 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
483 PacketResult::Success) {
484 const char *response_cstr = response.GetStringRef().c_str();
485 if (::strstr(response_cstr, ";c"))
486 m_supports_vCont_c = eLazyBoolYes;
487
488 if (::strstr(response_cstr, ";C"))
489 m_supports_vCont_C = eLazyBoolYes;
490
491 if (::strstr(response_cstr, ";s"))
492 m_supports_vCont_s = eLazyBoolYes;
493
494 if (::strstr(response_cstr, ";S"))
495 m_supports_vCont_S = eLazyBoolYes;
496
497 if (m_supports_vCont_c == eLazyBoolYes &&
498 m_supports_vCont_C == eLazyBoolYes &&
499 m_supports_vCont_s == eLazyBoolYes &&
500 m_supports_vCont_S == eLazyBoolYes) {
501 m_supports_vCont_all = eLazyBoolYes;
502 }
503
504 if (m_supports_vCont_c == eLazyBoolYes ||
505 m_supports_vCont_C == eLazyBoolYes ||
506 m_supports_vCont_s == eLazyBoolYes ||
507 m_supports_vCont_S == eLazyBoolYes) {
508 m_supports_vCont_any = eLazyBoolYes;
509 }
510 }
511 }
512
513 switch (flavor) {
514 case 'a':
515 return m_supports_vCont_any;
516 case 'A':
517 return m_supports_vCont_all;
518 case 'c':
519 return m_supports_vCont_c;
520 case 'C':
521 return m_supports_vCont_C;
522 case 's':
523 return m_supports_vCont_s;
524 case 'S':
525 return m_supports_vCont_S;
526 default:
527 break;
528 }
529 return false;
530}
531
Pavel Labath4b6f9592016-08-18 08:30:03 +0000532GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
534 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
535 bool send_async) {
536 Lock lock(*this, send_async);
537 if (!lock) {
538 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
539 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
540 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
541 "for %s packet.",
Zachary Turnerc1564272016-11-16 21:15:24 +0000542 __FUNCTION__, payload.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 return PacketResult::ErrorNoSequenceLock;
544 }
Pavel Labath5c95ee42016-08-30 13:56:11 +0000545
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 if (GetThreadSuffixSupported())
547 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
548 else {
549 if (!SetCurrentThread(tid))
550 return PacketResult::ErrorSendFailed;
551 }
Pavel Labath4b6f9592016-08-18 08:30:03 +0000552
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000554}
555
Adrian Prantl05097242018-04-30 16:49:04 +0000556// Check if the target supports 'p' packet. It sends out a 'p' packet and
557// checks the response. A normal packet will tell us that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000558//
559// Takes a valid thread ID because p needs to apply to a thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
561 if (m_supports_p == eLazyBoolCalculate) {
562 m_supports_p = eLazyBoolNo;
563 StreamString payload;
564 payload.PutCString("p0");
565 StringExtractorGDBRemote response;
566 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
567 response, false) ==
568 PacketResult::Success &&
569 response.IsNormalResponse()) {
570 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000571 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 }
573 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000574}
Greg Clayton576d8832011-03-22 04:00:09 +0000575
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
577 // Get information on all threads at one using the "jThreadsInfo" packet
578 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000579
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580 if (m_supports_jThreadsInfo) {
581 StringExtractorGDBRemote response;
582 response.SetResponseValidatorToJSON();
583 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
584 PacketResult::Success) {
585 if (response.IsUnsupportedResponse()) {
586 m_supports_jThreadsInfo = false;
587 } else if (!response.Empty()) {
588 object_sp = StructuredData::ParseJSON(response.GetStringRef());
589 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000590 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591 }
592 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000593}
594
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
596 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
597 StringExtractorGDBRemote response;
598 m_supports_jThreadExtendedInfo = eLazyBoolNo;
599 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
600 PacketResult::Success) {
601 if (response.IsOKResponse()) {
602 m_supports_jThreadExtendedInfo = eLazyBoolYes;
603 }
Jason Molenda705b1802014-06-13 02:37:02 +0000604 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 }
606 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000607}
608
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000609void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
610 if (m_supports_error_string_reply == eLazyBoolCalculate) {
611 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +0000612 // We try to enable error strings in remote packets but if we fail, we just
613 // work in the older way.
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000614 m_supports_error_string_reply = eLazyBoolNo;
615 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
616 PacketResult::Success) {
617 if (response.IsOKResponse()) {
618 m_supports_error_string_reply = eLazyBoolYes;
619 }
620 }
621 }
622}
623
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
625 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
626 StringExtractorGDBRemote response;
627 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
628 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
629 response,
630 false) == PacketResult::Success) {
631 if (response.IsOKResponse()) {
632 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
633 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000634 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635 }
636 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000637}
638
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
640 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
641 StringExtractorGDBRemote response;
642 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
643 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
644 PacketResult::Success) {
645 if (response.IsOKResponse()) {
646 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
647 }
Jason Molenda37397352016-07-22 00:17:55 +0000648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 }
650 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000651}
652
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653bool GDBRemoteCommunicationClient::GetxPacketSupported() {
654 if (m_supports_x == eLazyBoolCalculate) {
655 StringExtractorGDBRemote response;
656 m_supports_x = eLazyBoolNo;
657 char packet[256];
658 snprintf(packet, sizeof(packet), "x0,0");
659 if (SendPacketAndWaitForResponse(packet, response, false) ==
660 PacketResult::Success) {
661 if (response.IsOKResponse())
662 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000663 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 }
665 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000666}
667
Greg Clayton3dedae12013-12-06 21:45:27 +0000668GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
670 const char *payload_prefix, std::string &response_string) {
671 Lock lock(*this, false);
672 if (!lock) {
673 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
674 GDBR_LOG_PACKETS));
675 if (log)
676 log->Printf("error: failed to get packet sequence mutex, not sending "
677 "packets with prefix '%s'",
678 payload_prefix);
679 return PacketResult::ErrorNoSequenceLock;
680 }
681
682 response_string = "";
683 std::string payload_prefix_str(payload_prefix);
684 unsigned int response_size = 0x1000;
685 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
686 response_size = GetRemoteMaxPacketSize();
687 }
688
689 for (unsigned int offset = 0; true; offset += response_size) {
690 StringExtractorGDBRemote this_response;
691 // Construct payload
692 char sizeDescriptor[128];
693 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
694 response_size);
695 PacketResult result = SendPacketAndWaitForResponseNoLock(
696 payload_prefix_str + sizeDescriptor, this_response);
697 if (result != PacketResult::Success)
698 return result;
699
700 const std::string &this_string = this_response.GetStringRef();
701
702 // Check for m or l as first character; l seems to mean this is the last
703 // chunk
704 char first_char = *this_string.c_str();
705 if (first_char != 'm' && first_char != 'l') {
706 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000707 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 // Concatenate the result so far (skipping 'm' or 'l')
709 response_string.append(this_string, 1, std::string::npos);
710 if (first_char == 'l')
711 // We're done
712 return PacketResult::Success;
713 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000714}
715
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
717 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
718 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000719
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720 // First try to retrieve the pid via the qProcessInfo request.
721 GetCurrentProcessInfo(allow_lazy);
722 if (m_curr_pid_is_valid == eLazyBoolYes) {
723 // We really got it.
724 return m_curr_pid;
725 } else {
726 // If we don't get a response for qProcessInfo, check if $qC gives us a
Adrian Prantl05097242018-04-30 16:49:04 +0000727 // result. $qC only returns a real process id on older debugserver and
728 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
729 // the thread id, which newer debugserver and lldb-gdbserver stubs return
730 // correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000731 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000732 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 PacketResult::Success) {
734 if (response.GetChar() == 'Q') {
735 if (response.GetChar() == 'C') {
736 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
737 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
738 m_curr_pid_is_valid = eLazyBoolYes;
739 return m_curr_pid;
740 }
Greg Clayton576d8832011-03-22 04:00:09 +0000741 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 }
Greg Clayton576d8832011-03-22 04:00:09 +0000743 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744
745 // If we don't get a response for $qC, check if $qfThreadID gives us a
746 // result.
747 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
748 std::vector<lldb::tid_t> thread_ids;
749 bool sequence_mutex_unavailable;
750 size_t size;
751 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
752 if (size && sequence_mutex_unavailable == false) {
753 m_curr_pid = thread_ids.front();
754 m_curr_pid_is_valid = eLazyBoolYes;
755 return m_curr_pid;
756 }
Greg Clayton576d8832011-03-22 04:00:09 +0000757 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758 }
759
760 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000761}
762
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
764 error_str.clear();
765 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000766 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
767 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 if (response.IsOKResponse())
769 return true;
770 if (response.GetChar() == 'E') {
771 // A string the describes what failed when launching...
772 error_str = response.GetStringRef().substr(1);
773 } else {
774 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000775 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 } else {
777 error_str.assign("timed out waiting for app to launch");
778 }
779 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000780}
781
Kate Stoneb9c1b512016-09-06 20:57:50 +0000782int GDBRemoteCommunicationClient::SendArgumentsPacket(
783 const ProcessLaunchInfo &launch_info) {
784 // Since we don't get the send argv0 separate from the executable path, we
Adrian Prantl05097242018-04-30 16:49:04 +0000785 // need to make sure to use the actual executable path found in the
786 // launch_info...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 std::vector<const char *> argv;
788 FileSpec exe_file = launch_info.GetExecutableFile();
789 std::string exe_path;
790 const char *arg = NULL;
791 const Args &launch_args = launch_info.GetArguments();
792 if (exe_file)
793 exe_path = exe_file.GetPath(false);
794 else {
795 arg = launch_args.GetArgumentAtIndex(0);
796 if (arg)
797 exe_path = arg;
798 }
799 if (!exe_path.empty()) {
800 argv.push_back(exe_path.c_str());
801 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
802 ++i) {
803 if (arg)
804 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000805 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 }
807 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000808 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809 packet.PutChar('A');
810 for (size_t i = 0, n = argv.size(); i < n; ++i) {
811 arg = argv[i];
812 const int arg_len = strlen(arg);
813 if (i > 0)
814 packet.PutChar(',');
815 packet.Printf("%i,%i,", arg_len * 2, (int)i);
816 packet.PutBytesAsRawHex8(arg, arg_len);
817 }
818
Vince Harrone0be4252015-02-06 18:32:57 +0000819 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000820 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
821 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000823 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824 uint8_t error = response.GetError();
825 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000826 return error;
827 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 }
829 return -1;
830}
Johnny Chen64637202012-05-23 21:09:52 +0000831
Pavel Labath62930e52018-01-10 11:57:31 +0000832int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
833 for (const auto &KV : env) {
834 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
835 if (r != 0)
836 return r;
837 }
838 return 0;
839}
840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841int GDBRemoteCommunicationClient::SendEnvironmentPacket(
842 char const *name_equal_value) {
843 if (name_equal_value && name_equal_value[0]) {
844 StreamString packet;
845 bool send_hex_encoding = false;
846 for (const char *p = name_equal_value;
847 *p != '\0' && send_hex_encoding == false; ++p) {
848 if (isprint(*p)) {
849 switch (*p) {
850 case '$':
851 case '#':
852 case '*':
853 case '}':
854 send_hex_encoding = true;
855 break;
856 default:
857 break;
Johnny Chen64637202012-05-23 21:09:52 +0000858 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 } else {
860 // We have non printable characters, lets hex encode this...
861 send_hex_encoding = true;
862 }
Johnny Chen64637202012-05-23 21:09:52 +0000863 }
864
Greg Claytonfbb76342013-11-20 21:07:01 +0000865 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 if (send_hex_encoding) {
867 if (m_supports_QEnvironmentHexEncoded) {
868 packet.PutCString("QEnvironmentHexEncoded:");
869 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000870 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
871 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 if (response.IsOKResponse())
873 return 0;
874 uint8_t error = response.GetError();
875 if (error)
876 return error;
877 if (response.IsUnsupportedResponse())
878 m_supports_QEnvironmentHexEncoded = false;
879 }
880 }
881
882 } else if (m_supports_QEnvironment) {
883 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000884 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
885 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886 if (response.IsOKResponse())
887 return 0;
888 uint8_t error = response.GetError();
889 if (error)
890 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000891 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 m_supports_QEnvironment = false;
893 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000894 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895 }
896 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000897}
898
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
900 if (arch && arch[0]) {
901 StreamString packet;
902 packet.Printf("QLaunchArch:%s", arch);
903 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000904 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
905 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 if (response.IsOKResponse())
907 return 0;
908 uint8_t error = response.GetError();
909 if (error)
910 return error;
911 }
912 }
913 return -1;
914}
Chaoren Lind3173f32015-05-29 19:52:29 +0000915
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
917 char const *data, bool *was_supported) {
918 if (data && *data != '\0') {
919 StreamString packet;
920 packet.Printf("QSetProcessEvent:%s", data);
921 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000922 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
923 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 if (response.IsOKResponse()) {
925 if (was_supported)
926 *was_supported = true;
927 return 0;
928 } else if (response.IsUnsupportedResponse()) {
929 if (was_supported)
930 *was_supported = false;
931 return -1;
932 } else {
933 uint8_t error = response.GetError();
934 if (was_supported)
935 *was_supported = true;
936 if (error)
937 return error;
938 }
939 }
940 }
941 return -1;
942}
943
Pavel Labath2272c482018-06-18 15:02:23 +0000944llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() {
945 GetHostInfo();
946 return m_os_version;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947}
948
949bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
950 if (GetHostInfo()) {
951 if (!m_os_build.empty()) {
952 s = m_os_build;
953 return true;
954 }
955 }
956 s.clear();
957 return false;
958}
959
960bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
961 if (GetHostInfo()) {
962 if (!m_os_kernel.empty()) {
963 s = m_os_kernel;
964 return true;
965 }
966 }
967 s.clear();
968 return false;
969}
970
971bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
972 if (GetHostInfo()) {
973 if (!m_hostname.empty()) {
974 s = m_hostname;
975 return true;
976 }
977 }
978 s.clear();
979 return false;
980}
981
982ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
983 if (GetHostInfo())
984 return m_host_arch;
985 return ArchSpec();
986}
987
988const lldb_private::ArchSpec &
989GDBRemoteCommunicationClient::GetProcessArchitecture() {
990 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
991 GetCurrentProcessInfo();
992 return m_process_arch;
993}
994
995bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
996 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
997 m_gdb_server_name.clear();
998 m_gdb_server_version = 0;
999 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1000
1001 StringExtractorGDBRemote response;
1002 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
1003 PacketResult::Success) {
1004 if (response.IsNormalResponse()) {
1005 llvm::StringRef name, value;
1006 bool success = false;
1007 while (response.GetNameColonValue(name, value)) {
1008 if (name.equals("name")) {
1009 success = true;
1010 m_gdb_server_name = value;
1011 } else if (name.equals("version")) {
1012 llvm::StringRef major, minor;
1013 std::tie(major, minor) = value.split('.');
1014 if (!major.getAsInteger(0, m_gdb_server_version))
1015 success = true;
1016 }
Greg Clayton576d8832011-03-22 04:00:09 +00001017 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 if (success)
1019 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1020 }
Greg Clayton576d8832011-03-22 04:00:09 +00001021 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 }
1023 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001024}
1025
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026void GDBRemoteCommunicationClient::MaybeEnableCompression(
1027 std::vector<std::string> supported_compressions) {
1028 CompressionType avail_type = CompressionType::None;
1029 std::string avail_name;
1030
1031#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001032 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 for (auto compression : supported_compressions) {
1034 if (compression == "lzfse") {
1035 avail_type = CompressionType::LZFSE;
1036 avail_name = compression;
1037 break;
1038 }
1039 }
1040 }
1041#endif
1042
1043#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001044 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 for (auto compression : supported_compressions) {
1046 if (compression == "zlib-deflate") {
1047 avail_type = CompressionType::ZlibDeflate;
1048 avail_name = compression;
1049 break;
1050 }
1051 }
1052 }
1053#endif
1054
1055#if defined(HAVE_LIBZ)
1056 if (avail_type == CompressionType::None) {
1057 for (auto compression : supported_compressions) {
1058 if (compression == "zlib-deflate") {
1059 avail_type = CompressionType::ZlibDeflate;
1060 avail_name = compression;
1061 break;
1062 }
1063 }
1064 }
1065#endif
1066
1067#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001068 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001069 for (auto compression : supported_compressions) {
1070 if (compression == "lz4") {
1071 avail_type = CompressionType::LZ4;
1072 avail_name = compression;
1073 break;
1074 }
1075 }
1076 }
1077#endif
1078
1079#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001080 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081 for (auto compression : supported_compressions) {
1082 if (compression == "lzma") {
1083 avail_type = CompressionType::LZMA;
1084 avail_name = compression;
1085 break;
1086 }
1087 }
1088 }
1089#endif
1090
1091 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001092 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001094 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 PacketResult::Success)
1096 return;
1097
1098 if (response.IsOKResponse()) {
1099 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001100 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 }
Greg Clayton576d8832011-03-22 04:00:09 +00001102}
Greg Clayton32e0a752011-03-30 18:16:51 +00001103
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1105 if (GetGDBServerVersion()) {
1106 if (!m_gdb_server_name.empty())
1107 return m_gdb_server_name.c_str();
1108 }
1109 return NULL;
1110}
1111
1112uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1113 if (GetGDBServerVersion())
1114 return m_gdb_server_version;
1115 return 0;
1116}
1117
1118bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1119 StringExtractorGDBRemote response;
1120 if (SendPacketAndWaitForResponse("qC", response, false) !=
1121 PacketResult::Success)
1122 return false;
1123
1124 if (!response.IsNormalResponse())
1125 return false;
1126
1127 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1128 tid = response.GetHexMaxU32(true, -1);
1129
1130 return true;
1131}
1132
1133bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1134 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1135
1136 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1137 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001138 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1140 PacketResult::Success) {
1141 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001142 llvm::StringRef name;
1143 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001144 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1145 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 std::string arch_name;
1147 std::string os_name;
1148 std::string vendor_name;
1149 std::string triple;
1150 std::string distribution_id;
1151 uint32_t pointer_byte_size = 0;
1152 ByteOrder byte_order = eByteOrderInvalid;
1153 uint32_t num_keys_decoded = 0;
1154 while (response.GetNameColonValue(name, value)) {
1155 if (name.equals("cputype")) {
1156 // exception type in big endian hex
1157 if (!value.getAsInteger(0, cpu))
1158 ++num_keys_decoded;
1159 } else if (name.equals("cpusubtype")) {
1160 // exception count in big endian hex
1161 if (!value.getAsInteger(0, sub))
1162 ++num_keys_decoded;
1163 } else if (name.equals("arch")) {
1164 arch_name = value;
1165 ++num_keys_decoded;
1166 } else if (name.equals("triple")) {
1167 StringExtractor extractor(value);
1168 extractor.GetHexByteString(triple);
1169 ++num_keys_decoded;
1170 } else if (name.equals("distribution_id")) {
1171 StringExtractor extractor(value);
1172 extractor.GetHexByteString(distribution_id);
1173 ++num_keys_decoded;
1174 } else if (name.equals("os_build")) {
1175 StringExtractor extractor(value);
1176 extractor.GetHexByteString(m_os_build);
1177 ++num_keys_decoded;
1178 } else if (name.equals("hostname")) {
1179 StringExtractor extractor(value);
1180 extractor.GetHexByteString(m_hostname);
1181 ++num_keys_decoded;
1182 } else if (name.equals("os_kernel")) {
1183 StringExtractor extractor(value);
1184 extractor.GetHexByteString(m_os_kernel);
1185 ++num_keys_decoded;
1186 } else if (name.equals("ostype")) {
1187 os_name = value;
1188 ++num_keys_decoded;
1189 } else if (name.equals("vendor")) {
1190 vendor_name = value;
1191 ++num_keys_decoded;
1192 } else if (name.equals("endian")) {
1193 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1194 .Case("little", eByteOrderLittle)
1195 .Case("big", eByteOrderBig)
1196 .Case("pdp", eByteOrderPDP)
1197 .Default(eByteOrderInvalid);
1198 if (byte_order != eByteOrderInvalid)
1199 ++num_keys_decoded;
1200 } else if (name.equals("ptrsize")) {
1201 if (!value.getAsInteger(0, pointer_byte_size))
1202 ++num_keys_decoded;
1203 } else if (name.equals("os_version") ||
1204 name.equals(
1205 "version")) // Older debugserver binaries used the
1206 // "version" key instead of
1207 // "os_version"...
1208 {
Pavel Labath2272c482018-06-18 15:02:23 +00001209 if (!m_os_version.tryParse(value))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 ++num_keys_decoded;
1211 } else if (name.equals("watchpoint_exceptions_received")) {
1212 m_watchpoints_trigger_after_instruction =
1213 llvm::StringSwitch<LazyBool>(value)
1214 .Case("before", eLazyBoolNo)
1215 .Case("after", eLazyBoolYes)
1216 .Default(eLazyBoolCalculate);
1217 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1218 ++num_keys_decoded;
1219 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001220 uint32_t timeout_seconds;
1221 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001222 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223 SetPacketTimeout(m_default_packet_timeout);
1224 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001225 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226 }
Jason Molenda89c37492014-01-27 22:23:20 +00001227 }
1228
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 if (num_keys_decoded > 0)
1230 m_qHostInfo_is_valid = eLazyBoolYes;
1231
1232 if (triple.empty()) {
1233 if (arch_name.empty()) {
1234 if (cpu != LLDB_INVALID_CPUTYPE) {
1235 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1236 if (pointer_byte_size) {
1237 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1238 }
1239 if (byte_order != eByteOrderInvalid) {
1240 assert(byte_order == m_host_arch.GetByteOrder());
1241 }
1242
1243 if (!vendor_name.empty())
1244 m_host_arch.GetTriple().setVendorName(
1245 llvm::StringRef(vendor_name));
1246 if (!os_name.empty())
1247 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001248 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001250 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001251 triple += arch_name;
1252 if (!vendor_name.empty() || !os_name.empty()) {
1253 triple += '-';
1254 if (vendor_name.empty())
1255 triple += "unknown";
1256 else
1257 triple += vendor_name;
1258 triple += '-';
1259 if (os_name.empty())
1260 triple += "unknown";
1261 else
1262 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001263 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001265
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 llvm::Triple &host_triple = m_host_arch.GetTriple();
1267 if (host_triple.getVendor() == llvm::Triple::Apple &&
1268 host_triple.getOS() == llvm::Triple::Darwin) {
1269 switch (m_host_arch.GetMachine()) {
1270 case llvm::Triple::aarch64:
1271 case llvm::Triple::arm:
1272 case llvm::Triple::thumb:
1273 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001274 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001275 default:
1276 host_triple.setOS(llvm::Triple::MacOSX);
1277 break;
1278 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001279 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280 if (pointer_byte_size) {
1281 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1282 }
1283 if (byte_order != eByteOrderInvalid) {
1284 assert(byte_order == m_host_arch.GetByteOrder());
1285 }
1286 }
1287 } else {
1288 m_host_arch.SetTriple(triple.c_str());
1289 if (pointer_byte_size) {
1290 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1291 }
1292 if (byte_order != eByteOrderInvalid) {
1293 assert(byte_order == m_host_arch.GetByteOrder());
1294 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001295
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 if (log)
1297 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1298 "architecture as %s, triple as %s from triple text %s",
1299 __FUNCTION__, m_host_arch.GetArchitectureName()
1300 ? m_host_arch.GetArchitectureName()
1301 : "<null-arch-name>",
1302 m_host_arch.GetTriple().getTriple().c_str(),
1303 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001304 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305 if (!distribution_id.empty())
1306 m_host_arch.SetDistributionId(distribution_id.c_str());
1307 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001308 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 }
1310 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001311}
Greg Clayton37a0a242012-04-11 00:24:49 +00001312
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313int GDBRemoteCommunicationClient::SendAttach(
1314 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1315 if (pid != LLDB_INVALID_PROCESS_ID) {
1316 char packet[64];
1317 const int packet_len =
1318 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001319 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001321 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322 PacketResult::Success) {
1323 if (response.IsErrorResponse())
1324 return response.GetError();
1325 return 0;
1326 }
1327 }
1328 return -1;
1329}
1330
1331int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1332 size_t data_len) {
1333 StreamString packet;
1334 packet.PutCString("I");
1335 packet.PutBytesAsRawHex8(data, data_len);
1336 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001337 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1338 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339 return 0;
1340 }
1341 return response.GetError();
1342}
1343
1344const lldb_private::ArchSpec &
1345GDBRemoteCommunicationClient::GetHostArchitecture() {
1346 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1347 GetHostInfo();
1348 return m_host_arch;
1349}
1350
Pavel Labath1eff73c2016-11-24 10:54:49 +00001351seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001352 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1353 GetHostInfo();
1354 return m_default_packet_timeout;
1355}
1356
1357addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1358 uint32_t permissions) {
1359 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1360 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1361 char packet[64];
1362 const int packet_len = ::snprintf(
1363 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1364 permissions & lldb::ePermissionsReadable ? "r" : "",
1365 permissions & lldb::ePermissionsWritable ? "w" : "",
1366 permissions & lldb::ePermissionsExecutable ? "x" : "");
1367 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001368 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001369 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001370 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 PacketResult::Success) {
1372 if (response.IsUnsupportedResponse())
1373 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1374 else if (!response.IsErrorResponse())
1375 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1376 } else {
1377 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1378 }
1379 }
1380 return LLDB_INVALID_ADDRESS;
1381}
1382
1383bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1384 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1385 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1386 char packet[64];
1387 const int packet_len =
1388 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1389 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001390 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001391 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001392 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001393 PacketResult::Success) {
1394 if (response.IsUnsupportedResponse())
1395 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1396 else if (response.IsOKResponse())
1397 return true;
1398 } else {
1399 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1400 }
1401 }
1402 return false;
1403}
1404
Zachary Turner97206d52017-05-12 04:51:55 +00001405Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1406 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001407
1408 if (keep_stopped) {
1409 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1410 char packet[64];
1411 const int packet_len =
1412 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1413 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001414 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001415 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001416 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001417 PacketResult::Success &&
1418 response.IsOKResponse()) {
1419 m_supports_detach_stay_stopped = eLazyBoolYes;
1420 } else {
1421 m_supports_detach_stay_stopped = eLazyBoolNo;
1422 }
1423 }
1424
1425 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1426 error.SetErrorString("Stays stopped not supported by this target.");
1427 return error;
1428 } else {
1429 StringExtractorGDBRemote response;
1430 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001431 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432 if (packet_result != PacketResult::Success)
1433 error.SetErrorString("Sending extended disconnect packet failed.");
1434 }
1435 } else {
1436 StringExtractorGDBRemote response;
1437 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001438 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 if (packet_result != PacketResult::Success)
1440 error.SetErrorString("Sending disconnect packet failed.");
1441 }
1442 return error;
1443}
1444
Zachary Turner97206d52017-05-12 04:51:55 +00001445Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001447 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448 region_info.Clear();
1449
1450 if (m_supports_memory_region_info != eLazyBoolNo) {
1451 m_supports_memory_region_info = eLazyBoolYes;
1452 char packet[64];
1453 const int packet_len = ::snprintf(
1454 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1455 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001456 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001457 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001458 if (SendPacketAndWaitForResponse(packet, response, false) ==
Pavel Labath16064d32018-03-20 11:56:24 +00001459 PacketResult::Success &&
1460 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 llvm::StringRef name;
1462 llvm::StringRef value;
1463 addr_t addr_value = LLDB_INVALID_ADDRESS;
1464 bool success = true;
1465 bool saw_permissions = false;
1466 while (success && response.GetNameColonValue(name, value)) {
1467 if (name.equals("start")) {
1468 if (!value.getAsInteger(16, addr_value))
1469 region_info.GetRange().SetRangeBase(addr_value);
1470 } else if (name.equals("size")) {
1471 if (!value.getAsInteger(16, addr_value))
1472 region_info.GetRange().SetByteSize(addr_value);
1473 } else if (name.equals("permissions") &&
1474 region_info.GetRange().IsValid()) {
1475 saw_permissions = true;
1476 if (region_info.GetRange().Contains(addr)) {
1477 if (value.find('r') != llvm::StringRef::npos)
1478 region_info.SetReadable(MemoryRegionInfo::eYes);
1479 else
1480 region_info.SetReadable(MemoryRegionInfo::eNo);
1481
1482 if (value.find('w') != llvm::StringRef::npos)
1483 region_info.SetWritable(MemoryRegionInfo::eYes);
1484 else
1485 region_info.SetWritable(MemoryRegionInfo::eNo);
1486
1487 if (value.find('x') != llvm::StringRef::npos)
1488 region_info.SetExecutable(MemoryRegionInfo::eYes);
1489 else
1490 region_info.SetExecutable(MemoryRegionInfo::eNo);
1491
1492 region_info.SetMapped(MemoryRegionInfo::eYes);
1493 } else {
1494 // The reported region does not contain this address -- we're
1495 // looking at an unmapped page
1496 region_info.SetReadable(MemoryRegionInfo::eNo);
1497 region_info.SetWritable(MemoryRegionInfo::eNo);
1498 region_info.SetExecutable(MemoryRegionInfo::eNo);
1499 region_info.SetMapped(MemoryRegionInfo::eNo);
1500 }
1501 } else if (name.equals("name")) {
1502 StringExtractorGDBRemote name_extractor(value);
1503 std::string name;
1504 name_extractor.GetHexByteString(name);
1505 region_info.SetName(name.c_str());
1506 } else if (name.equals("error")) {
1507 StringExtractorGDBRemote error_extractor(value);
1508 std::string error_string;
1509 // Now convert the HEX bytes into a string value
1510 error_extractor.GetHexByteString(error_string);
1511 error.SetErrorString(error_string.c_str());
1512 }
1513 }
1514
Stephane Sezer48d14272017-03-31 18:00:48 +00001515 if (region_info.GetRange().IsValid()) {
1516 // We got a valid address range back but no permissions -- which means
1517 // this is an unmapped page
1518 if (!saw_permissions) {
1519 region_info.SetReadable(MemoryRegionInfo::eNo);
1520 region_info.SetWritable(MemoryRegionInfo::eNo);
1521 region_info.SetExecutable(MemoryRegionInfo::eNo);
1522 region_info.SetMapped(MemoryRegionInfo::eNo);
1523 }
1524 } else {
1525 // We got an invalid address range back
1526 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001527 }
1528 } else {
1529 m_supports_memory_region_info = eLazyBoolNo;
1530 }
1531 }
1532
1533 if (m_supports_memory_region_info == eLazyBoolNo) {
1534 error.SetErrorString("qMemoryRegionInfo is not supported");
1535 }
Pavel Labath16064d32018-03-20 11:56:24 +00001536
1537 // Try qXfer:memory-map:read to get region information not included in
1538 // qMemoryRegionInfo
1539 MemoryRegionInfo qXfer_region_info;
1540 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1541
1542 if (error.Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001543 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1544 // the qXfer result as a fallback
Pavel Labath16064d32018-03-20 11:56:24 +00001545 if (qXfer_error.Success()) {
1546 region_info = qXfer_region_info;
1547 error.Clear();
1548 } else {
1549 region_info.Clear();
1550 }
1551 } else if (qXfer_error.Success()) {
1552 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
Adrian Prantl05097242018-04-30 16:49:04 +00001553 // both regions are the same range, update the result to include the flash-
1554 // memory information that is specific to the qXfer result.
Pavel Labath16064d32018-03-20 11:56:24 +00001555 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1556 region_info.SetFlash(qXfer_region_info.GetFlash());
1557 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1558 }
1559 }
1560 return error;
1561}
1562
1563Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1564 lldb::addr_t addr, MemoryRegionInfo &region) {
1565 Status error = LoadQXferMemoryMap();
1566 if (!error.Success())
1567 return error;
1568 for (const auto &map_region : m_qXfer_memory_map) {
1569 if (map_region.GetRange().Contains(addr)) {
1570 region = map_region;
1571 return error;
1572 }
1573 }
1574 error.SetErrorString("Region not found");
1575 return error;
1576}
1577
1578Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1579
1580 Status error;
1581
1582 if (m_qXfer_memory_map_loaded)
1583 // Already loaded, return success
1584 return error;
1585
1586 if (!XMLDocument::XMLEnabled()) {
1587 error.SetErrorString("XML is not supported");
1588 return error;
1589 }
1590
1591 if (!GetQXferMemoryMapReadSupported()) {
1592 error.SetErrorString("Memory map is not supported");
1593 return error;
1594 }
1595
1596 std::string xml;
1597 lldb_private::Status lldberr;
1598 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1599 lldberr)) {
1600 error.SetErrorString("Failed to read memory map");
1601 return error;
1602 }
1603
1604 XMLDocument xml_document;
1605
1606 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1607 error.SetErrorString("Failed to parse memory map xml");
1608 return error;
1609 }
1610
1611 XMLNode map_node = xml_document.GetRootElement("memory-map");
1612 if (!map_node) {
1613 error.SetErrorString("Invalid root node in memory map xml");
1614 return error;
1615 }
1616
1617 m_qXfer_memory_map.clear();
1618
1619 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1620 if (!memory_node.IsElement())
1621 return true;
1622 if (memory_node.GetName() != "memory")
1623 return true;
1624 auto type = memory_node.GetAttributeValue("type", "");
1625 uint64_t start;
1626 uint64_t length;
1627 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1628 return true;
1629 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1630 return true;
1631 MemoryRegionInfo region;
1632 region.GetRange().SetRangeBase(start);
1633 region.GetRange().SetByteSize(length);
1634 if (type == "rom") {
1635 region.SetReadable(MemoryRegionInfo::eYes);
1636 this->m_qXfer_memory_map.push_back(region);
1637 } else if (type == "ram") {
1638 region.SetReadable(MemoryRegionInfo::eYes);
1639 region.SetWritable(MemoryRegionInfo::eYes);
1640 this->m_qXfer_memory_map.push_back(region);
1641 } else if (type == "flash") {
1642 region.SetFlash(MemoryRegionInfo::eYes);
1643 memory_node.ForEachChildElement(
1644 [&region](const XMLNode &prop_node) -> bool {
1645 if (!prop_node.IsElement())
1646 return true;
1647 if (prop_node.GetName() != "property")
1648 return true;
1649 auto propname = prop_node.GetAttributeValue("name", "");
1650 if (propname == "blocksize") {
1651 uint64_t blocksize;
1652 if (prop_node.GetElementTextAsUnsigned(blocksize))
1653 region.SetBlocksize(blocksize);
1654 }
1655 return true;
1656 });
1657 this->m_qXfer_memory_map.push_back(region);
1658 }
1659 return true;
1660 });
1661
1662 m_qXfer_memory_map_loaded = true;
1663
Kate Stoneb9c1b512016-09-06 20:57:50 +00001664 return error;
1665}
1666
Zachary Turner97206d52017-05-12 04:51:55 +00001667Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1668 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669
1670 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1671 num = m_num_supported_hardware_watchpoints;
1672 return error;
1673 }
1674
1675 // Set num to 0 first.
1676 num = 0;
1677 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1678 char packet[64];
1679 const int packet_len =
1680 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1681 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001682 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001683 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001684 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685 PacketResult::Success) {
1686 m_supports_watchpoint_support_info = eLazyBoolYes;
1687 llvm::StringRef name;
1688 llvm::StringRef value;
1689 while (response.GetNameColonValue(name, value)) {
1690 if (name.equals("num")) {
1691 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1692 num = m_num_supported_hardware_watchpoints;
1693 }
1694 }
1695 } else {
1696 m_supports_watchpoint_support_info = eLazyBoolNo;
1697 }
1698 }
1699
1700 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1701 error.SetErrorString("qWatchpointSupportInfo is not supported");
1702 }
1703 return error;
1704}
1705
Zachary Turner97206d52017-05-12 04:51:55 +00001706lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001707 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001708 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001709 if (error.Success())
1710 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1711 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001712}
1713
Zachary Turner97206d52017-05-12 04:51:55 +00001714lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1716 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001717 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718 llvm::Triple::ArchType atype = arch.GetMachine();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001719
Adrian Prantl05097242018-04-30 16:49:04 +00001720 // we assume watchpoints will happen after running the relevant opcode and we
1721 // only want to override this behavior if we have explicitly received a
1722 // qHostInfo telling us otherwise
Kate Stoneb9c1b512016-09-06 20:57:50 +00001723 if (m_qHostInfo_is_valid != eLazyBoolYes) {
Pavel Labathc51ad482017-10-27 17:02:32 +00001724 // On targets like MIPS and ppc64le, watchpoint exceptions are always
Adrian Prantl05097242018-04-30 16:49:04 +00001725 // generated before the instruction is executed. The connected target may
1726 // not support qHostInfo or qWatchpointSupportInfo packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001727 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
Pavel Labathc51ad482017-10-27 17:02:32 +00001728 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el ||
1729 atype == llvm::Triple::ppc64le)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 after = false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001731 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 after = true;
1733 } else {
Pavel Labathc51ad482017-10-27 17:02:32 +00001734 // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to
1735 // eLazyBoolNo if it is not calculated before.
1736 if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1737 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1738 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) ||
1739 atype == llvm::Triple::ppc64le) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001740 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
Pavel Labathc51ad482017-10-27 17:02:32 +00001741 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742
1743 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1744 }
1745 return error;
1746}
1747
1748int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1749 if (file_spec) {
1750 std::string path{file_spec.GetPath(false)};
1751 StreamString packet;
1752 packet.PutCString("QSetSTDIN:");
1753 packet.PutCStringAsRawHex8(path.c_str());
1754
1755 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001756 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1757 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 if (response.IsOKResponse())
1759 return 0;
1760 uint8_t error = response.GetError();
1761 if (error)
1762 return error;
1763 }
1764 }
1765 return -1;
1766}
1767
1768int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1769 if (file_spec) {
1770 std::string path{file_spec.GetPath(false)};
1771 StreamString packet;
1772 packet.PutCString("QSetSTDOUT:");
1773 packet.PutCStringAsRawHex8(path.c_str());
1774
1775 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001776 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1777 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001778 if (response.IsOKResponse())
1779 return 0;
1780 uint8_t error = response.GetError();
1781 if (error)
1782 return error;
1783 }
1784 }
1785 return -1;
1786}
1787
1788int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1789 if (file_spec) {
1790 std::string path{file_spec.GetPath(false)};
1791 StreamString packet;
1792 packet.PutCString("QSetSTDERR:");
1793 packet.PutCStringAsRawHex8(path.c_str());
1794
1795 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001796 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1797 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798 if (response.IsOKResponse())
1799 return 0;
1800 uint8_t error = response.GetError();
1801 if (error)
1802 return error;
1803 }
1804 }
1805 return -1;
1806}
1807
1808bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1809 StringExtractorGDBRemote response;
1810 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1811 PacketResult::Success) {
1812 if (response.IsUnsupportedResponse())
1813 return false;
1814 if (response.IsErrorResponse())
1815 return false;
1816 std::string cwd;
1817 response.GetHexByteString(cwd);
Zachary Turner8c6b5462017-03-06 23:42:44 +00001818 working_dir.SetFile(cwd, false, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001819 return !cwd.empty();
1820 }
1821 return false;
1822}
1823
1824int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1825 if (working_dir) {
1826 std::string path{working_dir.GetPath(false)};
1827 StreamString packet;
1828 packet.PutCString("QSetWorkingDir:");
1829 packet.PutCStringAsRawHex8(path.c_str());
1830
1831 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001832 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1833 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001834 if (response.IsOKResponse())
1835 return 0;
1836 uint8_t error = response.GetError();
1837 if (error)
1838 return error;
1839 }
1840 }
1841 return -1;
1842}
1843
1844int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1845 char packet[32];
1846 const int packet_len =
1847 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1848 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001849 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001851 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001852 PacketResult::Success) {
1853 if (response.IsOKResponse())
1854 return 0;
1855 uint8_t error = response.GetError();
1856 if (error)
1857 return error;
1858 }
1859 return -1;
1860}
1861
1862int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1863 char packet[32];
1864 const int packet_len = ::snprintf(packet, sizeof(packet),
1865 "QSetDetachOnError:%i", enable ? 1 : 0);
1866 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001867 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001868 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001869 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001870 PacketResult::Success) {
1871 if (response.IsOKResponse())
1872 return 0;
1873 uint8_t error = response.GetError();
1874 if (error)
1875 return error;
1876 }
1877 return -1;
1878}
1879
1880bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1881 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1882 if (response.IsNormalResponse()) {
1883 llvm::StringRef name;
1884 llvm::StringRef value;
1885 StringExtractor extractor;
1886
1887 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1888 uint32_t sub = 0;
1889 std::string vendor;
1890 std::string os_type;
1891
1892 while (response.GetNameColonValue(name, value)) {
1893 if (name.equals("pid")) {
1894 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1895 value.getAsInteger(0, pid);
1896 process_info.SetProcessID(pid);
1897 } else if (name.equals("ppid")) {
1898 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1899 value.getAsInteger(0, pid);
1900 process_info.SetParentProcessID(pid);
1901 } else if (name.equals("uid")) {
1902 uint32_t uid = UINT32_MAX;
1903 value.getAsInteger(0, uid);
1904 process_info.SetUserID(uid);
1905 } else if (name.equals("euid")) {
1906 uint32_t uid = UINT32_MAX;
1907 value.getAsInteger(0, uid);
1908 process_info.SetEffectiveGroupID(uid);
1909 } else if (name.equals("gid")) {
1910 uint32_t gid = UINT32_MAX;
1911 value.getAsInteger(0, gid);
1912 process_info.SetGroupID(gid);
1913 } else if (name.equals("egid")) {
1914 uint32_t gid = UINT32_MAX;
1915 value.getAsInteger(0, gid);
1916 process_info.SetEffectiveGroupID(gid);
1917 } else if (name.equals("triple")) {
1918 StringExtractor extractor(value);
1919 std::string triple;
1920 extractor.GetHexByteString(triple);
1921 process_info.GetArchitecture().SetTriple(triple.c_str());
1922 } else if (name.equals("name")) {
1923 StringExtractor extractor(value);
Adrian Prantl05097242018-04-30 16:49:04 +00001924 // The process name from ASCII hex bytes since we can't control the
1925 // characters in a process name
Kate Stoneb9c1b512016-09-06 20:57:50 +00001926 std::string name;
1927 extractor.GetHexByteString(name);
Jonas Devlieghere937348c2018-06-13 22:08:14 +00001928 process_info.GetExecutableFile().SetFile(name, false,
1929 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930 } else if (name.equals("cputype")) {
1931 value.getAsInteger(0, cpu);
1932 } else if (name.equals("cpusubtype")) {
1933 value.getAsInteger(0, sub);
1934 } else if (name.equals("vendor")) {
1935 vendor = value;
1936 } else if (name.equals("ostype")) {
1937 os_type = value;
1938 }
1939 }
1940
1941 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1942 if (vendor == "apple") {
1943 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1944 sub);
1945 process_info.GetArchitecture().GetTriple().setVendorName(
1946 llvm::StringRef(vendor));
1947 process_info.GetArchitecture().GetTriple().setOSName(
1948 llvm::StringRef(os_type));
1949 }
1950 }
1951
1952 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1953 return true;
1954 }
1955 return false;
1956}
1957
1958bool GDBRemoteCommunicationClient::GetProcessInfo(
1959 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1960 process_info.Clear();
1961
1962 if (m_supports_qProcessInfoPID) {
1963 char packet[32];
1964 const int packet_len =
1965 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1966 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001967 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001968 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001969 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001970 PacketResult::Success) {
1971 return DecodeProcessInfoResponse(response, process_info);
1972 } else {
1973 m_supports_qProcessInfoPID = false;
1974 return false;
1975 }
1976 }
1977 return false;
1978}
1979
1980bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1981 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1982 GDBR_LOG_PACKETS));
1983
1984 if (allow_lazy) {
1985 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1986 return true;
1987 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1988 return false;
1989 }
1990
1991 GetHostInfo();
1992
1993 StringExtractorGDBRemote response;
1994 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1995 PacketResult::Success) {
1996 if (response.IsNormalResponse()) {
1997 llvm::StringRef name;
1998 llvm::StringRef value;
1999 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2000 uint32_t sub = 0;
2001 std::string arch_name;
2002 std::string os_name;
2003 std::string vendor_name;
2004 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002005 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002006 uint32_t pointer_byte_size = 0;
2007 StringExtractor extractor;
2008 ByteOrder byte_order = eByteOrderInvalid;
2009 uint32_t num_keys_decoded = 0;
2010 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2011 while (response.GetNameColonValue(name, value)) {
2012 if (name.equals("cputype")) {
2013 if (!value.getAsInteger(16, cpu))
2014 ++num_keys_decoded;
2015 } else if (name.equals("cpusubtype")) {
2016 if (!value.getAsInteger(16, sub))
2017 ++num_keys_decoded;
2018 } else if (name.equals("triple")) {
2019 StringExtractor extractor(value);
2020 extractor.GetHexByteString(triple);
2021 ++num_keys_decoded;
2022 } else if (name.equals("ostype")) {
2023 os_name = value;
2024 ++num_keys_decoded;
2025 } else if (name.equals("vendor")) {
2026 vendor_name = value;
2027 ++num_keys_decoded;
2028 } else if (name.equals("endian")) {
2029 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2030 .Case("little", eByteOrderLittle)
2031 .Case("big", eByteOrderBig)
2032 .Case("pdp", eByteOrderPDP)
2033 .Default(eByteOrderInvalid);
2034 if (byte_order != eByteOrderInvalid)
2035 ++num_keys_decoded;
2036 } else if (name.equals("ptrsize")) {
2037 if (!value.getAsInteger(16, pointer_byte_size))
2038 ++num_keys_decoded;
2039 } else if (name.equals("pid")) {
2040 if (!value.getAsInteger(16, pid))
2041 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002042 } else if (name.equals("elf_abi")) {
2043 elf_abi = value;
2044 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002045 }
2046 }
2047 if (num_keys_decoded > 0)
2048 m_qProcessInfo_is_valid = eLazyBoolYes;
2049 if (pid != LLDB_INVALID_PROCESS_ID) {
2050 m_curr_pid_is_valid = eLazyBoolYes;
2051 m_curr_pid = pid;
2052 }
2053
2054 // Set the ArchSpec from the triple if we have it.
2055 if (!triple.empty()) {
2056 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00002057 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002058 if (pointer_byte_size) {
2059 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2060 }
2061 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2062 !vendor_name.empty()) {
2063 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2064
2065 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00002066 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002067 switch (triple.getObjectFormat()) {
2068 case llvm::Triple::MachO:
2069 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2070 break;
2071 case llvm::Triple::ELF:
2072 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2073 break;
2074 case llvm::Triple::COFF:
2075 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2076 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00002077 case llvm::Triple::Wasm:
2078 if (log)
2079 log->Printf("error: not supported target architecture");
2080 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081 case llvm::Triple::UnknownObjectFormat:
2082 if (log)
2083 log->Printf("error: failed to determine target architecture");
2084 return false;
2085 }
2086
2087 if (pointer_byte_size) {
2088 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2089 }
2090 if (byte_order != eByteOrderInvalid) {
2091 assert(byte_order == m_process_arch.GetByteOrder());
2092 }
2093 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2094 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2095 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2096 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2097 }
2098 return true;
2099 }
2100 } else {
2101 m_qProcessInfo_is_valid = eLazyBoolNo;
2102 }
2103
2104 return false;
2105}
2106
2107uint32_t GDBRemoteCommunicationClient::FindProcesses(
2108 const ProcessInstanceInfoMatch &match_info,
2109 ProcessInstanceInfoList &process_infos) {
2110 process_infos.Clear();
2111
2112 if (m_supports_qfProcessInfo) {
2113 StreamString packet;
2114 packet.PutCString("qfProcessInfo");
2115 if (!match_info.MatchAllProcesses()) {
2116 packet.PutChar(':');
2117 const char *name = match_info.GetProcessInfo().GetName();
2118 bool has_name_match = false;
2119 if (name && name[0]) {
2120 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00002121 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002122 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00002123 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002124 has_name_match = false;
2125 break;
2126
Pavel Labathc4a33952017-02-20 11:35:33 +00002127 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 packet.PutCString("name_match:equals;");
2129 break;
2130
Pavel Labathc4a33952017-02-20 11:35:33 +00002131 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132 packet.PutCString("name_match:contains;");
2133 break;
2134
Pavel Labathc4a33952017-02-20 11:35:33 +00002135 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002136 packet.PutCString("name_match:starts_with;");
2137 break;
2138
Pavel Labathc4a33952017-02-20 11:35:33 +00002139 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002140 packet.PutCString("name_match:ends_with;");
2141 break;
2142
Pavel Labathc4a33952017-02-20 11:35:33 +00002143 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002144 packet.PutCString("name_match:regex;");
2145 break;
2146 }
2147 if (has_name_match) {
2148 packet.PutCString("name:");
2149 packet.PutBytesAsRawHex8(name, ::strlen(name));
2150 packet.PutChar(';');
2151 }
2152 }
2153
2154 if (match_info.GetProcessInfo().ProcessIDIsValid())
2155 packet.Printf("pid:%" PRIu64 ";",
2156 match_info.GetProcessInfo().GetProcessID());
2157 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2158 packet.Printf("parent_pid:%" PRIu64 ";",
2159 match_info.GetProcessInfo().GetParentProcessID());
2160 if (match_info.GetProcessInfo().UserIDIsValid())
2161 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2162 if (match_info.GetProcessInfo().GroupIDIsValid())
2163 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2164 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2165 packet.Printf("euid:%u;",
2166 match_info.GetProcessInfo().GetEffectiveUserID());
2167 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2168 packet.Printf("egid:%u;",
2169 match_info.GetProcessInfo().GetEffectiveGroupID());
2170 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2171 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2172 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2173 const ArchSpec &match_arch =
2174 match_info.GetProcessInfo().GetArchitecture();
2175 const llvm::Triple &triple = match_arch.GetTriple();
2176 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002177 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002178 packet.PutChar(';');
2179 }
2180 }
2181 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +00002182 // Increase timeout as the first qfProcessInfo packet takes a long time on
2183 // Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002184 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002185 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2186 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002187 do {
2188 ProcessInstanceInfo process_info;
2189 if (!DecodeProcessInfoResponse(response, process_info))
2190 break;
2191 process_infos.Append(process_info);
2192 response.GetStringRef().clear();
2193 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002194 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2195 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196 } else {
2197 m_supports_qfProcessInfo = false;
2198 return 0;
2199 }
2200 }
2201 return process_infos.GetSize();
2202}
2203
2204bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2205 std::string &name) {
2206 if (m_supports_qUserName) {
2207 char packet[32];
2208 const int packet_len =
2209 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2210 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002211 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002212 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002213 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214 PacketResult::Success) {
2215 if (response.IsNormalResponse()) {
2216 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002217 // the hex encoded user name and should make up the entire packet. If
2218 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002219 if (response.GetHexByteString(name) * 2 ==
2220 response.GetStringRef().size())
2221 return true;
2222 }
2223 } else {
2224 m_supports_qUserName = false;
2225 return false;
2226 }
2227 }
2228 return false;
2229}
2230
2231bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2232 std::string &name) {
2233 if (m_supports_qGroupName) {
2234 char packet[32];
2235 const int packet_len =
2236 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2237 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002238 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002239 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002240 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002241 PacketResult::Success) {
2242 if (response.IsNormalResponse()) {
2243 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002244 // the hex encoded group name and should make up the entire packet. If
2245 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 if (response.GetHexByteString(name) * 2 ==
2247 response.GetStringRef().size())
2248 return true;
2249 }
2250 } else {
2251 m_supports_qGroupName = false;
2252 return false;
2253 }
2254 }
2255 return false;
2256}
2257
2258bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2259 // Form non-stop packet request
2260 char packet[32];
2261 const int packet_len =
2262 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2263 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002264 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265
2266 StringExtractorGDBRemote response;
2267 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002268 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002269 PacketResult::Success)
2270 if (response.IsOKResponse())
2271 return true;
2272
2273 // Failed or not supported
2274 return false;
2275}
2276
2277static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2278 uint32_t recv_size) {
2279 packet.Clear();
2280 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2281 uint32_t bytes_left = send_size;
2282 while (bytes_left > 0) {
2283 if (bytes_left >= 26) {
2284 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2285 bytes_left -= 26;
2286 } else {
2287 packet.Printf("%*.*s;", bytes_left, bytes_left,
2288 "abcdefghijklmnopqrstuvwxyz");
2289 bytes_left = 0;
2290 }
2291 }
2292}
2293
Pavel Labath1eff73c2016-11-24 10:54:49 +00002294duration<float>
2295calculate_standard_deviation(const std::vector<duration<float>> &v) {
2296 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002297 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2298 Dur mean = sum / v.size();
2299 float accum = 0;
2300 for (auto d : v) {
2301 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002303 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002304
Pavel Labath3aa04912016-10-31 17:19:42 +00002305 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002306}
2307
2308void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2309 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002310 uint32_t max_recv,
2311 uint64_t recv_amount,
2312 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002313 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002314 if (SendSpeedTestPacket(0, 0)) {
2315 StreamString packet;
2316 if (json)
2317 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2318 "\"results\" : [",
2319 num_packets);
2320 else
2321 strm.Printf("Testing sending %u packets of various sizes:\n",
2322 num_packets);
2323 strm.Flush();
2324
2325 uint32_t result_idx = 0;
2326 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002327 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002328
2329 for (send_size = 0; send_size <= max_send;
2330 send_size ? send_size *= 2 : send_size = 4) {
2331 for (uint32_t recv_size = 0; recv_size <= max_recv;
2332 recv_size ? recv_size *= 2 : recv_size = 4) {
2333 MakeSpeedTestPacket(packet, send_size, recv_size);
2334
2335 packet_times.clear();
2336 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002337 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002338 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002339 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002340 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002341 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002342 const auto packet_end_time = steady_clock::now();
2343 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002345 const auto end_time = steady_clock::now();
2346 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002347
2348 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002349 ((float)num_packets) / duration<float>(total_time).count();
2350 auto average_per_packet = total_time / num_packets;
2351 const duration<float> standard_deviation =
2352 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002353 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002354 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2355 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2356 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002358 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359 ++result_idx;
2360 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002361 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2362 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2363 "standard deviation of {5,10:ms+f6}\n",
2364 send_size, recv_size, duration<float>(total_time),
2365 packets_per_second, duration<float>(average_per_packet),
2366 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002367 }
2368 strm.Flush();
2369 }
2370 }
2371
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002372 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002373 if (json)
2374 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2375 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002376 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002377 else
2378 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2379 "packet sizes:\n",
2380 k_recv_amount_mb);
2381 strm.Flush();
2382 send_size = 0;
2383 result_idx = 0;
2384 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2385 MakeSpeedTestPacket(packet, send_size, recv_size);
2386
2387 // If we have a receive size, test how long it takes to receive 4MB of
2388 // data
2389 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002390 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002391 uint32_t bytes_read = 0;
2392 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002393 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002394 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002395 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396 bytes_read += recv_size;
2397 ++packet_count;
2398 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002399 const auto end_time = steady_clock::now();
2400 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002401 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002402 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 (1024.0 * 1024.0);
2404 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002405 ((float)packet_count) / duration<float>(total_time).count();
2406 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407
2408 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002409 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2410 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002411 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002412 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002413 ++result_idx;
2414 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002415 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2416 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2417 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002419 duration<float>(total_time), mb_second,
2420 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002421 }
2422 strm.Flush();
2423 }
2424 }
2425 if (json)
2426 strm.Printf("\n ]\n }\n}\n");
2427 else
2428 strm.EOL();
2429 }
2430}
2431
2432bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2433 uint32_t recv_size) {
2434 StreamString packet;
2435 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2436 uint32_t bytes_left = send_size;
2437 while (bytes_left > 0) {
2438 if (bytes_left >= 26) {
2439 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2440 bytes_left -= 26;
2441 } else {
2442 packet.Printf("%*.*s;", bytes_left, bytes_left,
2443 "abcdefghijklmnopqrstuvwxyz");
2444 bytes_left = 0;
2445 }
2446 }
2447
2448 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002449 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2450 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002451}
2452
2453bool GDBRemoteCommunicationClient::LaunchGDBServer(
2454 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2455 std::string &socket_name) {
2456 pid = LLDB_INVALID_PROCESS_ID;
2457 port = 0;
2458 socket_name.clear();
2459
2460 StringExtractorGDBRemote response;
2461 StreamString stream;
2462 stream.PutCString("qLaunchGDBServer;");
2463 std::string hostname;
2464 if (remote_accept_hostname && remote_accept_hostname[0])
2465 hostname = remote_accept_hostname;
2466 else {
2467 if (HostInfo::GetHostname(hostname)) {
2468 // Make the GDB server we launch only accept connections from this host
2469 stream.Printf("host:%s;", hostname.c_str());
2470 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002471 // Make the GDB server we launch accept connections from any host since
2472 // we can't figure out the hostname
Kate Stoneb9c1b512016-09-06 20:57:50 +00002473 stream.Printf("host:*;");
2474 }
2475 }
2476 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002477 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478
2479 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2480 PacketResult::Success) {
2481 llvm::StringRef name;
2482 llvm::StringRef value;
2483 while (response.GetNameColonValue(name, value)) {
2484 if (name.equals("port"))
2485 value.getAsInteger(0, port);
2486 else if (name.equals("pid"))
2487 value.getAsInteger(0, pid);
2488 else if (name.compare("socket_name") == 0) {
2489 StringExtractor extractor(value);
2490 extractor.GetHexByteString(socket_name);
2491 }
2492 }
2493 return true;
2494 }
2495 return false;
2496}
2497
2498size_t GDBRemoteCommunicationClient::QueryGDBServer(
2499 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2500 connection_urls.clear();
2501
2502 StringExtractorGDBRemote response;
2503 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2504 PacketResult::Success)
2505 return 0;
2506
2507 StructuredData::ObjectSP data =
2508 StructuredData::ParseJSON(response.GetStringRef());
2509 if (!data)
2510 return 0;
2511
2512 StructuredData::Array *array = data->GetAsArray();
2513 if (!array)
2514 return 0;
2515
2516 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2517 StructuredData::Dictionary *element = nullptr;
2518 if (!array->GetItemAtIndexAsDictionary(i, element))
2519 continue;
2520
2521 uint16_t port = 0;
2522 if (StructuredData::ObjectSP port_osp =
2523 element->GetValueForKey(llvm::StringRef("port")))
2524 port = port_osp->GetIntegerValue(0);
2525
2526 std::string socket_name;
2527 if (StructuredData::ObjectSP socket_name_osp =
2528 element->GetValueForKey(llvm::StringRef("socket_name")))
2529 socket_name = socket_name_osp->GetStringValue();
2530
2531 if (port != 0 || !socket_name.empty())
2532 connection_urls.emplace_back(port, socket_name);
2533 }
2534 return connection_urls.size();
2535}
2536
2537bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2538 StreamString stream;
2539 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002540
2541 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002542 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543 PacketResult::Success) {
2544 if (response.IsOKResponse())
2545 return true;
2546 }
2547 return false;
2548}
2549
2550bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2551 if (m_curr_tid == tid)
2552 return true;
2553
2554 char packet[32];
2555 int packet_len;
2556 if (tid == UINT64_MAX)
2557 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2558 else
2559 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2560 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002561 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002562 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002563 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002564 PacketResult::Success) {
2565 if (response.IsOKResponse()) {
2566 m_curr_tid = tid;
2567 return true;
2568 }
2569
2570 /*
2571 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2572 * Hg packet.
2573 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2574 * which can
2575 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2576 */
2577 if (response.IsUnsupportedResponse() && IsConnected()) {
2578 m_curr_tid = 1;
2579 return true;
2580 }
2581 }
2582 return false;
2583}
2584
2585bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2586 if (m_curr_tid_run == tid)
2587 return true;
2588
2589 char packet[32];
2590 int packet_len;
2591 if (tid == UINT64_MAX)
2592 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2593 else
2594 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2595
2596 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002597 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002598 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002599 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002600 PacketResult::Success) {
2601 if (response.IsOKResponse()) {
2602 m_curr_tid_run = tid;
2603 return true;
2604 }
2605
2606 /*
2607 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2608 * Hc packet.
2609 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2610 * which can
2611 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2612 */
2613 if (response.IsUnsupportedResponse() && IsConnected()) {
2614 m_curr_tid_run = 1;
2615 return true;
2616 }
2617 }
2618 return false;
2619}
2620
2621bool GDBRemoteCommunicationClient::GetStopReply(
2622 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002623 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002624 PacketResult::Success)
2625 return response.IsNormalResponse();
2626 return false;
2627}
2628
2629bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2630 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2631 if (m_supports_qThreadStopInfo) {
2632 char packet[256];
2633 int packet_len =
2634 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2635 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002636 UNUSED_IF_ASSERT_DISABLED(packet_len);
2637 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002638 PacketResult::Success) {
2639 if (response.IsUnsupportedResponse())
2640 m_supports_qThreadStopInfo = false;
2641 else if (response.IsNormalResponse())
2642 return true;
2643 else
2644 return false;
2645 } else {
2646 m_supports_qThreadStopInfo = false;
2647 }
2648 }
2649 return false;
2650}
2651
2652uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2653 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2654 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2655 if (log)
2656 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2657 __FUNCTION__, insert ? "add" : "remove", addr);
2658
2659 // Check if the stub is known not to support this breakpoint type
2660 if (!SupportsGDBStoppointPacket(type))
2661 return UINT8_MAX;
2662 // Construct the breakpoint packet
2663 char packet[64];
2664 const int packet_len =
2665 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2666 insert ? 'Z' : 'z', type, addr, length);
2667 // Check we haven't overwritten the end of the packet buffer
2668 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002669 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002670 StringExtractorGDBRemote response;
2671 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2672 // or "" (unsupported)
2673 response.SetResponseValidatorToOKErrorNotSupported();
2674 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002675 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002676 PacketResult::Success) {
2677 // Receive and OK packet when the breakpoint successfully placed
2678 if (response.IsOKResponse())
2679 return 0;
2680
Zachary Turner97206d52017-05-12 04:51:55 +00002681 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002682 if (response.IsErrorResponse())
2683 return response.GetError();
2684
2685 // Empty packet informs us that breakpoint is not supported
2686 if (response.IsUnsupportedResponse()) {
2687 // Disable this breakpoint type since it is unsupported
2688 switch (type) {
2689 case eBreakpointSoftware:
2690 m_supports_z0 = false;
2691 break;
2692 case eBreakpointHardware:
2693 m_supports_z1 = false;
2694 break;
2695 case eWatchpointWrite:
2696 m_supports_z2 = false;
2697 break;
2698 case eWatchpointRead:
2699 m_supports_z3 = false;
2700 break;
2701 case eWatchpointReadWrite:
2702 m_supports_z4 = false;
2703 break;
2704 case eStoppointInvalid:
2705 return UINT8_MAX;
2706 }
2707 }
2708 }
2709 // Signal generic failure
2710 return UINT8_MAX;
2711}
2712
2713size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2714 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2715 thread_ids.clear();
2716
2717 Lock lock(*this, false);
2718 if (lock) {
2719 sequence_mutex_unavailable = false;
2720 StringExtractorGDBRemote response;
2721
2722 PacketResult packet_result;
2723 for (packet_result =
2724 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2725 packet_result == PacketResult::Success && response.IsNormalResponse();
2726 packet_result =
2727 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2728 char ch = response.GetChar();
2729 if (ch == 'l')
2730 break;
2731 if (ch == 'm') {
2732 do {
2733 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2734
2735 if (tid != LLDB_INVALID_THREAD_ID) {
2736 thread_ids.push_back(tid);
2737 }
2738 ch = response.GetChar(); // Skip the command separator
2739 } while (ch == ','); // Make sure we got a comma separator
2740 }
2741 }
2742
2743 /*
2744 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2745 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2746 * could
2747 * be as simple as 'S05'. There is no packet which can give us pid and/or
2748 * tid.
2749 * Assume pid=tid=1 in such cases.
2750 */
Tamas Berghammer1492cb82017-09-18 10:24:48 +00002751 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2752 thread_ids.size() == 0 && IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002753 thread_ids.push_back(1);
2754 }
2755 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002756#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2758 GDBR_LOG_PACKETS));
2759 if (log)
2760 log->Printf("error: failed to get packet sequence mutex, not sending "
2761 "packet 'qfThreadInfo'");
2762#endif
2763 sequence_mutex_unavailable = true;
2764 }
2765 return thread_ids.size();
2766}
2767
2768lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2769 StringExtractorGDBRemote response;
2770 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2771 PacketResult::Success ||
2772 !response.IsNormalResponse())
2773 return LLDB_INVALID_ADDRESS;
2774 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2775}
2776
Zachary Turner97206d52017-05-12 04:51:55 +00002777lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002778 const char *command, // Shouldn't be NULL
2779 const FileSpec &
2780 working_dir, // Pass empty FileSpec to use the current working directory
2781 int *status_ptr, // Pass NULL if you don't want the process exit status
2782 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2783 // process to exit
2784 std::string
2785 *command_output, // Pass NULL if you don't want the command output
Pavel Labath19dd1a02018-05-10 10:46:03 +00002786 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002787 lldb_private::StreamString stream;
2788 stream.PutCString("qPlatform_shell:");
2789 stream.PutBytesAsRawHex8(command, strlen(command));
2790 stream.PutChar(',');
Pavel Labath19dd1a02018-05-10 10:46:03 +00002791 uint32_t timeout_sec = UINT32_MAX;
2792 if (timeout) {
2793 // TODO: Use chrono version of std::ceil once c++17 is available.
2794 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2795 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002796 stream.PutHex32(timeout_sec);
2797 if (working_dir) {
2798 std::string path{working_dir.GetPath(false)};
2799 stream.PutChar(',');
2800 stream.PutCStringAsRawHex8(path.c_str());
2801 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002802 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002803 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 PacketResult::Success) {
2805 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002806 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002808 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2810 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002811 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 else if (status_ptr)
2813 *status_ptr = exitcode;
2814 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002815 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002816 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2817 if (signo_ptr)
2818 *signo_ptr = signo;
2819 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002820 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 std::string output;
2822 response.GetEscapedBinaryData(output);
2823 if (command_output)
2824 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002825 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 }
Zachary Turner97206d52017-05-12 04:51:55 +00002827 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828}
2829
Zachary Turner97206d52017-05-12 04:51:55 +00002830Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2831 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002832 std::string path{file_spec.GetPath(false)};
2833 lldb_private::StreamString stream;
2834 stream.PutCString("qPlatform_mkdir:");
2835 stream.PutHex32(file_permissions);
2836 stream.PutChar(',');
2837 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002838 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002839 StringExtractorGDBRemote response;
2840
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002841 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002842 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002843 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002844
2845 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002846 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847
Zachary Turner97206d52017-05-12 04:51:55 +00002848 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002849}
2850
Zachary Turner97206d52017-05-12 04:51:55 +00002851Status
2852GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2853 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854 std::string path{file_spec.GetPath(false)};
2855 lldb_private::StreamString stream;
2856 stream.PutCString("qPlatform_chmod:");
2857 stream.PutHex32(file_permissions);
2858 stream.PutChar(',');
2859 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002860 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002861 StringExtractorGDBRemote response;
2862
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002863 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002865 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866
2867 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002868 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002869
Zachary Turner97206d52017-05-12 04:51:55 +00002870 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002871}
2872
2873static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002874 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875 response.SetFilePos(0);
2876 if (response.GetChar() != 'F')
2877 return fail_result;
2878 int32_t result = response.GetS32(-2);
2879 if (result == -2)
2880 return fail_result;
2881 if (response.GetChar() == ',') {
2882 int result_errno = response.GetS32(-2);
2883 if (result_errno != -2)
2884 error.SetError(result_errno, eErrorTypePOSIX);
2885 else
2886 error.SetError(-1, eErrorTypeGeneric);
2887 } else
2888 error.Clear();
2889 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002890}
2891lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002892GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2893 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002894 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 std::string path(file_spec.GetPath(false));
2896 lldb_private::StreamString stream;
2897 stream.PutCString("vFile:open:");
2898 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002899 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002900 stream.PutCStringAsRawHex8(path.c_str());
2901 stream.PutChar(',');
2902 stream.PutHex32(flags);
2903 stream.PutChar(',');
2904 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002906 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002907 PacketResult::Success) {
2908 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2909 }
2910 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002911}
2912
Zachary Turner97206d52017-05-12 04:51:55 +00002913bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2914 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002915 lldb_private::StreamString stream;
2916 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002917 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002918 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002919 PacketResult::Success) {
2920 return ParseHostIOPacketResponse(response, -1, error) == 0;
2921 }
2922 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002923}
2924
2925// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002926lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2927 const lldb_private::FileSpec &file_spec) {
2928 std::string path(file_spec.GetPath(false));
2929 lldb_private::StreamString stream;
2930 stream.PutCString("vFile:size:");
2931 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002932 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002933 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002934 PacketResult::Success) {
2935 if (response.GetChar() != 'F')
2936 return UINT64_MAX;
2937 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2938 return retcode;
2939 }
2940 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002941}
2942
Zachary Turner97206d52017-05-12 04:51:55 +00002943Status
2944GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2945 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002946 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002947 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 lldb_private::StreamString stream;
2949 stream.PutCString("vFile:mode:");
2950 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002952 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002953 PacketResult::Success) {
2954 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002955 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002956 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957 } else {
2958 const uint32_t mode = response.GetS32(-1);
2959 if (static_cast<int32_t>(mode) == -1) {
2960 if (response.GetChar() == ',') {
2961 int response_errno = response.GetS32(-1);
2962 if (response_errno > 0)
2963 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2964 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002965 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002966 } else
2967 error.SetErrorToGenericError();
2968 } else {
2969 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2970 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002971 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002972 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002973 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002974 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 }
2976 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002977}
2978
Kate Stoneb9c1b512016-09-06 20:57:50 +00002979uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2980 uint64_t offset, void *dst,
2981 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002982 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983 lldb_private::StreamString stream;
2984 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2985 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002986 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002987 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002988 PacketResult::Success) {
2989 if (response.GetChar() != 'F')
2990 return 0;
2991 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2992 if (retcode == UINT32_MAX)
2993 return retcode;
2994 const char next = (response.Peek() ? *response.Peek() : 0);
2995 if (next == ',')
2996 return 0;
2997 if (next == ';') {
2998 response.GetChar(); // skip the semicolon
2999 std::string buffer;
3000 if (response.GetEscapedBinaryData(buffer)) {
3001 const uint64_t data_to_write =
3002 std::min<uint64_t>(dst_len, buffer.size());
3003 if (data_to_write > 0)
3004 memcpy(dst, &buffer[0], data_to_write);
3005 return data_to_write;
3006 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003007 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003008 }
3009 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003010}
3011
Kate Stoneb9c1b512016-09-06 20:57:50 +00003012uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3013 uint64_t offset,
3014 const void *src,
3015 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003016 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003017 lldb_private::StreamGDBRemote stream;
3018 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3019 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003020 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003021 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003022 PacketResult::Success) {
3023 if (response.GetChar() != 'F') {
3024 error.SetErrorStringWithFormat("write file failed");
3025 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003026 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003027 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3028 if (bytes_written == UINT64_MAX) {
3029 error.SetErrorToGenericError();
3030 if (response.GetChar() == ',') {
3031 int response_errno = response.GetS32(-1);
3032 if (response_errno > 0)
3033 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3034 }
3035 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003036 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 return bytes_written;
3038 } else {
3039 error.SetErrorString("failed to send vFile:pwrite packet");
3040 }
3041 return 0;
3042}
3043
Zachary Turner97206d52017-05-12 04:51:55 +00003044Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3045 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003047 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 lldb_private::StreamGDBRemote stream;
3049 stream.PutCString("vFile:symlink:");
3050 // the unix symlink() command reverses its parameters where the dst if first,
3051 // so we follow suit here
3052 stream.PutCStringAsRawHex8(dst_path.c_str());
3053 stream.PutChar(',');
3054 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003055 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003056 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003057 PacketResult::Success) {
3058 if (response.GetChar() == 'F') {
3059 uint32_t result = response.GetU32(UINT32_MAX);
3060 if (result != 0) {
3061 error.SetErrorToGenericError();
3062 if (response.GetChar() == ',') {
3063 int response_errno = response.GetS32(-1);
3064 if (response_errno > 0)
3065 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3066 }
3067 }
3068 } else {
3069 // Should have returned with 'F<result>[,<errno>]'
3070 error.SetErrorStringWithFormat("symlink failed");
3071 }
3072 } else {
3073 error.SetErrorString("failed to send vFile:symlink packet");
3074 }
3075 return error;
3076}
3077
Zachary Turner97206d52017-05-12 04:51:55 +00003078Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003079 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003080 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003081 lldb_private::StreamGDBRemote stream;
3082 stream.PutCString("vFile:unlink:");
3083 // the unix symlink() command reverses its parameters where the dst if first,
3084 // so we follow suit here
3085 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003087 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003088 PacketResult::Success) {
3089 if (response.GetChar() == 'F') {
3090 uint32_t result = response.GetU32(UINT32_MAX);
3091 if (result != 0) {
3092 error.SetErrorToGenericError();
3093 if (response.GetChar() == ',') {
3094 int response_errno = response.GetS32(-1);
3095 if (response_errno > 0)
3096 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3097 }
3098 }
3099 } else {
3100 // Should have returned with 'F<result>[,<errno>]'
3101 error.SetErrorStringWithFormat("unlink failed");
3102 }
3103 } else {
3104 error.SetErrorString("failed to send vFile:unlink packet");
3105 }
3106 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00003107}
3108
Daniel Maleae0f8f572013-08-26 23:57:52 +00003109// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110bool GDBRemoteCommunicationClient::GetFileExists(
3111 const lldb_private::FileSpec &file_spec) {
3112 std::string path(file_spec.GetPath(false));
3113 lldb_private::StreamString stream;
3114 stream.PutCString("vFile:exists:");
3115 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003116 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003117 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003118 PacketResult::Success) {
3119 if (response.GetChar() != 'F')
3120 return false;
3121 if (response.GetChar() != ',')
3122 return false;
3123 bool retcode = (response.GetChar() != '0');
3124 return retcode;
3125 }
3126 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003127}
3128
Kate Stoneb9c1b512016-09-06 20:57:50 +00003129bool GDBRemoteCommunicationClient::CalculateMD5(
3130 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3131 std::string path(file_spec.GetPath(false));
3132 lldb_private::StreamString stream;
3133 stream.PutCString("vFile:MD5:");
3134 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003136 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003137 PacketResult::Success) {
3138 if (response.GetChar() != 'F')
3139 return false;
3140 if (response.GetChar() != ',')
3141 return false;
3142 if (response.Peek() && *response.Peek() == 'x')
3143 return false;
3144 low = response.GetHexMaxU64(false, UINT64_MAX);
3145 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003146 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003147 }
3148 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003149}
3150
Kate Stoneb9c1b512016-09-06 20:57:50 +00003151bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3152 // Some targets have issues with g/G packets and we need to avoid using them
3153 if (m_avoid_g_packets == eLazyBoolCalculate) {
3154 if (process) {
3155 m_avoid_g_packets = eLazyBoolNo;
3156 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3157 if (arch.IsValid() &&
3158 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3159 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3160 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3161 m_avoid_g_packets = eLazyBoolYes;
3162 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3163 if (gdb_server_version != 0) {
3164 const char *gdb_server_name = GetGDBServerProgramName();
3165 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3166 if (gdb_server_version >= 310)
3167 m_avoid_g_packets = eLazyBoolNo;
3168 }
3169 }
3170 }
3171 }
3172 }
3173 return m_avoid_g_packets == eLazyBoolYes;
3174}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003175
Kate Stoneb9c1b512016-09-06 20:57:50 +00003176DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3177 uint32_t reg) {
3178 StreamString payload;
3179 payload.Printf("p%x", reg);
3180 StringExtractorGDBRemote response;
3181 if (SendThreadSpecificPacketAndWaitForResponse(
3182 tid, std::move(payload), response, false) != PacketResult::Success ||
3183 !response.IsNormalResponse())
3184 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003185
Kate Stoneb9c1b512016-09-06 20:57:50 +00003186 DataBufferSP buffer_sp(
3187 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3188 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3189 return buffer_sp;
3190}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003191
Kate Stoneb9c1b512016-09-06 20:57:50 +00003192DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3193 StreamString payload;
3194 payload.PutChar('g');
3195 StringExtractorGDBRemote response;
3196 if (SendThreadSpecificPacketAndWaitForResponse(
3197 tid, std::move(payload), response, false) != PacketResult::Success ||
3198 !response.IsNormalResponse())
3199 return nullptr;
3200
3201 DataBufferSP buffer_sp(
3202 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3203 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3204 return buffer_sp;
3205}
3206
3207bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3208 uint32_t reg_num,
3209 llvm::ArrayRef<uint8_t> data) {
3210 StreamString payload;
3211 payload.Printf("P%x=", reg_num);
3212 payload.PutBytesAsRawHex8(data.data(), data.size(),
3213 endian::InlHostByteOrder(),
3214 endian::InlHostByteOrder());
3215 StringExtractorGDBRemote response;
3216 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3217 response, false) ==
3218 PacketResult::Success &&
3219 response.IsOKResponse();
3220}
3221
3222bool GDBRemoteCommunicationClient::WriteAllRegisters(
3223 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3224 StreamString payload;
3225 payload.PutChar('G');
3226 payload.PutBytesAsRawHex8(data.data(), data.size(),
3227 endian::InlHostByteOrder(),
3228 endian::InlHostByteOrder());
3229 StringExtractorGDBRemote response;
3230 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3231 response, false) ==
3232 PacketResult::Success &&
3233 response.IsOKResponse();
3234}
3235
3236bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3237 uint32_t &save_id) {
3238 save_id = 0; // Set to invalid save ID
3239 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003240 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003241
3242 m_supports_QSaveRegisterState = eLazyBoolYes;
3243 StreamString payload;
3244 payload.PutCString("QSaveRegisterState");
3245 StringExtractorGDBRemote response;
3246 if (SendThreadSpecificPacketAndWaitForResponse(
3247 tid, std::move(payload), response, false) != PacketResult::Success)
3248 return false;
3249
3250 if (response.IsUnsupportedResponse())
3251 m_supports_QSaveRegisterState = eLazyBoolNo;
3252
3253 const uint32_t response_save_id = response.GetU32(0);
3254 if (response_save_id == 0)
3255 return false;
3256
3257 save_id = response_save_id;
3258 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003259}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003260
Kate Stoneb9c1b512016-09-06 20:57:50 +00003261bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3262 uint32_t save_id) {
3263 // We use the "m_supports_QSaveRegisterState" variable here because the
Adrian Prantl05097242018-04-30 16:49:04 +00003264 // QSaveRegisterState and QRestoreRegisterState packets must both be
3265 // supported in order to be useful
Kate Stoneb9c1b512016-09-06 20:57:50 +00003266 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3267 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003268
Kate Stoneb9c1b512016-09-06 20:57:50 +00003269 StreamString payload;
3270 payload.Printf("QRestoreRegisterState:%u", save_id);
3271 StringExtractorGDBRemote response;
3272 if (SendThreadSpecificPacketAndWaitForResponse(
3273 tid, std::move(payload), response, false) != PacketResult::Success)
3274 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003275
Kate Stoneb9c1b512016-09-06 20:57:50 +00003276 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003277 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003278
3279 if (response.IsUnsupportedResponse())
3280 m_supports_QSaveRegisterState = eLazyBoolNo;
3281 return false;
3282}
3283
3284bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3285 if (!GetSyncThreadStateSupported())
3286 return false;
3287
3288 StreamString packet;
3289 StringExtractorGDBRemote response;
3290 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3291 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3292 GDBRemoteCommunication::PacketResult::Success &&
3293 response.IsOKResponse();
3294}
3295
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003296lldb::user_id_t
3297GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3298 Status &error) {
3299 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3300 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3301
3302 StreamGDBRemote escaped_packet;
3303 escaped_packet.PutCString("jTraceStart:");
3304
3305 StructuredData::Dictionary json_packet;
3306 json_packet.AddIntegerItem("type", options.getType());
3307 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3308 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3309
3310 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3311 json_packet.AddIntegerItem("threadid", options.getThreadID());
3312
3313 StructuredData::DictionarySP custom_params = options.getTraceParams();
3314 if (custom_params)
3315 json_packet.AddItem("params", custom_params);
3316
3317 StreamString json_string;
3318 json_packet.Dump(json_string, false);
3319 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3320
3321 StringExtractorGDBRemote response;
3322 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3323 true) ==
3324 GDBRemoteCommunication::PacketResult::Success) {
3325 if (!response.IsNormalResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003326 error = response.GetStatus();
3327 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003328 } else {
3329 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3330 }
3331 } else {
3332 LLDB_LOG(log, "failed to send packet");
3333 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3334 escaped_packet.GetData());
3335 }
3336 return ret_uid;
3337}
3338
3339Status
3340GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3341 lldb::tid_t thread_id) {
3342 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3343 StringExtractorGDBRemote response;
3344 Status error;
3345
3346 StructuredData::Dictionary json_packet;
3347 StreamGDBRemote escaped_packet;
3348 StreamString json_string;
3349 escaped_packet.PutCString("jTraceStop:");
3350
3351 json_packet.AddIntegerItem("traceid", uid);
3352
3353 if (thread_id != LLDB_INVALID_THREAD_ID)
3354 json_packet.AddIntegerItem("threadid", thread_id);
3355
3356 json_packet.Dump(json_string, false);
3357
3358 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3359
3360 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3361 true) ==
3362 GDBRemoteCommunication::PacketResult::Success) {
3363 if (!response.IsOKResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003364 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003365 LLDB_LOG(log, "stop tracing failed");
3366 }
3367 } else {
3368 LLDB_LOG(log, "failed to send packet");
3369 error.SetErrorStringWithFormat(
3370 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3371 response.GetError());
3372 }
3373 return error;
3374}
3375
3376Status GDBRemoteCommunicationClient::SendGetDataPacket(
3377 lldb::user_id_t uid, lldb::tid_t thread_id,
3378 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003379
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003380 StreamGDBRemote escaped_packet;
3381 escaped_packet.PutCString("jTraceBufferRead:");
3382 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3383}
3384
3385Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3386 lldb::user_id_t uid, lldb::tid_t thread_id,
3387 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003388
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003389 StreamGDBRemote escaped_packet;
3390 escaped_packet.PutCString("jTraceMetaRead:");
3391 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3392}
3393
3394Status
3395GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3396 TraceOptions &options) {
3397 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3398 StringExtractorGDBRemote response;
3399 Status error;
3400
3401 StreamString json_string;
3402 StreamGDBRemote escaped_packet;
3403 escaped_packet.PutCString("jTraceConfigRead:");
3404
3405 StructuredData::Dictionary json_packet;
3406 json_packet.AddIntegerItem("traceid", uid);
3407
3408 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3409 json_packet.AddIntegerItem("threadid", options.getThreadID());
3410
3411 json_packet.Dump(json_string, false);
3412 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3413
3414 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3415 true) ==
3416 GDBRemoteCommunication::PacketResult::Success) {
3417 if (response.IsNormalResponse()) {
3418 uint64_t type = std::numeric_limits<uint64_t>::max();
3419 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3420 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3421
3422 auto json_object = StructuredData::ParseJSON(response.Peek());
3423
3424 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003425 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003426 error.SetErrorString("Invalid Configuration obtained");
3427 return error;
3428 }
3429
3430 auto json_dict = json_object->GetAsDictionary();
3431
3432 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3433 metabuffersize);
3434 options.setMetaDataBufferSize(metabuffersize);
3435
3436 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3437 options.setTraceBufferSize(buffersize);
3438
3439 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3440 options.setType(static_cast<lldb::TraceType>(type));
3441
3442 StructuredData::ObjectSP custom_params_sp =
3443 json_dict->GetValueForKey("params");
3444 if (custom_params_sp) {
3445 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003446 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003447 error.SetErrorString("Invalid Configuration obtained");
3448 return error;
3449 } else
3450 options.setTraceParams(
3451 static_pointer_cast<StructuredData::Dictionary>(
3452 custom_params_sp));
3453 }
3454 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003455 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003456 }
3457 } else {
3458 LLDB_LOG(log, "failed to send packet");
3459 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3460 escaped_packet.GetData());
3461 }
3462 return error;
3463}
3464
3465Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3466 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3467 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3468 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3469 Status error;
3470
3471 StructuredData::Dictionary json_packet;
3472
3473 json_packet.AddIntegerItem("traceid", uid);
3474 json_packet.AddIntegerItem("offset", offset);
3475 json_packet.AddIntegerItem("buffersize", buffer.size());
3476
3477 if (thread_id != LLDB_INVALID_THREAD_ID)
3478 json_packet.AddIntegerItem("threadid", thread_id);
3479
3480 StreamString json_string;
3481 json_packet.Dump(json_string, false);
3482
3483 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3484 StringExtractorGDBRemote response;
3485 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3486 GDBRemoteCommunication::PacketResult::Success) {
3487 if (response.IsNormalResponse()) {
3488 size_t filled_size = response.GetHexBytesAvail(buffer);
3489 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3490 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003491 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003492 buffer = buffer.slice(buffer.size());
3493 }
3494 } else {
3495 LLDB_LOG(log, "failed to send packet");
3496 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3497 packet.GetData());
3498 buffer = buffer.slice(buffer.size());
3499 }
3500 return error;
3501}
3502
Kate Stoneb9c1b512016-09-06 20:57:50 +00003503bool GDBRemoteCommunicationClient::GetModuleInfo(
3504 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3505 ModuleSpec &module_spec) {
3506 if (!m_supports_qModuleInfo)
3507 return false;
3508
3509 std::string module_path = module_file_spec.GetPath(false);
3510 if (module_path.empty())
3511 return false;
3512
3513 StreamString packet;
3514 packet.PutCString("qModuleInfo:");
3515 packet.PutCStringAsRawHex8(module_path.c_str());
3516 packet.PutCString(";");
3517 const auto &triple = arch_spec.GetTriple().getTriple();
3518 packet.PutCStringAsRawHex8(triple.c_str());
3519
3520 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003521 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3522 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003523 return false;
3524
3525 if (response.IsErrorResponse())
3526 return false;
3527
3528 if (response.IsUnsupportedResponse()) {
3529 m_supports_qModuleInfo = false;
3530 return false;
3531 }
3532
3533 llvm::StringRef name;
3534 llvm::StringRef value;
3535
3536 module_spec.Clear();
3537 module_spec.GetFileSpec() = module_file_spec;
3538
3539 while (response.GetNameColonValue(name, value)) {
3540 if (name == "uuid" || name == "md5") {
3541 StringExtractor extractor(value);
3542 std::string uuid;
3543 extractor.GetHexByteString(uuid);
3544 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3545 } else if (name == "triple") {
3546 StringExtractor extractor(value);
3547 std::string triple;
3548 extractor.GetHexByteString(triple);
3549 module_spec.GetArchitecture().SetTriple(triple.c_str());
3550 } else if (name == "file_offset") {
3551 uint64_t ival = 0;
3552 if (!value.getAsInteger(16, ival))
3553 module_spec.SetObjectOffset(ival);
3554 } else if (name == "file_size") {
3555 uint64_t ival = 0;
3556 if (!value.getAsInteger(16, ival))
3557 module_spec.SetObjectSize(ival);
3558 } else if (name == "file_path") {
3559 StringExtractor extractor(value);
3560 std::string path;
3561 extractor.GetHexByteString(path);
Zachary Turner8c6b5462017-03-06 23:42:44 +00003562 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003563 }
3564 }
3565
3566 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003567}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003568
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003569static llvm::Optional<ModuleSpec>
3570ParseModuleSpec(StructuredData::Dictionary *dict) {
3571 ModuleSpec result;
3572 if (!dict)
3573 return llvm::None;
3574
Zachary Turner28333212017-05-12 05:49:54 +00003575 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003576 uint64_t integer;
3577
3578 if (!dict->GetValueForKeyAsString("uuid", string))
3579 return llvm::None;
Pavel Labath8c92c892017-12-18 14:31:44 +00003580 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3581 string.size())
3582 return llvm::None;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003583
3584 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3585 return llvm::None;
3586 result.SetObjectOffset(integer);
3587
3588 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3589 return llvm::None;
3590 result.SetObjectSize(integer);
3591
3592 if (!dict->GetValueForKeyAsString("triple", string))
3593 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003594 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003595
3596 if (!dict->GetValueForKeyAsString("file_path", string))
3597 return llvm::None;
Zachary Turner8c6b5462017-03-06 23:42:44 +00003598 result.GetFileSpec() =
3599 FileSpec(string, false, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003600
3601 return result;
3602}
3603
3604llvm::Optional<std::vector<ModuleSpec>>
3605GDBRemoteCommunicationClient::GetModulesInfo(
3606 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3607 if (!m_supports_jModulesInfo)
3608 return llvm::None;
3609
3610 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3611 for (const FileSpec &module_file_spec : module_file_specs) {
3612 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3613 module_array_sp->AppendObject(module_sp);
3614 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003615 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003616 module_sp->SetObject("triple",
3617 std::make_shared<JSONString>(triple.getTriple()));
3618 }
3619 StreamString unescaped_payload;
3620 unescaped_payload.PutCString("jModulesInfo:");
3621 module_array_sp->Write(unescaped_payload);
3622 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003623 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003624 unescaped_payload.GetSize());
3625
Greg Clayton70a9f512017-04-14 17:10:04 +00003626 // Increase the timeout for jModulesInfo since this packet can take longer.
3627 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3628
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003629 StringExtractorGDBRemote response;
3630 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3631 PacketResult::Success ||
3632 response.IsErrorResponse())
3633 return llvm::None;
3634
3635 if (response.IsUnsupportedResponse()) {
3636 m_supports_jModulesInfo = false;
3637 return llvm::None;
3638 }
3639
3640 StructuredData::ObjectSP response_object_sp =
3641 StructuredData::ParseJSON(response.GetStringRef());
3642 if (!response_object_sp)
3643 return llvm::None;
3644
3645 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3646 if (!response_array)
3647 return llvm::None;
3648
3649 std::vector<ModuleSpec> result;
3650 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3651 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3652 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3653 result.push_back(*module_spec);
3654 }
3655
3656 return result;
3657}
3658
Colin Rileyc3c95b22015-04-16 15:51:33 +00003659// query the target remote for extended information using the qXfer packet
3660//
Adrian Prantl05097242018-04-30 16:49:04 +00003661// example: object='features', annex='target.xml', out=<xml output> return:
3662// 'true' on success
Colin Rileyc3c95b22015-04-16 15:51:33 +00003663// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003664bool GDBRemoteCommunicationClient::ReadExtFeature(
3665 const lldb_private::ConstString object,
3666 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003667 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003668
Kate Stoneb9c1b512016-09-06 20:57:50 +00003669 std::stringstream output;
3670 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003671
Kate Stoneb9c1b512016-09-06 20:57:50 +00003672 uint64_t size = GetRemoteMaxPacketSize();
3673 if (size == 0)
3674 size = 0x1000;
3675 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3676 int offset = 0;
3677 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003678
Kate Stoneb9c1b512016-09-06 20:57:50 +00003679 // loop until all data has been read
3680 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003681
Kate Stoneb9c1b512016-09-06 20:57:50 +00003682 // send query extended feature packet
3683 std::stringstream packet;
3684 packet << "qXfer:" << object.AsCString("")
3685 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3686 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003687
Kate Stoneb9c1b512016-09-06 20:57:50 +00003688 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003689 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003690
Kate Stoneb9c1b512016-09-06 20:57:50 +00003691 if (res != GDBRemoteCommunication::PacketResult::Success) {
3692 err.SetErrorString("Error sending $qXfer packet");
3693 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003694 }
3695
Kate Stoneb9c1b512016-09-06 20:57:50 +00003696 const std::string &str = chunk.GetStringRef();
3697 if (str.length() == 0) {
3698 // should have some data in chunk
3699 err.SetErrorString("Empty response from $qXfer packet");
3700 return false;
3701 }
3702
3703 // check packet code
3704 switch (str[0]) {
3705 // last chunk
3706 case ('l'):
3707 active = false;
3708 LLVM_FALLTHROUGH;
3709
3710 // more chunks
3711 case ('m'):
3712 if (str.length() > 1)
3713 output << &str[1];
3714 offset += size;
3715 break;
3716
3717 // unknown chunk
3718 default:
3719 err.SetErrorString("Invalid continuation code from $qXfer packet");
3720 return false;
3721 }
3722 }
3723
3724 out = output.str();
3725 err.Success();
3726 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003727}
Greg Clayton0b90be12015-06-23 21:27:50 +00003728
3729// Notify the target that gdb is prepared to serve symbol lookup requests.
3730// packet: "qSymbol::"
3731// reply:
3732// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003733// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3734// encoded).
3735// LLDB may provide the value by sending another qSymbol
3736// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003737// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003738//
3739// Three examples:
3740//
3741// lldb sends: qSymbol::
3742// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003743// Remote gdb stub does not need to know the addresses of any symbols, lldb
3744// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003745// need to ask again in this session.
3746//
3747// lldb sends: qSymbol::
3748// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3749// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3750// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003751// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3752// not know
3753// the address at this time. lldb needs to send qSymbol:: again when it has
3754// more
Jason Molenda50018d32016-01-13 04:08:10 +00003755// solibs loaded.
3756//
3757// lldb sends: qSymbol::
3758// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3759// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3760// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003761// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3762// that it
3763// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3764// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003765// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003766
Kate Stoneb9c1b512016-09-06 20:57:50 +00003767void GDBRemoteCommunicationClient::ServeSymbolLookups(
3768 lldb_private::Process *process) {
Adrian Prantl05097242018-04-30 16:49:04 +00003769 // Set to true once we've resolved a symbol to an address for the remote
3770 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3771 // any more symbols and we can stop asking.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003772 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003773
Kate Stoneb9c1b512016-09-06 20:57:50 +00003774 // Is this the initial qSymbol:: packet?
3775 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003776
Kate Stoneb9c1b512016-09-06 20:57:50 +00003777 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3778 Lock lock(*this, false);
3779 if (lock) {
3780 StreamString packet;
3781 packet.PutCString("qSymbol::");
3782 StringExtractorGDBRemote response;
3783 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3784 PacketResult::Success) {
3785 if (response.IsOKResponse()) {
3786 if (symbol_response_provided || first_qsymbol_query) {
3787 m_qSymbol_requests_done = true;
3788 }
3789
3790 // We are done serving symbols requests
3791 return;
3792 }
3793 first_qsymbol_query = false;
3794
3795 if (response.IsUnsupportedResponse()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003796 // qSymbol is not supported by the current GDB server we are
3797 // connected to
Kate Stoneb9c1b512016-09-06 20:57:50 +00003798 m_supports_qSymbol = false;
3799 return;
3800 } else {
3801 llvm::StringRef response_str(response.GetStringRef());
3802 if (response_str.startswith("qSymbol:")) {
3803 response.SetFilePos(strlen("qSymbol:"));
3804 std::string symbol_name;
3805 if (response.GetHexByteString(symbol_name)) {
3806 if (symbol_name.empty())
3807 return;
3808
3809 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3810 lldb_private::SymbolContextList sc_list;
3811 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3812 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3813 const size_t num_scs = sc_list.GetSize();
3814 for (size_t sc_idx = 0;
3815 sc_idx < num_scs &&
3816 symbol_load_addr == LLDB_INVALID_ADDRESS;
3817 ++sc_idx) {
3818 SymbolContext sc;
3819 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3820 if (sc.symbol) {
3821 switch (sc.symbol->GetType()) {
3822 case eSymbolTypeInvalid:
3823 case eSymbolTypeAbsolute:
3824 case eSymbolTypeUndefined:
3825 case eSymbolTypeSourceFile:
3826 case eSymbolTypeHeaderFile:
3827 case eSymbolTypeObjectFile:
3828 case eSymbolTypeCommonBlock:
3829 case eSymbolTypeBlock:
3830 case eSymbolTypeLocal:
3831 case eSymbolTypeParam:
3832 case eSymbolTypeVariable:
3833 case eSymbolTypeVariableType:
3834 case eSymbolTypeLineEntry:
3835 case eSymbolTypeLineHeader:
3836 case eSymbolTypeScopeBegin:
3837 case eSymbolTypeScopeEnd:
3838 case eSymbolTypeAdditional:
3839 case eSymbolTypeCompiler:
3840 case eSymbolTypeInstrumentation:
3841 case eSymbolTypeTrampoline:
3842 break;
3843
3844 case eSymbolTypeCode:
3845 case eSymbolTypeResolver:
3846 case eSymbolTypeData:
3847 case eSymbolTypeRuntime:
3848 case eSymbolTypeException:
3849 case eSymbolTypeObjCClass:
3850 case eSymbolTypeObjCMetaClass:
3851 case eSymbolTypeObjCIVar:
3852 case eSymbolTypeReExported:
3853 symbol_load_addr =
3854 sc.symbol->GetLoadAddress(&process->GetTarget());
3855 break;
3856 }
Jason Molenda50018d32016-01-13 04:08:10 +00003857 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003858 }
Greg Clayton42b01482015-08-11 22:07:46 +00003859 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003860 }
3861 // This is the normal path where our symbol lookup was successful
Adrian Prantl05097242018-04-30 16:49:04 +00003862 // and we want to send a packet with the new symbol value and see
3863 // if another lookup needs to be done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003864
Kate Stoneb9c1b512016-09-06 20:57:50 +00003865 // Change "packet" to contain the requested symbol value and name
3866 packet.Clear();
3867 packet.PutCString("qSymbol:");
3868 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3869 packet.Printf("%" PRIx64, symbol_load_addr);
3870 symbol_response_provided = true;
3871 } else {
3872 symbol_response_provided = false;
3873 }
3874 packet.PutCString(":");
3875 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3876 continue; // go back to the while loop and send "packet" and wait
3877 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003878 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003879 }
3880 }
3881 }
3882 // If we make it here, the symbol request packet response wasn't valid or
3883 // our symbol lookup failed so we must abort
3884 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003885
Kate Stoneb9c1b512016-09-06 20:57:50 +00003886 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3887 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3888 log->Printf(
3889 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3890 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003891 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003892 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003893}
3894
Kate Stoneb9c1b512016-09-06 20:57:50 +00003895StructuredData::Array *
3896GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3897 if (!m_supported_async_json_packets_is_valid) {
Adrian Prantl05097242018-04-30 16:49:04 +00003898 // Query the server for the array of supported asynchronous JSON packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003899 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003900
Kate Stoneb9c1b512016-09-06 20:57:50 +00003901 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003902
Kate Stoneb9c1b512016-09-06 20:57:50 +00003903 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003904 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003905 const bool send_async = false;
3906 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3907 send_async) == PacketResult::Success) {
3908 m_supported_async_json_packets_sp =
3909 StructuredData::ParseJSON(response.GetStringRef());
3910 if (m_supported_async_json_packets_sp &&
3911 !m_supported_async_json_packets_sp->GetAsArray()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003912 // We were returned something other than a JSON array. This is
3913 // invalid. Clear it out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003914 if (log)
3915 log->Printf("GDBRemoteCommunicationClient::%s(): "
3916 "QSupportedAsyncJSONPackets returned invalid "
3917 "result: %s",
3918 __FUNCTION__, response.GetStringRef().c_str());
3919 m_supported_async_json_packets_sp.reset();
3920 }
3921 } else {
3922 if (log)
3923 log->Printf("GDBRemoteCommunicationClient::%s(): "
3924 "QSupportedAsyncJSONPackets unsupported",
3925 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003926 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003927
3928 if (log && m_supported_async_json_packets_sp) {
3929 StreamString stream;
3930 m_supported_async_json_packets_sp->Dump(stream);
3931 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3932 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003933 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003935 }
3936
3937 return m_supported_async_json_packets_sp
3938 ? m_supported_async_json_packets_sp->GetAsArray()
3939 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003940}
3941
Zachary Turner97206d52017-05-12 04:51:55 +00003942Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003943 llvm::ArrayRef<int32_t> signals) {
3944 // Format packet:
3945 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3946 auto range = llvm::make_range(signals.begin(), signals.end());
3947 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3948
3949 StringExtractorGDBRemote response;
3950 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3951
3952 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003953 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003954
3955 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003956 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003957 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003958 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003959 }
3960}
3961
Zachary Turner97206d52017-05-12 04:51:55 +00003962Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003963 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003964 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003965
3966 if (type_name.GetLength() == 0) {
3967 error.SetErrorString("invalid type_name argument");
3968 return error;
3969 }
3970
Adrian Prantl05097242018-04-30 16:49:04 +00003971 // Build command: Configure{type_name}: serialized config data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003972 StreamGDBRemote stream;
3973 stream.PutCString("QConfigure");
3974 stream.PutCString(type_name.AsCString());
3975 stream.PutChar(':');
3976 if (config_sp) {
3977 // Gather the plain-text version of the configuration data.
3978 StreamString unescaped_stream;
3979 config_sp->Dump(unescaped_stream);
3980 unescaped_stream.Flush();
3981
3982 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003983 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003984 unescaped_stream.GetSize());
3985 }
3986 stream.Flush();
3987
3988 // Send the packet.
3989 const bool send_async = false;
3990 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003991 auto result =
3992 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003993 if (result == PacketResult::Success) {
3994 // We failed if the config result comes back other than OK.
3995 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3996 // Okay!
3997 error.Clear();
3998 } else {
3999 error.SetErrorStringWithFormat("configuring StructuredData feature "
4000 "%s failed with error %s",
4001 type_name.AsCString(),
4002 response.GetStringRef().c_str());
4003 }
4004 } else {
4005 // Can we get more data here on the failure?
4006 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4007 "failed when sending packet: "
4008 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00004009 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004010 }
4011 return error;
4012}
4013
4014void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4015 GDBRemoteClientBase::OnRunPacketSent(first);
4016 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004017}