blob: 1e12ea6b2d5666783891615478e463fe80af2205 [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
Greg Claytone034a042015-05-21 20:52:06 +000012#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000013#include <sys/stat.h>
14
Greg Claytone034a042015-05-21 20:52:06 +000015#include <numeric>
Kate Stoneb9c1b512016-09-06 20:57:50 +000016#include <sstream>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000017
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000018#include "lldb/Core/ModuleSpec.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000019#include "lldb/Host/HostInfo.h"
Pavel Labath16064d32018-03-20 11:56:24 +000020#include "lldb/Host/XML.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000021#include "lldb/Symbol/Symbol.h"
Pavel Labath4cb69922016-07-29 15:41:52 +000022#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000023#include "lldb/Target/Target.h"
Todd Fiala75930012016-08-19 04:21:48 +000024#include "lldb/Target/UnixSignals.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000025#include "lldb/Utility/Args.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000026#include "lldb/Utility/DataBufferHeap.h"
Pavel Labath2f1fbae2016-09-08 10:07:04 +000027#include "lldb/Utility/JSON.h"
Todd Fiala75930012016-08-19 04:21:48 +000028#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000029#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000030#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000031#include "lldb/Utility/StreamString.h"
Greg Clayton576d8832011-03-22 04:00:09 +000032
Greg Clayton576d8832011-03-22 04:00:09 +000033#include "ProcessGDBRemote.h"
34#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000035#include "lldb/Host/Config.h"
Pavel Labath9af71b32018-03-20 16:14:00 +000036#include "lldb/Utility/StringExtractorGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000037
Zachary Turner54695a32016-08-29 19:58:14 +000038#include "llvm/ADT/StringSwitch.h"
39
Jason Molenda4a793c82018-12-18 23:02:50 +000040#if defined(__APPLE__)
41#define HAVE_LIBCOMPRESSION
Jason Molenda91ffe0a2015-06-18 21:46:06 +000042#include <compression.h>
43#endif
44
Greg Clayton576d8832011-03-22 04:00:09 +000045using namespace lldb;
46using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000047using namespace lldb_private::process_gdb_remote;
Pavel Labath1eff73c2016-11-24 10:54:49 +000048using namespace std::chrono;
Greg Clayton576d8832011-03-22 04:00:09 +000049
50//----------------------------------------------------------------------
51// GDBRemoteCommunicationClient constructor
52//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000053GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000054 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000055 m_supports_not_sending_acks(eLazyBoolCalculate),
56 m_supports_thread_suffix(eLazyBoolCalculate),
57 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
58 m_supports_vCont_all(eLazyBoolCalculate),
59 m_supports_vCont_any(eLazyBoolCalculate),
60 m_supports_vCont_c(eLazyBoolCalculate),
61 m_supports_vCont_C(eLazyBoolCalculate),
62 m_supports_vCont_s(eLazyBoolCalculate),
63 m_supports_vCont_S(eLazyBoolCalculate),
64 m_qHostInfo_is_valid(eLazyBoolCalculate),
65 m_curr_pid_is_valid(eLazyBoolCalculate),
66 m_qProcessInfo_is_valid(eLazyBoolCalculate),
67 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
68 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
69 m_supports_memory_region_info(eLazyBoolCalculate),
70 m_supports_watchpoint_support_info(eLazyBoolCalculate),
71 m_supports_detach_stay_stopped(eLazyBoolCalculate),
72 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
73 m_attach_or_wait_reply(eLazyBoolCalculate),
74 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000075 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000076 m_avoid_g_packets(eLazyBoolCalculate),
77 m_supports_QSaveRegisterState(eLazyBoolCalculate),
78 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
79 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
80 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
81 m_supports_qXfer_features_read(eLazyBoolCalculate),
Pavel Labath16064d32018-03-20 11:56:24 +000082 m_supports_qXfer_memory_map_read(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000083 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
84 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
85 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000086 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000087 m_supports_QPassSignals(eLazyBoolCalculate),
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +000088 m_supports_error_string_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000089 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
90 m_supports_qUserName(true), m_supports_qGroupName(true),
91 m_supports_qThreadStopInfo(true), m_supports_z0(true),
92 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
93 m_supports_z4(true), m_supports_QEnvironment(true),
94 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
95 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
Pavel Labath2f1fbae2016-09-08 10:07:04 +000096 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
97 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000098 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
Kate Stoneb9c1b512016-09-06 20:57:50 +000099 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
Pavel Labath2272c482018-06-18 15:02:23 +0000100 m_os_build(), m_os_kernel(), m_hostname(), m_gdb_server_name(),
101 m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0),
102 m_max_packet_size(0), m_qSupported_response(),
103 m_supported_async_json_packets_is_valid(false),
Pavel Labath16064d32018-03-20 11:56:24 +0000104 m_supported_async_json_packets_sp(), m_qXfer_memory_map(),
105 m_qXfer_memory_map_loaded(false) {}
Greg Clayton576d8832011-03-22 04:00:09 +0000106
107//----------------------------------------------------------------------
108// Destructor
109//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
111 if (IsConnected())
112 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000113}
114
Zachary Turner97206d52017-05-12 04:51:55 +0000115bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000117
Adrian Prantl05097242018-04-30 16:49:04 +0000118 // Start the read thread after we send the handshake ack since if we fail to
119 // send the handshake ack, there is no reason to continue...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 if (SendAck()) {
121 // Wait for any responses that might have been queued up in the remote
122 // GDB server and flush them all
123 StringExtractorGDBRemote response;
124 PacketResult packet_result = PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 while (packet_result == PacketResult::Success)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000126 packet_result = ReadPacket(response, milliseconds(10), false);
Ed Maste48f986f2013-12-18 15:31:45 +0000127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 // The return value from QueryNoAckModeSupported() is true if the packet
Adrian Prantl05097242018-04-30 16:49:04 +0000129 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
130 // false if no response was received. This quickly tells us if we have a
131 // live connection to a remote GDB server...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 if (QueryNoAckModeSupported()) {
133 return true;
134 } else {
135 if (error_ptr)
136 error_ptr->SetErrorString("failed to get reply to handshake packet");
Greg Claytonfb909312013-11-23 01:58:15 +0000137 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 } else {
139 if (error_ptr)
140 error_ptr->SetErrorString("failed to send the handshake ack");
141 }
142 return false;
Greg Clayton1cb64962011-03-24 04:28:38 +0000143}
144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145bool GDBRemoteCommunicationClient::GetEchoSupported() {
146 if (m_supports_qEcho == eLazyBoolCalculate) {
147 GetRemoteQSupported();
148 }
149 return m_supports_qEcho == eLazyBoolYes;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000150}
151
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000152bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
153 if (m_supports_QPassSignals == eLazyBoolCalculate) {
154 GetRemoteQSupported();
155 }
156 return m_supports_QPassSignals == eLazyBoolYes;
157}
158
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
160 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
161 GetRemoteQSupported();
162 }
163 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000164}
165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
167 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
168 GetRemoteQSupported();
169 }
170 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000171}
172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
174 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
175 GetRemoteQSupported();
176 }
177 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000178}
179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
181 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
182 GetRemoteQSupported();
183 }
184 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000185}
186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
188 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
189 GetRemoteQSupported();
190 }
191 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000192}
193
Pavel Labath16064d32018-03-20 11:56:24 +0000194bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() {
195 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) {
196 GetRemoteQSupported();
197 }
198 return m_supports_qXfer_memory_map_read == eLazyBoolYes;
199}
200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
202 if (m_max_packet_size == 0) {
203 GetRemoteQSupported();
204 }
205 return m_max_packet_size;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000206}
207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
209 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
210 m_send_acks = true;
211 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 // This is the first real packet that we'll send in a debug session and it
Adrian Prantl05097242018-04-30 16:49:04 +0000214 // may take a little longer than normal to receive a reply. Wait at least
215 // 6 seconds for a reply to this packet.
Jason Molenda36a216e2014-07-24 01:36:24 +0000216
Pavel Labath1eff73c2016-11-24 10:54:49 +0000217 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
Colin Rileyc3c95b22015-04-16 15:51:33 +0000218
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000219 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
221 PacketResult::Success) {
222 if (response.IsOKResponse()) {
223 m_send_acks = false;
224 m_supports_not_sending_acks = eLazyBoolYes;
225 }
226 return true;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000227 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 }
229 return false;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000230}
Greg Clayton576d8832011-03-22 04:00:09 +0000231
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
233 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
234 m_supports_threads_in_stop_reply = eLazyBoolNo;
235
236 StringExtractorGDBRemote response;
237 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
238 false) == PacketResult::Success) {
239 if (response.IsOKResponse())
240 m_supports_threads_in_stop_reply = eLazyBoolYes;
Pavel Labath5c95ee42016-08-30 13:56:11 +0000241 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242 }
Pavel Labath0faf3732016-08-25 08:34:57 +0000243}
Greg Clayton576d8832011-03-22 04:00:09 +0000244
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
246 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
247 m_attach_or_wait_reply = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +0000248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 StringExtractorGDBRemote response;
250 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
251 false) == PacketResult::Success) {
252 if (response.IsOKResponse())
253 m_attach_or_wait_reply = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000254 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000256 return m_attach_or_wait_reply == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000257}
258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
260 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
261 m_prepare_for_reg_writing_reply = eLazyBoolNo;
262
263 StringExtractorGDBRemote response;
264 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
265 false) == PacketResult::Success) {
266 if (response.IsOKResponse())
267 m_prepare_for_reg_writing_reply = eLazyBoolYes;
268 }
269 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000270 return m_prepare_for_reg_writing_reply == eLazyBoolYes;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271}
272
273void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000274 if (!did_exec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 // Hard reset everything, this is when we first connect to a GDB server
276 m_supports_not_sending_acks = eLazyBoolCalculate;
277 m_supports_thread_suffix = eLazyBoolCalculate;
278 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
279 m_supports_vCont_c = eLazyBoolCalculate;
280 m_supports_vCont_C = eLazyBoolCalculate;
281 m_supports_vCont_s = eLazyBoolCalculate;
282 m_supports_vCont_S = eLazyBoolCalculate;
283 m_supports_p = eLazyBoolCalculate;
284 m_supports_x = eLazyBoolCalculate;
285 m_supports_QSaveRegisterState = eLazyBoolCalculate;
286 m_qHostInfo_is_valid = eLazyBoolCalculate;
287 m_curr_pid_is_valid = eLazyBoolCalculate;
288 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
289 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
290 m_supports_memory_region_info = eLazyBoolCalculate;
291 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
292 m_attach_or_wait_reply = eLazyBoolCalculate;
293 m_avoid_g_packets = eLazyBoolCalculate;
294 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
295 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
296 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
297 m_supports_qXfer_features_read = eLazyBoolCalculate;
Pavel Labath16064d32018-03-20 11:56:24 +0000298 m_supports_qXfer_memory_map_read = eLazyBoolCalculate;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
300 m_supports_qProcessInfoPID = true;
301 m_supports_qfProcessInfo = true;
302 m_supports_qUserName = true;
303 m_supports_qGroupName = true;
304 m_supports_qThreadStopInfo = true;
305 m_supports_z0 = true;
306 m_supports_z1 = true;
307 m_supports_z2 = true;
308 m_supports_z3 = true;
309 m_supports_z4 = true;
310 m_supports_QEnvironment = true;
311 m_supports_QEnvironmentHexEncoded = true;
312 m_supports_qSymbol = true;
313 m_qSymbol_requests_done = false;
314 m_supports_qModuleInfo = true;
315 m_host_arch.Clear();
Pavel Labath2272c482018-06-18 15:02:23 +0000316 m_os_version = llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317 m_os_build.clear();
318 m_os_kernel.clear();
319 m_hostname.clear();
320 m_gdb_server_name.clear();
321 m_gdb_server_version = UINT32_MAX;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000322 m_default_packet_timeout = seconds(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 m_max_packet_size = 0;
324 m_qSupported_response.clear();
325 m_supported_async_json_packets_is_valid = false;
326 m_supported_async_json_packets_sp.reset();
Pavel Labath2f1fbae2016-09-08 10:07:04 +0000327 m_supports_jModulesInfo = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 }
329
Adrian Prantl05097242018-04-30 16:49:04 +0000330 // These flags should be reset when we first connect to a GDB server and when
331 // our inferior process execs
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 m_qProcessInfo_is_valid = eLazyBoolCalculate;
333 m_process_arch.Clear();
334}
335
336void GDBRemoteCommunicationClient::GetRemoteQSupported() {
337 // Clear out any capabilities we expect to see in the qSupported response
338 m_supports_qXfer_auxv_read = eLazyBoolNo;
339 m_supports_qXfer_libraries_read = eLazyBoolNo;
340 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
341 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
342 m_supports_qXfer_features_read = eLazyBoolNo;
Pavel Labath16064d32018-03-20 11:56:24 +0000343 m_supports_qXfer_memory_map_read = eLazyBoolNo;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
345 // not, we assume no limit
346
347 // build the qSupported packet
348 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
349 StreamString packet;
350 packet.PutCString("qSupported");
351 for (uint32_t i = 0; i < features.size(); ++i) {
352 packet.PutCString(i == 0 ? ":" : ";");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000353 packet.PutCString(features[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 }
355
356 StringExtractorGDBRemote response;
Zachary Turnerc1564272016-11-16 21:15:24 +0000357 if (SendPacketAndWaitForResponse(packet.GetString(), response,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 /*send_async=*/false) ==
359 PacketResult::Success) {
360 const char *response_cstr = response.GetStringRef().c_str();
361
362 // Hang on to the qSupported packet, so that platforms can do custom
Adrian Prantl05097242018-04-30 16:49:04 +0000363 // configuration of the transport before attaching/launching the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 m_qSupported_response = response_cstr;
365
366 if (::strstr(response_cstr, "qXfer:auxv:read+"))
367 m_supports_qXfer_auxv_read = eLazyBoolYes;
368 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
369 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
370 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
371 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
372 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
373 }
374 if (::strstr(response_cstr, "qXfer:libraries:read+"))
375 m_supports_qXfer_libraries_read = eLazyBoolYes;
376 if (::strstr(response_cstr, "qXfer:features:read+"))
377 m_supports_qXfer_features_read = eLazyBoolYes;
Pavel Labath16064d32018-03-20 11:56:24 +0000378 if (::strstr(response_cstr, "qXfer:memory-map:read+"))
379 m_supports_qXfer_memory_map_read = eLazyBoolYes;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380
381 // Look for a list of compressions in the features list e.g.
Adrian Prantl05097242018-04-30 16:49:04 +0000382 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
383 // deflate,lzma
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
385 if (features_list) {
386 const char *compressions =
387 ::strstr(features_list, "SupportedCompressions=");
388 if (compressions) {
389 std::vector<std::string> supported_compressions;
390 compressions += sizeof("SupportedCompressions=") - 1;
391 const char *end_of_compressions = strchr(compressions, ';');
392 if (end_of_compressions == NULL) {
393 end_of_compressions = strchr(compressions, '\0');
394 }
395 const char *current_compression = compressions;
396 while (current_compression < end_of_compressions) {
397 const char *next_compression_name = strchr(current_compression, ',');
398 const char *end_of_this_word = next_compression_name;
399 if (next_compression_name == NULL ||
400 end_of_compressions < next_compression_name) {
401 end_of_this_word = end_of_compressions;
402 }
403
404 if (end_of_this_word) {
405 if (end_of_this_word == current_compression) {
406 current_compression++;
407 } else {
408 std::string this_compression(
409 current_compression, end_of_this_word - current_compression);
410 supported_compressions.push_back(this_compression);
411 current_compression = end_of_this_word + 1;
412 }
413 } else {
414 supported_compressions.push_back(current_compression);
415 current_compression = end_of_compressions;
416 }
417 }
418
419 if (supported_compressions.size() > 0) {
420 MaybeEnableCompression(supported_compressions);
421 }
422 }
423 }
424
425 if (::strstr(response_cstr, "qEcho"))
426 m_supports_qEcho = eLazyBoolYes;
427 else
428 m_supports_qEcho = eLazyBoolNo;
429
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000430 if (::strstr(response_cstr, "QPassSignals+"))
431 m_supports_QPassSignals = eLazyBoolYes;
432 else
433 m_supports_QPassSignals = eLazyBoolNo;
434
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
436 if (packet_size_str) {
437 StringExtractorGDBRemote packet_response(packet_size_str +
438 strlen("PacketSize="));
439 m_max_packet_size =
440 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
441 if (m_max_packet_size == 0) {
442 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
443 Log *log(
444 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
445 if (log)
446 log->Printf("Garbled PacketSize spec in qSupported response");
447 }
448 }
449 }
450}
451
452bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
453 if (m_supports_thread_suffix == eLazyBoolCalculate) {
454 StringExtractorGDBRemote response;
455 m_supports_thread_suffix = eLazyBoolNo;
456 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
457 false) == PacketResult::Success) {
458 if (response.IsOKResponse())
459 m_supports_thread_suffix = eLazyBoolYes;
460 }
461 }
462 return m_supports_thread_suffix;
463}
464bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
465 if (m_supports_vCont_c == eLazyBoolCalculate) {
466 StringExtractorGDBRemote response;
467 m_supports_vCont_any = eLazyBoolNo;
468 m_supports_vCont_all = eLazyBoolNo;
469 m_supports_vCont_c = eLazyBoolNo;
470 m_supports_vCont_C = eLazyBoolNo;
471 m_supports_vCont_s = eLazyBoolNo;
472 m_supports_vCont_S = eLazyBoolNo;
473 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
474 PacketResult::Success) {
475 const char *response_cstr = response.GetStringRef().c_str();
476 if (::strstr(response_cstr, ";c"))
477 m_supports_vCont_c = eLazyBoolYes;
478
479 if (::strstr(response_cstr, ";C"))
480 m_supports_vCont_C = eLazyBoolYes;
481
482 if (::strstr(response_cstr, ";s"))
483 m_supports_vCont_s = eLazyBoolYes;
484
485 if (::strstr(response_cstr, ";S"))
486 m_supports_vCont_S = eLazyBoolYes;
487
488 if (m_supports_vCont_c == eLazyBoolYes &&
489 m_supports_vCont_C == eLazyBoolYes &&
490 m_supports_vCont_s == eLazyBoolYes &&
491 m_supports_vCont_S == eLazyBoolYes) {
492 m_supports_vCont_all = eLazyBoolYes;
493 }
494
495 if (m_supports_vCont_c == eLazyBoolYes ||
496 m_supports_vCont_C == eLazyBoolYes ||
497 m_supports_vCont_s == eLazyBoolYes ||
498 m_supports_vCont_S == eLazyBoolYes) {
499 m_supports_vCont_any = eLazyBoolYes;
500 }
501 }
502 }
503
504 switch (flavor) {
505 case 'a':
506 return m_supports_vCont_any;
507 case 'A':
508 return m_supports_vCont_all;
509 case 'c':
510 return m_supports_vCont_c;
511 case 'C':
512 return m_supports_vCont_C;
513 case 's':
514 return m_supports_vCont_s;
515 case 'S':
516 return m_supports_vCont_S;
517 default:
518 break;
519 }
520 return false;
521}
522
Pavel Labath4b6f9592016-08-18 08:30:03 +0000523GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
525 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
526 bool send_async) {
527 Lock lock(*this, send_async);
528 if (!lock) {
529 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
530 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
531 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
532 "for %s packet.",
Zachary Turnerc1564272016-11-16 21:15:24 +0000533 __FUNCTION__, payload.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 return PacketResult::ErrorNoSequenceLock;
535 }
Pavel Labath5c95ee42016-08-30 13:56:11 +0000536
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537 if (GetThreadSuffixSupported())
538 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
539 else {
540 if (!SetCurrentThread(tid))
541 return PacketResult::ErrorSendFailed;
542 }
Pavel Labath4b6f9592016-08-18 08:30:03 +0000543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000545}
546
Adrian Prantl05097242018-04-30 16:49:04 +0000547// Check if the target supports 'p' packet. It sends out a 'p' packet and
548// checks the response. A normal packet will tell us that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000549//
550// Takes a valid thread ID because p needs to apply to a thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
552 if (m_supports_p == eLazyBoolCalculate) {
553 m_supports_p = eLazyBoolNo;
554 StreamString payload;
555 payload.PutCString("p0");
556 StringExtractorGDBRemote response;
557 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
558 response, false) ==
559 PacketResult::Success &&
560 response.IsNormalResponse()) {
561 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000562 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 }
564 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000565}
Greg Clayton576d8832011-03-22 04:00:09 +0000566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
568 // Get information on all threads at one using the "jThreadsInfo" packet
569 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 if (m_supports_jThreadsInfo) {
572 StringExtractorGDBRemote response;
573 response.SetResponseValidatorToJSON();
574 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
575 PacketResult::Success) {
576 if (response.IsUnsupportedResponse()) {
577 m_supports_jThreadsInfo = false;
578 } else if (!response.Empty()) {
579 object_sp = StructuredData::ParseJSON(response.GetStringRef());
580 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
583 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000584}
585
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
587 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
588 StringExtractorGDBRemote response;
589 m_supports_jThreadExtendedInfo = eLazyBoolNo;
590 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
591 PacketResult::Success) {
592 if (response.IsOKResponse()) {
593 m_supports_jThreadExtendedInfo = eLazyBoolYes;
594 }
Jason Molenda705b1802014-06-13 02:37:02 +0000595 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 }
597 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000598}
599
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000600void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
601 if (m_supports_error_string_reply == eLazyBoolCalculate) {
602 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +0000603 // We try to enable error strings in remote packets but if we fail, we just
604 // work in the older way.
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000605 m_supports_error_string_reply = eLazyBoolNo;
606 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
607 PacketResult::Success) {
608 if (response.IsOKResponse()) {
609 m_supports_error_string_reply = eLazyBoolYes;
610 }
611 }
612 }
613}
614
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
616 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
617 StringExtractorGDBRemote response;
618 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
619 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
620 response,
621 false) == PacketResult::Success) {
622 if (response.IsOKResponse()) {
623 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
624 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000625 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626 }
627 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000628}
629
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
631 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
632 StringExtractorGDBRemote response;
633 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
634 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
635 PacketResult::Success) {
636 if (response.IsOKResponse()) {
637 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
638 }
Jason Molenda37397352016-07-22 00:17:55 +0000639 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640 }
641 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000642}
643
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644bool GDBRemoteCommunicationClient::GetxPacketSupported() {
645 if (m_supports_x == eLazyBoolCalculate) {
646 StringExtractorGDBRemote response;
647 m_supports_x = eLazyBoolNo;
648 char packet[256];
649 snprintf(packet, sizeof(packet), "x0,0");
650 if (SendPacketAndWaitForResponse(packet, response, false) ==
651 PacketResult::Success) {
652 if (response.IsOKResponse())
653 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000654 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000655 }
656 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000657}
658
Greg Clayton3dedae12013-12-06 21:45:27 +0000659GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
661 const char *payload_prefix, std::string &response_string) {
662 Lock lock(*this, false);
663 if (!lock) {
664 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
665 GDBR_LOG_PACKETS));
666 if (log)
667 log->Printf("error: failed to get packet sequence mutex, not sending "
668 "packets with prefix '%s'",
669 payload_prefix);
670 return PacketResult::ErrorNoSequenceLock;
671 }
672
673 response_string = "";
674 std::string payload_prefix_str(payload_prefix);
675 unsigned int response_size = 0x1000;
676 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
677 response_size = GetRemoteMaxPacketSize();
678 }
679
680 for (unsigned int offset = 0; true; offset += response_size) {
681 StringExtractorGDBRemote this_response;
682 // Construct payload
683 char sizeDescriptor[128];
684 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
685 response_size);
686 PacketResult result = SendPacketAndWaitForResponseNoLock(
687 payload_prefix_str + sizeDescriptor, this_response);
688 if (result != PacketResult::Success)
689 return result;
690
691 const std::string &this_string = this_response.GetStringRef();
692
693 // Check for m or l as first character; l seems to mean this is the last
694 // chunk
695 char first_char = *this_string.c_str();
696 if (first_char != 'm' && first_char != 'l') {
697 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000698 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 // Concatenate the result so far (skipping 'm' or 'l')
700 response_string.append(this_string, 1, std::string::npos);
701 if (first_char == 'l')
702 // We're done
703 return PacketResult::Success;
704 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000705}
706
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
708 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
709 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000710
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 // First try to retrieve the pid via the qProcessInfo request.
712 GetCurrentProcessInfo(allow_lazy);
713 if (m_curr_pid_is_valid == eLazyBoolYes) {
714 // We really got it.
715 return m_curr_pid;
716 } else {
717 // If we don't get a response for qProcessInfo, check if $qC gives us a
Adrian Prantl05097242018-04-30 16:49:04 +0000718 // result. $qC only returns a real process id on older debugserver and
719 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
720 // the thread id, which newer debugserver and lldb-gdbserver stubs return
721 // correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000722 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000723 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 PacketResult::Success) {
725 if (response.GetChar() == 'Q') {
726 if (response.GetChar() == 'C') {
727 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
728 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
729 m_curr_pid_is_valid = eLazyBoolYes;
730 return m_curr_pid;
731 }
Greg Clayton576d8832011-03-22 04:00:09 +0000732 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 }
Greg Clayton576d8832011-03-22 04:00:09 +0000734 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735
736 // If we don't get a response for $qC, check if $qfThreadID gives us a
737 // result.
738 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
739 std::vector<lldb::tid_t> thread_ids;
740 bool sequence_mutex_unavailable;
741 size_t size;
742 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000743 if (size && !sequence_mutex_unavailable) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 m_curr_pid = thread_ids.front();
745 m_curr_pid_is_valid = eLazyBoolYes;
746 return m_curr_pid;
747 }
Greg Clayton576d8832011-03-22 04:00:09 +0000748 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 }
750
751 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000752}
753
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
755 error_str.clear();
756 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000757 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
758 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759 if (response.IsOKResponse())
760 return true;
761 if (response.GetChar() == 'E') {
762 // A string the describes what failed when launching...
763 error_str = response.GetStringRef().substr(1);
764 } else {
765 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000766 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767 } else {
768 error_str.assign("timed out waiting for app to launch");
769 }
770 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000771}
772
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773int GDBRemoteCommunicationClient::SendArgumentsPacket(
774 const ProcessLaunchInfo &launch_info) {
775 // Since we don't get the send argv0 separate from the executable path, we
Adrian Prantl05097242018-04-30 16:49:04 +0000776 // need to make sure to use the actual executable path found in the
777 // launch_info...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000778 std::vector<const char *> argv;
779 FileSpec exe_file = launch_info.GetExecutableFile();
780 std::string exe_path;
781 const char *arg = NULL;
782 const Args &launch_args = launch_info.GetArguments();
783 if (exe_file)
784 exe_path = exe_file.GetPath(false);
785 else {
786 arg = launch_args.GetArgumentAtIndex(0);
787 if (arg)
788 exe_path = arg;
789 }
790 if (!exe_path.empty()) {
791 argv.push_back(exe_path.c_str());
792 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
793 ++i) {
794 if (arg)
795 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000796 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 }
798 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000799 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 packet.PutChar('A');
801 for (size_t i = 0, n = argv.size(); i < n; ++i) {
802 arg = argv[i];
803 const int arg_len = strlen(arg);
804 if (i > 0)
805 packet.PutChar(',');
806 packet.Printf("%i,%i,", arg_len * 2, (int)i);
807 packet.PutBytesAsRawHex8(arg, arg_len);
808 }
809
Vince Harrone0be4252015-02-06 18:32:57 +0000810 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000811 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
812 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000814 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815 uint8_t error = response.GetError();
816 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000817 return error;
818 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819 }
820 return -1;
821}
Johnny Chen64637202012-05-23 21:09:52 +0000822
Pavel Labath62930e52018-01-10 11:57:31 +0000823int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
824 for (const auto &KV : env) {
825 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
826 if (r != 0)
827 return r;
828 }
829 return 0;
830}
831
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832int GDBRemoteCommunicationClient::SendEnvironmentPacket(
833 char const *name_equal_value) {
834 if (name_equal_value && name_equal_value[0]) {
835 StreamString packet;
836 bool send_hex_encoding = false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000837 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
838 ++p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 if (isprint(*p)) {
840 switch (*p) {
841 case '$':
842 case '#':
843 case '*':
844 case '}':
845 send_hex_encoding = true;
846 break;
847 default:
848 break;
Johnny Chen64637202012-05-23 21:09:52 +0000849 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 } else {
851 // We have non printable characters, lets hex encode this...
852 send_hex_encoding = true;
853 }
Johnny Chen64637202012-05-23 21:09:52 +0000854 }
855
Greg Claytonfbb76342013-11-20 21:07:01 +0000856 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857 if (send_hex_encoding) {
858 if (m_supports_QEnvironmentHexEncoded) {
859 packet.PutCString("QEnvironmentHexEncoded:");
860 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000861 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
862 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 if (response.IsOKResponse())
864 return 0;
865 uint8_t error = response.GetError();
866 if (error)
867 return error;
868 if (response.IsUnsupportedResponse())
869 m_supports_QEnvironmentHexEncoded = false;
870 }
871 }
872
873 } else if (m_supports_QEnvironment) {
874 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000875 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
876 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 if (response.IsOKResponse())
878 return 0;
879 uint8_t error = response.GetError();
880 if (error)
881 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000882 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 m_supports_QEnvironment = false;
884 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000885 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886 }
887 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000888}
889
Kate Stoneb9c1b512016-09-06 20:57:50 +0000890int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
891 if (arch && arch[0]) {
892 StreamString packet;
893 packet.Printf("QLaunchArch:%s", arch);
894 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000895 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
896 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 if (response.IsOKResponse())
898 return 0;
899 uint8_t error = response.GetError();
900 if (error)
901 return error;
902 }
903 }
904 return -1;
905}
Chaoren Lind3173f32015-05-29 19:52:29 +0000906
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
908 char const *data, bool *was_supported) {
909 if (data && *data != '\0') {
910 StreamString packet;
911 packet.Printf("QSetProcessEvent:%s", data);
912 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000913 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
914 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915 if (response.IsOKResponse()) {
916 if (was_supported)
917 *was_supported = true;
918 return 0;
919 } else if (response.IsUnsupportedResponse()) {
920 if (was_supported)
921 *was_supported = false;
922 return -1;
923 } else {
924 uint8_t error = response.GetError();
925 if (was_supported)
926 *was_supported = true;
927 if (error)
928 return error;
929 }
930 }
931 }
932 return -1;
933}
934
Pavel Labath2272c482018-06-18 15:02:23 +0000935llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() {
936 GetHostInfo();
937 return m_os_version;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000938}
939
940bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
941 if (GetHostInfo()) {
942 if (!m_os_build.empty()) {
943 s = m_os_build;
944 return true;
945 }
946 }
947 s.clear();
948 return false;
949}
950
951bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
952 if (GetHostInfo()) {
953 if (!m_os_kernel.empty()) {
954 s = m_os_kernel;
955 return true;
956 }
957 }
958 s.clear();
959 return false;
960}
961
962bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
963 if (GetHostInfo()) {
964 if (!m_hostname.empty()) {
965 s = m_hostname;
966 return true;
967 }
968 }
969 s.clear();
970 return false;
971}
972
973ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
974 if (GetHostInfo())
975 return m_host_arch;
976 return ArchSpec();
977}
978
979const lldb_private::ArchSpec &
980GDBRemoteCommunicationClient::GetProcessArchitecture() {
981 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
982 GetCurrentProcessInfo();
983 return m_process_arch;
984}
985
986bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
987 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
988 m_gdb_server_name.clear();
989 m_gdb_server_version = 0;
990 m_qGDBServerVersion_is_valid = eLazyBoolNo;
991
992 StringExtractorGDBRemote response;
993 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
994 PacketResult::Success) {
995 if (response.IsNormalResponse()) {
996 llvm::StringRef name, value;
997 bool success = false;
998 while (response.GetNameColonValue(name, value)) {
999 if (name.equals("name")) {
1000 success = true;
1001 m_gdb_server_name = value;
1002 } else if (name.equals("version")) {
1003 llvm::StringRef major, minor;
1004 std::tie(major, minor) = value.split('.');
1005 if (!major.getAsInteger(0, m_gdb_server_version))
1006 success = true;
1007 }
Greg Clayton576d8832011-03-22 04:00:09 +00001008 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 if (success)
1010 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1011 }
Greg Clayton576d8832011-03-22 04:00:09 +00001012 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 }
1014 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001015}
1016
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017void GDBRemoteCommunicationClient::MaybeEnableCompression(
1018 std::vector<std::string> supported_compressions) {
1019 CompressionType avail_type = CompressionType::None;
1020 std::string avail_name;
1021
1022#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001023 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 for (auto compression : supported_compressions) {
1025 if (compression == "lzfse") {
1026 avail_type = CompressionType::LZFSE;
1027 avail_name = compression;
1028 break;
1029 }
1030 }
1031 }
1032#endif
1033
1034#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001035 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 for (auto compression : supported_compressions) {
1037 if (compression == "zlib-deflate") {
1038 avail_type = CompressionType::ZlibDeflate;
1039 avail_name = compression;
1040 break;
1041 }
1042 }
1043 }
1044#endif
1045
1046#if defined(HAVE_LIBZ)
1047 if (avail_type == CompressionType::None) {
1048 for (auto compression : supported_compressions) {
1049 if (compression == "zlib-deflate") {
1050 avail_type = CompressionType::ZlibDeflate;
1051 avail_name = compression;
1052 break;
1053 }
1054 }
1055 }
1056#endif
1057
1058#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001059 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060 for (auto compression : supported_compressions) {
1061 if (compression == "lz4") {
1062 avail_type = CompressionType::LZ4;
1063 avail_name = compression;
1064 break;
1065 }
1066 }
1067 }
1068#endif
1069
1070#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001071 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 for (auto compression : supported_compressions) {
1073 if (compression == "lzma") {
1074 avail_type = CompressionType::LZMA;
1075 avail_name = compression;
1076 break;
1077 }
1078 }
1079 }
1080#endif
1081
1082 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001083 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001085 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 PacketResult::Success)
1087 return;
1088
1089 if (response.IsOKResponse()) {
1090 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001091 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092 }
Greg Clayton576d8832011-03-22 04:00:09 +00001093}
Greg Clayton32e0a752011-03-30 18:16:51 +00001094
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1096 if (GetGDBServerVersion()) {
1097 if (!m_gdb_server_name.empty())
1098 return m_gdb_server_name.c_str();
1099 }
1100 return NULL;
1101}
1102
1103uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1104 if (GetGDBServerVersion())
1105 return m_gdb_server_version;
1106 return 0;
1107}
1108
1109bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1110 StringExtractorGDBRemote response;
1111 if (SendPacketAndWaitForResponse("qC", response, false) !=
1112 PacketResult::Success)
1113 return false;
1114
1115 if (!response.IsNormalResponse())
1116 return false;
1117
1118 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1119 tid = response.GetHexMaxU32(true, -1);
1120
1121 return true;
1122}
1123
1124bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1125 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1126
1127 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
Pavel Labathe7ec0832018-08-31 05:34:03 +00001128 // host info computation can require DNS traffic and shelling out to external processes.
1129 // Increase the timeout to account for that.
1130 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001132 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1134 PacketResult::Success) {
1135 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001136 llvm::StringRef name;
1137 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001138 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1139 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140 std::string arch_name;
1141 std::string os_name;
1142 std::string vendor_name;
1143 std::string triple;
1144 std::string distribution_id;
1145 uint32_t pointer_byte_size = 0;
1146 ByteOrder byte_order = eByteOrderInvalid;
1147 uint32_t num_keys_decoded = 0;
1148 while (response.GetNameColonValue(name, value)) {
1149 if (name.equals("cputype")) {
1150 // exception type in big endian hex
1151 if (!value.getAsInteger(0, cpu))
1152 ++num_keys_decoded;
1153 } else if (name.equals("cpusubtype")) {
1154 // exception count in big endian hex
1155 if (!value.getAsInteger(0, sub))
1156 ++num_keys_decoded;
1157 } else if (name.equals("arch")) {
1158 arch_name = value;
1159 ++num_keys_decoded;
1160 } else if (name.equals("triple")) {
1161 StringExtractor extractor(value);
1162 extractor.GetHexByteString(triple);
1163 ++num_keys_decoded;
1164 } else if (name.equals("distribution_id")) {
1165 StringExtractor extractor(value);
1166 extractor.GetHexByteString(distribution_id);
1167 ++num_keys_decoded;
1168 } else if (name.equals("os_build")) {
1169 StringExtractor extractor(value);
1170 extractor.GetHexByteString(m_os_build);
1171 ++num_keys_decoded;
1172 } else if (name.equals("hostname")) {
1173 StringExtractor extractor(value);
1174 extractor.GetHexByteString(m_hostname);
1175 ++num_keys_decoded;
1176 } else if (name.equals("os_kernel")) {
1177 StringExtractor extractor(value);
1178 extractor.GetHexByteString(m_os_kernel);
1179 ++num_keys_decoded;
1180 } else if (name.equals("ostype")) {
1181 os_name = value;
1182 ++num_keys_decoded;
1183 } else if (name.equals("vendor")) {
1184 vendor_name = value;
1185 ++num_keys_decoded;
1186 } else if (name.equals("endian")) {
1187 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1188 .Case("little", eByteOrderLittle)
1189 .Case("big", eByteOrderBig)
1190 .Case("pdp", eByteOrderPDP)
1191 .Default(eByteOrderInvalid);
1192 if (byte_order != eByteOrderInvalid)
1193 ++num_keys_decoded;
1194 } else if (name.equals("ptrsize")) {
1195 if (!value.getAsInteger(0, pointer_byte_size))
1196 ++num_keys_decoded;
1197 } else if (name.equals("os_version") ||
1198 name.equals(
1199 "version")) // Older debugserver binaries used the
1200 // "version" key instead of
1201 // "os_version"...
1202 {
Pavel Labath2272c482018-06-18 15:02:23 +00001203 if (!m_os_version.tryParse(value))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 ++num_keys_decoded;
1205 } else if (name.equals("watchpoint_exceptions_received")) {
1206 m_watchpoints_trigger_after_instruction =
1207 llvm::StringSwitch<LazyBool>(value)
1208 .Case("before", eLazyBoolNo)
1209 .Case("after", eLazyBoolYes)
1210 .Default(eLazyBoolCalculate);
1211 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1212 ++num_keys_decoded;
1213 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001214 uint32_t timeout_seconds;
1215 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001216 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 SetPacketTimeout(m_default_packet_timeout);
1218 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001219 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 }
Jason Molenda89c37492014-01-27 22:23:20 +00001221 }
1222
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223 if (num_keys_decoded > 0)
1224 m_qHostInfo_is_valid = eLazyBoolYes;
1225
1226 if (triple.empty()) {
1227 if (arch_name.empty()) {
1228 if (cpu != LLDB_INVALID_CPUTYPE) {
1229 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1230 if (pointer_byte_size) {
1231 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1232 }
1233 if (byte_order != eByteOrderInvalid) {
1234 assert(byte_order == m_host_arch.GetByteOrder());
1235 }
1236
1237 if (!vendor_name.empty())
1238 m_host_arch.GetTriple().setVendorName(
1239 llvm::StringRef(vendor_name));
1240 if (!os_name.empty())
1241 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001242 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001243 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001244 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245 triple += arch_name;
1246 if (!vendor_name.empty() || !os_name.empty()) {
1247 triple += '-';
1248 if (vendor_name.empty())
1249 triple += "unknown";
1250 else
1251 triple += vendor_name;
1252 triple += '-';
1253 if (os_name.empty())
1254 triple += "unknown";
1255 else
1256 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001257 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001259
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260 llvm::Triple &host_triple = m_host_arch.GetTriple();
1261 if (host_triple.getVendor() == llvm::Triple::Apple &&
1262 host_triple.getOS() == llvm::Triple::Darwin) {
1263 switch (m_host_arch.GetMachine()) {
1264 case llvm::Triple::aarch64:
1265 case llvm::Triple::arm:
1266 case llvm::Triple::thumb:
1267 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001268 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 default:
1270 host_triple.setOS(llvm::Triple::MacOSX);
1271 break;
1272 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001273 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 if (pointer_byte_size) {
1275 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1276 }
1277 if (byte_order != eByteOrderInvalid) {
1278 assert(byte_order == m_host_arch.GetByteOrder());
1279 }
1280 }
1281 } else {
1282 m_host_arch.SetTriple(triple.c_str());
1283 if (pointer_byte_size) {
1284 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1285 }
1286 if (byte_order != eByteOrderInvalid) {
1287 assert(byte_order == m_host_arch.GetByteOrder());
1288 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001289
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 if (log)
1291 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1292 "architecture as %s, triple as %s from triple text %s",
1293 __FUNCTION__, m_host_arch.GetArchitectureName()
1294 ? m_host_arch.GetArchitectureName()
1295 : "<null-arch-name>",
1296 m_host_arch.GetTriple().getTriple().c_str(),
1297 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001298 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 if (!distribution_id.empty())
1300 m_host_arch.SetDistributionId(distribution_id.c_str());
1301 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001302 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 }
1304 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001305}
Greg Clayton37a0a242012-04-11 00:24:49 +00001306
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307int GDBRemoteCommunicationClient::SendAttach(
1308 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1309 if (pid != LLDB_INVALID_PROCESS_ID) {
1310 char packet[64];
1311 const int packet_len =
1312 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001313 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001315 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 PacketResult::Success) {
1317 if (response.IsErrorResponse())
1318 return response.GetError();
1319 return 0;
1320 }
1321 }
1322 return -1;
1323}
1324
1325int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1326 size_t data_len) {
1327 StreamString packet;
1328 packet.PutCString("I");
1329 packet.PutBytesAsRawHex8(data, data_len);
1330 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001331 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1332 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333 return 0;
1334 }
1335 return response.GetError();
1336}
1337
1338const lldb_private::ArchSpec &
1339GDBRemoteCommunicationClient::GetHostArchitecture() {
1340 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1341 GetHostInfo();
1342 return m_host_arch;
1343}
1344
Pavel Labath1eff73c2016-11-24 10:54:49 +00001345seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001346 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1347 GetHostInfo();
1348 return m_default_packet_timeout;
1349}
1350
1351addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1352 uint32_t permissions) {
1353 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1354 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1355 char packet[64];
1356 const int packet_len = ::snprintf(
1357 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1358 permissions & lldb::ePermissionsReadable ? "r" : "",
1359 permissions & lldb::ePermissionsWritable ? "w" : "",
1360 permissions & lldb::ePermissionsExecutable ? "x" : "");
1361 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001362 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001363 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001364 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 PacketResult::Success) {
1366 if (response.IsUnsupportedResponse())
1367 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1368 else if (!response.IsErrorResponse())
1369 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1370 } else {
1371 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1372 }
1373 }
1374 return LLDB_INVALID_ADDRESS;
1375}
1376
1377bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1378 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1379 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1380 char packet[64];
1381 const int packet_len =
1382 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1383 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001384 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001386 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387 PacketResult::Success) {
1388 if (response.IsUnsupportedResponse())
1389 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1390 else if (response.IsOKResponse())
1391 return true;
1392 } else {
1393 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1394 }
1395 }
1396 return false;
1397}
1398
Zachary Turner97206d52017-05-12 04:51:55 +00001399Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1400 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001401
1402 if (keep_stopped) {
1403 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1404 char packet[64];
1405 const int packet_len =
1406 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1407 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001408 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001410 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411 PacketResult::Success &&
1412 response.IsOKResponse()) {
1413 m_supports_detach_stay_stopped = eLazyBoolYes;
1414 } else {
1415 m_supports_detach_stay_stopped = eLazyBoolNo;
1416 }
1417 }
1418
1419 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1420 error.SetErrorString("Stays stopped not supported by this target.");
1421 return error;
1422 } else {
1423 StringExtractorGDBRemote response;
1424 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001425 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 if (packet_result != PacketResult::Success)
1427 error.SetErrorString("Sending extended disconnect packet failed.");
1428 }
1429 } else {
1430 StringExtractorGDBRemote response;
1431 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001432 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001433 if (packet_result != PacketResult::Success)
1434 error.SetErrorString("Sending disconnect packet failed.");
1435 }
1436 return error;
1437}
1438
Zachary Turner97206d52017-05-12 04:51:55 +00001439Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001441 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001442 region_info.Clear();
1443
1444 if (m_supports_memory_region_info != eLazyBoolNo) {
1445 m_supports_memory_region_info = eLazyBoolYes;
1446 char packet[64];
1447 const int packet_len = ::snprintf(
1448 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1449 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001450 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001452 if (SendPacketAndWaitForResponse(packet, response, false) ==
Pavel Labath16064d32018-03-20 11:56:24 +00001453 PacketResult::Success &&
1454 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455 llvm::StringRef name;
1456 llvm::StringRef value;
1457 addr_t addr_value = LLDB_INVALID_ADDRESS;
1458 bool success = true;
1459 bool saw_permissions = false;
1460 while (success && response.GetNameColonValue(name, value)) {
1461 if (name.equals("start")) {
1462 if (!value.getAsInteger(16, addr_value))
1463 region_info.GetRange().SetRangeBase(addr_value);
1464 } else if (name.equals("size")) {
1465 if (!value.getAsInteger(16, addr_value))
1466 region_info.GetRange().SetByteSize(addr_value);
1467 } else if (name.equals("permissions") &&
1468 region_info.GetRange().IsValid()) {
1469 saw_permissions = true;
1470 if (region_info.GetRange().Contains(addr)) {
1471 if (value.find('r') != llvm::StringRef::npos)
1472 region_info.SetReadable(MemoryRegionInfo::eYes);
1473 else
1474 region_info.SetReadable(MemoryRegionInfo::eNo);
1475
1476 if (value.find('w') != llvm::StringRef::npos)
1477 region_info.SetWritable(MemoryRegionInfo::eYes);
1478 else
1479 region_info.SetWritable(MemoryRegionInfo::eNo);
1480
1481 if (value.find('x') != llvm::StringRef::npos)
1482 region_info.SetExecutable(MemoryRegionInfo::eYes);
1483 else
1484 region_info.SetExecutable(MemoryRegionInfo::eNo);
1485
1486 region_info.SetMapped(MemoryRegionInfo::eYes);
1487 } else {
1488 // The reported region does not contain this address -- we're
1489 // looking at an unmapped page
1490 region_info.SetReadable(MemoryRegionInfo::eNo);
1491 region_info.SetWritable(MemoryRegionInfo::eNo);
1492 region_info.SetExecutable(MemoryRegionInfo::eNo);
1493 region_info.SetMapped(MemoryRegionInfo::eNo);
1494 }
1495 } else if (name.equals("name")) {
1496 StringExtractorGDBRemote name_extractor(value);
1497 std::string name;
1498 name_extractor.GetHexByteString(name);
1499 region_info.SetName(name.c_str());
1500 } else if (name.equals("error")) {
1501 StringExtractorGDBRemote error_extractor(value);
1502 std::string error_string;
1503 // Now convert the HEX bytes into a string value
1504 error_extractor.GetHexByteString(error_string);
1505 error.SetErrorString(error_string.c_str());
1506 }
1507 }
1508
Stephane Sezer48d14272017-03-31 18:00:48 +00001509 if (region_info.GetRange().IsValid()) {
1510 // We got a valid address range back but no permissions -- which means
1511 // this is an unmapped page
1512 if (!saw_permissions) {
1513 region_info.SetReadable(MemoryRegionInfo::eNo);
1514 region_info.SetWritable(MemoryRegionInfo::eNo);
1515 region_info.SetExecutable(MemoryRegionInfo::eNo);
1516 region_info.SetMapped(MemoryRegionInfo::eNo);
1517 }
1518 } else {
1519 // We got an invalid address range back
1520 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521 }
1522 } else {
1523 m_supports_memory_region_info = eLazyBoolNo;
1524 }
1525 }
1526
1527 if (m_supports_memory_region_info == eLazyBoolNo) {
1528 error.SetErrorString("qMemoryRegionInfo is not supported");
1529 }
Pavel Labath16064d32018-03-20 11:56:24 +00001530
1531 // Try qXfer:memory-map:read to get region information not included in
1532 // qMemoryRegionInfo
1533 MemoryRegionInfo qXfer_region_info;
1534 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1535
1536 if (error.Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001537 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1538 // the qXfer result as a fallback
Pavel Labath16064d32018-03-20 11:56:24 +00001539 if (qXfer_error.Success()) {
1540 region_info = qXfer_region_info;
1541 error.Clear();
1542 } else {
1543 region_info.Clear();
1544 }
1545 } else if (qXfer_error.Success()) {
1546 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
Adrian Prantl05097242018-04-30 16:49:04 +00001547 // both regions are the same range, update the result to include the flash-
1548 // memory information that is specific to the qXfer result.
Pavel Labath16064d32018-03-20 11:56:24 +00001549 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1550 region_info.SetFlash(qXfer_region_info.GetFlash());
1551 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1552 }
1553 }
1554 return error;
1555}
1556
1557Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1558 lldb::addr_t addr, MemoryRegionInfo &region) {
1559 Status error = LoadQXferMemoryMap();
1560 if (!error.Success())
1561 return error;
1562 for (const auto &map_region : m_qXfer_memory_map) {
1563 if (map_region.GetRange().Contains(addr)) {
1564 region = map_region;
1565 return error;
1566 }
1567 }
1568 error.SetErrorString("Region not found");
1569 return error;
1570}
1571
1572Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1573
1574 Status error;
1575
1576 if (m_qXfer_memory_map_loaded)
1577 // Already loaded, return success
1578 return error;
1579
1580 if (!XMLDocument::XMLEnabled()) {
1581 error.SetErrorString("XML is not supported");
1582 return error;
1583 }
1584
1585 if (!GetQXferMemoryMapReadSupported()) {
1586 error.SetErrorString("Memory map is not supported");
1587 return error;
1588 }
1589
1590 std::string xml;
1591 lldb_private::Status lldberr;
1592 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1593 lldberr)) {
1594 error.SetErrorString("Failed to read memory map");
1595 return error;
1596 }
1597
1598 XMLDocument xml_document;
1599
1600 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1601 error.SetErrorString("Failed to parse memory map xml");
1602 return error;
1603 }
1604
1605 XMLNode map_node = xml_document.GetRootElement("memory-map");
1606 if (!map_node) {
1607 error.SetErrorString("Invalid root node in memory map xml");
1608 return error;
1609 }
1610
1611 m_qXfer_memory_map.clear();
1612
1613 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1614 if (!memory_node.IsElement())
1615 return true;
1616 if (memory_node.GetName() != "memory")
1617 return true;
1618 auto type = memory_node.GetAttributeValue("type", "");
1619 uint64_t start;
1620 uint64_t length;
1621 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1622 return true;
1623 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1624 return true;
1625 MemoryRegionInfo region;
1626 region.GetRange().SetRangeBase(start);
1627 region.GetRange().SetByteSize(length);
1628 if (type == "rom") {
1629 region.SetReadable(MemoryRegionInfo::eYes);
1630 this->m_qXfer_memory_map.push_back(region);
1631 } else if (type == "ram") {
1632 region.SetReadable(MemoryRegionInfo::eYes);
1633 region.SetWritable(MemoryRegionInfo::eYes);
1634 this->m_qXfer_memory_map.push_back(region);
1635 } else if (type == "flash") {
1636 region.SetFlash(MemoryRegionInfo::eYes);
1637 memory_node.ForEachChildElement(
1638 [&region](const XMLNode &prop_node) -> bool {
1639 if (!prop_node.IsElement())
1640 return true;
1641 if (prop_node.GetName() != "property")
1642 return true;
1643 auto propname = prop_node.GetAttributeValue("name", "");
1644 if (propname == "blocksize") {
1645 uint64_t blocksize;
1646 if (prop_node.GetElementTextAsUnsigned(blocksize))
1647 region.SetBlocksize(blocksize);
1648 }
1649 return true;
1650 });
1651 this->m_qXfer_memory_map.push_back(region);
1652 }
1653 return true;
1654 });
1655
1656 m_qXfer_memory_map_loaded = true;
1657
Kate Stoneb9c1b512016-09-06 20:57:50 +00001658 return error;
1659}
1660
Zachary Turner97206d52017-05-12 04:51:55 +00001661Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1662 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001663
1664 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1665 num = m_num_supported_hardware_watchpoints;
1666 return error;
1667 }
1668
1669 // Set num to 0 first.
1670 num = 0;
1671 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1672 char packet[64];
1673 const int packet_len =
1674 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1675 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001676 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001678 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001679 PacketResult::Success) {
1680 m_supports_watchpoint_support_info = eLazyBoolYes;
1681 llvm::StringRef name;
1682 llvm::StringRef value;
Jason Molendac0e793d2018-11-09 22:33:26 +00001683 bool found_num_field = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001684 while (response.GetNameColonValue(name, value)) {
1685 if (name.equals("num")) {
1686 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1687 num = m_num_supported_hardware_watchpoints;
Jason Molendac0e793d2018-11-09 22:33:26 +00001688 found_num_field = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 }
1690 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001691 if (!found_num_field) {
Jason Molendac0e793d2018-11-09 22:33:26 +00001692 m_supports_watchpoint_support_info = eLazyBoolNo;
1693 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001694 } else {
1695 m_supports_watchpoint_support_info = eLazyBoolNo;
1696 }
1697 }
1698
1699 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1700 error.SetErrorString("qWatchpointSupportInfo is not supported");
1701 }
1702 return error;
1703}
1704
Zachary Turner97206d52017-05-12 04:51:55 +00001705lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001706 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001707 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001708 if (error.Success())
1709 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1710 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001711}
1712
Zachary Turner97206d52017-05-12 04:51:55 +00001713lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001714GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1715 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001716 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 llvm::Triple::ArchType atype = arch.GetMachine();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001718
Adrian Prantl05097242018-04-30 16:49:04 +00001719 // we assume watchpoints will happen after running the relevant opcode and we
1720 // only want to override this behavior if we have explicitly received a
1721 // qHostInfo telling us otherwise
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722 if (m_qHostInfo_is_valid != eLazyBoolYes) {
Pavel Labathc51ad482017-10-27 17:02:32 +00001723 // On targets like MIPS and ppc64le, watchpoint exceptions are always
Adrian Prantl05097242018-04-30 16:49:04 +00001724 // generated before the instruction is executed. The connected target may
1725 // not support qHostInfo or qWatchpointSupportInfo packets.
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001726 after =
1727 !(atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1728 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el ||
1729 atype == llvm::Triple::ppc64le);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 } else {
Pavel Labathc51ad482017-10-27 17:02:32 +00001731 // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to
1732 // eLazyBoolNo if it is not calculated before.
1733 if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1734 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1735 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) ||
1736 atype == llvm::Triple::ppc64le) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
Pavel Labathc51ad482017-10-27 17:02:32 +00001738 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001739
1740 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1741 }
1742 return error;
1743}
1744
1745int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1746 if (file_spec) {
1747 std::string path{file_spec.GetPath(false)};
1748 StreamString packet;
1749 packet.PutCString("QSetSTDIN:");
1750 packet.PutCStringAsRawHex8(path.c_str());
1751
1752 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001753 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1754 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 if (response.IsOKResponse())
1756 return 0;
1757 uint8_t error = response.GetError();
1758 if (error)
1759 return error;
1760 }
1761 }
1762 return -1;
1763}
1764
1765int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1766 if (file_spec) {
1767 std::string path{file_spec.GetPath(false)};
1768 StreamString packet;
1769 packet.PutCString("QSetSTDOUT:");
1770 packet.PutCStringAsRawHex8(path.c_str());
1771
1772 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001773 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1774 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001775 if (response.IsOKResponse())
1776 return 0;
1777 uint8_t error = response.GetError();
1778 if (error)
1779 return error;
1780 }
1781 }
1782 return -1;
1783}
1784
1785int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1786 if (file_spec) {
1787 std::string path{file_spec.GetPath(false)};
1788 StreamString packet;
1789 packet.PutCString("QSetSTDERR:");
1790 packet.PutCStringAsRawHex8(path.c_str());
1791
1792 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001793 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1794 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795 if (response.IsOKResponse())
1796 return 0;
1797 uint8_t error = response.GetError();
1798 if (error)
1799 return error;
1800 }
1801 }
1802 return -1;
1803}
1804
1805bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1806 StringExtractorGDBRemote response;
1807 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1808 PacketResult::Success) {
1809 if (response.IsUnsupportedResponse())
1810 return false;
1811 if (response.IsErrorResponse())
1812 return false;
1813 std::string cwd;
1814 response.GetHexByteString(cwd);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001815 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816 return !cwd.empty();
1817 }
1818 return false;
1819}
1820
1821int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1822 if (working_dir) {
1823 std::string path{working_dir.GetPath(false)};
1824 StreamString packet;
1825 packet.PutCString("QSetWorkingDir:");
1826 packet.PutCStringAsRawHex8(path.c_str());
1827
1828 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001829 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1830 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001831 if (response.IsOKResponse())
1832 return 0;
1833 uint8_t error = response.GetError();
1834 if (error)
1835 return error;
1836 }
1837 }
1838 return -1;
1839}
1840
1841int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1842 char packet[32];
1843 const int packet_len =
1844 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1845 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001846 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001847 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001848 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849 PacketResult::Success) {
1850 if (response.IsOKResponse())
1851 return 0;
1852 uint8_t error = response.GetError();
1853 if (error)
1854 return error;
1855 }
1856 return -1;
1857}
1858
1859int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1860 char packet[32];
1861 const int packet_len = ::snprintf(packet, sizeof(packet),
1862 "QSetDetachOnError:%i", enable ? 1 : 0);
1863 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001864 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001865 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001866 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001867 PacketResult::Success) {
1868 if (response.IsOKResponse())
1869 return 0;
1870 uint8_t error = response.GetError();
1871 if (error)
1872 return error;
1873 }
1874 return -1;
1875}
1876
1877bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1878 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1879 if (response.IsNormalResponse()) {
1880 llvm::StringRef name;
1881 llvm::StringRef value;
1882 StringExtractor extractor;
1883
1884 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1885 uint32_t sub = 0;
1886 std::string vendor;
1887 std::string os_type;
1888
1889 while (response.GetNameColonValue(name, value)) {
1890 if (name.equals("pid")) {
1891 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1892 value.getAsInteger(0, pid);
1893 process_info.SetProcessID(pid);
1894 } else if (name.equals("ppid")) {
1895 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1896 value.getAsInteger(0, pid);
1897 process_info.SetParentProcessID(pid);
1898 } else if (name.equals("uid")) {
1899 uint32_t uid = UINT32_MAX;
1900 value.getAsInteger(0, uid);
1901 process_info.SetUserID(uid);
1902 } else if (name.equals("euid")) {
1903 uint32_t uid = UINT32_MAX;
1904 value.getAsInteger(0, uid);
1905 process_info.SetEffectiveGroupID(uid);
1906 } else if (name.equals("gid")) {
1907 uint32_t gid = UINT32_MAX;
1908 value.getAsInteger(0, gid);
1909 process_info.SetGroupID(gid);
1910 } else if (name.equals("egid")) {
1911 uint32_t gid = UINT32_MAX;
1912 value.getAsInteger(0, gid);
1913 process_info.SetEffectiveGroupID(gid);
1914 } else if (name.equals("triple")) {
1915 StringExtractor extractor(value);
1916 std::string triple;
1917 extractor.GetHexByteString(triple);
1918 process_info.GetArchitecture().SetTriple(triple.c_str());
1919 } else if (name.equals("name")) {
1920 StringExtractor extractor(value);
Adrian Prantl05097242018-04-30 16:49:04 +00001921 // The process name from ASCII hex bytes since we can't control the
1922 // characters in a process name
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923 std::string name;
1924 extractor.GetHexByteString(name);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001925 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001926 } else if (name.equals("cputype")) {
1927 value.getAsInteger(0, cpu);
1928 } else if (name.equals("cpusubtype")) {
1929 value.getAsInteger(0, sub);
1930 } else if (name.equals("vendor")) {
1931 vendor = value;
1932 } else if (name.equals("ostype")) {
1933 os_type = value;
1934 }
1935 }
1936
1937 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1938 if (vendor == "apple") {
1939 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1940 sub);
1941 process_info.GetArchitecture().GetTriple().setVendorName(
1942 llvm::StringRef(vendor));
1943 process_info.GetArchitecture().GetTriple().setOSName(
1944 llvm::StringRef(os_type));
1945 }
1946 }
1947
1948 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1949 return true;
1950 }
1951 return false;
1952}
1953
1954bool GDBRemoteCommunicationClient::GetProcessInfo(
1955 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1956 process_info.Clear();
1957
1958 if (m_supports_qProcessInfoPID) {
1959 char packet[32];
1960 const int packet_len =
1961 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1962 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001963 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001964 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001965 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001966 PacketResult::Success) {
1967 return DecodeProcessInfoResponse(response, process_info);
1968 } else {
1969 m_supports_qProcessInfoPID = false;
1970 return false;
1971 }
1972 }
1973 return false;
1974}
1975
1976bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1977 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1978 GDBR_LOG_PACKETS));
1979
1980 if (allow_lazy) {
1981 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1982 return true;
1983 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1984 return false;
1985 }
1986
1987 GetHostInfo();
1988
1989 StringExtractorGDBRemote response;
1990 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1991 PacketResult::Success) {
1992 if (response.IsNormalResponse()) {
1993 llvm::StringRef name;
1994 llvm::StringRef value;
1995 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1996 uint32_t sub = 0;
1997 std::string arch_name;
1998 std::string os_name;
1999 std::string vendor_name;
2000 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002001 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002002 uint32_t pointer_byte_size = 0;
2003 StringExtractor extractor;
2004 ByteOrder byte_order = eByteOrderInvalid;
2005 uint32_t num_keys_decoded = 0;
2006 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2007 while (response.GetNameColonValue(name, value)) {
2008 if (name.equals("cputype")) {
2009 if (!value.getAsInteger(16, cpu))
2010 ++num_keys_decoded;
2011 } else if (name.equals("cpusubtype")) {
2012 if (!value.getAsInteger(16, sub))
2013 ++num_keys_decoded;
2014 } else if (name.equals("triple")) {
2015 StringExtractor extractor(value);
2016 extractor.GetHexByteString(triple);
2017 ++num_keys_decoded;
2018 } else if (name.equals("ostype")) {
2019 os_name = value;
2020 ++num_keys_decoded;
2021 } else if (name.equals("vendor")) {
2022 vendor_name = value;
2023 ++num_keys_decoded;
2024 } else if (name.equals("endian")) {
2025 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2026 .Case("little", eByteOrderLittle)
2027 .Case("big", eByteOrderBig)
2028 .Case("pdp", eByteOrderPDP)
2029 .Default(eByteOrderInvalid);
2030 if (byte_order != eByteOrderInvalid)
2031 ++num_keys_decoded;
2032 } else if (name.equals("ptrsize")) {
2033 if (!value.getAsInteger(16, pointer_byte_size))
2034 ++num_keys_decoded;
2035 } else if (name.equals("pid")) {
2036 if (!value.getAsInteger(16, pid))
2037 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002038 } else if (name.equals("elf_abi")) {
2039 elf_abi = value;
2040 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002041 }
2042 }
2043 if (num_keys_decoded > 0)
2044 m_qProcessInfo_is_valid = eLazyBoolYes;
2045 if (pid != LLDB_INVALID_PROCESS_ID) {
2046 m_curr_pid_is_valid = eLazyBoolYes;
2047 m_curr_pid = pid;
2048 }
2049
2050 // Set the ArchSpec from the triple if we have it.
2051 if (!triple.empty()) {
2052 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00002053 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002054 if (pointer_byte_size) {
2055 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2056 }
2057 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2058 !vendor_name.empty()) {
2059 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2060
2061 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00002062 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002063 switch (triple.getObjectFormat()) {
2064 case llvm::Triple::MachO:
2065 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2066 break;
2067 case llvm::Triple::ELF:
2068 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2069 break;
2070 case llvm::Triple::COFF:
2071 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2072 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00002073 case llvm::Triple::Wasm:
2074 if (log)
2075 log->Printf("error: not supported target architecture");
2076 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002077 case llvm::Triple::UnknownObjectFormat:
2078 if (log)
2079 log->Printf("error: failed to determine target architecture");
2080 return false;
2081 }
2082
2083 if (pointer_byte_size) {
2084 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2085 }
2086 if (byte_order != eByteOrderInvalid) {
2087 assert(byte_order == m_process_arch.GetByteOrder());
2088 }
2089 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2090 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2091 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2092 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2093 }
2094 return true;
2095 }
2096 } else {
2097 m_qProcessInfo_is_valid = eLazyBoolNo;
2098 }
2099
2100 return false;
2101}
2102
2103uint32_t GDBRemoteCommunicationClient::FindProcesses(
2104 const ProcessInstanceInfoMatch &match_info,
2105 ProcessInstanceInfoList &process_infos) {
2106 process_infos.Clear();
2107
2108 if (m_supports_qfProcessInfo) {
2109 StreamString packet;
2110 packet.PutCString("qfProcessInfo");
2111 if (!match_info.MatchAllProcesses()) {
2112 packet.PutChar(':');
2113 const char *name = match_info.GetProcessInfo().GetName();
2114 bool has_name_match = false;
2115 if (name && name[0]) {
2116 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00002117 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002118 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00002119 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002120 has_name_match = false;
2121 break;
2122
Pavel Labathc4a33952017-02-20 11:35:33 +00002123 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002124 packet.PutCString("name_match:equals;");
2125 break;
2126
Pavel Labathc4a33952017-02-20 11:35:33 +00002127 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 packet.PutCString("name_match:contains;");
2129 break;
2130
Pavel Labathc4a33952017-02-20 11:35:33 +00002131 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132 packet.PutCString("name_match:starts_with;");
2133 break;
2134
Pavel Labathc4a33952017-02-20 11:35:33 +00002135 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002136 packet.PutCString("name_match:ends_with;");
2137 break;
2138
Pavel Labathc4a33952017-02-20 11:35:33 +00002139 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002140 packet.PutCString("name_match:regex;");
2141 break;
2142 }
2143 if (has_name_match) {
2144 packet.PutCString("name:");
2145 packet.PutBytesAsRawHex8(name, ::strlen(name));
2146 packet.PutChar(';');
2147 }
2148 }
2149
2150 if (match_info.GetProcessInfo().ProcessIDIsValid())
2151 packet.Printf("pid:%" PRIu64 ";",
2152 match_info.GetProcessInfo().GetProcessID());
2153 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2154 packet.Printf("parent_pid:%" PRIu64 ";",
2155 match_info.GetProcessInfo().GetParentProcessID());
2156 if (match_info.GetProcessInfo().UserIDIsValid())
2157 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2158 if (match_info.GetProcessInfo().GroupIDIsValid())
2159 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2160 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2161 packet.Printf("euid:%u;",
2162 match_info.GetProcessInfo().GetEffectiveUserID());
2163 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2164 packet.Printf("egid:%u;",
2165 match_info.GetProcessInfo().GetEffectiveGroupID());
2166 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2167 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2168 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2169 const ArchSpec &match_arch =
2170 match_info.GetProcessInfo().GetArchitecture();
2171 const llvm::Triple &triple = match_arch.GetTriple();
2172 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002173 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 packet.PutChar(';');
2175 }
2176 }
2177 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +00002178 // Increase timeout as the first qfProcessInfo packet takes a long time on
2179 // Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002180 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002181 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2182 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 do {
2184 ProcessInstanceInfo process_info;
2185 if (!DecodeProcessInfoResponse(response, process_info))
2186 break;
2187 process_infos.Append(process_info);
2188 response.GetStringRef().clear();
2189 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002190 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2191 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192 } else {
2193 m_supports_qfProcessInfo = false;
2194 return 0;
2195 }
2196 }
2197 return process_infos.GetSize();
2198}
2199
2200bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2201 std::string &name) {
2202 if (m_supports_qUserName) {
2203 char packet[32];
2204 const int packet_len =
2205 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2206 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002207 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002209 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002210 PacketResult::Success) {
2211 if (response.IsNormalResponse()) {
2212 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002213 // the hex encoded user name and should make up the entire packet. If
2214 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215 if (response.GetHexByteString(name) * 2 ==
2216 response.GetStringRef().size())
2217 return true;
2218 }
2219 } else {
2220 m_supports_qUserName = false;
2221 return false;
2222 }
2223 }
2224 return false;
2225}
2226
2227bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2228 std::string &name) {
2229 if (m_supports_qGroupName) {
2230 char packet[32];
2231 const int packet_len =
2232 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2233 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002234 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002236 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237 PacketResult::Success) {
2238 if (response.IsNormalResponse()) {
2239 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002240 // the hex encoded group name and should make up the entire packet. If
2241 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002242 if (response.GetHexByteString(name) * 2 ==
2243 response.GetStringRef().size())
2244 return true;
2245 }
2246 } else {
2247 m_supports_qGroupName = false;
2248 return false;
2249 }
2250 }
2251 return false;
2252}
2253
2254bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2255 // Form non-stop packet request
2256 char packet[32];
2257 const int packet_len =
2258 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2259 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002260 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261
2262 StringExtractorGDBRemote response;
2263 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002264 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 PacketResult::Success)
2266 if (response.IsOKResponse())
2267 return true;
2268
2269 // Failed or not supported
2270 return false;
2271}
2272
2273static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2274 uint32_t recv_size) {
2275 packet.Clear();
2276 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2277 uint32_t bytes_left = send_size;
2278 while (bytes_left > 0) {
2279 if (bytes_left >= 26) {
2280 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2281 bytes_left -= 26;
2282 } else {
2283 packet.Printf("%*.*s;", bytes_left, bytes_left,
2284 "abcdefghijklmnopqrstuvwxyz");
2285 bytes_left = 0;
2286 }
2287 }
2288}
2289
Pavel Labath1eff73c2016-11-24 10:54:49 +00002290duration<float>
2291calculate_standard_deviation(const std::vector<duration<float>> &v) {
2292 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002293 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2294 Dur mean = sum / v.size();
2295 float accum = 0;
2296 for (auto d : v) {
2297 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002299 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002300
Pavel Labath3aa04912016-10-31 17:19:42 +00002301 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302}
2303
2304void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2305 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002306 uint32_t max_recv,
2307 uint64_t recv_amount,
2308 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002309 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002310 if (SendSpeedTestPacket(0, 0)) {
2311 StreamString packet;
2312 if (json)
2313 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2314 "\"results\" : [",
2315 num_packets);
2316 else
2317 strm.Printf("Testing sending %u packets of various sizes:\n",
2318 num_packets);
2319 strm.Flush();
2320
2321 uint32_t result_idx = 0;
2322 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002323 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324
2325 for (send_size = 0; send_size <= max_send;
2326 send_size ? send_size *= 2 : send_size = 4) {
2327 for (uint32_t recv_size = 0; recv_size <= max_recv;
2328 recv_size ? recv_size *= 2 : recv_size = 4) {
2329 MakeSpeedTestPacket(packet, send_size, recv_size);
2330
2331 packet_times.clear();
2332 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002333 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002334 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002335 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002336 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002337 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002338 const auto packet_end_time = steady_clock::now();
2339 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002340 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002341 const auto end_time = steady_clock::now();
2342 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002343
2344 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002345 ((float)num_packets) / duration<float>(total_time).count();
2346 auto average_per_packet = total_time / num_packets;
2347 const duration<float> standard_deviation =
2348 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002349 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002350 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2351 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2352 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002353 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002354 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002355 ++result_idx;
2356 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002357 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2358 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2359 "standard deviation of {5,10:ms+f6}\n",
2360 send_size, recv_size, duration<float>(total_time),
2361 packets_per_second, duration<float>(average_per_packet),
2362 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002363 }
2364 strm.Flush();
2365 }
2366 }
2367
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002368 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002369 if (json)
2370 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2371 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002372 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002373 else
2374 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2375 "packet sizes:\n",
2376 k_recv_amount_mb);
2377 strm.Flush();
2378 send_size = 0;
2379 result_idx = 0;
2380 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2381 MakeSpeedTestPacket(packet, send_size, recv_size);
2382
2383 // If we have a receive size, test how long it takes to receive 4MB of
2384 // data
2385 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002386 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387 uint32_t bytes_read = 0;
2388 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002389 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002390 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002391 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392 bytes_read += recv_size;
2393 ++packet_count;
2394 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002395 const auto end_time = steady_clock::now();
2396 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002397 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002398 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002399 (1024.0 * 1024.0);
2400 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002401 ((float)packet_count) / duration<float>(total_time).count();
2402 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403
2404 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002405 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2406 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002408 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002409 ++result_idx;
2410 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002411 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2412 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2413 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002414 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002415 duration<float>(total_time), mb_second,
2416 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002417 }
2418 strm.Flush();
2419 }
2420 }
2421 if (json)
2422 strm.Printf("\n ]\n }\n}\n");
2423 else
2424 strm.EOL();
2425 }
2426}
2427
2428bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2429 uint32_t recv_size) {
2430 StreamString packet;
2431 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2432 uint32_t bytes_left = send_size;
2433 while (bytes_left > 0) {
2434 if (bytes_left >= 26) {
2435 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2436 bytes_left -= 26;
2437 } else {
2438 packet.Printf("%*.*s;", bytes_left, bytes_left,
2439 "abcdefghijklmnopqrstuvwxyz");
2440 bytes_left = 0;
2441 }
2442 }
2443
2444 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002445 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2446 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447}
2448
2449bool GDBRemoteCommunicationClient::LaunchGDBServer(
2450 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2451 std::string &socket_name) {
2452 pid = LLDB_INVALID_PROCESS_ID;
2453 port = 0;
2454 socket_name.clear();
2455
2456 StringExtractorGDBRemote response;
2457 StreamString stream;
2458 stream.PutCString("qLaunchGDBServer;");
2459 std::string hostname;
2460 if (remote_accept_hostname && remote_accept_hostname[0])
2461 hostname = remote_accept_hostname;
2462 else {
2463 if (HostInfo::GetHostname(hostname)) {
2464 // Make the GDB server we launch only accept connections from this host
2465 stream.Printf("host:%s;", hostname.c_str());
2466 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002467 // Make the GDB server we launch accept connections from any host since
2468 // we can't figure out the hostname
Kate Stoneb9c1b512016-09-06 20:57:50 +00002469 stream.Printf("host:*;");
2470 }
2471 }
2472 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002473 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474
2475 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2476 PacketResult::Success) {
2477 llvm::StringRef name;
2478 llvm::StringRef value;
2479 while (response.GetNameColonValue(name, value)) {
2480 if (name.equals("port"))
2481 value.getAsInteger(0, port);
2482 else if (name.equals("pid"))
2483 value.getAsInteger(0, pid);
2484 else if (name.compare("socket_name") == 0) {
2485 StringExtractor extractor(value);
2486 extractor.GetHexByteString(socket_name);
2487 }
2488 }
2489 return true;
2490 }
2491 return false;
2492}
2493
2494size_t GDBRemoteCommunicationClient::QueryGDBServer(
2495 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2496 connection_urls.clear();
2497
2498 StringExtractorGDBRemote response;
2499 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2500 PacketResult::Success)
2501 return 0;
2502
2503 StructuredData::ObjectSP data =
2504 StructuredData::ParseJSON(response.GetStringRef());
2505 if (!data)
2506 return 0;
2507
2508 StructuredData::Array *array = data->GetAsArray();
2509 if (!array)
2510 return 0;
2511
2512 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2513 StructuredData::Dictionary *element = nullptr;
2514 if (!array->GetItemAtIndexAsDictionary(i, element))
2515 continue;
2516
2517 uint16_t port = 0;
2518 if (StructuredData::ObjectSP port_osp =
2519 element->GetValueForKey(llvm::StringRef("port")))
2520 port = port_osp->GetIntegerValue(0);
2521
2522 std::string socket_name;
2523 if (StructuredData::ObjectSP socket_name_osp =
2524 element->GetValueForKey(llvm::StringRef("socket_name")))
2525 socket_name = socket_name_osp->GetStringValue();
2526
2527 if (port != 0 || !socket_name.empty())
2528 connection_urls.emplace_back(port, socket_name);
2529 }
2530 return connection_urls.size();
2531}
2532
2533bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2534 StreamString stream;
2535 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536
2537 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002538 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002539 PacketResult::Success) {
2540 if (response.IsOKResponse())
2541 return true;
2542 }
2543 return false;
2544}
2545
2546bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2547 if (m_curr_tid == tid)
2548 return true;
2549
2550 char packet[32];
2551 int packet_len;
2552 if (tid == UINT64_MAX)
2553 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2554 else
2555 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2556 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002557 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002558 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002559 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002560 PacketResult::Success) {
2561 if (response.IsOKResponse()) {
2562 m_curr_tid = tid;
2563 return true;
2564 }
2565
2566 /*
2567 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2568 * Hg packet.
2569 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2570 * which can
2571 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2572 */
2573 if (response.IsUnsupportedResponse() && IsConnected()) {
2574 m_curr_tid = 1;
2575 return true;
2576 }
2577 }
2578 return false;
2579}
2580
2581bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2582 if (m_curr_tid_run == tid)
2583 return true;
2584
2585 char packet[32];
2586 int packet_len;
2587 if (tid == UINT64_MAX)
2588 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2589 else
2590 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2591
2592 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002593 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002594 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002595 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002596 PacketResult::Success) {
2597 if (response.IsOKResponse()) {
2598 m_curr_tid_run = tid;
2599 return true;
2600 }
2601
2602 /*
2603 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2604 * Hc packet.
2605 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2606 * which can
2607 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2608 */
2609 if (response.IsUnsupportedResponse() && IsConnected()) {
2610 m_curr_tid_run = 1;
2611 return true;
2612 }
2613 }
2614 return false;
2615}
2616
2617bool GDBRemoteCommunicationClient::GetStopReply(
2618 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002619 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002620 PacketResult::Success)
2621 return response.IsNormalResponse();
2622 return false;
2623}
2624
2625bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2626 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2627 if (m_supports_qThreadStopInfo) {
2628 char packet[256];
2629 int packet_len =
2630 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2631 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002632 UNUSED_IF_ASSERT_DISABLED(packet_len);
2633 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634 PacketResult::Success) {
2635 if (response.IsUnsupportedResponse())
2636 m_supports_qThreadStopInfo = false;
2637 else if (response.IsNormalResponse())
2638 return true;
2639 else
2640 return false;
2641 } else {
2642 m_supports_qThreadStopInfo = false;
2643 }
2644 }
2645 return false;
2646}
2647
2648uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2649 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2650 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2651 if (log)
2652 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2653 __FUNCTION__, insert ? "add" : "remove", addr);
2654
2655 // Check if the stub is known not to support this breakpoint type
2656 if (!SupportsGDBStoppointPacket(type))
2657 return UINT8_MAX;
2658 // Construct the breakpoint packet
2659 char packet[64];
2660 const int packet_len =
2661 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2662 insert ? 'Z' : 'z', type, addr, length);
2663 // Check we haven't overwritten the end of the packet buffer
2664 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002665 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002666 StringExtractorGDBRemote response;
2667 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2668 // or "" (unsupported)
2669 response.SetResponseValidatorToOKErrorNotSupported();
2670 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002671 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002672 PacketResult::Success) {
2673 // Receive and OK packet when the breakpoint successfully placed
2674 if (response.IsOKResponse())
2675 return 0;
2676
Zachary Turner97206d52017-05-12 04:51:55 +00002677 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 if (response.IsErrorResponse())
2679 return response.GetError();
2680
2681 // Empty packet informs us that breakpoint is not supported
2682 if (response.IsUnsupportedResponse()) {
2683 // Disable this breakpoint type since it is unsupported
2684 switch (type) {
2685 case eBreakpointSoftware:
2686 m_supports_z0 = false;
2687 break;
2688 case eBreakpointHardware:
2689 m_supports_z1 = false;
2690 break;
2691 case eWatchpointWrite:
2692 m_supports_z2 = false;
2693 break;
2694 case eWatchpointRead:
2695 m_supports_z3 = false;
2696 break;
2697 case eWatchpointReadWrite:
2698 m_supports_z4 = false;
2699 break;
2700 case eStoppointInvalid:
2701 return UINT8_MAX;
2702 }
2703 }
2704 }
2705 // Signal generic failure
2706 return UINT8_MAX;
2707}
2708
2709size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2710 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2711 thread_ids.clear();
2712
2713 Lock lock(*this, false);
2714 if (lock) {
2715 sequence_mutex_unavailable = false;
2716 StringExtractorGDBRemote response;
2717
2718 PacketResult packet_result;
2719 for (packet_result =
2720 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2721 packet_result == PacketResult::Success && response.IsNormalResponse();
2722 packet_result =
2723 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2724 char ch = response.GetChar();
2725 if (ch == 'l')
2726 break;
2727 if (ch == 'm') {
2728 do {
2729 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2730
2731 if (tid != LLDB_INVALID_THREAD_ID) {
2732 thread_ids.push_back(tid);
2733 }
2734 ch = response.GetChar(); // Skip the command separator
2735 } while (ch == ','); // Make sure we got a comma separator
2736 }
2737 }
2738
2739 /*
2740 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2741 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2742 * could
2743 * be as simple as 'S05'. There is no packet which can give us pid and/or
2744 * tid.
2745 * Assume pid=tid=1 in such cases.
2746 */
Tamas Berghammer1492cb82017-09-18 10:24:48 +00002747 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2748 thread_ids.size() == 0 && IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749 thread_ids.push_back(1);
2750 }
2751 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002752#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002753 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2754 GDBR_LOG_PACKETS));
2755 if (log)
2756 log->Printf("error: failed to get packet sequence mutex, not sending "
2757 "packet 'qfThreadInfo'");
2758#endif
2759 sequence_mutex_unavailable = true;
2760 }
2761 return thread_ids.size();
2762}
2763
2764lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2765 StringExtractorGDBRemote response;
2766 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2767 PacketResult::Success ||
2768 !response.IsNormalResponse())
2769 return LLDB_INVALID_ADDRESS;
2770 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2771}
2772
Zachary Turner97206d52017-05-12 04:51:55 +00002773lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002774 const char *command, // Shouldn't be NULL
2775 const FileSpec &
2776 working_dir, // Pass empty FileSpec to use the current working directory
2777 int *status_ptr, // Pass NULL if you don't want the process exit status
2778 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2779 // process to exit
2780 std::string
2781 *command_output, // Pass NULL if you don't want the command output
Pavel Labath19dd1a02018-05-10 10:46:03 +00002782 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 lldb_private::StreamString stream;
2784 stream.PutCString("qPlatform_shell:");
2785 stream.PutBytesAsRawHex8(command, strlen(command));
2786 stream.PutChar(',');
Pavel Labath19dd1a02018-05-10 10:46:03 +00002787 uint32_t timeout_sec = UINT32_MAX;
2788 if (timeout) {
2789 // TODO: Use chrono version of std::ceil once c++17 is available.
2790 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2791 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 stream.PutHex32(timeout_sec);
2793 if (working_dir) {
2794 std::string path{working_dir.GetPath(false)};
2795 stream.PutChar(',');
2796 stream.PutCStringAsRawHex8(path.c_str());
2797 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002798 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002799 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 PacketResult::Success) {
2801 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002802 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002804 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2806 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002807 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808 else if (status_ptr)
2809 *status_ptr = exitcode;
2810 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002811 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2813 if (signo_ptr)
2814 *signo_ptr = signo;
2815 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002816 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 std::string output;
2818 response.GetEscapedBinaryData(output);
2819 if (command_output)
2820 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002821 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 }
Zachary Turner97206d52017-05-12 04:51:55 +00002823 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002824}
2825
Zachary Turner97206d52017-05-12 04:51:55 +00002826Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2827 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 std::string path{file_spec.GetPath(false)};
2829 lldb_private::StreamString stream;
2830 stream.PutCString("qPlatform_mkdir:");
2831 stream.PutHex32(file_permissions);
2832 stream.PutChar(',');
2833 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002834 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002835 StringExtractorGDBRemote response;
2836
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002837 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002839 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002840
2841 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002842 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843
Zachary Turner97206d52017-05-12 04:51:55 +00002844 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845}
2846
Zachary Turner97206d52017-05-12 04:51:55 +00002847Status
2848GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2849 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 std::string path{file_spec.GetPath(false)};
2851 lldb_private::StreamString stream;
2852 stream.PutCString("qPlatform_chmod:");
2853 stream.PutHex32(file_permissions);
2854 stream.PutChar(',');
2855 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002856 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857 StringExtractorGDBRemote response;
2858
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002859 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002860 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002861 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002862
2863 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002864 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002865
Zachary Turner97206d52017-05-12 04:51:55 +00002866 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867}
2868
2869static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002870 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002871 response.SetFilePos(0);
2872 if (response.GetChar() != 'F')
2873 return fail_result;
2874 int32_t result = response.GetS32(-2);
2875 if (result == -2)
2876 return fail_result;
2877 if (response.GetChar() == ',') {
2878 int result_errno = response.GetS32(-2);
2879 if (result_errno != -2)
2880 error.SetError(result_errno, eErrorTypePOSIX);
2881 else
2882 error.SetError(-1, eErrorTypeGeneric);
2883 } else
2884 error.Clear();
2885 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002886}
2887lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2889 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002890 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002891 std::string path(file_spec.GetPath(false));
2892 lldb_private::StreamString stream;
2893 stream.PutCString("vFile:open:");
2894 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002895 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002896 stream.PutCStringAsRawHex8(path.c_str());
2897 stream.PutChar(',');
2898 stream.PutHex32(flags);
2899 stream.PutChar(',');
2900 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002902 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 PacketResult::Success) {
2904 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2905 }
2906 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002907}
2908
Zachary Turner97206d52017-05-12 04:51:55 +00002909bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2910 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002911 lldb_private::StreamString stream;
2912 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002914 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002915 PacketResult::Success) {
2916 return ParseHostIOPacketResponse(response, -1, error) == 0;
2917 }
2918 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002919}
2920
2921// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002922lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2923 const lldb_private::FileSpec &file_spec) {
2924 std::string path(file_spec.GetPath(false));
2925 lldb_private::StreamString stream;
2926 stream.PutCString("vFile:size:");
2927 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002928 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002929 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002930 PacketResult::Success) {
2931 if (response.GetChar() != 'F')
2932 return UINT64_MAX;
2933 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2934 return retcode;
2935 }
2936 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002937}
2938
Zachary Turner97206d52017-05-12 04:51:55 +00002939Status
2940GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2941 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002942 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002943 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002944 lldb_private::StreamString stream;
2945 stream.PutCString("vFile:mode:");
2946 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002947 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002948 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002949 PacketResult::Success) {
2950 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002951 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002952 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002953 } else {
2954 const uint32_t mode = response.GetS32(-1);
2955 if (static_cast<int32_t>(mode) == -1) {
2956 if (response.GetChar() == ',') {
2957 int response_errno = response.GetS32(-1);
2958 if (response_errno > 0)
2959 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2960 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002961 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002962 } else
2963 error.SetErrorToGenericError();
2964 } else {
2965 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2966 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002967 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002968 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002969 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002970 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002971 }
2972 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002973}
2974
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2976 uint64_t offset, void *dst,
2977 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002978 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002979 lldb_private::StreamString stream;
2980 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2981 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002983 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984 PacketResult::Success) {
2985 if (response.GetChar() != 'F')
2986 return 0;
2987 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2988 if (retcode == UINT32_MAX)
2989 return retcode;
2990 const char next = (response.Peek() ? *response.Peek() : 0);
2991 if (next == ',')
2992 return 0;
2993 if (next == ';') {
2994 response.GetChar(); // skip the semicolon
2995 std::string buffer;
2996 if (response.GetEscapedBinaryData(buffer)) {
2997 const uint64_t data_to_write =
2998 std::min<uint64_t>(dst_len, buffer.size());
2999 if (data_to_write > 0)
3000 memcpy(dst, &buffer[0], data_to_write);
3001 return data_to_write;
3002 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003003 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003004 }
3005 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003006}
3007
Kate Stoneb9c1b512016-09-06 20:57:50 +00003008uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3009 uint64_t offset,
3010 const void *src,
3011 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003012 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003013 lldb_private::StreamGDBRemote stream;
3014 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3015 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003016 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003017 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003018 PacketResult::Success) {
3019 if (response.GetChar() != 'F') {
3020 error.SetErrorStringWithFormat("write file failed");
3021 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003022 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003023 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3024 if (bytes_written == UINT64_MAX) {
3025 error.SetErrorToGenericError();
3026 if (response.GetChar() == ',') {
3027 int response_errno = response.GetS32(-1);
3028 if (response_errno > 0)
3029 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3030 }
3031 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003032 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003033 return bytes_written;
3034 } else {
3035 error.SetErrorString("failed to send vFile:pwrite packet");
3036 }
3037 return 0;
3038}
3039
Zachary Turner97206d52017-05-12 04:51:55 +00003040Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3041 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003043 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003044 lldb_private::StreamGDBRemote stream;
3045 stream.PutCString("vFile:symlink:");
3046 // the unix symlink() command reverses its parameters where the dst if first,
3047 // so we follow suit here
3048 stream.PutCStringAsRawHex8(dst_path.c_str());
3049 stream.PutChar(',');
3050 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003051 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003052 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003053 PacketResult::Success) {
3054 if (response.GetChar() == 'F') {
3055 uint32_t result = response.GetU32(UINT32_MAX);
3056 if (result != 0) {
3057 error.SetErrorToGenericError();
3058 if (response.GetChar() == ',') {
3059 int response_errno = response.GetS32(-1);
3060 if (response_errno > 0)
3061 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3062 }
3063 }
3064 } else {
3065 // Should have returned with 'F<result>[,<errno>]'
3066 error.SetErrorStringWithFormat("symlink failed");
3067 }
3068 } else {
3069 error.SetErrorString("failed to send vFile:symlink packet");
3070 }
3071 return error;
3072}
3073
Zachary Turner97206d52017-05-12 04:51:55 +00003074Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003075 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003076 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003077 lldb_private::StreamGDBRemote stream;
3078 stream.PutCString("vFile:unlink:");
3079 // the unix symlink() command reverses its parameters where the dst if first,
3080 // so we follow suit here
3081 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003083 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003084 PacketResult::Success) {
3085 if (response.GetChar() == 'F') {
3086 uint32_t result = response.GetU32(UINT32_MAX);
3087 if (result != 0) {
3088 error.SetErrorToGenericError();
3089 if (response.GetChar() == ',') {
3090 int response_errno = response.GetS32(-1);
3091 if (response_errno > 0)
3092 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3093 }
3094 }
3095 } else {
3096 // Should have returned with 'F<result>[,<errno>]'
3097 error.SetErrorStringWithFormat("unlink failed");
3098 }
3099 } else {
3100 error.SetErrorString("failed to send vFile:unlink packet");
3101 }
3102 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00003103}
3104
Daniel Maleae0f8f572013-08-26 23:57:52 +00003105// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003106bool GDBRemoteCommunicationClient::GetFileExists(
3107 const lldb_private::FileSpec &file_spec) {
3108 std::string path(file_spec.GetPath(false));
3109 lldb_private::StreamString stream;
3110 stream.PutCString("vFile:exists:");
3111 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003112 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003113 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003114 PacketResult::Success) {
3115 if (response.GetChar() != 'F')
3116 return false;
3117 if (response.GetChar() != ',')
3118 return false;
3119 bool retcode = (response.GetChar() != '0');
3120 return retcode;
3121 }
3122 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003123}
3124
Kate Stoneb9c1b512016-09-06 20:57:50 +00003125bool GDBRemoteCommunicationClient::CalculateMD5(
3126 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3127 std::string path(file_spec.GetPath(false));
3128 lldb_private::StreamString stream;
3129 stream.PutCString("vFile:MD5:");
3130 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003132 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003133 PacketResult::Success) {
3134 if (response.GetChar() != 'F')
3135 return false;
3136 if (response.GetChar() != ',')
3137 return false;
3138 if (response.Peek() && *response.Peek() == 'x')
3139 return false;
3140 low = response.GetHexMaxU64(false, UINT64_MAX);
3141 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003142 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003143 }
3144 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003145}
3146
Kate Stoneb9c1b512016-09-06 20:57:50 +00003147bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3148 // Some targets have issues with g/G packets and we need to avoid using them
3149 if (m_avoid_g_packets == eLazyBoolCalculate) {
3150 if (process) {
3151 m_avoid_g_packets = eLazyBoolNo;
3152 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3153 if (arch.IsValid() &&
3154 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3155 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3156 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3157 m_avoid_g_packets = eLazyBoolYes;
3158 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3159 if (gdb_server_version != 0) {
3160 const char *gdb_server_name = GetGDBServerProgramName();
3161 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3162 if (gdb_server_version >= 310)
3163 m_avoid_g_packets = eLazyBoolNo;
3164 }
3165 }
3166 }
3167 }
3168 }
3169 return m_avoid_g_packets == eLazyBoolYes;
3170}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003171
Kate Stoneb9c1b512016-09-06 20:57:50 +00003172DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3173 uint32_t reg) {
3174 StreamString payload;
3175 payload.Printf("p%x", reg);
3176 StringExtractorGDBRemote response;
3177 if (SendThreadSpecificPacketAndWaitForResponse(
3178 tid, std::move(payload), response, false) != PacketResult::Success ||
3179 !response.IsNormalResponse())
3180 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003181
Kate Stoneb9c1b512016-09-06 20:57:50 +00003182 DataBufferSP buffer_sp(
3183 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3184 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3185 return buffer_sp;
3186}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003187
Kate Stoneb9c1b512016-09-06 20:57:50 +00003188DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3189 StreamString payload;
3190 payload.PutChar('g');
3191 StringExtractorGDBRemote response;
3192 if (SendThreadSpecificPacketAndWaitForResponse(
3193 tid, std::move(payload), response, false) != PacketResult::Success ||
3194 !response.IsNormalResponse())
3195 return nullptr;
3196
3197 DataBufferSP buffer_sp(
3198 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3199 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3200 return buffer_sp;
3201}
3202
3203bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3204 uint32_t reg_num,
3205 llvm::ArrayRef<uint8_t> data) {
3206 StreamString payload;
3207 payload.Printf("P%x=", reg_num);
3208 payload.PutBytesAsRawHex8(data.data(), data.size(),
3209 endian::InlHostByteOrder(),
3210 endian::InlHostByteOrder());
3211 StringExtractorGDBRemote response;
3212 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3213 response, false) ==
3214 PacketResult::Success &&
3215 response.IsOKResponse();
3216}
3217
3218bool GDBRemoteCommunicationClient::WriteAllRegisters(
3219 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3220 StreamString payload;
3221 payload.PutChar('G');
3222 payload.PutBytesAsRawHex8(data.data(), data.size(),
3223 endian::InlHostByteOrder(),
3224 endian::InlHostByteOrder());
3225 StringExtractorGDBRemote response;
3226 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3227 response, false) ==
3228 PacketResult::Success &&
3229 response.IsOKResponse();
3230}
3231
3232bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3233 uint32_t &save_id) {
3234 save_id = 0; // Set to invalid save ID
3235 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003236 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003237
3238 m_supports_QSaveRegisterState = eLazyBoolYes;
3239 StreamString payload;
3240 payload.PutCString("QSaveRegisterState");
3241 StringExtractorGDBRemote response;
3242 if (SendThreadSpecificPacketAndWaitForResponse(
3243 tid, std::move(payload), response, false) != PacketResult::Success)
3244 return false;
3245
3246 if (response.IsUnsupportedResponse())
3247 m_supports_QSaveRegisterState = eLazyBoolNo;
3248
3249 const uint32_t response_save_id = response.GetU32(0);
3250 if (response_save_id == 0)
3251 return false;
3252
3253 save_id = response_save_id;
3254 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003255}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003256
Kate Stoneb9c1b512016-09-06 20:57:50 +00003257bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3258 uint32_t save_id) {
3259 // We use the "m_supports_QSaveRegisterState" variable here because the
Adrian Prantl05097242018-04-30 16:49:04 +00003260 // QSaveRegisterState and QRestoreRegisterState packets must both be
3261 // supported in order to be useful
Kate Stoneb9c1b512016-09-06 20:57:50 +00003262 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3263 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003264
Kate Stoneb9c1b512016-09-06 20:57:50 +00003265 StreamString payload;
3266 payload.Printf("QRestoreRegisterState:%u", save_id);
3267 StringExtractorGDBRemote response;
3268 if (SendThreadSpecificPacketAndWaitForResponse(
3269 tid, std::move(payload), response, false) != PacketResult::Success)
3270 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003271
Kate Stoneb9c1b512016-09-06 20:57:50 +00003272 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003273 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003274
3275 if (response.IsUnsupportedResponse())
3276 m_supports_QSaveRegisterState = eLazyBoolNo;
3277 return false;
3278}
3279
3280bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3281 if (!GetSyncThreadStateSupported())
3282 return false;
3283
3284 StreamString packet;
3285 StringExtractorGDBRemote response;
3286 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3287 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3288 GDBRemoteCommunication::PacketResult::Success &&
3289 response.IsOKResponse();
3290}
3291
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003292lldb::user_id_t
3293GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3294 Status &error) {
3295 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3296 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3297
3298 StreamGDBRemote escaped_packet;
3299 escaped_packet.PutCString("jTraceStart:");
3300
3301 StructuredData::Dictionary json_packet;
3302 json_packet.AddIntegerItem("type", options.getType());
3303 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3304 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3305
3306 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3307 json_packet.AddIntegerItem("threadid", options.getThreadID());
3308
3309 StructuredData::DictionarySP custom_params = options.getTraceParams();
3310 if (custom_params)
3311 json_packet.AddItem("params", custom_params);
3312
3313 StreamString json_string;
3314 json_packet.Dump(json_string, false);
3315 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3316
3317 StringExtractorGDBRemote response;
3318 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3319 true) ==
3320 GDBRemoteCommunication::PacketResult::Success) {
3321 if (!response.IsNormalResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003322 error = response.GetStatus();
3323 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003324 } else {
3325 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3326 }
3327 } else {
3328 LLDB_LOG(log, "failed to send packet");
3329 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3330 escaped_packet.GetData());
3331 }
3332 return ret_uid;
3333}
3334
3335Status
3336GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3337 lldb::tid_t thread_id) {
3338 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3339 StringExtractorGDBRemote response;
3340 Status error;
3341
3342 StructuredData::Dictionary json_packet;
3343 StreamGDBRemote escaped_packet;
3344 StreamString json_string;
3345 escaped_packet.PutCString("jTraceStop:");
3346
3347 json_packet.AddIntegerItem("traceid", uid);
3348
3349 if (thread_id != LLDB_INVALID_THREAD_ID)
3350 json_packet.AddIntegerItem("threadid", thread_id);
3351
3352 json_packet.Dump(json_string, false);
3353
3354 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3355
3356 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3357 true) ==
3358 GDBRemoteCommunication::PacketResult::Success) {
3359 if (!response.IsOKResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003360 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003361 LLDB_LOG(log, "stop tracing failed");
3362 }
3363 } else {
3364 LLDB_LOG(log, "failed to send packet");
3365 error.SetErrorStringWithFormat(
3366 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3367 response.GetError());
3368 }
3369 return error;
3370}
3371
3372Status GDBRemoteCommunicationClient::SendGetDataPacket(
3373 lldb::user_id_t uid, lldb::tid_t thread_id,
3374 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003375
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003376 StreamGDBRemote escaped_packet;
3377 escaped_packet.PutCString("jTraceBufferRead:");
3378 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3379}
3380
3381Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3382 lldb::user_id_t uid, lldb::tid_t thread_id,
3383 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003384
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003385 StreamGDBRemote escaped_packet;
3386 escaped_packet.PutCString("jTraceMetaRead:");
3387 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3388}
3389
3390Status
3391GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3392 TraceOptions &options) {
3393 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3394 StringExtractorGDBRemote response;
3395 Status error;
3396
3397 StreamString json_string;
3398 StreamGDBRemote escaped_packet;
3399 escaped_packet.PutCString("jTraceConfigRead:");
3400
3401 StructuredData::Dictionary json_packet;
3402 json_packet.AddIntegerItem("traceid", uid);
3403
3404 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3405 json_packet.AddIntegerItem("threadid", options.getThreadID());
3406
3407 json_packet.Dump(json_string, false);
3408 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3409
3410 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3411 true) ==
3412 GDBRemoteCommunication::PacketResult::Success) {
3413 if (response.IsNormalResponse()) {
3414 uint64_t type = std::numeric_limits<uint64_t>::max();
3415 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3416 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3417
3418 auto json_object = StructuredData::ParseJSON(response.Peek());
3419
3420 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003421 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003422 error.SetErrorString("Invalid Configuration obtained");
3423 return error;
3424 }
3425
3426 auto json_dict = json_object->GetAsDictionary();
3427
3428 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3429 metabuffersize);
3430 options.setMetaDataBufferSize(metabuffersize);
3431
3432 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3433 options.setTraceBufferSize(buffersize);
3434
3435 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3436 options.setType(static_cast<lldb::TraceType>(type));
3437
3438 StructuredData::ObjectSP custom_params_sp =
3439 json_dict->GetValueForKey("params");
3440 if (custom_params_sp) {
3441 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003442 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003443 error.SetErrorString("Invalid Configuration obtained");
3444 return error;
3445 } else
3446 options.setTraceParams(
3447 static_pointer_cast<StructuredData::Dictionary>(
3448 custom_params_sp));
3449 }
3450 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003451 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003452 }
3453 } else {
3454 LLDB_LOG(log, "failed to send packet");
3455 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3456 escaped_packet.GetData());
3457 }
3458 return error;
3459}
3460
3461Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3462 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3463 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3464 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3465 Status error;
3466
3467 StructuredData::Dictionary json_packet;
3468
3469 json_packet.AddIntegerItem("traceid", uid);
3470 json_packet.AddIntegerItem("offset", offset);
3471 json_packet.AddIntegerItem("buffersize", buffer.size());
3472
3473 if (thread_id != LLDB_INVALID_THREAD_ID)
3474 json_packet.AddIntegerItem("threadid", thread_id);
3475
3476 StreamString json_string;
3477 json_packet.Dump(json_string, false);
3478
3479 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3480 StringExtractorGDBRemote response;
3481 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3482 GDBRemoteCommunication::PacketResult::Success) {
3483 if (response.IsNormalResponse()) {
3484 size_t filled_size = response.GetHexBytesAvail(buffer);
3485 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3486 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003487 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003488 buffer = buffer.slice(buffer.size());
3489 }
3490 } else {
3491 LLDB_LOG(log, "failed to send packet");
3492 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3493 packet.GetData());
3494 buffer = buffer.slice(buffer.size());
3495 }
3496 return error;
3497}
3498
Kate Stoneb9c1b512016-09-06 20:57:50 +00003499bool GDBRemoteCommunicationClient::GetModuleInfo(
3500 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3501 ModuleSpec &module_spec) {
3502 if (!m_supports_qModuleInfo)
3503 return false;
3504
3505 std::string module_path = module_file_spec.GetPath(false);
3506 if (module_path.empty())
3507 return false;
3508
3509 StreamString packet;
3510 packet.PutCString("qModuleInfo:");
3511 packet.PutCStringAsRawHex8(module_path.c_str());
3512 packet.PutCString(";");
3513 const auto &triple = arch_spec.GetTriple().getTriple();
3514 packet.PutCStringAsRawHex8(triple.c_str());
3515
3516 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003517 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3518 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003519 return false;
3520
3521 if (response.IsErrorResponse())
3522 return false;
3523
3524 if (response.IsUnsupportedResponse()) {
3525 m_supports_qModuleInfo = false;
3526 return false;
3527 }
3528
3529 llvm::StringRef name;
3530 llvm::StringRef value;
3531
3532 module_spec.Clear();
3533 module_spec.GetFileSpec() = module_file_spec;
3534
3535 while (response.GetNameColonValue(name, value)) {
3536 if (name == "uuid" || name == "md5") {
3537 StringExtractor extractor(value);
3538 std::string uuid;
3539 extractor.GetHexByteString(uuid);
Pavel Labatha174bcb2018-06-21 15:24:39 +00003540 module_spec.GetUUID().SetFromStringRef(uuid, uuid.size() / 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003541 } else if (name == "triple") {
3542 StringExtractor extractor(value);
3543 std::string triple;
3544 extractor.GetHexByteString(triple);
3545 module_spec.GetArchitecture().SetTriple(triple.c_str());
3546 } else if (name == "file_offset") {
3547 uint64_t ival = 0;
3548 if (!value.getAsInteger(16, ival))
3549 module_spec.SetObjectOffset(ival);
3550 } else if (name == "file_size") {
3551 uint64_t ival = 0;
3552 if (!value.getAsInteger(16, ival))
3553 module_spec.SetObjectSize(ival);
3554 } else if (name == "file_path") {
3555 StringExtractor extractor(value);
3556 std::string path;
3557 extractor.GetHexByteString(path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003558 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003559 }
3560 }
3561
3562 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003563}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003564
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003565static llvm::Optional<ModuleSpec>
3566ParseModuleSpec(StructuredData::Dictionary *dict) {
3567 ModuleSpec result;
3568 if (!dict)
3569 return llvm::None;
3570
Zachary Turner28333212017-05-12 05:49:54 +00003571 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003572 uint64_t integer;
3573
3574 if (!dict->GetValueForKeyAsString("uuid", string))
3575 return llvm::None;
Pavel Labath8c92c892017-12-18 14:31:44 +00003576 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3577 string.size())
3578 return llvm::None;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003579
3580 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3581 return llvm::None;
3582 result.SetObjectOffset(integer);
3583
3584 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3585 return llvm::None;
3586 result.SetObjectSize(integer);
3587
3588 if (!dict->GetValueForKeyAsString("triple", string))
3589 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003590 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003591
3592 if (!dict->GetValueForKeyAsString("file_path", string))
3593 return llvm::None;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003594 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003595
3596 return result;
3597}
3598
3599llvm::Optional<std::vector<ModuleSpec>>
3600GDBRemoteCommunicationClient::GetModulesInfo(
3601 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3602 if (!m_supports_jModulesInfo)
3603 return llvm::None;
3604
3605 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3606 for (const FileSpec &module_file_spec : module_file_specs) {
3607 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3608 module_array_sp->AppendObject(module_sp);
3609 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003610 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003611 module_sp->SetObject("triple",
3612 std::make_shared<JSONString>(triple.getTriple()));
3613 }
3614 StreamString unescaped_payload;
3615 unescaped_payload.PutCString("jModulesInfo:");
3616 module_array_sp->Write(unescaped_payload);
3617 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003618 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003619 unescaped_payload.GetSize());
3620
Greg Clayton70a9f512017-04-14 17:10:04 +00003621 // Increase the timeout for jModulesInfo since this packet can take longer.
3622 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3623
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003624 StringExtractorGDBRemote response;
3625 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3626 PacketResult::Success ||
3627 response.IsErrorResponse())
3628 return llvm::None;
3629
3630 if (response.IsUnsupportedResponse()) {
3631 m_supports_jModulesInfo = false;
3632 return llvm::None;
3633 }
3634
3635 StructuredData::ObjectSP response_object_sp =
3636 StructuredData::ParseJSON(response.GetStringRef());
3637 if (!response_object_sp)
3638 return llvm::None;
3639
3640 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3641 if (!response_array)
3642 return llvm::None;
3643
3644 std::vector<ModuleSpec> result;
3645 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3646 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3647 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3648 result.push_back(*module_spec);
3649 }
3650
3651 return result;
3652}
3653
Colin Rileyc3c95b22015-04-16 15:51:33 +00003654// query the target remote for extended information using the qXfer packet
3655//
Adrian Prantl05097242018-04-30 16:49:04 +00003656// example: object='features', annex='target.xml', out=<xml output> return:
3657// 'true' on success
Colin Rileyc3c95b22015-04-16 15:51:33 +00003658// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003659bool GDBRemoteCommunicationClient::ReadExtFeature(
3660 const lldb_private::ConstString object,
3661 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003662 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003663
Kate Stoneb9c1b512016-09-06 20:57:50 +00003664 std::stringstream output;
3665 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003666
Kate Stoneb9c1b512016-09-06 20:57:50 +00003667 uint64_t size = GetRemoteMaxPacketSize();
3668 if (size == 0)
3669 size = 0x1000;
3670 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3671 int offset = 0;
3672 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003673
Kate Stoneb9c1b512016-09-06 20:57:50 +00003674 // loop until all data has been read
3675 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003676
Kate Stoneb9c1b512016-09-06 20:57:50 +00003677 // send query extended feature packet
3678 std::stringstream packet;
3679 packet << "qXfer:" << object.AsCString("")
3680 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3681 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003682
Kate Stoneb9c1b512016-09-06 20:57:50 +00003683 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003684 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003685
Kate Stoneb9c1b512016-09-06 20:57:50 +00003686 if (res != GDBRemoteCommunication::PacketResult::Success) {
3687 err.SetErrorString("Error sending $qXfer packet");
3688 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003689 }
3690
Kate Stoneb9c1b512016-09-06 20:57:50 +00003691 const std::string &str = chunk.GetStringRef();
3692 if (str.length() == 0) {
3693 // should have some data in chunk
3694 err.SetErrorString("Empty response from $qXfer packet");
3695 return false;
3696 }
3697
3698 // check packet code
3699 switch (str[0]) {
3700 // last chunk
3701 case ('l'):
3702 active = false;
3703 LLVM_FALLTHROUGH;
3704
3705 // more chunks
3706 case ('m'):
3707 if (str.length() > 1)
3708 output << &str[1];
3709 offset += size;
3710 break;
3711
3712 // unknown chunk
3713 default:
3714 err.SetErrorString("Invalid continuation code from $qXfer packet");
3715 return false;
3716 }
3717 }
3718
3719 out = output.str();
3720 err.Success();
3721 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003722}
Greg Clayton0b90be12015-06-23 21:27:50 +00003723
3724// Notify the target that gdb is prepared to serve symbol lookup requests.
3725// packet: "qSymbol::"
3726// reply:
3727// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003728// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3729// encoded).
3730// LLDB may provide the value by sending another qSymbol
3731// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003732// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003733//
3734// Three examples:
3735//
3736// lldb sends: qSymbol::
3737// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003738// Remote gdb stub does not need to know the addresses of any symbols, lldb
3739// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003740// need to ask again in this session.
3741//
3742// lldb sends: qSymbol::
3743// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3744// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3745// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003746// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3747// not know
3748// the address at this time. lldb needs to send qSymbol:: again when it has
3749// more
Jason Molenda50018d32016-01-13 04:08:10 +00003750// solibs loaded.
3751//
3752// lldb sends: qSymbol::
3753// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3754// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3755// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003756// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3757// that it
3758// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3759// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003760// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003761
Kate Stoneb9c1b512016-09-06 20:57:50 +00003762void GDBRemoteCommunicationClient::ServeSymbolLookups(
3763 lldb_private::Process *process) {
Adrian Prantl05097242018-04-30 16:49:04 +00003764 // Set to true once we've resolved a symbol to an address for the remote
3765 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3766 // any more symbols and we can stop asking.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003767 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003768
Kate Stoneb9c1b512016-09-06 20:57:50 +00003769 // Is this the initial qSymbol:: packet?
3770 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003771
Jonas Devliegherea6682a42018-12-15 00:15:33 +00003772 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003773 Lock lock(*this, false);
3774 if (lock) {
3775 StreamString packet;
3776 packet.PutCString("qSymbol::");
3777 StringExtractorGDBRemote response;
3778 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3779 PacketResult::Success) {
3780 if (response.IsOKResponse()) {
3781 if (symbol_response_provided || first_qsymbol_query) {
3782 m_qSymbol_requests_done = true;
3783 }
3784
3785 // We are done serving symbols requests
3786 return;
3787 }
3788 first_qsymbol_query = false;
3789
3790 if (response.IsUnsupportedResponse()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003791 // qSymbol is not supported by the current GDB server we are
3792 // connected to
Kate Stoneb9c1b512016-09-06 20:57:50 +00003793 m_supports_qSymbol = false;
3794 return;
3795 } else {
3796 llvm::StringRef response_str(response.GetStringRef());
3797 if (response_str.startswith("qSymbol:")) {
3798 response.SetFilePos(strlen("qSymbol:"));
3799 std::string symbol_name;
3800 if (response.GetHexByteString(symbol_name)) {
3801 if (symbol_name.empty())
3802 return;
3803
3804 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3805 lldb_private::SymbolContextList sc_list;
3806 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3807 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3808 const size_t num_scs = sc_list.GetSize();
3809 for (size_t sc_idx = 0;
3810 sc_idx < num_scs &&
3811 symbol_load_addr == LLDB_INVALID_ADDRESS;
3812 ++sc_idx) {
3813 SymbolContext sc;
3814 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3815 if (sc.symbol) {
3816 switch (sc.symbol->GetType()) {
3817 case eSymbolTypeInvalid:
3818 case eSymbolTypeAbsolute:
3819 case eSymbolTypeUndefined:
3820 case eSymbolTypeSourceFile:
3821 case eSymbolTypeHeaderFile:
3822 case eSymbolTypeObjectFile:
3823 case eSymbolTypeCommonBlock:
3824 case eSymbolTypeBlock:
3825 case eSymbolTypeLocal:
3826 case eSymbolTypeParam:
3827 case eSymbolTypeVariable:
3828 case eSymbolTypeVariableType:
3829 case eSymbolTypeLineEntry:
3830 case eSymbolTypeLineHeader:
3831 case eSymbolTypeScopeBegin:
3832 case eSymbolTypeScopeEnd:
3833 case eSymbolTypeAdditional:
3834 case eSymbolTypeCompiler:
3835 case eSymbolTypeInstrumentation:
3836 case eSymbolTypeTrampoline:
3837 break;
3838
3839 case eSymbolTypeCode:
3840 case eSymbolTypeResolver:
3841 case eSymbolTypeData:
3842 case eSymbolTypeRuntime:
3843 case eSymbolTypeException:
3844 case eSymbolTypeObjCClass:
3845 case eSymbolTypeObjCMetaClass:
3846 case eSymbolTypeObjCIVar:
3847 case eSymbolTypeReExported:
3848 symbol_load_addr =
3849 sc.symbol->GetLoadAddress(&process->GetTarget());
3850 break;
3851 }
Jason Molenda50018d32016-01-13 04:08:10 +00003852 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003853 }
Greg Clayton42b01482015-08-11 22:07:46 +00003854 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003855 }
3856 // This is the normal path where our symbol lookup was successful
Adrian Prantl05097242018-04-30 16:49:04 +00003857 // and we want to send a packet with the new symbol value and see
3858 // if another lookup needs to be done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003859
Kate Stoneb9c1b512016-09-06 20:57:50 +00003860 // Change "packet" to contain the requested symbol value and name
3861 packet.Clear();
3862 packet.PutCString("qSymbol:");
3863 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3864 packet.Printf("%" PRIx64, symbol_load_addr);
3865 symbol_response_provided = true;
3866 } else {
3867 symbol_response_provided = false;
3868 }
3869 packet.PutCString(":");
3870 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3871 continue; // go back to the while loop and send "packet" and wait
3872 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003873 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003874 }
3875 }
3876 }
3877 // If we make it here, the symbol request packet response wasn't valid or
3878 // our symbol lookup failed so we must abort
3879 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003880
Kate Stoneb9c1b512016-09-06 20:57:50 +00003881 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3882 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3883 log->Printf(
3884 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3885 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003886 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003887 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003888}
3889
Kate Stoneb9c1b512016-09-06 20:57:50 +00003890StructuredData::Array *
3891GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3892 if (!m_supported_async_json_packets_is_valid) {
Adrian Prantl05097242018-04-30 16:49:04 +00003893 // Query the server for the array of supported asynchronous JSON packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003894 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003895
Kate Stoneb9c1b512016-09-06 20:57:50 +00003896 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003897
Kate Stoneb9c1b512016-09-06 20:57:50 +00003898 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003899 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003900 const bool send_async = false;
3901 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3902 send_async) == PacketResult::Success) {
3903 m_supported_async_json_packets_sp =
3904 StructuredData::ParseJSON(response.GetStringRef());
3905 if (m_supported_async_json_packets_sp &&
3906 !m_supported_async_json_packets_sp->GetAsArray()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003907 // We were returned something other than a JSON array. This is
3908 // invalid. Clear it out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003909 if (log)
3910 log->Printf("GDBRemoteCommunicationClient::%s(): "
3911 "QSupportedAsyncJSONPackets returned invalid "
3912 "result: %s",
3913 __FUNCTION__, response.GetStringRef().c_str());
3914 m_supported_async_json_packets_sp.reset();
3915 }
3916 } else {
3917 if (log)
3918 log->Printf("GDBRemoteCommunicationClient::%s(): "
3919 "QSupportedAsyncJSONPackets unsupported",
3920 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003921 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003922
3923 if (log && m_supported_async_json_packets_sp) {
3924 StreamString stream;
3925 m_supported_async_json_packets_sp->Dump(stream);
3926 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3927 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003928 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003929 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003930 }
3931
3932 return m_supported_async_json_packets_sp
3933 ? m_supported_async_json_packets_sp->GetAsArray()
3934 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003935}
3936
Zachary Turner97206d52017-05-12 04:51:55 +00003937Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003938 llvm::ArrayRef<int32_t> signals) {
3939 // Format packet:
3940 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3941 auto range = llvm::make_range(signals.begin(), signals.end());
3942 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3943
3944 StringExtractorGDBRemote response;
3945 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3946
3947 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003948 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003949
3950 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003951 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003952 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003953 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003954 }
3955}
3956
Zachary Turner97206d52017-05-12 04:51:55 +00003957Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003958 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003959 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003960
3961 if (type_name.GetLength() == 0) {
3962 error.SetErrorString("invalid type_name argument");
3963 return error;
3964 }
3965
Adrian Prantl05097242018-04-30 16:49:04 +00003966 // Build command: Configure{type_name}: serialized config data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003967 StreamGDBRemote stream;
3968 stream.PutCString("QConfigure");
3969 stream.PutCString(type_name.AsCString());
3970 stream.PutChar(':');
3971 if (config_sp) {
3972 // Gather the plain-text version of the configuration data.
3973 StreamString unescaped_stream;
3974 config_sp->Dump(unescaped_stream);
3975 unescaped_stream.Flush();
3976
3977 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003978 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003979 unescaped_stream.GetSize());
3980 }
3981 stream.Flush();
3982
3983 // Send the packet.
3984 const bool send_async = false;
3985 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003986 auto result =
3987 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003988 if (result == PacketResult::Success) {
3989 // We failed if the config result comes back other than OK.
3990 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3991 // Okay!
3992 error.Clear();
3993 } else {
3994 error.SetErrorStringWithFormat("configuring StructuredData feature "
3995 "%s failed with error %s",
3996 type_name.AsCString(),
3997 response.GetStringRef().c_str());
3998 }
3999 } else {
4000 // Can we get more data here on the failure?
4001 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4002 "failed when sending packet: "
4003 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00004004 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004005 }
4006 return error;
4007}
4008
4009void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4010 GDBRemoteClientBase::OnRunPacketSent(first);
4011 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004012}