blob: f5ce1374b333d93b4ef87d84c01f648306b044eb [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Greg Clayton576d8832011-03-22 04:00:09 +00006//
7//===----------------------------------------------------------------------===//
8
Greg Clayton576d8832011-03-22 04:00:09 +00009#include "GDBRemoteCommunicationClient.h"
10
Greg Claytone034a042015-05-21 20:52:06 +000011#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000012#include <sys/stat.h>
13
Greg Claytone034a042015-05-21 20:52:06 +000014#include <numeric>
Kate Stoneb9c1b512016-09-06 20:57:50 +000015#include <sstream>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000016
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000017#include "lldb/Core/ModuleSpec.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000018#include "lldb/Host/HostInfo.h"
Pavel Labath16064d32018-03-20 11:56:24 +000019#include "lldb/Host/XML.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000020#include "lldb/Symbol/Symbol.h"
Pavel Labath4cb69922016-07-29 15:41:52 +000021#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000022#include "lldb/Target/Target.h"
Todd Fiala75930012016-08-19 04:21:48 +000023#include "lldb/Target/UnixSignals.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000024#include "lldb/Utility/Args.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000025#include "lldb/Utility/DataBufferHeap.h"
Pavel Labath2f1fbae2016-09-08 10:07:04 +000026#include "lldb/Utility/JSON.h"
Todd Fiala75930012016-08-19 04:21:48 +000027#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000028#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000029#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000030#include "lldb/Utility/StreamString.h"
Greg Clayton576d8832011-03-22 04:00:09 +000031
Greg Clayton576d8832011-03-22 04:00:09 +000032#include "ProcessGDBRemote.h"
33#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000034#include "lldb/Host/Config.h"
Pavel Labath9af71b32018-03-20 16:14:00 +000035#include "lldb/Utility/StringExtractorGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000036
Zachary Turner54695a32016-08-29 19:58:14 +000037#include "llvm/ADT/StringSwitch.h"
38
Haibo Huang7debc932019-08-08 21:42:33 +000039#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000040#include <compression.h>
41#endif
42
Greg Clayton576d8832011-03-22 04:00:09 +000043using namespace lldb;
44using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000045using namespace lldb_private::process_gdb_remote;
Pavel Labath1eff73c2016-11-24 10:54:49 +000046using namespace std::chrono;
Greg Clayton576d8832011-03-22 04:00:09 +000047
Greg Clayton576d8832011-03-22 04:00:09 +000048// GDBRemoteCommunicationClient constructor
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000049GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000050 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000051 m_supports_not_sending_acks(eLazyBoolCalculate),
52 m_supports_thread_suffix(eLazyBoolCalculate),
53 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
54 m_supports_vCont_all(eLazyBoolCalculate),
55 m_supports_vCont_any(eLazyBoolCalculate),
56 m_supports_vCont_c(eLazyBoolCalculate),
57 m_supports_vCont_C(eLazyBoolCalculate),
58 m_supports_vCont_s(eLazyBoolCalculate),
59 m_supports_vCont_S(eLazyBoolCalculate),
60 m_qHostInfo_is_valid(eLazyBoolCalculate),
61 m_curr_pid_is_valid(eLazyBoolCalculate),
62 m_qProcessInfo_is_valid(eLazyBoolCalculate),
63 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
64 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
65 m_supports_memory_region_info(eLazyBoolCalculate),
66 m_supports_watchpoint_support_info(eLazyBoolCalculate),
67 m_supports_detach_stay_stopped(eLazyBoolCalculate),
68 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
69 m_attach_or_wait_reply(eLazyBoolCalculate),
70 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000071 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000072 m_avoid_g_packets(eLazyBoolCalculate),
73 m_supports_QSaveRegisterState(eLazyBoolCalculate),
74 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
75 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
76 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
77 m_supports_qXfer_features_read(eLazyBoolCalculate),
Pavel Labath16064d32018-03-20 11:56:24 +000078 m_supports_qXfer_memory_map_read(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000079 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
80 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
81 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000082 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000083 m_supports_QPassSignals(eLazyBoolCalculate),
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +000084 m_supports_error_string_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
86 m_supports_qUserName(true), m_supports_qGroupName(true),
87 m_supports_qThreadStopInfo(true), m_supports_z0(true),
88 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
89 m_supports_z4(true), m_supports_QEnvironment(true),
90 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
91 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
Pavel Labath2f1fbae2016-09-08 10:07:04 +000092 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
93 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000094 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
Kate Stoneb9c1b512016-09-06 20:57:50 +000095 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
Pavel Labath2272c482018-06-18 15:02:23 +000096 m_os_build(), m_os_kernel(), m_hostname(), m_gdb_server_name(),
97 m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0),
98 m_max_packet_size(0), m_qSupported_response(),
99 m_supported_async_json_packets_is_valid(false),
Pavel Labath16064d32018-03-20 11:56:24 +0000100 m_supported_async_json_packets_sp(), m_qXfer_memory_map(),
101 m_qXfer_memory_map_loaded(false) {}
Greg Clayton576d8832011-03-22 04:00:09 +0000102
Greg Clayton576d8832011-03-22 04:00:09 +0000103// Destructor
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
105 if (IsConnected())
106 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000107}
108
Zachary Turner97206d52017-05-12 04:51:55 +0000109bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000111
Adrian Prantl05097242018-04-30 16:49:04 +0000112 // Start the read thread after we send the handshake ack since if we fail to
113 // send the handshake ack, there is no reason to continue...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 if (SendAck()) {
Jonas Devlieghere135cf982019-06-30 19:00:09 +0000115 // Wait for any responses that might have been queued up in the remote
116 // GDB server and flush them all
117 StringExtractorGDBRemote response;
118 PacketResult packet_result = PacketResult::Success;
119 while (packet_result == PacketResult::Success)
120 packet_result = ReadPacket(response, milliseconds(10), false);
121
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 // The return value from QueryNoAckModeSupported() is true if the packet
Adrian Prantl05097242018-04-30 16:49:04 +0000123 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
124 // false if no response was received. This quickly tells us if we have a
125 // live connection to a remote GDB server...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 if (QueryNoAckModeSupported()) {
127 return true;
128 } else {
129 if (error_ptr)
130 error_ptr->SetErrorString("failed to get reply to handshake packet");
Greg Claytonfb909312013-11-23 01:58:15 +0000131 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 } else {
133 if (error_ptr)
134 error_ptr->SetErrorString("failed to send the handshake ack");
135 }
136 return false;
Greg Clayton1cb64962011-03-24 04:28:38 +0000137}
138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139bool GDBRemoteCommunicationClient::GetEchoSupported() {
140 if (m_supports_qEcho == eLazyBoolCalculate) {
141 GetRemoteQSupported();
142 }
143 return m_supports_qEcho == eLazyBoolYes;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000144}
145
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000146bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
147 if (m_supports_QPassSignals == eLazyBoolCalculate) {
148 GetRemoteQSupported();
149 }
150 return m_supports_QPassSignals == eLazyBoolYes;
151}
152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
154 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
155 GetRemoteQSupported();
156 }
157 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000158}
159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
161 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
162 GetRemoteQSupported();
163 }
164 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
168 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
169 GetRemoteQSupported();
170 }
171 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
175 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
176 GetRemoteQSupported();
177 }
178 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
182 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
183 GetRemoteQSupported();
184 }
185 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000186}
187
Pavel Labath16064d32018-03-20 11:56:24 +0000188bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() {
189 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) {
190 GetRemoteQSupported();
191 }
192 return m_supports_qXfer_memory_map_read == eLazyBoolYes;
193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
196 if (m_max_packet_size == 0) {
197 GetRemoteQSupported();
198 }
199 return m_max_packet_size;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
203 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
204 m_send_acks = true;
205 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 // This is the first real packet that we'll send in a debug session and it
Adrian Prantl05097242018-04-30 16:49:04 +0000208 // may take a little longer than normal to receive a reply. Wait at least
209 // 6 seconds for a reply to this packet.
Jason Molenda36a216e2014-07-24 01:36:24 +0000210
Pavel Labath1eff73c2016-11-24 10:54:49 +0000211 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
Colin Rileyc3c95b22015-04-16 15:51:33 +0000212
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000213 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
215 PacketResult::Success) {
216 if (response.IsOKResponse()) {
217 m_send_acks = false;
218 m_supports_not_sending_acks = eLazyBoolYes;
219 }
220 return true;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000221 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222 }
223 return false;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000224}
Greg Clayton576d8832011-03-22 04:00:09 +0000225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
227 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
228 m_supports_threads_in_stop_reply = eLazyBoolNo;
229
230 StringExtractorGDBRemote response;
231 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
232 false) == PacketResult::Success) {
233 if (response.IsOKResponse())
234 m_supports_threads_in_stop_reply = eLazyBoolYes;
Pavel Labath5c95ee42016-08-30 13:56:11 +0000235 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 }
Pavel Labath0faf3732016-08-25 08:34:57 +0000237}
Greg Clayton576d8832011-03-22 04:00:09 +0000238
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
240 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
241 m_attach_or_wait_reply = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +0000242
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 StringExtractorGDBRemote response;
244 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
245 false) == PacketResult::Success) {
246 if (response.IsOKResponse())
247 m_attach_or_wait_reply = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000248 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000250 return m_attach_or_wait_reply == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000251}
252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
254 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
255 m_prepare_for_reg_writing_reply = eLazyBoolNo;
256
257 StringExtractorGDBRemote response;
258 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
259 false) == PacketResult::Success) {
260 if (response.IsOKResponse())
261 m_prepare_for_reg_writing_reply = eLazyBoolYes;
262 }
263 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000264 return m_prepare_for_reg_writing_reply == eLazyBoolYes;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265}
266
267void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000268 if (!did_exec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 // Hard reset everything, this is when we first connect to a GDB server
270 m_supports_not_sending_acks = eLazyBoolCalculate;
271 m_supports_thread_suffix = eLazyBoolCalculate;
272 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
273 m_supports_vCont_c = eLazyBoolCalculate;
274 m_supports_vCont_C = eLazyBoolCalculate;
275 m_supports_vCont_s = eLazyBoolCalculate;
276 m_supports_vCont_S = eLazyBoolCalculate;
277 m_supports_p = eLazyBoolCalculate;
278 m_supports_x = eLazyBoolCalculate;
279 m_supports_QSaveRegisterState = eLazyBoolCalculate;
280 m_qHostInfo_is_valid = eLazyBoolCalculate;
281 m_curr_pid_is_valid = eLazyBoolCalculate;
282 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
283 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
284 m_supports_memory_region_info = eLazyBoolCalculate;
285 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
286 m_attach_or_wait_reply = eLazyBoolCalculate;
287 m_avoid_g_packets = eLazyBoolCalculate;
288 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
289 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
290 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
291 m_supports_qXfer_features_read = eLazyBoolCalculate;
Pavel Labath16064d32018-03-20 11:56:24 +0000292 m_supports_qXfer_memory_map_read = eLazyBoolCalculate;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
294 m_supports_qProcessInfoPID = true;
295 m_supports_qfProcessInfo = true;
296 m_supports_qUserName = true;
297 m_supports_qGroupName = true;
298 m_supports_qThreadStopInfo = true;
299 m_supports_z0 = true;
300 m_supports_z1 = true;
301 m_supports_z2 = true;
302 m_supports_z3 = true;
303 m_supports_z4 = true;
304 m_supports_QEnvironment = true;
305 m_supports_QEnvironmentHexEncoded = true;
306 m_supports_qSymbol = true;
307 m_qSymbol_requests_done = false;
308 m_supports_qModuleInfo = true;
309 m_host_arch.Clear();
Pavel Labath2272c482018-06-18 15:02:23 +0000310 m_os_version = llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311 m_os_build.clear();
312 m_os_kernel.clear();
313 m_hostname.clear();
314 m_gdb_server_name.clear();
315 m_gdb_server_version = UINT32_MAX;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000316 m_default_packet_timeout = seconds(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317 m_max_packet_size = 0;
318 m_qSupported_response.clear();
319 m_supported_async_json_packets_is_valid = false;
320 m_supported_async_json_packets_sp.reset();
Pavel Labath2f1fbae2016-09-08 10:07:04 +0000321 m_supports_jModulesInfo = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322 }
323
Adrian Prantl05097242018-04-30 16:49:04 +0000324 // These flags should be reset when we first connect to a GDB server and when
325 // our inferior process execs
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 m_qProcessInfo_is_valid = eLazyBoolCalculate;
327 m_process_arch.Clear();
328}
329
330void GDBRemoteCommunicationClient::GetRemoteQSupported() {
331 // Clear out any capabilities we expect to see in the qSupported response
332 m_supports_qXfer_auxv_read = eLazyBoolNo;
333 m_supports_qXfer_libraries_read = eLazyBoolNo;
334 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
335 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
336 m_supports_qXfer_features_read = eLazyBoolNo;
Pavel Labath16064d32018-03-20 11:56:24 +0000337 m_supports_qXfer_memory_map_read = eLazyBoolNo;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
339 // not, we assume no limit
340
341 // build the qSupported packet
342 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
343 StreamString packet;
344 packet.PutCString("qSupported");
345 for (uint32_t i = 0; i < features.size(); ++i) {
346 packet.PutCString(i == 0 ? ":" : ";");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000347 packet.PutCString(features[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 }
349
350 StringExtractorGDBRemote response;
Zachary Turnerc1564272016-11-16 21:15:24 +0000351 if (SendPacketAndWaitForResponse(packet.GetString(), response,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 /*send_async=*/false) ==
353 PacketResult::Success) {
354 const char *response_cstr = response.GetStringRef().c_str();
355
356 // Hang on to the qSupported packet, so that platforms can do custom
Adrian Prantl05097242018-04-30 16:49:04 +0000357 // configuration of the transport before attaching/launching the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 m_qSupported_response = response_cstr;
359
360 if (::strstr(response_cstr, "qXfer:auxv:read+"))
361 m_supports_qXfer_auxv_read = eLazyBoolYes;
362 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
363 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
364 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
365 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
366 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
367 }
368 if (::strstr(response_cstr, "qXfer:libraries:read+"))
369 m_supports_qXfer_libraries_read = eLazyBoolYes;
370 if (::strstr(response_cstr, "qXfer:features:read+"))
371 m_supports_qXfer_features_read = eLazyBoolYes;
Pavel Labath16064d32018-03-20 11:56:24 +0000372 if (::strstr(response_cstr, "qXfer:memory-map:read+"))
373 m_supports_qXfer_memory_map_read = eLazyBoolYes;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374
375 // Look for a list of compressions in the features list e.g.
Adrian Prantl05097242018-04-30 16:49:04 +0000376 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
377 // deflate,lzma
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
379 if (features_list) {
380 const char *compressions =
381 ::strstr(features_list, "SupportedCompressions=");
382 if (compressions) {
383 std::vector<std::string> supported_compressions;
384 compressions += sizeof("SupportedCompressions=") - 1;
385 const char *end_of_compressions = strchr(compressions, ';');
Konrad Kleine248a1302019-05-23 11:14:47 +0000386 if (end_of_compressions == nullptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 end_of_compressions = strchr(compressions, '\0');
388 }
389 const char *current_compression = compressions;
390 while (current_compression < end_of_compressions) {
391 const char *next_compression_name = strchr(current_compression, ',');
392 const char *end_of_this_word = next_compression_name;
Konrad Kleine248a1302019-05-23 11:14:47 +0000393 if (next_compression_name == nullptr ||
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 end_of_compressions < next_compression_name) {
395 end_of_this_word = end_of_compressions;
396 }
397
398 if (end_of_this_word) {
399 if (end_of_this_word == current_compression) {
400 current_compression++;
401 } else {
402 std::string this_compression(
403 current_compression, end_of_this_word - current_compression);
404 supported_compressions.push_back(this_compression);
405 current_compression = end_of_this_word + 1;
406 }
407 } else {
408 supported_compressions.push_back(current_compression);
409 current_compression = end_of_compressions;
410 }
411 }
412
413 if (supported_compressions.size() > 0) {
414 MaybeEnableCompression(supported_compressions);
415 }
416 }
417 }
418
419 if (::strstr(response_cstr, "qEcho"))
420 m_supports_qEcho = eLazyBoolYes;
421 else
422 m_supports_qEcho = eLazyBoolNo;
423
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000424 if (::strstr(response_cstr, "QPassSignals+"))
425 m_supports_QPassSignals = eLazyBoolYes;
426 else
427 m_supports_QPassSignals = eLazyBoolNo;
428
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
430 if (packet_size_str) {
431 StringExtractorGDBRemote packet_response(packet_size_str +
432 strlen("PacketSize="));
433 m_max_packet_size =
434 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
435 if (m_max_packet_size == 0) {
436 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
437 Log *log(
438 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000439 LLDB_LOGF(log, "Garbled PacketSize spec in qSupported response");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440 }
441 }
442 }
443}
444
445bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
446 if (m_supports_thread_suffix == eLazyBoolCalculate) {
447 StringExtractorGDBRemote response;
448 m_supports_thread_suffix = eLazyBoolNo;
449 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
450 false) == PacketResult::Success) {
451 if (response.IsOKResponse())
452 m_supports_thread_suffix = eLazyBoolYes;
453 }
454 }
455 return m_supports_thread_suffix;
456}
457bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
458 if (m_supports_vCont_c == eLazyBoolCalculate) {
459 StringExtractorGDBRemote response;
460 m_supports_vCont_any = eLazyBoolNo;
461 m_supports_vCont_all = eLazyBoolNo;
462 m_supports_vCont_c = eLazyBoolNo;
463 m_supports_vCont_C = eLazyBoolNo;
464 m_supports_vCont_s = eLazyBoolNo;
465 m_supports_vCont_S = eLazyBoolNo;
466 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
467 PacketResult::Success) {
468 const char *response_cstr = response.GetStringRef().c_str();
469 if (::strstr(response_cstr, ";c"))
470 m_supports_vCont_c = eLazyBoolYes;
471
472 if (::strstr(response_cstr, ";C"))
473 m_supports_vCont_C = eLazyBoolYes;
474
475 if (::strstr(response_cstr, ";s"))
476 m_supports_vCont_s = eLazyBoolYes;
477
478 if (::strstr(response_cstr, ";S"))
479 m_supports_vCont_S = eLazyBoolYes;
480
481 if (m_supports_vCont_c == eLazyBoolYes &&
482 m_supports_vCont_C == eLazyBoolYes &&
483 m_supports_vCont_s == eLazyBoolYes &&
484 m_supports_vCont_S == eLazyBoolYes) {
485 m_supports_vCont_all = eLazyBoolYes;
486 }
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_any = eLazyBoolYes;
493 }
494 }
495 }
496
497 switch (flavor) {
498 case 'a':
499 return m_supports_vCont_any;
500 case 'A':
501 return m_supports_vCont_all;
502 case 'c':
503 return m_supports_vCont_c;
504 case 'C':
505 return m_supports_vCont_C;
506 case 's':
507 return m_supports_vCont_s;
508 case 'S':
509 return m_supports_vCont_S;
510 default:
511 break;
512 }
513 return false;
514}
515
Pavel Labath4b6f9592016-08-18 08:30:03 +0000516GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
518 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
519 bool send_async) {
520 Lock lock(*this, send_async);
521 if (!lock) {
522 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
523 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000524 LLDB_LOGF(log,
525 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
526 "for %s packet.",
527 __FUNCTION__, payload.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 return PacketResult::ErrorNoSequenceLock;
529 }
Pavel Labath5c95ee42016-08-30 13:56:11 +0000530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 if (GetThreadSuffixSupported())
532 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
533 else {
534 if (!SetCurrentThread(tid))
535 return PacketResult::ErrorSendFailed;
536 }
Pavel Labath4b6f9592016-08-18 08:30:03 +0000537
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000539}
540
Adrian Prantl05097242018-04-30 16:49:04 +0000541// Check if the target supports 'p' packet. It sends out a 'p' packet and
542// checks the response. A normal packet will tell us that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000543//
544// Takes a valid thread ID because p needs to apply to a thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
546 if (m_supports_p == eLazyBoolCalculate) {
547 m_supports_p = eLazyBoolNo;
548 StreamString payload;
549 payload.PutCString("p0");
550 StringExtractorGDBRemote response;
551 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
552 response, false) ==
553 PacketResult::Success &&
554 response.IsNormalResponse()) {
555 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000556 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 }
558 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000559}
Greg Clayton576d8832011-03-22 04:00:09 +0000560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
562 // Get information on all threads at one using the "jThreadsInfo" packet
563 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 if (m_supports_jThreadsInfo) {
566 StringExtractorGDBRemote response;
567 response.SetResponseValidatorToJSON();
568 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
569 PacketResult::Success) {
570 if (response.IsUnsupportedResponse()) {
571 m_supports_jThreadsInfo = false;
572 } else if (!response.Empty()) {
573 object_sp = StructuredData::ParseJSON(response.GetStringRef());
574 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000575 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576 }
577 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000578}
579
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
581 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
582 StringExtractorGDBRemote response;
583 m_supports_jThreadExtendedInfo = eLazyBoolNo;
584 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
585 PacketResult::Success) {
586 if (response.IsOKResponse()) {
587 m_supports_jThreadExtendedInfo = eLazyBoolYes;
588 }
Jason Molenda705b1802014-06-13 02:37:02 +0000589 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 }
591 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000592}
593
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000594void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
595 if (m_supports_error_string_reply == eLazyBoolCalculate) {
596 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +0000597 // We try to enable error strings in remote packets but if we fail, we just
598 // work in the older way.
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000599 m_supports_error_string_reply = eLazyBoolNo;
600 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
601 PacketResult::Success) {
602 if (response.IsOKResponse()) {
603 m_supports_error_string_reply = eLazyBoolYes;
604 }
605 }
606 }
607}
608
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
610 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
611 StringExtractorGDBRemote response;
612 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
613 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
614 response,
615 false) == PacketResult::Success) {
616 if (response.IsOKResponse()) {
617 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
618 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000619 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620 }
621 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000622}
623
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
625 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
626 StringExtractorGDBRemote response;
627 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
628 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
629 PacketResult::Success) {
630 if (response.IsOKResponse()) {
631 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
632 }
Jason Molenda37397352016-07-22 00:17:55 +0000633 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634 }
635 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000636}
637
Kate Stoneb9c1b512016-09-06 20:57:50 +0000638bool GDBRemoteCommunicationClient::GetxPacketSupported() {
639 if (m_supports_x == eLazyBoolCalculate) {
640 StringExtractorGDBRemote response;
641 m_supports_x = eLazyBoolNo;
642 char packet[256];
643 snprintf(packet, sizeof(packet), "x0,0");
644 if (SendPacketAndWaitForResponse(packet, response, false) ==
645 PacketResult::Success) {
646 if (response.IsOKResponse())
647 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 }
650 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000651}
652
Greg Clayton3dedae12013-12-06 21:45:27 +0000653GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
655 const char *payload_prefix, std::string &response_string) {
656 Lock lock(*this, false);
657 if (!lock) {
658 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
659 GDBR_LOG_PACKETS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000660 LLDB_LOGF(log,
661 "error: failed to get packet sequence mutex, not sending "
662 "packets with prefix '%s'",
663 payload_prefix);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 return PacketResult::ErrorNoSequenceLock;
665 }
666
667 response_string = "";
668 std::string payload_prefix_str(payload_prefix);
669 unsigned int response_size = 0x1000;
670 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
671 response_size = GetRemoteMaxPacketSize();
672 }
673
674 for (unsigned int offset = 0; true; offset += response_size) {
675 StringExtractorGDBRemote this_response;
676 // Construct payload
677 char sizeDescriptor[128];
678 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
679 response_size);
680 PacketResult result = SendPacketAndWaitForResponseNoLock(
681 payload_prefix_str + sizeDescriptor, this_response);
682 if (result != PacketResult::Success)
683 return result;
684
685 const std::string &this_string = this_response.GetStringRef();
686
687 // Check for m or l as first character; l seems to mean this is the last
688 // chunk
689 char first_char = *this_string.c_str();
690 if (first_char != 'm' && first_char != 'l') {
691 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000692 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 // Concatenate the result so far (skipping 'm' or 'l')
694 response_string.append(this_string, 1, std::string::npos);
695 if (first_char == 'l')
696 // We're done
697 return PacketResult::Success;
698 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000699}
700
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
702 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
703 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 // First try to retrieve the pid via the qProcessInfo request.
706 GetCurrentProcessInfo(allow_lazy);
707 if (m_curr_pid_is_valid == eLazyBoolYes) {
708 // We really got it.
709 return m_curr_pid;
710 } else {
711 // If we don't get a response for qProcessInfo, check if $qC gives us a
Adrian Prantl05097242018-04-30 16:49:04 +0000712 // result. $qC only returns a real process id on older debugserver and
713 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
714 // the thread id, which newer debugserver and lldb-gdbserver stubs return
715 // correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000716 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000717 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 PacketResult::Success) {
719 if (response.GetChar() == 'Q') {
720 if (response.GetChar() == 'C') {
721 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
722 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
723 m_curr_pid_is_valid = eLazyBoolYes;
724 return m_curr_pid;
725 }
Greg Clayton576d8832011-03-22 04:00:09 +0000726 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 }
Greg Clayton576d8832011-03-22 04:00:09 +0000728 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729
730 // If we don't get a response for $qC, check if $qfThreadID gives us a
731 // result.
732 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
733 std::vector<lldb::tid_t> thread_ids;
734 bool sequence_mutex_unavailable;
735 size_t size;
736 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000737 if (size && !sequence_mutex_unavailable) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 m_curr_pid = thread_ids.front();
739 m_curr_pid_is_valid = eLazyBoolYes;
740 return m_curr_pid;
741 }
Greg Clayton576d8832011-03-22 04:00:09 +0000742 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 }
744
745 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000746}
747
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
749 error_str.clear();
750 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000751 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
752 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 if (response.IsOKResponse())
754 return true;
755 if (response.GetChar() == 'E') {
756 // A string the describes what failed when launching...
757 error_str = response.GetStringRef().substr(1);
758 } else {
759 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000760 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761 } else {
762 error_str.assign("timed out waiting for app to launch");
763 }
764 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000765}
766
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767int GDBRemoteCommunicationClient::SendArgumentsPacket(
768 const ProcessLaunchInfo &launch_info) {
769 // Since we don't get the send argv0 separate from the executable path, we
Adrian Prantl05097242018-04-30 16:49:04 +0000770 // need to make sure to use the actual executable path found in the
771 // launch_info...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 std::vector<const char *> argv;
773 FileSpec exe_file = launch_info.GetExecutableFile();
774 std::string exe_path;
Konrad Kleine248a1302019-05-23 11:14:47 +0000775 const char *arg = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 const Args &launch_args = launch_info.GetArguments();
777 if (exe_file)
778 exe_path = exe_file.GetPath(false);
779 else {
780 arg = launch_args.GetArgumentAtIndex(0);
781 if (arg)
782 exe_path = arg;
783 }
784 if (!exe_path.empty()) {
785 argv.push_back(exe_path.c_str());
Konrad Kleine248a1302019-05-23 11:14:47 +0000786 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 ++i) {
788 if (arg)
789 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000790 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 }
792 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000793 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 packet.PutChar('A');
795 for (size_t i = 0, n = argv.size(); i < n; ++i) {
796 arg = argv[i];
797 const int arg_len = strlen(arg);
798 if (i > 0)
799 packet.PutChar(',');
800 packet.Printf("%i,%i,", arg_len * 2, (int)i);
801 packet.PutBytesAsRawHex8(arg, arg_len);
802 }
803
Vince Harrone0be4252015-02-06 18:32:57 +0000804 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000805 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
806 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000808 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809 uint8_t error = response.GetError();
810 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000811 return error;
812 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 }
814 return -1;
815}
Johnny Chen64637202012-05-23 21:09:52 +0000816
Pavel Labath62930e52018-01-10 11:57:31 +0000817int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
818 for (const auto &KV : env) {
819 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
820 if (r != 0)
821 return r;
822 }
823 return 0;
824}
825
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826int GDBRemoteCommunicationClient::SendEnvironmentPacket(
827 char const *name_equal_value) {
828 if (name_equal_value && name_equal_value[0]) {
829 StreamString packet;
830 bool send_hex_encoding = false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000831 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
832 ++p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 if (isprint(*p)) {
834 switch (*p) {
835 case '$':
836 case '#':
837 case '*':
838 case '}':
839 send_hex_encoding = true;
840 break;
841 default:
842 break;
Johnny Chen64637202012-05-23 21:09:52 +0000843 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 } else {
845 // We have non printable characters, lets hex encode this...
846 send_hex_encoding = true;
847 }
Johnny Chen64637202012-05-23 21:09:52 +0000848 }
849
Greg Claytonfbb76342013-11-20 21:07:01 +0000850 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 if (send_hex_encoding) {
852 if (m_supports_QEnvironmentHexEncoded) {
853 packet.PutCString("QEnvironmentHexEncoded:");
854 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000855 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
856 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857 if (response.IsOKResponse())
858 return 0;
859 uint8_t error = response.GetError();
860 if (error)
861 return error;
862 if (response.IsUnsupportedResponse())
863 m_supports_QEnvironmentHexEncoded = false;
864 }
865 }
866
867 } else if (m_supports_QEnvironment) {
868 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000869 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
870 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 if (response.IsOKResponse())
872 return 0;
873 uint8_t error = response.GetError();
874 if (error)
875 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000876 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 m_supports_QEnvironment = false;
878 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000879 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 }
881 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000882}
883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
885 if (arch && arch[0]) {
886 StreamString packet;
887 packet.Printf("QLaunchArch:%s", arch);
888 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000889 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
890 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891 if (response.IsOKResponse())
892 return 0;
893 uint8_t error = response.GetError();
894 if (error)
895 return error;
896 }
897 }
898 return -1;
899}
Chaoren Lind3173f32015-05-29 19:52:29 +0000900
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
902 char const *data, bool *was_supported) {
903 if (data && *data != '\0') {
904 StreamString packet;
905 packet.Printf("QSetProcessEvent:%s", data);
906 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000907 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
908 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 if (response.IsOKResponse()) {
910 if (was_supported)
911 *was_supported = true;
912 return 0;
913 } else if (response.IsUnsupportedResponse()) {
914 if (was_supported)
915 *was_supported = false;
916 return -1;
917 } else {
918 uint8_t error = response.GetError();
919 if (was_supported)
920 *was_supported = true;
921 if (error)
922 return error;
923 }
924 }
925 }
926 return -1;
927}
928
Pavel Labath2272c482018-06-18 15:02:23 +0000929llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() {
930 GetHostInfo();
931 return m_os_version;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932}
933
934bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
935 if (GetHostInfo()) {
936 if (!m_os_build.empty()) {
937 s = m_os_build;
938 return true;
939 }
940 }
941 s.clear();
942 return false;
943}
944
945bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
946 if (GetHostInfo()) {
947 if (!m_os_kernel.empty()) {
948 s = m_os_kernel;
949 return true;
950 }
951 }
952 s.clear();
953 return false;
954}
955
956bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
957 if (GetHostInfo()) {
958 if (!m_hostname.empty()) {
959 s = m_hostname;
960 return true;
961 }
962 }
963 s.clear();
964 return false;
965}
966
967ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
968 if (GetHostInfo())
969 return m_host_arch;
970 return ArchSpec();
971}
972
973const lldb_private::ArchSpec &
974GDBRemoteCommunicationClient::GetProcessArchitecture() {
975 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
976 GetCurrentProcessInfo();
977 return m_process_arch;
978}
979
980bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
981 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
982 m_gdb_server_name.clear();
983 m_gdb_server_version = 0;
984 m_qGDBServerVersion_is_valid = eLazyBoolNo;
985
986 StringExtractorGDBRemote response;
987 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
988 PacketResult::Success) {
989 if (response.IsNormalResponse()) {
990 llvm::StringRef name, value;
991 bool success = false;
992 while (response.GetNameColonValue(name, value)) {
993 if (name.equals("name")) {
994 success = true;
995 m_gdb_server_name = value;
996 } else if (name.equals("version")) {
997 llvm::StringRef major, minor;
998 std::tie(major, minor) = value.split('.');
999 if (!major.getAsInteger(0, m_gdb_server_version))
1000 success = true;
1001 }
Greg Clayton576d8832011-03-22 04:00:09 +00001002 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 if (success)
1004 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1005 }
Greg Clayton576d8832011-03-22 04:00:09 +00001006 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 }
1008 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001009}
1010
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011void GDBRemoteCommunicationClient::MaybeEnableCompression(
1012 std::vector<std::string> supported_compressions) {
1013 CompressionType avail_type = CompressionType::None;
1014 std::string avail_name;
1015
1016#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001017 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 for (auto compression : supported_compressions) {
1019 if (compression == "lzfse") {
1020 avail_type = CompressionType::LZFSE;
1021 avail_name = compression;
1022 break;
1023 }
1024 }
1025 }
1026#endif
1027
1028#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001029 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 for (auto compression : supported_compressions) {
1031 if (compression == "zlib-deflate") {
1032 avail_type = CompressionType::ZlibDeflate;
1033 avail_name = compression;
1034 break;
1035 }
1036 }
1037 }
1038#endif
1039
1040#if defined(HAVE_LIBZ)
1041 if (avail_type == CompressionType::None) {
1042 for (auto compression : supported_compressions) {
1043 if (compression == "zlib-deflate") {
1044 avail_type = CompressionType::ZlibDeflate;
1045 avail_name = compression;
1046 break;
1047 }
1048 }
1049 }
1050#endif
1051
1052#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001053 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054 for (auto compression : supported_compressions) {
1055 if (compression == "lz4") {
1056 avail_type = CompressionType::LZ4;
1057 avail_name = compression;
1058 break;
1059 }
1060 }
1061 }
1062#endif
1063
1064#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001065 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066 for (auto compression : supported_compressions) {
1067 if (compression == "lzma") {
1068 avail_type = CompressionType::LZMA;
1069 avail_name = compression;
1070 break;
1071 }
1072 }
1073 }
1074#endif
1075
1076 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001077 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001079 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 PacketResult::Success)
1081 return;
1082
1083 if (response.IsOKResponse()) {
1084 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001085 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 }
Greg Clayton576d8832011-03-22 04:00:09 +00001087}
Greg Clayton32e0a752011-03-30 18:16:51 +00001088
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1090 if (GetGDBServerVersion()) {
1091 if (!m_gdb_server_name.empty())
1092 return m_gdb_server_name.c_str();
1093 }
Konrad Kleine248a1302019-05-23 11:14:47 +00001094 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095}
1096
1097uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1098 if (GetGDBServerVersion())
1099 return m_gdb_server_version;
1100 return 0;
1101}
1102
1103bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1104 StringExtractorGDBRemote response;
1105 if (SendPacketAndWaitForResponse("qC", response, false) !=
1106 PacketResult::Success)
1107 return false;
1108
1109 if (!response.IsNormalResponse())
1110 return false;
1111
1112 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1113 tid = response.GetHexMaxU32(true, -1);
1114
1115 return true;
1116}
1117
1118bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1119 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1120
1121 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
Pavel Labathe7ec0832018-08-31 05:34:03 +00001122 // host info computation can require DNS traffic and shelling out to external processes.
1123 // Increase the timeout to account for that.
1124 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001126 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1128 PacketResult::Success) {
1129 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001130 llvm::StringRef name;
1131 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001132 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1133 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134 std::string arch_name;
1135 std::string os_name;
1136 std::string vendor_name;
1137 std::string triple;
1138 std::string distribution_id;
1139 uint32_t pointer_byte_size = 0;
1140 ByteOrder byte_order = eByteOrderInvalid;
1141 uint32_t num_keys_decoded = 0;
1142 while (response.GetNameColonValue(name, value)) {
1143 if (name.equals("cputype")) {
1144 // exception type in big endian hex
1145 if (!value.getAsInteger(0, cpu))
1146 ++num_keys_decoded;
1147 } else if (name.equals("cpusubtype")) {
1148 // exception count in big endian hex
1149 if (!value.getAsInteger(0, sub))
1150 ++num_keys_decoded;
1151 } else if (name.equals("arch")) {
1152 arch_name = value;
1153 ++num_keys_decoded;
1154 } else if (name.equals("triple")) {
1155 StringExtractor extractor(value);
1156 extractor.GetHexByteString(triple);
1157 ++num_keys_decoded;
1158 } else if (name.equals("distribution_id")) {
1159 StringExtractor extractor(value);
1160 extractor.GetHexByteString(distribution_id);
1161 ++num_keys_decoded;
1162 } else if (name.equals("os_build")) {
1163 StringExtractor extractor(value);
1164 extractor.GetHexByteString(m_os_build);
1165 ++num_keys_decoded;
1166 } else if (name.equals("hostname")) {
1167 StringExtractor extractor(value);
1168 extractor.GetHexByteString(m_hostname);
1169 ++num_keys_decoded;
1170 } else if (name.equals("os_kernel")) {
1171 StringExtractor extractor(value);
1172 extractor.GetHexByteString(m_os_kernel);
1173 ++num_keys_decoded;
1174 } else if (name.equals("ostype")) {
1175 os_name = value;
1176 ++num_keys_decoded;
1177 } else if (name.equals("vendor")) {
1178 vendor_name = value;
1179 ++num_keys_decoded;
1180 } else if (name.equals("endian")) {
1181 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1182 .Case("little", eByteOrderLittle)
1183 .Case("big", eByteOrderBig)
1184 .Case("pdp", eByteOrderPDP)
1185 .Default(eByteOrderInvalid);
1186 if (byte_order != eByteOrderInvalid)
1187 ++num_keys_decoded;
1188 } else if (name.equals("ptrsize")) {
1189 if (!value.getAsInteger(0, pointer_byte_size))
1190 ++num_keys_decoded;
1191 } else if (name.equals("os_version") ||
1192 name.equals(
1193 "version")) // Older debugserver binaries used the
1194 // "version" key instead of
1195 // "os_version"...
1196 {
Pavel Labath2272c482018-06-18 15:02:23 +00001197 if (!m_os_version.tryParse(value))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 ++num_keys_decoded;
1199 } else if (name.equals("watchpoint_exceptions_received")) {
1200 m_watchpoints_trigger_after_instruction =
1201 llvm::StringSwitch<LazyBool>(value)
1202 .Case("before", eLazyBoolNo)
1203 .Case("after", eLazyBoolYes)
1204 .Default(eLazyBoolCalculate);
1205 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1206 ++num_keys_decoded;
1207 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001208 uint32_t timeout_seconds;
1209 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001210 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 SetPacketTimeout(m_default_packet_timeout);
1212 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001213 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 }
Jason Molenda89c37492014-01-27 22:23:20 +00001215 }
1216
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 if (num_keys_decoded > 0)
1218 m_qHostInfo_is_valid = eLazyBoolYes;
1219
1220 if (triple.empty()) {
1221 if (arch_name.empty()) {
1222 if (cpu != LLDB_INVALID_CPUTYPE) {
1223 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1224 if (pointer_byte_size) {
1225 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1226 }
1227 if (byte_order != eByteOrderInvalid) {
1228 assert(byte_order == m_host_arch.GetByteOrder());
1229 }
1230
1231 if (!vendor_name.empty())
1232 m_host_arch.GetTriple().setVendorName(
1233 llvm::StringRef(vendor_name));
1234 if (!os_name.empty())
1235 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001236 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001237 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001238 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239 triple += arch_name;
1240 if (!vendor_name.empty() || !os_name.empty()) {
1241 triple += '-';
1242 if (vendor_name.empty())
1243 triple += "unknown";
1244 else
1245 triple += vendor_name;
1246 triple += '-';
1247 if (os_name.empty())
1248 triple += "unknown";
1249 else
1250 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001251 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001253
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 llvm::Triple &host_triple = m_host_arch.GetTriple();
1255 if (host_triple.getVendor() == llvm::Triple::Apple &&
1256 host_triple.getOS() == llvm::Triple::Darwin) {
1257 switch (m_host_arch.GetMachine()) {
1258 case llvm::Triple::aarch64:
1259 case llvm::Triple::arm:
1260 case llvm::Triple::thumb:
1261 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001262 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 default:
1264 host_triple.setOS(llvm::Triple::MacOSX);
1265 break;
1266 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001267 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 if (pointer_byte_size) {
1269 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1270 }
1271 if (byte_order != eByteOrderInvalid) {
1272 assert(byte_order == m_host_arch.GetByteOrder());
1273 }
1274 }
1275 } else {
1276 m_host_arch.SetTriple(triple.c_str());
1277 if (pointer_byte_size) {
1278 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1279 }
1280 if (byte_order != eByteOrderInvalid) {
1281 assert(byte_order == m_host_arch.GetByteOrder());
1282 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001283
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001284 LLDB_LOGF(log,
1285 "GDBRemoteCommunicationClient::%s parsed host "
1286 "architecture as %s, triple as %s from triple text %s",
1287 __FUNCTION__,
1288 m_host_arch.GetArchitectureName()
1289 ? m_host_arch.GetArchitectureName()
1290 : "<null-arch-name>",
1291 m_host_arch.GetTriple().getTriple().c_str(),
1292 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001293 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 if (!distribution_id.empty())
1295 m_host_arch.SetDistributionId(distribution_id.c_str());
1296 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001297 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 }
1299 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001300}
Greg Clayton37a0a242012-04-11 00:24:49 +00001301
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302int GDBRemoteCommunicationClient::SendAttach(
1303 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1304 if (pid != LLDB_INVALID_PROCESS_ID) {
1305 char packet[64];
1306 const int packet_len =
1307 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001308 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001310 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001311 PacketResult::Success) {
1312 if (response.IsErrorResponse())
1313 return response.GetError();
1314 return 0;
1315 }
1316 }
1317 return -1;
1318}
1319
1320int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1321 size_t data_len) {
1322 StreamString packet;
1323 packet.PutCString("I");
1324 packet.PutBytesAsRawHex8(data, data_len);
1325 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001326 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1327 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328 return 0;
1329 }
1330 return response.GetError();
1331}
1332
1333const lldb_private::ArchSpec &
1334GDBRemoteCommunicationClient::GetHostArchitecture() {
1335 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1336 GetHostInfo();
1337 return m_host_arch;
1338}
1339
Pavel Labath1eff73c2016-11-24 10:54:49 +00001340seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001341 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1342 GetHostInfo();
1343 return m_default_packet_timeout;
1344}
1345
1346addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1347 uint32_t permissions) {
1348 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1349 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1350 char packet[64];
1351 const int packet_len = ::snprintf(
1352 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1353 permissions & lldb::ePermissionsReadable ? "r" : "",
1354 permissions & lldb::ePermissionsWritable ? "w" : "",
1355 permissions & lldb::ePermissionsExecutable ? "x" : "");
1356 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001357 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001358 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001359 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001360 PacketResult::Success) {
1361 if (response.IsUnsupportedResponse())
1362 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1363 else if (!response.IsErrorResponse())
1364 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1365 } else {
1366 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1367 }
1368 }
1369 return LLDB_INVALID_ADDRESS;
1370}
1371
1372bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1373 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1374 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1375 char packet[64];
1376 const int packet_len =
1377 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1378 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001379 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001380 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001381 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 PacketResult::Success) {
1383 if (response.IsUnsupportedResponse())
1384 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1385 else if (response.IsOKResponse())
1386 return true;
1387 } else {
1388 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1389 }
1390 }
1391 return false;
1392}
1393
Zachary Turner97206d52017-05-12 04:51:55 +00001394Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1395 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001396
1397 if (keep_stopped) {
1398 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1399 char packet[64];
1400 const int packet_len =
1401 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1402 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001403 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001404 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001405 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 PacketResult::Success &&
1407 response.IsOKResponse()) {
1408 m_supports_detach_stay_stopped = eLazyBoolYes;
1409 } else {
1410 m_supports_detach_stay_stopped = eLazyBoolNo;
1411 }
1412 }
1413
1414 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1415 error.SetErrorString("Stays stopped not supported by this target.");
1416 return error;
1417 } else {
1418 StringExtractorGDBRemote response;
1419 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001420 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421 if (packet_result != PacketResult::Success)
1422 error.SetErrorString("Sending extended disconnect packet failed.");
1423 }
1424 } else {
1425 StringExtractorGDBRemote response;
1426 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001427 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428 if (packet_result != PacketResult::Success)
1429 error.SetErrorString("Sending disconnect packet failed.");
1430 }
1431 return error;
1432}
1433
Zachary Turner97206d52017-05-12 04:51:55 +00001434Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001435 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001436 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 region_info.Clear();
1438
1439 if (m_supports_memory_region_info != eLazyBoolNo) {
1440 m_supports_memory_region_info = eLazyBoolYes;
1441 char packet[64];
1442 const int packet_len = ::snprintf(
1443 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1444 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001445 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001447 if (SendPacketAndWaitForResponse(packet, response, false) ==
Pavel Labath16064d32018-03-20 11:56:24 +00001448 PacketResult::Success &&
1449 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 llvm::StringRef name;
1451 llvm::StringRef value;
1452 addr_t addr_value = LLDB_INVALID_ADDRESS;
1453 bool success = true;
1454 bool saw_permissions = false;
1455 while (success && response.GetNameColonValue(name, value)) {
1456 if (name.equals("start")) {
1457 if (!value.getAsInteger(16, addr_value))
1458 region_info.GetRange().SetRangeBase(addr_value);
1459 } else if (name.equals("size")) {
1460 if (!value.getAsInteger(16, addr_value))
1461 region_info.GetRange().SetByteSize(addr_value);
1462 } else if (name.equals("permissions") &&
1463 region_info.GetRange().IsValid()) {
1464 saw_permissions = true;
1465 if (region_info.GetRange().Contains(addr)) {
1466 if (value.find('r') != llvm::StringRef::npos)
1467 region_info.SetReadable(MemoryRegionInfo::eYes);
1468 else
1469 region_info.SetReadable(MemoryRegionInfo::eNo);
1470
1471 if (value.find('w') != llvm::StringRef::npos)
1472 region_info.SetWritable(MemoryRegionInfo::eYes);
1473 else
1474 region_info.SetWritable(MemoryRegionInfo::eNo);
1475
1476 if (value.find('x') != llvm::StringRef::npos)
1477 region_info.SetExecutable(MemoryRegionInfo::eYes);
1478 else
1479 region_info.SetExecutable(MemoryRegionInfo::eNo);
1480
1481 region_info.SetMapped(MemoryRegionInfo::eYes);
1482 } else {
1483 // The reported region does not contain this address -- we're
1484 // looking at an unmapped page
1485 region_info.SetReadable(MemoryRegionInfo::eNo);
1486 region_info.SetWritable(MemoryRegionInfo::eNo);
1487 region_info.SetExecutable(MemoryRegionInfo::eNo);
1488 region_info.SetMapped(MemoryRegionInfo::eNo);
1489 }
1490 } else if (name.equals("name")) {
1491 StringExtractorGDBRemote name_extractor(value);
1492 std::string name;
1493 name_extractor.GetHexByteString(name);
1494 region_info.SetName(name.c_str());
1495 } else if (name.equals("error")) {
1496 StringExtractorGDBRemote error_extractor(value);
1497 std::string error_string;
1498 // Now convert the HEX bytes into a string value
1499 error_extractor.GetHexByteString(error_string);
1500 error.SetErrorString(error_string.c_str());
1501 }
1502 }
1503
Stephane Sezer48d14272017-03-31 18:00:48 +00001504 if (region_info.GetRange().IsValid()) {
1505 // We got a valid address range back but no permissions -- which means
1506 // this is an unmapped page
1507 if (!saw_permissions) {
1508 region_info.SetReadable(MemoryRegionInfo::eNo);
1509 region_info.SetWritable(MemoryRegionInfo::eNo);
1510 region_info.SetExecutable(MemoryRegionInfo::eNo);
1511 region_info.SetMapped(MemoryRegionInfo::eNo);
1512 }
1513 } else {
1514 // We got an invalid address range back
1515 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001516 }
1517 } else {
1518 m_supports_memory_region_info = eLazyBoolNo;
1519 }
1520 }
1521
1522 if (m_supports_memory_region_info == eLazyBoolNo) {
1523 error.SetErrorString("qMemoryRegionInfo is not supported");
1524 }
Pavel Labath16064d32018-03-20 11:56:24 +00001525
1526 // Try qXfer:memory-map:read to get region information not included in
1527 // qMemoryRegionInfo
1528 MemoryRegionInfo qXfer_region_info;
1529 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1530
1531 if (error.Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001532 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1533 // the qXfer result as a fallback
Pavel Labath16064d32018-03-20 11:56:24 +00001534 if (qXfer_error.Success()) {
1535 region_info = qXfer_region_info;
1536 error.Clear();
1537 } else {
1538 region_info.Clear();
1539 }
1540 } else if (qXfer_error.Success()) {
1541 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
Adrian Prantl05097242018-04-30 16:49:04 +00001542 // both regions are the same range, update the result to include the flash-
1543 // memory information that is specific to the qXfer result.
Pavel Labath16064d32018-03-20 11:56:24 +00001544 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1545 region_info.SetFlash(qXfer_region_info.GetFlash());
1546 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1547 }
1548 }
1549 return error;
1550}
1551
1552Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1553 lldb::addr_t addr, MemoryRegionInfo &region) {
1554 Status error = LoadQXferMemoryMap();
1555 if (!error.Success())
1556 return error;
1557 for (const auto &map_region : m_qXfer_memory_map) {
1558 if (map_region.GetRange().Contains(addr)) {
1559 region = map_region;
1560 return error;
1561 }
1562 }
1563 error.SetErrorString("Region not found");
1564 return error;
1565}
1566
1567Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1568
1569 Status error;
1570
1571 if (m_qXfer_memory_map_loaded)
1572 // Already loaded, return success
1573 return error;
1574
1575 if (!XMLDocument::XMLEnabled()) {
1576 error.SetErrorString("XML is not supported");
1577 return error;
1578 }
1579
1580 if (!GetQXferMemoryMapReadSupported()) {
1581 error.SetErrorString("Memory map is not supported");
1582 return error;
1583 }
1584
1585 std::string xml;
1586 lldb_private::Status lldberr;
1587 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1588 lldberr)) {
1589 error.SetErrorString("Failed to read memory map");
1590 return error;
1591 }
1592
1593 XMLDocument xml_document;
1594
1595 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1596 error.SetErrorString("Failed to parse memory map xml");
1597 return error;
1598 }
1599
1600 XMLNode map_node = xml_document.GetRootElement("memory-map");
1601 if (!map_node) {
1602 error.SetErrorString("Invalid root node in memory map xml");
1603 return error;
1604 }
1605
1606 m_qXfer_memory_map.clear();
1607
1608 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1609 if (!memory_node.IsElement())
1610 return true;
1611 if (memory_node.GetName() != "memory")
1612 return true;
1613 auto type = memory_node.GetAttributeValue("type", "");
1614 uint64_t start;
1615 uint64_t length;
1616 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1617 return true;
1618 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1619 return true;
1620 MemoryRegionInfo region;
1621 region.GetRange().SetRangeBase(start);
1622 region.GetRange().SetByteSize(length);
1623 if (type == "rom") {
1624 region.SetReadable(MemoryRegionInfo::eYes);
1625 this->m_qXfer_memory_map.push_back(region);
1626 } else if (type == "ram") {
1627 region.SetReadable(MemoryRegionInfo::eYes);
1628 region.SetWritable(MemoryRegionInfo::eYes);
1629 this->m_qXfer_memory_map.push_back(region);
1630 } else if (type == "flash") {
1631 region.SetFlash(MemoryRegionInfo::eYes);
1632 memory_node.ForEachChildElement(
1633 [&region](const XMLNode &prop_node) -> bool {
1634 if (!prop_node.IsElement())
1635 return true;
1636 if (prop_node.GetName() != "property")
1637 return true;
1638 auto propname = prop_node.GetAttributeValue("name", "");
1639 if (propname == "blocksize") {
1640 uint64_t blocksize;
1641 if (prop_node.GetElementTextAsUnsigned(blocksize))
1642 region.SetBlocksize(blocksize);
1643 }
1644 return true;
1645 });
1646 this->m_qXfer_memory_map.push_back(region);
1647 }
1648 return true;
1649 });
1650
1651 m_qXfer_memory_map_loaded = true;
1652
Kate Stoneb9c1b512016-09-06 20:57:50 +00001653 return error;
1654}
1655
Zachary Turner97206d52017-05-12 04:51:55 +00001656Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1657 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001658
1659 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1660 num = m_num_supported_hardware_watchpoints;
1661 return error;
1662 }
1663
1664 // Set num to 0 first.
1665 num = 0;
1666 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1667 char packet[64];
1668 const int packet_len =
1669 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1670 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001671 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001672 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001673 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001674 PacketResult::Success) {
1675 m_supports_watchpoint_support_info = eLazyBoolYes;
1676 llvm::StringRef name;
1677 llvm::StringRef value;
Jason Molendac0e793d2018-11-09 22:33:26 +00001678 bool found_num_field = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001679 while (response.GetNameColonValue(name, value)) {
1680 if (name.equals("num")) {
1681 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1682 num = m_num_supported_hardware_watchpoints;
Jason Molendac0e793d2018-11-09 22:33:26 +00001683 found_num_field = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001684 }
1685 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001686 if (!found_num_field) {
Jason Molendac0e793d2018-11-09 22:33:26 +00001687 m_supports_watchpoint_support_info = eLazyBoolNo;
1688 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 } else {
1690 m_supports_watchpoint_support_info = eLazyBoolNo;
1691 }
1692 }
1693
1694 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1695 error.SetErrorString("qWatchpointSupportInfo is not supported");
1696 }
1697 return error;
1698}
1699
Zachary Turner97206d52017-05-12 04:51:55 +00001700lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001701 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001702 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 if (error.Success())
1704 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1705 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001706}
1707
Zachary Turner97206d52017-05-12 04:51:55 +00001708lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001709GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1710 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001711 Status error;
Fangrui Song2f677ab2019-05-16 09:07:33 +00001712 llvm::Triple triple = arch.GetTriple();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001713
Adrian Prantl05097242018-04-30 16:49:04 +00001714 // we assume watchpoints will happen after running the relevant opcode and we
1715 // only want to override this behavior if we have explicitly received a
1716 // qHostInfo telling us otherwise
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 if (m_qHostInfo_is_valid != eLazyBoolYes) {
Fangrui Song2f677ab2019-05-16 09:07:33 +00001718 // On targets like MIPS and ppc64, watchpoint exceptions are always
Adrian Prantl05097242018-04-30 16:49:04 +00001719 // generated before the instruction is executed. The connected target may
1720 // not support qHostInfo or qWatchpointSupportInfo packets.
Fangrui Song2f677ab2019-05-16 09:07:33 +00001721 after = !(triple.isMIPS() || triple.isPPC64());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722 } else {
Fangrui Song2f677ab2019-05-16 09:07:33 +00001723 // For MIPS and ppc64, set m_watchpoints_trigger_after_instruction to
Pavel Labathc51ad482017-10-27 17:02:32 +00001724 // eLazyBoolNo if it is not calculated before.
Fangrui Songddb93b62019-05-16 08:37:32 +00001725 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
Fangrui Song2f677ab2019-05-16 09:07:33 +00001726 (triple.isMIPS() || triple.isPPC64()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001727 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1728
1729 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1730 }
1731 return error;
1732}
1733
1734int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1735 if (file_spec) {
1736 std::string path{file_spec.GetPath(false)};
1737 StreamString packet;
1738 packet.PutCString("QSetSTDIN:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001739 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001740
1741 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001742 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1743 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001744 if (response.IsOKResponse())
1745 return 0;
1746 uint8_t error = response.GetError();
1747 if (error)
1748 return error;
1749 }
1750 }
1751 return -1;
1752}
1753
1754int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1755 if (file_spec) {
1756 std::string path{file_spec.GetPath(false)};
1757 StreamString packet;
1758 packet.PutCString("QSetSTDOUT:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001759 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760
1761 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001762 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1763 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001764 if (response.IsOKResponse())
1765 return 0;
1766 uint8_t error = response.GetError();
1767 if (error)
1768 return error;
1769 }
1770 }
1771 return -1;
1772}
1773
1774int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1775 if (file_spec) {
1776 std::string path{file_spec.GetPath(false)};
1777 StreamString packet;
1778 packet.PutCString("QSetSTDERR:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001779 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001780
1781 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001782 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1783 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001784 if (response.IsOKResponse())
1785 return 0;
1786 uint8_t error = response.GetError();
1787 if (error)
1788 return error;
1789 }
1790 }
1791 return -1;
1792}
1793
1794bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1795 StringExtractorGDBRemote response;
1796 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1797 PacketResult::Success) {
1798 if (response.IsUnsupportedResponse())
1799 return false;
1800 if (response.IsErrorResponse())
1801 return false;
1802 std::string cwd;
1803 response.GetHexByteString(cwd);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001804 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001805 return !cwd.empty();
1806 }
1807 return false;
1808}
1809
1810int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1811 if (working_dir) {
1812 std::string path{working_dir.GetPath(false)};
1813 StreamString packet;
1814 packet.PutCString("QSetWorkingDir:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001815 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816
1817 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001818 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1819 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001820 if (response.IsOKResponse())
1821 return 0;
1822 uint8_t error = response.GetError();
1823 if (error)
1824 return error;
1825 }
1826 }
1827 return -1;
1828}
1829
1830int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1831 char packet[32];
1832 const int packet_len =
1833 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1834 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001835 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001836 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001837 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001838 PacketResult::Success) {
1839 if (response.IsOKResponse())
1840 return 0;
1841 uint8_t error = response.GetError();
1842 if (error)
1843 return error;
1844 }
1845 return -1;
1846}
1847
1848int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1849 char packet[32];
1850 const int packet_len = ::snprintf(packet, sizeof(packet),
1851 "QSetDetachOnError:%i", enable ? 1 : 0);
1852 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001853 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001854 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001855 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001856 PacketResult::Success) {
1857 if (response.IsOKResponse())
1858 return 0;
1859 uint8_t error = response.GetError();
1860 if (error)
1861 return error;
1862 }
1863 return -1;
1864}
1865
1866bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1867 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1868 if (response.IsNormalResponse()) {
1869 llvm::StringRef name;
1870 llvm::StringRef value;
1871 StringExtractor extractor;
1872
1873 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1874 uint32_t sub = 0;
1875 std::string vendor;
1876 std::string os_type;
1877
1878 while (response.GetNameColonValue(name, value)) {
1879 if (name.equals("pid")) {
1880 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1881 value.getAsInteger(0, pid);
1882 process_info.SetProcessID(pid);
1883 } else if (name.equals("ppid")) {
1884 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1885 value.getAsInteger(0, pid);
1886 process_info.SetParentProcessID(pid);
1887 } else if (name.equals("uid")) {
1888 uint32_t uid = UINT32_MAX;
1889 value.getAsInteger(0, uid);
1890 process_info.SetUserID(uid);
1891 } else if (name.equals("euid")) {
1892 uint32_t uid = UINT32_MAX;
1893 value.getAsInteger(0, uid);
1894 process_info.SetEffectiveGroupID(uid);
1895 } else if (name.equals("gid")) {
1896 uint32_t gid = UINT32_MAX;
1897 value.getAsInteger(0, gid);
1898 process_info.SetGroupID(gid);
1899 } else if (name.equals("egid")) {
1900 uint32_t gid = UINT32_MAX;
1901 value.getAsInteger(0, gid);
1902 process_info.SetEffectiveGroupID(gid);
1903 } else if (name.equals("triple")) {
1904 StringExtractor extractor(value);
1905 std::string triple;
1906 extractor.GetHexByteString(triple);
1907 process_info.GetArchitecture().SetTriple(triple.c_str());
1908 } else if (name.equals("name")) {
1909 StringExtractor extractor(value);
Adrian Prantl05097242018-04-30 16:49:04 +00001910 // The process name from ASCII hex bytes since we can't control the
1911 // characters in a process name
Kate Stoneb9c1b512016-09-06 20:57:50 +00001912 std::string name;
1913 extractor.GetHexByteString(name);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001914 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001915 } else if (name.equals("cputype")) {
1916 value.getAsInteger(0, cpu);
1917 } else if (name.equals("cpusubtype")) {
1918 value.getAsInteger(0, sub);
1919 } else if (name.equals("vendor")) {
1920 vendor = value;
1921 } else if (name.equals("ostype")) {
1922 os_type = value;
1923 }
1924 }
1925
1926 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1927 if (vendor == "apple") {
1928 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1929 sub);
1930 process_info.GetArchitecture().GetTriple().setVendorName(
1931 llvm::StringRef(vendor));
1932 process_info.GetArchitecture().GetTriple().setOSName(
1933 llvm::StringRef(os_type));
1934 }
1935 }
1936
1937 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1938 return true;
1939 }
1940 return false;
1941}
1942
1943bool GDBRemoteCommunicationClient::GetProcessInfo(
1944 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1945 process_info.Clear();
1946
1947 if (m_supports_qProcessInfoPID) {
1948 char packet[32];
1949 const int packet_len =
1950 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1951 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001952 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001953 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001954 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 PacketResult::Success) {
1956 return DecodeProcessInfoResponse(response, process_info);
1957 } else {
1958 m_supports_qProcessInfoPID = false;
1959 return false;
1960 }
1961 }
1962 return false;
1963}
1964
1965bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1966 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1967 GDBR_LOG_PACKETS));
1968
1969 if (allow_lazy) {
1970 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1971 return true;
1972 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1973 return false;
1974 }
1975
1976 GetHostInfo();
1977
1978 StringExtractorGDBRemote response;
1979 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1980 PacketResult::Success) {
1981 if (response.IsNormalResponse()) {
1982 llvm::StringRef name;
1983 llvm::StringRef value;
1984 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1985 uint32_t sub = 0;
1986 std::string arch_name;
1987 std::string os_name;
1988 std::string vendor_name;
1989 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001990 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991 uint32_t pointer_byte_size = 0;
1992 StringExtractor extractor;
1993 ByteOrder byte_order = eByteOrderInvalid;
1994 uint32_t num_keys_decoded = 0;
1995 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1996 while (response.GetNameColonValue(name, value)) {
1997 if (name.equals("cputype")) {
1998 if (!value.getAsInteger(16, cpu))
1999 ++num_keys_decoded;
2000 } else if (name.equals("cpusubtype")) {
2001 if (!value.getAsInteger(16, sub))
2002 ++num_keys_decoded;
2003 } else if (name.equals("triple")) {
2004 StringExtractor extractor(value);
2005 extractor.GetHexByteString(triple);
2006 ++num_keys_decoded;
2007 } else if (name.equals("ostype")) {
2008 os_name = value;
2009 ++num_keys_decoded;
2010 } else if (name.equals("vendor")) {
2011 vendor_name = value;
2012 ++num_keys_decoded;
2013 } else if (name.equals("endian")) {
2014 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2015 .Case("little", eByteOrderLittle)
2016 .Case("big", eByteOrderBig)
2017 .Case("pdp", eByteOrderPDP)
2018 .Default(eByteOrderInvalid);
2019 if (byte_order != eByteOrderInvalid)
2020 ++num_keys_decoded;
2021 } else if (name.equals("ptrsize")) {
2022 if (!value.getAsInteger(16, pointer_byte_size))
2023 ++num_keys_decoded;
2024 } else if (name.equals("pid")) {
2025 if (!value.getAsInteger(16, pid))
2026 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002027 } else if (name.equals("elf_abi")) {
2028 elf_abi = value;
2029 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 }
2031 }
2032 if (num_keys_decoded > 0)
2033 m_qProcessInfo_is_valid = eLazyBoolYes;
2034 if (pid != LLDB_INVALID_PROCESS_ID) {
2035 m_curr_pid_is_valid = eLazyBoolYes;
2036 m_curr_pid = pid;
2037 }
2038
2039 // Set the ArchSpec from the triple if we have it.
2040 if (!triple.empty()) {
2041 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00002042 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002043 if (pointer_byte_size) {
2044 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2045 }
2046 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2047 !vendor_name.empty()) {
2048 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2049
2050 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00002051 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Jason Liua03ae732019-03-12 22:01:10 +00002052 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002053 switch (triple.getObjectFormat()) {
2054 case llvm::Triple::MachO:
2055 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2056 break;
2057 case llvm::Triple::ELF:
2058 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2059 break;
2060 case llvm::Triple::COFF:
2061 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2062 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00002063 case llvm::Triple::Wasm:
Jason Liua03ae732019-03-12 22:01:10 +00002064 case llvm::Triple::XCOFF:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002065 LLDB_LOGF(log, "error: not supported target architecture");
Pavel Labath4f19fce22017-02-17 13:39:50 +00002066 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002067 case llvm::Triple::UnknownObjectFormat:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002068 LLDB_LOGF(log, "error: failed to determine target architecture");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002069 return false;
2070 }
2071
2072 if (pointer_byte_size) {
2073 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2074 }
2075 if (byte_order != eByteOrderInvalid) {
2076 assert(byte_order == m_process_arch.GetByteOrder());
2077 }
2078 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2079 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2080 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2081 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2082 }
2083 return true;
2084 }
2085 } else {
2086 m_qProcessInfo_is_valid = eLazyBoolNo;
2087 }
2088
2089 return false;
2090}
2091
2092uint32_t GDBRemoteCommunicationClient::FindProcesses(
2093 const ProcessInstanceInfoMatch &match_info,
2094 ProcessInstanceInfoList &process_infos) {
2095 process_infos.Clear();
2096
2097 if (m_supports_qfProcessInfo) {
2098 StreamString packet;
2099 packet.PutCString("qfProcessInfo");
2100 if (!match_info.MatchAllProcesses()) {
2101 packet.PutChar(':');
2102 const char *name = match_info.GetProcessInfo().GetName();
2103 bool has_name_match = false;
2104 if (name && name[0]) {
2105 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00002106 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002107 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00002108 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 has_name_match = false;
2110 break;
2111
Pavel Labathc4a33952017-02-20 11:35:33 +00002112 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002113 packet.PutCString("name_match:equals;");
2114 break;
2115
Pavel Labathc4a33952017-02-20 11:35:33 +00002116 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002117 packet.PutCString("name_match:contains;");
2118 break;
2119
Pavel Labathc4a33952017-02-20 11:35:33 +00002120 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002121 packet.PutCString("name_match:starts_with;");
2122 break;
2123
Pavel Labathc4a33952017-02-20 11:35:33 +00002124 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002125 packet.PutCString("name_match:ends_with;");
2126 break;
2127
Pavel Labathc4a33952017-02-20 11:35:33 +00002128 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002129 packet.PutCString("name_match:regex;");
2130 break;
2131 }
2132 if (has_name_match) {
2133 packet.PutCString("name:");
2134 packet.PutBytesAsRawHex8(name, ::strlen(name));
2135 packet.PutChar(';');
2136 }
2137 }
2138
2139 if (match_info.GetProcessInfo().ProcessIDIsValid())
2140 packet.Printf("pid:%" PRIu64 ";",
2141 match_info.GetProcessInfo().GetProcessID());
2142 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2143 packet.Printf("parent_pid:%" PRIu64 ";",
2144 match_info.GetProcessInfo().GetParentProcessID());
2145 if (match_info.GetProcessInfo().UserIDIsValid())
2146 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2147 if (match_info.GetProcessInfo().GroupIDIsValid())
2148 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2149 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2150 packet.Printf("euid:%u;",
2151 match_info.GetProcessInfo().GetEffectiveUserID());
2152 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2153 packet.Printf("egid:%u;",
2154 match_info.GetProcessInfo().GetEffectiveGroupID());
2155 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2156 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2157 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2158 const ArchSpec &match_arch =
2159 match_info.GetProcessInfo().GetArchitecture();
2160 const llvm::Triple &triple = match_arch.GetTriple();
2161 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002162 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002163 packet.PutChar(';');
2164 }
2165 }
2166 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +00002167 // Increase timeout as the first qfProcessInfo packet takes a long time on
2168 // Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002169 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002170 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2171 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002172 do {
2173 ProcessInstanceInfo process_info;
2174 if (!DecodeProcessInfoResponse(response, process_info))
2175 break;
2176 process_infos.Append(process_info);
2177 response.GetStringRef().clear();
2178 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002179 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2180 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002181 } else {
2182 m_supports_qfProcessInfo = false;
2183 return 0;
2184 }
2185 }
2186 return process_infos.GetSize();
2187}
2188
2189bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2190 std::string &name) {
2191 if (m_supports_qUserName) {
2192 char packet[32];
2193 const int packet_len =
2194 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2195 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002196 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002197 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002198 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002199 PacketResult::Success) {
2200 if (response.IsNormalResponse()) {
2201 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002202 // the hex encoded user name and should make up the entire packet. If
2203 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204 if (response.GetHexByteString(name) * 2 ==
2205 response.GetStringRef().size())
2206 return true;
2207 }
2208 } else {
2209 m_supports_qUserName = false;
2210 return false;
2211 }
2212 }
2213 return false;
2214}
2215
2216bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2217 std::string &name) {
2218 if (m_supports_qGroupName) {
2219 char packet[32];
2220 const int packet_len =
2221 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2222 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002223 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002224 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002225 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 PacketResult::Success) {
2227 if (response.IsNormalResponse()) {
2228 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002229 // the hex encoded group name and should make up the entire packet. If
2230 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002231 if (response.GetHexByteString(name) * 2 ==
2232 response.GetStringRef().size())
2233 return true;
2234 }
2235 } else {
2236 m_supports_qGroupName = false;
2237 return false;
2238 }
2239 }
2240 return false;
2241}
2242
2243bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2244 // Form non-stop packet request
2245 char packet[32];
2246 const int packet_len =
2247 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2248 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002249 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002250
2251 StringExtractorGDBRemote response;
2252 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002253 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002254 PacketResult::Success)
2255 if (response.IsOKResponse())
2256 return true;
2257
2258 // Failed or not supported
2259 return false;
2260}
2261
2262static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2263 uint32_t recv_size) {
2264 packet.Clear();
2265 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2266 uint32_t bytes_left = send_size;
2267 while (bytes_left > 0) {
2268 if (bytes_left >= 26) {
2269 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2270 bytes_left -= 26;
2271 } else {
2272 packet.Printf("%*.*s;", bytes_left, bytes_left,
2273 "abcdefghijklmnopqrstuvwxyz");
2274 bytes_left = 0;
2275 }
2276 }
2277}
2278
Pavel Labath1eff73c2016-11-24 10:54:49 +00002279duration<float>
2280calculate_standard_deviation(const std::vector<duration<float>> &v) {
2281 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002282 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2283 Dur mean = sum / v.size();
2284 float accum = 0;
2285 for (auto d : v) {
2286 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002288 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002289
Pavel Labath3aa04912016-10-31 17:19:42 +00002290 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002291}
2292
2293void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2294 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002295 uint32_t max_recv,
2296 uint64_t recv_amount,
2297 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299 if (SendSpeedTestPacket(0, 0)) {
2300 StreamString packet;
2301 if (json)
2302 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2303 "\"results\" : [",
2304 num_packets);
2305 else
2306 strm.Printf("Testing sending %u packets of various sizes:\n",
2307 num_packets);
2308 strm.Flush();
2309
2310 uint32_t result_idx = 0;
2311 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002312 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002313
2314 for (send_size = 0; send_size <= max_send;
2315 send_size ? send_size *= 2 : send_size = 4) {
2316 for (uint32_t recv_size = 0; recv_size <= max_recv;
2317 recv_size ? recv_size *= 2 : recv_size = 4) {
2318 MakeSpeedTestPacket(packet, send_size, recv_size);
2319
2320 packet_times.clear();
2321 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002322 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002323 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002324 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002325 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002326 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002327 const auto packet_end_time = steady_clock::now();
2328 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002330 const auto end_time = steady_clock::now();
2331 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002332
2333 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002334 ((float)num_packets) / duration<float>(total_time).count();
2335 auto average_per_packet = total_time / num_packets;
2336 const duration<float> standard_deviation =
2337 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002338 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002339 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2340 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2341 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002342 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002343 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344 ++result_idx;
2345 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002346 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2347 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2348 "standard deviation of {5,10:ms+f6}\n",
2349 send_size, recv_size, duration<float>(total_time),
2350 packets_per_second, duration<float>(average_per_packet),
2351 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002352 }
2353 strm.Flush();
2354 }
2355 }
2356
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002357 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002358 if (json)
2359 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2360 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002361 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362 else
2363 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2364 "packet sizes:\n",
2365 k_recv_amount_mb);
2366 strm.Flush();
2367 send_size = 0;
2368 result_idx = 0;
2369 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2370 MakeSpeedTestPacket(packet, send_size, recv_size);
2371
2372 // If we have a receive size, test how long it takes to receive 4MB of
2373 // data
2374 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002375 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002376 uint32_t bytes_read = 0;
2377 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002378 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002379 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002380 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002381 bytes_read += recv_size;
2382 ++packet_count;
2383 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002384 const auto end_time = steady_clock::now();
2385 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002386 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002387 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002388 (1024.0 * 1024.0);
2389 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002390 ((float)packet_count) / duration<float>(total_time).count();
2391 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392
2393 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002394 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2395 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002397 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002398 ++result_idx;
2399 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002400 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2401 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2402 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002404 duration<float>(total_time), mb_second,
2405 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002406 }
2407 strm.Flush();
2408 }
2409 }
2410 if (json)
2411 strm.Printf("\n ]\n }\n}\n");
2412 else
2413 strm.EOL();
2414 }
2415}
2416
2417bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2418 uint32_t recv_size) {
2419 StreamString packet;
2420 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2421 uint32_t bytes_left = send_size;
2422 while (bytes_left > 0) {
2423 if (bytes_left >= 26) {
2424 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2425 bytes_left -= 26;
2426 } else {
2427 packet.Printf("%*.*s;", bytes_left, bytes_left,
2428 "abcdefghijklmnopqrstuvwxyz");
2429 bytes_left = 0;
2430 }
2431 }
2432
2433 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002434 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2435 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002436}
2437
2438bool GDBRemoteCommunicationClient::LaunchGDBServer(
2439 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2440 std::string &socket_name) {
2441 pid = LLDB_INVALID_PROCESS_ID;
2442 port = 0;
2443 socket_name.clear();
2444
2445 StringExtractorGDBRemote response;
2446 StreamString stream;
2447 stream.PutCString("qLaunchGDBServer;");
2448 std::string hostname;
2449 if (remote_accept_hostname && remote_accept_hostname[0])
2450 hostname = remote_accept_hostname;
2451 else {
2452 if (HostInfo::GetHostname(hostname)) {
2453 // Make the GDB server we launch only accept connections from this host
2454 stream.Printf("host:%s;", hostname.c_str());
2455 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002456 // Make the GDB server we launch accept connections from any host since
2457 // we can't figure out the hostname
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458 stream.Printf("host:*;");
2459 }
2460 }
2461 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002462 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463
2464 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2465 PacketResult::Success) {
2466 llvm::StringRef name;
2467 llvm::StringRef value;
2468 while (response.GetNameColonValue(name, value)) {
2469 if (name.equals("port"))
2470 value.getAsInteger(0, port);
2471 else if (name.equals("pid"))
2472 value.getAsInteger(0, pid);
2473 else if (name.compare("socket_name") == 0) {
2474 StringExtractor extractor(value);
2475 extractor.GetHexByteString(socket_name);
2476 }
2477 }
2478 return true;
2479 }
2480 return false;
2481}
2482
2483size_t GDBRemoteCommunicationClient::QueryGDBServer(
2484 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2485 connection_urls.clear();
2486
2487 StringExtractorGDBRemote response;
2488 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2489 PacketResult::Success)
2490 return 0;
2491
2492 StructuredData::ObjectSP data =
2493 StructuredData::ParseJSON(response.GetStringRef());
2494 if (!data)
2495 return 0;
2496
2497 StructuredData::Array *array = data->GetAsArray();
2498 if (!array)
2499 return 0;
2500
2501 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2502 StructuredData::Dictionary *element = nullptr;
2503 if (!array->GetItemAtIndexAsDictionary(i, element))
2504 continue;
2505
2506 uint16_t port = 0;
2507 if (StructuredData::ObjectSP port_osp =
2508 element->GetValueForKey(llvm::StringRef("port")))
2509 port = port_osp->GetIntegerValue(0);
2510
2511 std::string socket_name;
2512 if (StructuredData::ObjectSP socket_name_osp =
2513 element->GetValueForKey(llvm::StringRef("socket_name")))
2514 socket_name = socket_name_osp->GetStringValue();
2515
2516 if (port != 0 || !socket_name.empty())
2517 connection_urls.emplace_back(port, socket_name);
2518 }
2519 return connection_urls.size();
2520}
2521
2522bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2523 StreamString stream;
2524 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002525
2526 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002527 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002528 PacketResult::Success) {
2529 if (response.IsOKResponse())
2530 return true;
2531 }
2532 return false;
2533}
2534
2535bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2536 if (m_curr_tid == tid)
2537 return true;
2538
2539 char packet[32];
2540 int packet_len;
2541 if (tid == UINT64_MAX)
2542 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2543 else
2544 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2545 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002546 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002547 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002548 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549 PacketResult::Success) {
2550 if (response.IsOKResponse()) {
2551 m_curr_tid = tid;
2552 return true;
2553 }
2554
2555 /*
2556 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2557 * Hg packet.
2558 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2559 * which can
2560 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2561 */
2562 if (response.IsUnsupportedResponse() && IsConnected()) {
2563 m_curr_tid = 1;
2564 return true;
2565 }
2566 }
2567 return false;
2568}
2569
2570bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2571 if (m_curr_tid_run == tid)
2572 return true;
2573
2574 char packet[32];
2575 int packet_len;
2576 if (tid == UINT64_MAX)
2577 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2578 else
2579 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2580
2581 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002582 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002583 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002584 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002585 PacketResult::Success) {
2586 if (response.IsOKResponse()) {
2587 m_curr_tid_run = tid;
2588 return true;
2589 }
2590
2591 /*
2592 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2593 * Hc packet.
2594 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2595 * which can
2596 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2597 */
2598 if (response.IsUnsupportedResponse() && IsConnected()) {
2599 m_curr_tid_run = 1;
2600 return true;
2601 }
2602 }
2603 return false;
2604}
2605
2606bool GDBRemoteCommunicationClient::GetStopReply(
2607 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002608 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002609 PacketResult::Success)
2610 return response.IsNormalResponse();
2611 return false;
2612}
2613
2614bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2615 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2616 if (m_supports_qThreadStopInfo) {
2617 char packet[256];
2618 int packet_len =
2619 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2620 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002621 UNUSED_IF_ASSERT_DISABLED(packet_len);
2622 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002623 PacketResult::Success) {
2624 if (response.IsUnsupportedResponse())
2625 m_supports_qThreadStopInfo = false;
2626 else if (response.IsNormalResponse())
2627 return true;
2628 else
2629 return false;
2630 } else {
2631 m_supports_qThreadStopInfo = false;
2632 }
2633 }
2634 return false;
2635}
2636
2637uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2638 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2639 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002640 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2641 __FUNCTION__, insert ? "add" : "remove", addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002642
2643 // Check if the stub is known not to support this breakpoint type
2644 if (!SupportsGDBStoppointPacket(type))
2645 return UINT8_MAX;
2646 // Construct the breakpoint packet
2647 char packet[64];
2648 const int packet_len =
2649 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2650 insert ? 'Z' : 'z', type, addr, length);
2651 // Check we haven't overwritten the end of the packet buffer
2652 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002653 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654 StringExtractorGDBRemote response;
2655 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2656 // or "" (unsupported)
2657 response.SetResponseValidatorToOKErrorNotSupported();
2658 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002659 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002660 PacketResult::Success) {
2661 // Receive and OK packet when the breakpoint successfully placed
2662 if (response.IsOKResponse())
2663 return 0;
2664
Zachary Turner97206d52017-05-12 04:51:55 +00002665 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002666 if (response.IsErrorResponse())
2667 return response.GetError();
2668
2669 // Empty packet informs us that breakpoint is not supported
2670 if (response.IsUnsupportedResponse()) {
2671 // Disable this breakpoint type since it is unsupported
2672 switch (type) {
2673 case eBreakpointSoftware:
2674 m_supports_z0 = false;
2675 break;
2676 case eBreakpointHardware:
2677 m_supports_z1 = false;
2678 break;
2679 case eWatchpointWrite:
2680 m_supports_z2 = false;
2681 break;
2682 case eWatchpointRead:
2683 m_supports_z3 = false;
2684 break;
2685 case eWatchpointReadWrite:
2686 m_supports_z4 = false;
2687 break;
2688 case eStoppointInvalid:
2689 return UINT8_MAX;
2690 }
2691 }
2692 }
2693 // Signal generic failure
2694 return UINT8_MAX;
2695}
2696
2697size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2698 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2699 thread_ids.clear();
2700
2701 Lock lock(*this, false);
2702 if (lock) {
2703 sequence_mutex_unavailable = false;
2704 StringExtractorGDBRemote response;
2705
2706 PacketResult packet_result;
2707 for (packet_result =
2708 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2709 packet_result == PacketResult::Success && response.IsNormalResponse();
2710 packet_result =
2711 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2712 char ch = response.GetChar();
2713 if (ch == 'l')
2714 break;
2715 if (ch == 'm') {
2716 do {
2717 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2718
2719 if (tid != LLDB_INVALID_THREAD_ID) {
2720 thread_ids.push_back(tid);
2721 }
2722 ch = response.GetChar(); // Skip the command separator
2723 } while (ch == ','); // Make sure we got a comma separator
2724 }
2725 }
2726
2727 /*
2728 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2729 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2730 * could
2731 * be as simple as 'S05'. There is no packet which can give us pid and/or
2732 * tid.
2733 * Assume pid=tid=1 in such cases.
2734 */
Tamas Berghammer1492cb82017-09-18 10:24:48 +00002735 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2736 thread_ids.size() == 0 && IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002737 thread_ids.push_back(1);
2738 }
2739 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002740#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002741 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2742 GDBR_LOG_PACKETS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002743 LLDB_LOGF(log, "error: failed to get packet sequence mutex, not sending "
2744 "packet 'qfThreadInfo'");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745#endif
2746 sequence_mutex_unavailable = true;
2747 }
2748 return thread_ids.size();
2749}
2750
2751lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2752 StringExtractorGDBRemote response;
2753 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2754 PacketResult::Success ||
2755 !response.IsNormalResponse())
2756 return LLDB_INVALID_ADDRESS;
2757 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2758}
2759
Zachary Turner97206d52017-05-12 04:51:55 +00002760lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002761 const char *command, // Shouldn't be NULL
2762 const FileSpec &
2763 working_dir, // Pass empty FileSpec to use the current working directory
2764 int *status_ptr, // Pass NULL if you don't want the process exit status
2765 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2766 // process to exit
2767 std::string
2768 *command_output, // Pass NULL if you don't want the command output
Pavel Labath19dd1a02018-05-10 10:46:03 +00002769 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770 lldb_private::StreamString stream;
2771 stream.PutCString("qPlatform_shell:");
2772 stream.PutBytesAsRawHex8(command, strlen(command));
2773 stream.PutChar(',');
Pavel Labath19dd1a02018-05-10 10:46:03 +00002774 uint32_t timeout_sec = UINT32_MAX;
2775 if (timeout) {
2776 // TODO: Use chrono version of std::ceil once c++17 is available.
2777 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2778 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 stream.PutHex32(timeout_sec);
2780 if (working_dir) {
2781 std::string path{working_dir.GetPath(false)};
2782 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002783 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002784 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002785 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002786 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002787 PacketResult::Success) {
2788 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002789 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002791 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2793 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002794 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 else if (status_ptr)
2796 *status_ptr = exitcode;
2797 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002798 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2800 if (signo_ptr)
2801 *signo_ptr = signo;
2802 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002803 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 std::string output;
2805 response.GetEscapedBinaryData(output);
2806 if (command_output)
2807 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002808 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 }
Zachary Turner97206d52017-05-12 04:51:55 +00002810 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811}
2812
Zachary Turner97206d52017-05-12 04:51:55 +00002813Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2814 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815 std::string path{file_spec.GetPath(false)};
2816 lldb_private::StreamString stream;
2817 stream.PutCString("qPlatform_mkdir:");
2818 stream.PutHex32(file_permissions);
2819 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002820 stream.PutStringAsRawHex8(path);
Zachary Turnerc1564272016-11-16 21:15:24 +00002821 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 StringExtractorGDBRemote response;
2823
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002824 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002825 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002826 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002827
2828 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002829 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830
Zachary Turner97206d52017-05-12 04:51:55 +00002831 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002832}
2833
Zachary Turner97206d52017-05-12 04:51:55 +00002834Status
2835GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2836 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002837 std::string path{file_spec.GetPath(false)};
2838 lldb_private::StreamString stream;
2839 stream.PutCString("qPlatform_chmod:");
2840 stream.PutHex32(file_permissions);
2841 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002842 stream.PutStringAsRawHex8(path);
Zachary Turnerc1564272016-11-16 21:15:24 +00002843 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002844 StringExtractorGDBRemote response;
2845
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002846 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002848 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002849
2850 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002851 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002852
Zachary Turner97206d52017-05-12 04:51:55 +00002853 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854}
2855
2856static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002857 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858 response.SetFilePos(0);
2859 if (response.GetChar() != 'F')
2860 return fail_result;
2861 int32_t result = response.GetS32(-2);
2862 if (result == -2)
2863 return fail_result;
2864 if (response.GetChar() == ',') {
2865 int result_errno = response.GetS32(-2);
2866 if (result_errno != -2)
2867 error.SetError(result_errno, eErrorTypePOSIX);
2868 else
2869 error.SetError(-1, eErrorTypeGeneric);
2870 } else
2871 error.Clear();
2872 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002873}
2874lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2876 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002877 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 std::string path(file_spec.GetPath(false));
2879 lldb_private::StreamString stream;
2880 stream.PutCString("vFile:open:");
2881 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002882 return UINT64_MAX;
Pavel Labath7f815a92019-02-12 14:28:55 +00002883 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002884 stream.PutChar(',');
2885 stream.PutHex32(flags);
2886 stream.PutChar(',');
2887 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002889 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 PacketResult::Success) {
2891 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2892 }
2893 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002894}
2895
Zachary Turner97206d52017-05-12 04:51:55 +00002896bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2897 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002898 lldb_private::StreamString stream;
2899 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002900 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002901 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 PacketResult::Success) {
2903 return ParseHostIOPacketResponse(response, -1, error) == 0;
2904 }
2905 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002906}
2907
2908// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002909lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2910 const lldb_private::FileSpec &file_spec) {
2911 std::string path(file_spec.GetPath(false));
2912 lldb_private::StreamString stream;
2913 stream.PutCString("vFile:size:");
Pavel Labath7f815a92019-02-12 14:28:55 +00002914 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002915 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002916 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002917 PacketResult::Success) {
2918 if (response.GetChar() != 'F')
2919 return UINT64_MAX;
2920 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2921 return retcode;
2922 }
2923 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002924}
2925
Zachary Turner97206d52017-05-12 04:51:55 +00002926Status
2927GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2928 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002929 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002930 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002931 lldb_private::StreamString stream;
2932 stream.PutCString("vFile:mode:");
Pavel Labath7f815a92019-02-12 14:28:55 +00002933 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002934 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002935 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002936 PacketResult::Success) {
2937 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002938 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002939 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002940 } else {
2941 const uint32_t mode = response.GetS32(-1);
2942 if (static_cast<int32_t>(mode) == -1) {
2943 if (response.GetChar() == ',') {
2944 int response_errno = response.GetS32(-1);
2945 if (response_errno > 0)
2946 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2947 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002948 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002949 } else
2950 error.SetErrorToGenericError();
2951 } else {
2952 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2953 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002954 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002955 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002956 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002957 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958 }
2959 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002960}
2961
Kate Stoneb9c1b512016-09-06 20:57:50 +00002962uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2963 uint64_t offset, void *dst,
2964 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002965 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002966 lldb_private::StreamString stream;
2967 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2968 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002969 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002970 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002971 PacketResult::Success) {
2972 if (response.GetChar() != 'F')
2973 return 0;
2974 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2975 if (retcode == UINT32_MAX)
2976 return retcode;
2977 const char next = (response.Peek() ? *response.Peek() : 0);
2978 if (next == ',')
2979 return 0;
2980 if (next == ';') {
2981 response.GetChar(); // skip the semicolon
2982 std::string buffer;
2983 if (response.GetEscapedBinaryData(buffer)) {
2984 const uint64_t data_to_write =
2985 std::min<uint64_t>(dst_len, buffer.size());
2986 if (data_to_write > 0)
2987 memcpy(dst, &buffer[0], data_to_write);
2988 return data_to_write;
2989 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002990 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 }
2992 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002993}
2994
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2996 uint64_t offset,
2997 const void *src,
2998 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002999 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003000 lldb_private::StreamGDBRemote stream;
3001 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3002 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003003 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003004 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005 PacketResult::Success) {
3006 if (response.GetChar() != 'F') {
3007 error.SetErrorStringWithFormat("write file failed");
3008 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003009 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3011 if (bytes_written == UINT64_MAX) {
3012 error.SetErrorToGenericError();
3013 if (response.GetChar() == ',') {
3014 int response_errno = response.GetS32(-1);
3015 if (response_errno > 0)
3016 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3017 }
3018 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003019 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003020 return bytes_written;
3021 } else {
3022 error.SetErrorString("failed to send vFile:pwrite packet");
3023 }
3024 return 0;
3025}
3026
Zachary Turner97206d52017-05-12 04:51:55 +00003027Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3028 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003030 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003031 lldb_private::StreamGDBRemote stream;
3032 stream.PutCString("vFile:symlink:");
3033 // the unix symlink() command reverses its parameters where the dst if first,
3034 // so we follow suit here
Pavel Labath7f815a92019-02-12 14:28:55 +00003035 stream.PutStringAsRawHex8(dst_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003036 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00003037 stream.PutStringAsRawHex8(src_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003039 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003040 PacketResult::Success) {
3041 if (response.GetChar() == 'F') {
3042 uint32_t result = response.GetU32(UINT32_MAX);
3043 if (result != 0) {
3044 error.SetErrorToGenericError();
3045 if (response.GetChar() == ',') {
3046 int response_errno = response.GetS32(-1);
3047 if (response_errno > 0)
3048 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3049 }
3050 }
3051 } else {
3052 // Should have returned with 'F<result>[,<errno>]'
3053 error.SetErrorStringWithFormat("symlink failed");
3054 }
3055 } else {
3056 error.SetErrorString("failed to send vFile:symlink packet");
3057 }
3058 return error;
3059}
3060
Zachary Turner97206d52017-05-12 04:51:55 +00003061Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003063 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003064 lldb_private::StreamGDBRemote stream;
3065 stream.PutCString("vFile:unlink:");
3066 // the unix symlink() command reverses its parameters where the dst if first,
3067 // so we follow suit here
Pavel Labath7f815a92019-02-12 14:28:55 +00003068 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003069 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003070 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003071 PacketResult::Success) {
3072 if (response.GetChar() == 'F') {
3073 uint32_t result = response.GetU32(UINT32_MAX);
3074 if (result != 0) {
3075 error.SetErrorToGenericError();
3076 if (response.GetChar() == ',') {
3077 int response_errno = response.GetS32(-1);
3078 if (response_errno > 0)
3079 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3080 }
3081 }
3082 } else {
3083 // Should have returned with 'F<result>[,<errno>]'
3084 error.SetErrorStringWithFormat("unlink failed");
3085 }
3086 } else {
3087 error.SetErrorString("failed to send vFile:unlink packet");
3088 }
3089 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00003090}
3091
Daniel Maleae0f8f572013-08-26 23:57:52 +00003092// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093bool GDBRemoteCommunicationClient::GetFileExists(
3094 const lldb_private::FileSpec &file_spec) {
3095 std::string path(file_spec.GetPath(false));
3096 lldb_private::StreamString stream;
3097 stream.PutCString("vFile:exists:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003098 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003100 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003101 PacketResult::Success) {
3102 if (response.GetChar() != 'F')
3103 return false;
3104 if (response.GetChar() != ',')
3105 return false;
3106 bool retcode = (response.GetChar() != '0');
3107 return retcode;
3108 }
3109 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003110}
3111
Kate Stoneb9c1b512016-09-06 20:57:50 +00003112bool GDBRemoteCommunicationClient::CalculateMD5(
3113 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3114 std::string path(file_spec.GetPath(false));
3115 lldb_private::StreamString stream;
3116 stream.PutCString("vFile:MD5:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003117 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003118 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003119 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 PacketResult::Success) {
3121 if (response.GetChar() != 'F')
3122 return false;
3123 if (response.GetChar() != ',')
3124 return false;
3125 if (response.Peek() && *response.Peek() == 'x')
3126 return false;
3127 low = response.GetHexMaxU64(false, UINT64_MAX);
3128 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003129 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130 }
3131 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003132}
3133
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3135 // Some targets have issues with g/G packets and we need to avoid using them
3136 if (m_avoid_g_packets == eLazyBoolCalculate) {
3137 if (process) {
3138 m_avoid_g_packets = eLazyBoolNo;
3139 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3140 if (arch.IsValid() &&
3141 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3142 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3143 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3144 m_avoid_g_packets = eLazyBoolYes;
3145 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3146 if (gdb_server_version != 0) {
3147 const char *gdb_server_name = GetGDBServerProgramName();
3148 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3149 if (gdb_server_version >= 310)
3150 m_avoid_g_packets = eLazyBoolNo;
3151 }
3152 }
3153 }
3154 }
3155 }
3156 return m_avoid_g_packets == eLazyBoolYes;
3157}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003158
Kate Stoneb9c1b512016-09-06 20:57:50 +00003159DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3160 uint32_t reg) {
3161 StreamString payload;
3162 payload.Printf("p%x", reg);
3163 StringExtractorGDBRemote response;
3164 if (SendThreadSpecificPacketAndWaitForResponse(
3165 tid, std::move(payload), response, false) != PacketResult::Success ||
3166 !response.IsNormalResponse())
3167 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003168
Kate Stoneb9c1b512016-09-06 20:57:50 +00003169 DataBufferSP buffer_sp(
3170 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3171 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3172 return buffer_sp;
3173}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003174
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3176 StreamString payload;
3177 payload.PutChar('g');
3178 StringExtractorGDBRemote response;
3179 if (SendThreadSpecificPacketAndWaitForResponse(
3180 tid, std::move(payload), response, false) != PacketResult::Success ||
3181 !response.IsNormalResponse())
3182 return nullptr;
3183
3184 DataBufferSP buffer_sp(
3185 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3186 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3187 return buffer_sp;
3188}
3189
3190bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3191 uint32_t reg_num,
3192 llvm::ArrayRef<uint8_t> data) {
3193 StreamString payload;
3194 payload.Printf("P%x=", reg_num);
3195 payload.PutBytesAsRawHex8(data.data(), data.size(),
3196 endian::InlHostByteOrder(),
3197 endian::InlHostByteOrder());
3198 StringExtractorGDBRemote response;
3199 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3200 response, false) ==
3201 PacketResult::Success &&
3202 response.IsOKResponse();
3203}
3204
3205bool GDBRemoteCommunicationClient::WriteAllRegisters(
3206 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3207 StreamString payload;
3208 payload.PutChar('G');
3209 payload.PutBytesAsRawHex8(data.data(), data.size(),
3210 endian::InlHostByteOrder(),
3211 endian::InlHostByteOrder());
3212 StringExtractorGDBRemote response;
3213 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3214 response, false) ==
3215 PacketResult::Success &&
3216 response.IsOKResponse();
3217}
3218
3219bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3220 uint32_t &save_id) {
3221 save_id = 0; // Set to invalid save ID
3222 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003223 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003224
3225 m_supports_QSaveRegisterState = eLazyBoolYes;
3226 StreamString payload;
3227 payload.PutCString("QSaveRegisterState");
3228 StringExtractorGDBRemote response;
3229 if (SendThreadSpecificPacketAndWaitForResponse(
3230 tid, std::move(payload), response, false) != PacketResult::Success)
3231 return false;
3232
3233 if (response.IsUnsupportedResponse())
3234 m_supports_QSaveRegisterState = eLazyBoolNo;
3235
3236 const uint32_t response_save_id = response.GetU32(0);
3237 if (response_save_id == 0)
3238 return false;
3239
3240 save_id = response_save_id;
3241 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003242}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003243
Kate Stoneb9c1b512016-09-06 20:57:50 +00003244bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3245 uint32_t save_id) {
3246 // We use the "m_supports_QSaveRegisterState" variable here because the
Adrian Prantl05097242018-04-30 16:49:04 +00003247 // QSaveRegisterState and QRestoreRegisterState packets must both be
3248 // supported in order to be useful
Kate Stoneb9c1b512016-09-06 20:57:50 +00003249 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3250 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003251
Kate Stoneb9c1b512016-09-06 20:57:50 +00003252 StreamString payload;
3253 payload.Printf("QRestoreRegisterState:%u", save_id);
3254 StringExtractorGDBRemote response;
3255 if (SendThreadSpecificPacketAndWaitForResponse(
3256 tid, std::move(payload), response, false) != PacketResult::Success)
3257 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003258
Kate Stoneb9c1b512016-09-06 20:57:50 +00003259 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003260 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003261
3262 if (response.IsUnsupportedResponse())
3263 m_supports_QSaveRegisterState = eLazyBoolNo;
3264 return false;
3265}
3266
3267bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3268 if (!GetSyncThreadStateSupported())
3269 return false;
3270
3271 StreamString packet;
3272 StringExtractorGDBRemote response;
3273 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3274 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3275 GDBRemoteCommunication::PacketResult::Success &&
3276 response.IsOKResponse();
3277}
3278
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003279lldb::user_id_t
3280GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3281 Status &error) {
3282 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3283 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3284
3285 StreamGDBRemote escaped_packet;
3286 escaped_packet.PutCString("jTraceStart:");
3287
3288 StructuredData::Dictionary json_packet;
3289 json_packet.AddIntegerItem("type", options.getType());
3290 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3291 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3292
3293 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3294 json_packet.AddIntegerItem("threadid", options.getThreadID());
3295
3296 StructuredData::DictionarySP custom_params = options.getTraceParams();
3297 if (custom_params)
3298 json_packet.AddItem("params", custom_params);
3299
3300 StreamString json_string;
3301 json_packet.Dump(json_string, false);
3302 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3303
3304 StringExtractorGDBRemote response;
3305 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3306 true) ==
3307 GDBRemoteCommunication::PacketResult::Success) {
3308 if (!response.IsNormalResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003309 error = response.GetStatus();
3310 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003311 } else {
3312 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3313 }
3314 } else {
3315 LLDB_LOG(log, "failed to send packet");
3316 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3317 escaped_packet.GetData());
3318 }
3319 return ret_uid;
3320}
3321
3322Status
3323GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3324 lldb::tid_t thread_id) {
3325 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3326 StringExtractorGDBRemote response;
3327 Status error;
3328
3329 StructuredData::Dictionary json_packet;
3330 StreamGDBRemote escaped_packet;
3331 StreamString json_string;
3332 escaped_packet.PutCString("jTraceStop:");
3333
3334 json_packet.AddIntegerItem("traceid", uid);
3335
3336 if (thread_id != LLDB_INVALID_THREAD_ID)
3337 json_packet.AddIntegerItem("threadid", thread_id);
3338
3339 json_packet.Dump(json_string, false);
3340
3341 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3342
3343 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3344 true) ==
3345 GDBRemoteCommunication::PacketResult::Success) {
3346 if (!response.IsOKResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003347 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003348 LLDB_LOG(log, "stop tracing failed");
3349 }
3350 } else {
3351 LLDB_LOG(log, "failed to send packet");
3352 error.SetErrorStringWithFormat(
3353 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3354 response.GetError());
3355 }
3356 return error;
3357}
3358
3359Status GDBRemoteCommunicationClient::SendGetDataPacket(
3360 lldb::user_id_t uid, lldb::tid_t thread_id,
3361 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003362
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003363 StreamGDBRemote escaped_packet;
3364 escaped_packet.PutCString("jTraceBufferRead:");
3365 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3366}
3367
3368Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3369 lldb::user_id_t uid, lldb::tid_t thread_id,
3370 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003371
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003372 StreamGDBRemote escaped_packet;
3373 escaped_packet.PutCString("jTraceMetaRead:");
3374 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3375}
3376
3377Status
3378GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3379 TraceOptions &options) {
3380 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3381 StringExtractorGDBRemote response;
3382 Status error;
3383
3384 StreamString json_string;
3385 StreamGDBRemote escaped_packet;
3386 escaped_packet.PutCString("jTraceConfigRead:");
3387
3388 StructuredData::Dictionary json_packet;
3389 json_packet.AddIntegerItem("traceid", uid);
3390
3391 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3392 json_packet.AddIntegerItem("threadid", options.getThreadID());
3393
3394 json_packet.Dump(json_string, false);
3395 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3396
3397 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3398 true) ==
3399 GDBRemoteCommunication::PacketResult::Success) {
3400 if (response.IsNormalResponse()) {
3401 uint64_t type = std::numeric_limits<uint64_t>::max();
3402 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3403 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3404
3405 auto json_object = StructuredData::ParseJSON(response.Peek());
3406
3407 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003408 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003409 error.SetErrorString("Invalid Configuration obtained");
3410 return error;
3411 }
3412
3413 auto json_dict = json_object->GetAsDictionary();
3414
3415 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3416 metabuffersize);
3417 options.setMetaDataBufferSize(metabuffersize);
3418
3419 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3420 options.setTraceBufferSize(buffersize);
3421
3422 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3423 options.setType(static_cast<lldb::TraceType>(type));
3424
3425 StructuredData::ObjectSP custom_params_sp =
3426 json_dict->GetValueForKey("params");
3427 if (custom_params_sp) {
3428 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003429 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003430 error.SetErrorString("Invalid Configuration obtained");
3431 return error;
3432 } else
3433 options.setTraceParams(
3434 static_pointer_cast<StructuredData::Dictionary>(
3435 custom_params_sp));
3436 }
3437 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003438 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003439 }
3440 } else {
3441 LLDB_LOG(log, "failed to send packet");
3442 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3443 escaped_packet.GetData());
3444 }
3445 return error;
3446}
3447
3448Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3449 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3450 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3451 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3452 Status error;
3453
3454 StructuredData::Dictionary json_packet;
3455
3456 json_packet.AddIntegerItem("traceid", uid);
3457 json_packet.AddIntegerItem("offset", offset);
3458 json_packet.AddIntegerItem("buffersize", buffer.size());
3459
3460 if (thread_id != LLDB_INVALID_THREAD_ID)
3461 json_packet.AddIntegerItem("threadid", thread_id);
3462
3463 StreamString json_string;
3464 json_packet.Dump(json_string, false);
3465
3466 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3467 StringExtractorGDBRemote response;
3468 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3469 GDBRemoteCommunication::PacketResult::Success) {
3470 if (response.IsNormalResponse()) {
3471 size_t filled_size = response.GetHexBytesAvail(buffer);
3472 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3473 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003474 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003475 buffer = buffer.slice(buffer.size());
3476 }
3477 } else {
3478 LLDB_LOG(log, "failed to send packet");
3479 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3480 packet.GetData());
3481 buffer = buffer.slice(buffer.size());
3482 }
3483 return error;
3484}
3485
Kate Stoneb9c1b512016-09-06 20:57:50 +00003486bool GDBRemoteCommunicationClient::GetModuleInfo(
3487 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3488 ModuleSpec &module_spec) {
3489 if (!m_supports_qModuleInfo)
3490 return false;
3491
3492 std::string module_path = module_file_spec.GetPath(false);
3493 if (module_path.empty())
3494 return false;
3495
3496 StreamString packet;
3497 packet.PutCString("qModuleInfo:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003498 packet.PutStringAsRawHex8(module_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003499 packet.PutCString(";");
3500 const auto &triple = arch_spec.GetTriple().getTriple();
Pavel Labath7f815a92019-02-12 14:28:55 +00003501 packet.PutStringAsRawHex8(triple);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003502
3503 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003504 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3505 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003506 return false;
3507
3508 if (response.IsErrorResponse())
3509 return false;
3510
3511 if (response.IsUnsupportedResponse()) {
3512 m_supports_qModuleInfo = false;
3513 return false;
3514 }
3515
3516 llvm::StringRef name;
3517 llvm::StringRef value;
3518
3519 module_spec.Clear();
3520 module_spec.GetFileSpec() = module_file_spec;
3521
3522 while (response.GetNameColonValue(name, value)) {
3523 if (name == "uuid" || name == "md5") {
3524 StringExtractor extractor(value);
3525 std::string uuid;
3526 extractor.GetHexByteString(uuid);
Pavel Labatha174bcb2018-06-21 15:24:39 +00003527 module_spec.GetUUID().SetFromStringRef(uuid, uuid.size() / 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003528 } else if (name == "triple") {
3529 StringExtractor extractor(value);
3530 std::string triple;
3531 extractor.GetHexByteString(triple);
3532 module_spec.GetArchitecture().SetTriple(triple.c_str());
3533 } else if (name == "file_offset") {
3534 uint64_t ival = 0;
3535 if (!value.getAsInteger(16, ival))
3536 module_spec.SetObjectOffset(ival);
3537 } else if (name == "file_size") {
3538 uint64_t ival = 0;
3539 if (!value.getAsInteger(16, ival))
3540 module_spec.SetObjectSize(ival);
3541 } else if (name == "file_path") {
3542 StringExtractor extractor(value);
3543 std::string path;
3544 extractor.GetHexByteString(path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003545 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003546 }
3547 }
3548
3549 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003550}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003551
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003552static llvm::Optional<ModuleSpec>
3553ParseModuleSpec(StructuredData::Dictionary *dict) {
3554 ModuleSpec result;
3555 if (!dict)
3556 return llvm::None;
3557
Zachary Turner28333212017-05-12 05:49:54 +00003558 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003559 uint64_t integer;
3560
3561 if (!dict->GetValueForKeyAsString("uuid", string))
3562 return llvm::None;
Pavel Labath8c92c892017-12-18 14:31:44 +00003563 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3564 string.size())
3565 return llvm::None;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003566
3567 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3568 return llvm::None;
3569 result.SetObjectOffset(integer);
3570
3571 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3572 return llvm::None;
3573 result.SetObjectSize(integer);
3574
3575 if (!dict->GetValueForKeyAsString("triple", string))
3576 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003577 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003578
3579 if (!dict->GetValueForKeyAsString("file_path", string))
3580 return llvm::None;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003581 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003582
3583 return result;
3584}
3585
3586llvm::Optional<std::vector<ModuleSpec>>
3587GDBRemoteCommunicationClient::GetModulesInfo(
3588 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3589 if (!m_supports_jModulesInfo)
3590 return llvm::None;
3591
3592 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3593 for (const FileSpec &module_file_spec : module_file_specs) {
3594 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3595 module_array_sp->AppendObject(module_sp);
3596 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003597 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003598 module_sp->SetObject("triple",
3599 std::make_shared<JSONString>(triple.getTriple()));
3600 }
3601 StreamString unescaped_payload;
3602 unescaped_payload.PutCString("jModulesInfo:");
3603 module_array_sp->Write(unescaped_payload);
3604 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003605 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003606 unescaped_payload.GetSize());
3607
Greg Clayton70a9f512017-04-14 17:10:04 +00003608 // Increase the timeout for jModulesInfo since this packet can take longer.
3609 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3610
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003611 StringExtractorGDBRemote response;
3612 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3613 PacketResult::Success ||
3614 response.IsErrorResponse())
3615 return llvm::None;
3616
3617 if (response.IsUnsupportedResponse()) {
3618 m_supports_jModulesInfo = false;
3619 return llvm::None;
3620 }
3621
3622 StructuredData::ObjectSP response_object_sp =
3623 StructuredData::ParseJSON(response.GetStringRef());
3624 if (!response_object_sp)
3625 return llvm::None;
3626
3627 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3628 if (!response_array)
3629 return llvm::None;
3630
3631 std::vector<ModuleSpec> result;
3632 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3633 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3634 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3635 result.push_back(*module_spec);
3636 }
3637
3638 return result;
3639}
3640
Colin Rileyc3c95b22015-04-16 15:51:33 +00003641// query the target remote for extended information using the qXfer packet
3642//
Adrian Prantl05097242018-04-30 16:49:04 +00003643// example: object='features', annex='target.xml', out=<xml output> return:
3644// 'true' on success
Colin Rileyc3c95b22015-04-16 15:51:33 +00003645// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003646bool GDBRemoteCommunicationClient::ReadExtFeature(
3647 const lldb_private::ConstString object,
3648 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003649 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003650
Kate Stoneb9c1b512016-09-06 20:57:50 +00003651 std::stringstream output;
3652 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003653
Kate Stoneb9c1b512016-09-06 20:57:50 +00003654 uint64_t size = GetRemoteMaxPacketSize();
3655 if (size == 0)
3656 size = 0x1000;
3657 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3658 int offset = 0;
3659 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003660
Kate Stoneb9c1b512016-09-06 20:57:50 +00003661 // loop until all data has been read
3662 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003663
Kate Stoneb9c1b512016-09-06 20:57:50 +00003664 // send query extended feature packet
3665 std::stringstream packet;
3666 packet << "qXfer:" << object.AsCString("")
3667 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3668 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003669
Kate Stoneb9c1b512016-09-06 20:57:50 +00003670 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003671 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003672
Kate Stoneb9c1b512016-09-06 20:57:50 +00003673 if (res != GDBRemoteCommunication::PacketResult::Success) {
3674 err.SetErrorString("Error sending $qXfer packet");
3675 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003676 }
3677
Kate Stoneb9c1b512016-09-06 20:57:50 +00003678 const std::string &str = chunk.GetStringRef();
3679 if (str.length() == 0) {
3680 // should have some data in chunk
3681 err.SetErrorString("Empty response from $qXfer packet");
3682 return false;
3683 }
3684
3685 // check packet code
3686 switch (str[0]) {
3687 // last chunk
3688 case ('l'):
3689 active = false;
3690 LLVM_FALLTHROUGH;
3691
3692 // more chunks
3693 case ('m'):
3694 if (str.length() > 1)
3695 output << &str[1];
3696 offset += size;
3697 break;
3698
3699 // unknown chunk
3700 default:
3701 err.SetErrorString("Invalid continuation code from $qXfer packet");
3702 return false;
3703 }
3704 }
3705
3706 out = output.str();
3707 err.Success();
3708 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003709}
Greg Clayton0b90be12015-06-23 21:27:50 +00003710
3711// Notify the target that gdb is prepared to serve symbol lookup requests.
3712// packet: "qSymbol::"
3713// reply:
3714// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003715// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3716// encoded).
3717// LLDB may provide the value by sending another qSymbol
3718// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003719// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003720//
3721// Three examples:
3722//
3723// lldb sends: qSymbol::
3724// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003725// Remote gdb stub does not need to know the addresses of any symbols, lldb
3726// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003727// need to ask again in this session.
3728//
3729// lldb sends: qSymbol::
3730// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3731// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3732// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003733// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3734// not know
3735// the address at this time. lldb needs to send qSymbol:: again when it has
3736// more
Jason Molenda50018d32016-01-13 04:08:10 +00003737// solibs loaded.
3738//
3739// lldb sends: qSymbol::
3740// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3741// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3742// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003743// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3744// that it
3745// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3746// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003747// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003748
Kate Stoneb9c1b512016-09-06 20:57:50 +00003749void GDBRemoteCommunicationClient::ServeSymbolLookups(
3750 lldb_private::Process *process) {
Adrian Prantl05097242018-04-30 16:49:04 +00003751 // Set to true once we've resolved a symbol to an address for the remote
3752 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3753 // any more symbols and we can stop asking.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003754 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003755
Kate Stoneb9c1b512016-09-06 20:57:50 +00003756 // Is this the initial qSymbol:: packet?
3757 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003758
Jonas Devliegherea6682a42018-12-15 00:15:33 +00003759 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003760 Lock lock(*this, false);
3761 if (lock) {
3762 StreamString packet;
3763 packet.PutCString("qSymbol::");
3764 StringExtractorGDBRemote response;
3765 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3766 PacketResult::Success) {
3767 if (response.IsOKResponse()) {
3768 if (symbol_response_provided || first_qsymbol_query) {
3769 m_qSymbol_requests_done = true;
3770 }
3771
3772 // We are done serving symbols requests
3773 return;
3774 }
3775 first_qsymbol_query = false;
3776
3777 if (response.IsUnsupportedResponse()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003778 // qSymbol is not supported by the current GDB server we are
3779 // connected to
Kate Stoneb9c1b512016-09-06 20:57:50 +00003780 m_supports_qSymbol = false;
3781 return;
3782 } else {
3783 llvm::StringRef response_str(response.GetStringRef());
3784 if (response_str.startswith("qSymbol:")) {
3785 response.SetFilePos(strlen("qSymbol:"));
3786 std::string symbol_name;
3787 if (response.GetHexByteString(symbol_name)) {
3788 if (symbol_name.empty())
3789 return;
3790
3791 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3792 lldb_private::SymbolContextList sc_list;
3793 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3794 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3795 const size_t num_scs = sc_list.GetSize();
3796 for (size_t sc_idx = 0;
3797 sc_idx < num_scs &&
3798 symbol_load_addr == LLDB_INVALID_ADDRESS;
3799 ++sc_idx) {
3800 SymbolContext sc;
3801 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3802 if (sc.symbol) {
3803 switch (sc.symbol->GetType()) {
3804 case eSymbolTypeInvalid:
3805 case eSymbolTypeAbsolute:
3806 case eSymbolTypeUndefined:
3807 case eSymbolTypeSourceFile:
3808 case eSymbolTypeHeaderFile:
3809 case eSymbolTypeObjectFile:
3810 case eSymbolTypeCommonBlock:
3811 case eSymbolTypeBlock:
3812 case eSymbolTypeLocal:
3813 case eSymbolTypeParam:
3814 case eSymbolTypeVariable:
3815 case eSymbolTypeVariableType:
3816 case eSymbolTypeLineEntry:
3817 case eSymbolTypeLineHeader:
3818 case eSymbolTypeScopeBegin:
3819 case eSymbolTypeScopeEnd:
3820 case eSymbolTypeAdditional:
3821 case eSymbolTypeCompiler:
3822 case eSymbolTypeInstrumentation:
3823 case eSymbolTypeTrampoline:
3824 break;
3825
3826 case eSymbolTypeCode:
3827 case eSymbolTypeResolver:
3828 case eSymbolTypeData:
3829 case eSymbolTypeRuntime:
3830 case eSymbolTypeException:
3831 case eSymbolTypeObjCClass:
3832 case eSymbolTypeObjCMetaClass:
3833 case eSymbolTypeObjCIVar:
3834 case eSymbolTypeReExported:
3835 symbol_load_addr =
3836 sc.symbol->GetLoadAddress(&process->GetTarget());
3837 break;
3838 }
Jason Molenda50018d32016-01-13 04:08:10 +00003839 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003840 }
Greg Clayton42b01482015-08-11 22:07:46 +00003841 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003842 }
3843 // This is the normal path where our symbol lookup was successful
Adrian Prantl05097242018-04-30 16:49:04 +00003844 // and we want to send a packet with the new symbol value and see
3845 // if another lookup needs to be done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003846
Kate Stoneb9c1b512016-09-06 20:57:50 +00003847 // Change "packet" to contain the requested symbol value and name
3848 packet.Clear();
3849 packet.PutCString("qSymbol:");
3850 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3851 packet.Printf("%" PRIx64, symbol_load_addr);
3852 symbol_response_provided = true;
3853 } else {
3854 symbol_response_provided = false;
3855 }
3856 packet.PutCString(":");
3857 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3858 continue; // go back to the while loop and send "packet" and wait
3859 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003860 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003861 }
3862 }
3863 }
3864 // If we make it here, the symbol request packet response wasn't valid or
3865 // our symbol lookup failed so we must abort
3866 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003867
Kate Stoneb9c1b512016-09-06 20:57:50 +00003868 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3869 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003870 LLDB_LOGF(log,
3871 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3872 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003873 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003874 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003875}
3876
Kate Stoneb9c1b512016-09-06 20:57:50 +00003877StructuredData::Array *
3878GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3879 if (!m_supported_async_json_packets_is_valid) {
Adrian Prantl05097242018-04-30 16:49:04 +00003880 // Query the server for the array of supported asynchronous JSON packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003881 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003882
Kate Stoneb9c1b512016-09-06 20:57:50 +00003883 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003884
Kate Stoneb9c1b512016-09-06 20:57:50 +00003885 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003886 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003887 const bool send_async = false;
3888 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3889 send_async) == PacketResult::Success) {
3890 m_supported_async_json_packets_sp =
3891 StructuredData::ParseJSON(response.GetStringRef());
3892 if (m_supported_async_json_packets_sp &&
3893 !m_supported_async_json_packets_sp->GetAsArray()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003894 // We were returned something other than a JSON array. This is
3895 // invalid. Clear it out.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003896 LLDB_LOGF(log,
3897 "GDBRemoteCommunicationClient::%s(): "
3898 "QSupportedAsyncJSONPackets returned invalid "
3899 "result: %s",
3900 __FUNCTION__, response.GetStringRef().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003901 m_supported_async_json_packets_sp.reset();
3902 }
3903 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003904 LLDB_LOGF(log,
3905 "GDBRemoteCommunicationClient::%s(): "
3906 "QSupportedAsyncJSONPackets unsupported",
3907 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003908 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003909
3910 if (log && m_supported_async_json_packets_sp) {
3911 StreamString stream;
3912 m_supported_async_json_packets_sp->Dump(stream);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003913 LLDB_LOGF(log,
3914 "GDBRemoteCommunicationClient::%s(): supported async "
3915 "JSON packets: %s",
3916 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003917 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003918 }
3919
3920 return m_supported_async_json_packets_sp
3921 ? m_supported_async_json_packets_sp->GetAsArray()
3922 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003923}
3924
Zachary Turner97206d52017-05-12 04:51:55 +00003925Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003926 llvm::ArrayRef<int32_t> signals) {
3927 // Format packet:
3928 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3929 auto range = llvm::make_range(signals.begin(), signals.end());
3930 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3931
3932 StringExtractorGDBRemote response;
3933 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3934
3935 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003936 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003937
3938 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003939 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003940 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003941 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003942 }
3943}
3944
Zachary Turner97206d52017-05-12 04:51:55 +00003945Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003946 ConstString type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003947 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003948
3949 if (type_name.GetLength() == 0) {
3950 error.SetErrorString("invalid type_name argument");
3951 return error;
3952 }
3953
Adrian Prantl05097242018-04-30 16:49:04 +00003954 // Build command: Configure{type_name}: serialized config data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003955 StreamGDBRemote stream;
3956 stream.PutCString("QConfigure");
3957 stream.PutCString(type_name.AsCString());
3958 stream.PutChar(':');
3959 if (config_sp) {
3960 // Gather the plain-text version of the configuration data.
3961 StreamString unescaped_stream;
3962 config_sp->Dump(unescaped_stream);
3963 unescaped_stream.Flush();
3964
3965 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003966 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003967 unescaped_stream.GetSize());
3968 }
3969 stream.Flush();
3970
3971 // Send the packet.
3972 const bool send_async = false;
3973 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003974 auto result =
3975 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003976 if (result == PacketResult::Success) {
3977 // We failed if the config result comes back other than OK.
3978 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3979 // Okay!
3980 error.Clear();
3981 } else {
3982 error.SetErrorStringWithFormat("configuring StructuredData feature "
3983 "%s failed with error %s",
3984 type_name.AsCString(),
3985 response.GetStringRef().c_str());
3986 }
3987 } else {
3988 // Can we get more data here on the failure?
3989 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3990 "failed when sending packet: "
3991 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003992 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003993 }
3994 return error;
3995}
3996
3997void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3998 GDBRemoteClientBase::OnRunPacketSent(first);
3999 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004000}