blob: f6ef45792459a97723a11fc70b1afe72cb28b2f0 [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"
Todd Fiala75930012016-08-19 04:21:48 +000026#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000027#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000028#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000029#include "lldb/Utility/StreamString.h"
Greg Clayton576d8832011-03-22 04:00:09 +000030
Greg Clayton576d8832011-03-22 04:00:09 +000031#include "ProcessGDBRemote.h"
32#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000033#include "lldb/Host/Config.h"
Pavel Labath9af71b32018-03-20 16:14:00 +000034#include "lldb/Utility/StringExtractorGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000035
Zachary Turner54695a32016-08-29 19:58:14 +000036#include "llvm/ADT/StringSwitch.h"
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +000037#include "llvm/Support/JSON.h"
Zachary Turner54695a32016-08-29 19:58:14 +000038
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;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000044using namespace lldb_private::process_gdb_remote;
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +000045using namespace lldb_private;
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) {
Jonas Devlieghered35b42f2019-08-21 04:55:56 +0000354 const char *response_cstr = response.GetStringRef().data();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355
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) {
Jonas Devlieghered35b42f2019-08-21 04:55:56 +0000468 const char *response_cstr = response.GetStringRef().data();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 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
Adrian Prantl24610612019-09-04 17:23:15 +0000934llvm::VersionTuple GDBRemoteCommunicationClient::GetMacCatalystVersion() {
935 GetHostInfo();
936 return m_maccatalyst_version;
937}
938
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
940 if (GetHostInfo()) {
941 if (!m_os_build.empty()) {
942 s = m_os_build;
943 return true;
944 }
945 }
946 s.clear();
947 return false;
948}
949
950bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
951 if (GetHostInfo()) {
952 if (!m_os_kernel.empty()) {
953 s = m_os_kernel;
954 return true;
955 }
956 }
957 s.clear();
958 return false;
959}
960
961bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
962 if (GetHostInfo()) {
963 if (!m_hostname.empty()) {
964 s = m_hostname;
965 return true;
966 }
967 }
968 s.clear();
969 return false;
970}
971
972ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
973 if (GetHostInfo())
974 return m_host_arch;
975 return ArchSpec();
976}
977
978const lldb_private::ArchSpec &
979GDBRemoteCommunicationClient::GetProcessArchitecture() {
980 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
981 GetCurrentProcessInfo();
982 return m_process_arch;
983}
984
985bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
986 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
987 m_gdb_server_name.clear();
988 m_gdb_server_version = 0;
989 m_qGDBServerVersion_is_valid = eLazyBoolNo;
990
991 StringExtractorGDBRemote response;
992 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
993 PacketResult::Success) {
994 if (response.IsNormalResponse()) {
995 llvm::StringRef name, value;
996 bool success = false;
997 while (response.GetNameColonValue(name, value)) {
998 if (name.equals("name")) {
999 success = true;
1000 m_gdb_server_name = value;
1001 } else if (name.equals("version")) {
1002 llvm::StringRef major, minor;
1003 std::tie(major, minor) = value.split('.');
1004 if (!major.getAsInteger(0, m_gdb_server_version))
1005 success = true;
1006 }
Greg Clayton576d8832011-03-22 04:00:09 +00001007 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 if (success)
1009 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1010 }
Greg Clayton576d8832011-03-22 04:00:09 +00001011 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 }
1013 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001014}
1015
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016void GDBRemoteCommunicationClient::MaybeEnableCompression(
1017 std::vector<std::string> supported_compressions) {
1018 CompressionType avail_type = CompressionType::None;
1019 std::string avail_name;
1020
1021#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001022 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 for (auto compression : supported_compressions) {
1024 if (compression == "lzfse") {
1025 avail_type = CompressionType::LZFSE;
1026 avail_name = compression;
1027 break;
1028 }
1029 }
1030 }
1031#endif
1032
1033#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001034 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 for (auto compression : supported_compressions) {
1036 if (compression == "zlib-deflate") {
1037 avail_type = CompressionType::ZlibDeflate;
1038 avail_name = compression;
1039 break;
1040 }
1041 }
1042 }
1043#endif
1044
1045#if defined(HAVE_LIBZ)
1046 if (avail_type == CompressionType::None) {
1047 for (auto compression : supported_compressions) {
1048 if (compression == "zlib-deflate") {
1049 avail_type = CompressionType::ZlibDeflate;
1050 avail_name = compression;
1051 break;
1052 }
1053 }
1054 }
1055#endif
1056
1057#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001058 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 for (auto compression : supported_compressions) {
1060 if (compression == "lz4") {
1061 avail_type = CompressionType::LZ4;
1062 avail_name = compression;
1063 break;
1064 }
1065 }
1066 }
1067#endif
1068
1069#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001070 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 for (auto compression : supported_compressions) {
1072 if (compression == "lzma") {
1073 avail_type = CompressionType::LZMA;
1074 avail_name = compression;
1075 break;
1076 }
1077 }
1078 }
1079#endif
1080
1081 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001082 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001084 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 PacketResult::Success)
1086 return;
1087
1088 if (response.IsOKResponse()) {
1089 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001090 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001091 }
Greg Clayton576d8832011-03-22 04:00:09 +00001092}
Greg Clayton32e0a752011-03-30 18:16:51 +00001093
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1095 if (GetGDBServerVersion()) {
1096 if (!m_gdb_server_name.empty())
1097 return m_gdb_server_name.c_str();
1098 }
Konrad Kleine248a1302019-05-23 11:14:47 +00001099 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100}
1101
1102uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1103 if (GetGDBServerVersion())
1104 return m_gdb_server_version;
1105 return 0;
1106}
1107
1108bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1109 StringExtractorGDBRemote response;
1110 if (SendPacketAndWaitForResponse("qC", response, false) !=
1111 PacketResult::Success)
1112 return false;
1113
1114 if (!response.IsNormalResponse())
1115 return false;
1116
1117 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1118 tid = response.GetHexMaxU32(true, -1);
1119
1120 return true;
1121}
1122
1123bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1124 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1125
1126 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
Pavel Labathe7ec0832018-08-31 05:34:03 +00001127 // host info computation can require DNS traffic and shelling out to external processes.
1128 // Increase the timeout to account for that.
1129 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001131 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1133 PacketResult::Success) {
1134 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001135 llvm::StringRef name;
1136 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001137 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1138 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 std::string arch_name;
1140 std::string os_name;
Adrian Prantl24610612019-09-04 17:23:15 +00001141 std::string environment;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001142 std::string vendor_name;
1143 std::string triple;
1144 std::string distribution_id;
1145 uint32_t pointer_byte_size = 0;
1146 ByteOrder byte_order = eByteOrderInvalid;
1147 uint32_t num_keys_decoded = 0;
1148 while (response.GetNameColonValue(name, value)) {
1149 if (name.equals("cputype")) {
1150 // exception type in big endian hex
1151 if (!value.getAsInteger(0, cpu))
1152 ++num_keys_decoded;
1153 } else if (name.equals("cpusubtype")) {
1154 // exception count in big endian hex
1155 if (!value.getAsInteger(0, sub))
1156 ++num_keys_decoded;
1157 } else if (name.equals("arch")) {
1158 arch_name = value;
1159 ++num_keys_decoded;
1160 } else if (name.equals("triple")) {
1161 StringExtractor extractor(value);
1162 extractor.GetHexByteString(triple);
1163 ++num_keys_decoded;
1164 } else if (name.equals("distribution_id")) {
1165 StringExtractor extractor(value);
1166 extractor.GetHexByteString(distribution_id);
1167 ++num_keys_decoded;
1168 } else if (name.equals("os_build")) {
1169 StringExtractor extractor(value);
1170 extractor.GetHexByteString(m_os_build);
1171 ++num_keys_decoded;
1172 } else if (name.equals("hostname")) {
1173 StringExtractor extractor(value);
1174 extractor.GetHexByteString(m_hostname);
1175 ++num_keys_decoded;
1176 } else if (name.equals("os_kernel")) {
1177 StringExtractor extractor(value);
1178 extractor.GetHexByteString(m_os_kernel);
1179 ++num_keys_decoded;
1180 } else if (name.equals("ostype")) {
Adrian Prantl24610612019-09-04 17:23:15 +00001181 if (value.equals("maccatalyst")) {
1182 os_name = "ios";
1183 environment = "macabi";
1184 } else
1185 os_name = value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186 ++num_keys_decoded;
1187 } else if (name.equals("vendor")) {
1188 vendor_name = value;
1189 ++num_keys_decoded;
1190 } else if (name.equals("endian")) {
1191 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1192 .Case("little", eByteOrderLittle)
1193 .Case("big", eByteOrderBig)
1194 .Case("pdp", eByteOrderPDP)
1195 .Default(eByteOrderInvalid);
1196 if (byte_order != eByteOrderInvalid)
1197 ++num_keys_decoded;
1198 } else if (name.equals("ptrsize")) {
1199 if (!value.getAsInteger(0, pointer_byte_size))
1200 ++num_keys_decoded;
1201 } else if (name.equals("os_version") ||
1202 name.equals(
1203 "version")) // Older debugserver binaries used the
1204 // "version" key instead of
1205 // "os_version"...
1206 {
Pavel Labath2272c482018-06-18 15:02:23 +00001207 if (!m_os_version.tryParse(value))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208 ++num_keys_decoded;
Adrian Prantl24610612019-09-04 17:23:15 +00001209 } else if (name.equals("maccatalyst_version")) {
1210 if (!m_maccatalyst_version.tryParse(value))
1211 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212 } else if (name.equals("watchpoint_exceptions_received")) {
1213 m_watchpoints_trigger_after_instruction =
1214 llvm::StringSwitch<LazyBool>(value)
1215 .Case("before", eLazyBoolNo)
1216 .Case("after", eLazyBoolYes)
1217 .Default(eLazyBoolCalculate);
1218 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1219 ++num_keys_decoded;
1220 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001221 uint32_t timeout_seconds;
1222 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001223 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224 SetPacketTimeout(m_default_packet_timeout);
1225 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001226 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227 }
Jason Molenda89c37492014-01-27 22:23:20 +00001228 }
1229
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 if (num_keys_decoded > 0)
1231 m_qHostInfo_is_valid = eLazyBoolYes;
1232
1233 if (triple.empty()) {
1234 if (arch_name.empty()) {
1235 if (cpu != LLDB_INVALID_CPUTYPE) {
1236 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1237 if (pointer_byte_size) {
1238 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1239 }
1240 if (byte_order != eByteOrderInvalid) {
1241 assert(byte_order == m_host_arch.GetByteOrder());
1242 }
1243
1244 if (!vendor_name.empty())
1245 m_host_arch.GetTriple().setVendorName(
1246 llvm::StringRef(vendor_name));
1247 if (!os_name.empty())
1248 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Adrian Prantl24610612019-09-04 17:23:15 +00001249 if (!environment.empty())
1250 m_host_arch.GetTriple().setEnvironmentName(environment);
Jason Molenda89c37492014-01-27 22:23:20 +00001251 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001253 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 triple += arch_name;
1255 if (!vendor_name.empty() || !os_name.empty()) {
1256 triple += '-';
1257 if (vendor_name.empty())
1258 triple += "unknown";
1259 else
1260 triple += vendor_name;
1261 triple += '-';
1262 if (os_name.empty())
1263 triple += "unknown";
1264 else
1265 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001266 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001267 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001268
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 llvm::Triple &host_triple = m_host_arch.GetTriple();
1270 if (host_triple.getVendor() == llvm::Triple::Apple &&
1271 host_triple.getOS() == llvm::Triple::Darwin) {
1272 switch (m_host_arch.GetMachine()) {
1273 case llvm::Triple::aarch64:
1274 case llvm::Triple::arm:
1275 case llvm::Triple::thumb:
1276 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001277 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 default:
1279 host_triple.setOS(llvm::Triple::MacOSX);
1280 break;
1281 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001282 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283 if (pointer_byte_size) {
1284 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1285 }
1286 if (byte_order != eByteOrderInvalid) {
1287 assert(byte_order == m_host_arch.GetByteOrder());
1288 }
1289 }
1290 } else {
1291 m_host_arch.SetTriple(triple.c_str());
1292 if (pointer_byte_size) {
1293 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1294 }
1295 if (byte_order != eByteOrderInvalid) {
1296 assert(byte_order == m_host_arch.GetByteOrder());
1297 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001298
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001299 LLDB_LOGF(log,
1300 "GDBRemoteCommunicationClient::%s parsed host "
1301 "architecture as %s, triple as %s from triple text %s",
1302 __FUNCTION__,
1303 m_host_arch.GetArchitectureName()
1304 ? m_host_arch.GetArchitectureName()
1305 : "<null-arch-name>",
1306 m_host_arch.GetTriple().getTriple().c_str(),
1307 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001308 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 if (!distribution_id.empty())
1310 m_host_arch.SetDistributionId(distribution_id.c_str());
1311 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001312 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 }
1314 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001315}
Greg Clayton37a0a242012-04-11 00:24:49 +00001316
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317int GDBRemoteCommunicationClient::SendAttach(
1318 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1319 if (pid != LLDB_INVALID_PROCESS_ID) {
1320 char packet[64];
1321 const int packet_len =
1322 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001323 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001325 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 PacketResult::Success) {
1327 if (response.IsErrorResponse())
1328 return response.GetError();
1329 return 0;
1330 }
1331 }
1332 return -1;
1333}
1334
1335int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1336 size_t data_len) {
1337 StreamString packet;
1338 packet.PutCString("I");
1339 packet.PutBytesAsRawHex8(data, data_len);
1340 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001341 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1342 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343 return 0;
1344 }
1345 return response.GetError();
1346}
1347
1348const lldb_private::ArchSpec &
1349GDBRemoteCommunicationClient::GetHostArchitecture() {
1350 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1351 GetHostInfo();
1352 return m_host_arch;
1353}
1354
Pavel Labath1eff73c2016-11-24 10:54:49 +00001355seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1357 GetHostInfo();
1358 return m_default_packet_timeout;
1359}
1360
1361addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1362 uint32_t permissions) {
1363 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1364 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1365 char packet[64];
1366 const int packet_len = ::snprintf(
1367 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1368 permissions & lldb::ePermissionsReadable ? "r" : "",
1369 permissions & lldb::ePermissionsWritable ? "w" : "",
1370 permissions & lldb::ePermissionsExecutable ? "x" : "");
1371 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001372 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001373 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001374 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375 PacketResult::Success) {
1376 if (response.IsUnsupportedResponse())
1377 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1378 else if (!response.IsErrorResponse())
1379 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1380 } else {
1381 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1382 }
1383 }
1384 return LLDB_INVALID_ADDRESS;
1385}
1386
1387bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1388 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1389 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1390 char packet[64];
1391 const int packet_len =
1392 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1393 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001394 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001396 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 PacketResult::Success) {
1398 if (response.IsUnsupportedResponse())
1399 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1400 else if (response.IsOKResponse())
1401 return true;
1402 } else {
1403 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1404 }
1405 }
1406 return false;
1407}
1408
Zachary Turner97206d52017-05-12 04:51:55 +00001409Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1410 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411
1412 if (keep_stopped) {
1413 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1414 char packet[64];
1415 const int packet_len =
1416 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1417 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001418 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001419 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001420 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421 PacketResult::Success &&
1422 response.IsOKResponse()) {
1423 m_supports_detach_stay_stopped = eLazyBoolYes;
1424 } else {
1425 m_supports_detach_stay_stopped = eLazyBoolNo;
1426 }
1427 }
1428
1429 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1430 error.SetErrorString("Stays stopped not supported by this target.");
1431 return error;
1432 } else {
1433 StringExtractorGDBRemote response;
1434 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001435 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001436 if (packet_result != PacketResult::Success)
1437 error.SetErrorString("Sending extended disconnect packet failed.");
1438 }
1439 } else {
1440 StringExtractorGDBRemote response;
1441 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001442 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 if (packet_result != PacketResult::Success)
1444 error.SetErrorString("Sending disconnect packet failed.");
1445 }
1446 return error;
1447}
1448
Zachary Turner97206d52017-05-12 04:51:55 +00001449Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001451 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 region_info.Clear();
1453
1454 if (m_supports_memory_region_info != eLazyBoolNo) {
1455 m_supports_memory_region_info = eLazyBoolYes;
1456 char packet[64];
1457 const int packet_len = ::snprintf(
1458 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1459 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001460 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001462 if (SendPacketAndWaitForResponse(packet, response, false) ==
Pavel Labath16064d32018-03-20 11:56:24 +00001463 PacketResult::Success &&
1464 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465 llvm::StringRef name;
1466 llvm::StringRef value;
1467 addr_t addr_value = LLDB_INVALID_ADDRESS;
1468 bool success = true;
1469 bool saw_permissions = false;
1470 while (success && response.GetNameColonValue(name, value)) {
1471 if (name.equals("start")) {
1472 if (!value.getAsInteger(16, addr_value))
1473 region_info.GetRange().SetRangeBase(addr_value);
1474 } else if (name.equals("size")) {
1475 if (!value.getAsInteger(16, addr_value))
1476 region_info.GetRange().SetByteSize(addr_value);
1477 } else if (name.equals("permissions") &&
1478 region_info.GetRange().IsValid()) {
1479 saw_permissions = true;
1480 if (region_info.GetRange().Contains(addr)) {
1481 if (value.find('r') != llvm::StringRef::npos)
1482 region_info.SetReadable(MemoryRegionInfo::eYes);
1483 else
1484 region_info.SetReadable(MemoryRegionInfo::eNo);
1485
1486 if (value.find('w') != llvm::StringRef::npos)
1487 region_info.SetWritable(MemoryRegionInfo::eYes);
1488 else
1489 region_info.SetWritable(MemoryRegionInfo::eNo);
1490
1491 if (value.find('x') != llvm::StringRef::npos)
1492 region_info.SetExecutable(MemoryRegionInfo::eYes);
1493 else
1494 region_info.SetExecutable(MemoryRegionInfo::eNo);
1495
1496 region_info.SetMapped(MemoryRegionInfo::eYes);
1497 } else {
1498 // The reported region does not contain this address -- we're
1499 // looking at an unmapped page
1500 region_info.SetReadable(MemoryRegionInfo::eNo);
1501 region_info.SetWritable(MemoryRegionInfo::eNo);
1502 region_info.SetExecutable(MemoryRegionInfo::eNo);
1503 region_info.SetMapped(MemoryRegionInfo::eNo);
1504 }
1505 } else if (name.equals("name")) {
1506 StringExtractorGDBRemote name_extractor(value);
1507 std::string name;
1508 name_extractor.GetHexByteString(name);
1509 region_info.SetName(name.c_str());
1510 } else if (name.equals("error")) {
1511 StringExtractorGDBRemote error_extractor(value);
1512 std::string error_string;
1513 // Now convert the HEX bytes into a string value
1514 error_extractor.GetHexByteString(error_string);
1515 error.SetErrorString(error_string.c_str());
1516 }
1517 }
1518
Stephane Sezer48d14272017-03-31 18:00:48 +00001519 if (region_info.GetRange().IsValid()) {
1520 // We got a valid address range back but no permissions -- which means
1521 // this is an unmapped page
1522 if (!saw_permissions) {
1523 region_info.SetReadable(MemoryRegionInfo::eNo);
1524 region_info.SetWritable(MemoryRegionInfo::eNo);
1525 region_info.SetExecutable(MemoryRegionInfo::eNo);
1526 region_info.SetMapped(MemoryRegionInfo::eNo);
1527 }
1528 } else {
1529 // We got an invalid address range back
1530 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531 }
1532 } else {
1533 m_supports_memory_region_info = eLazyBoolNo;
1534 }
1535 }
1536
1537 if (m_supports_memory_region_info == eLazyBoolNo) {
1538 error.SetErrorString("qMemoryRegionInfo is not supported");
1539 }
Pavel Labath16064d32018-03-20 11:56:24 +00001540
1541 // Try qXfer:memory-map:read to get region information not included in
1542 // qMemoryRegionInfo
1543 MemoryRegionInfo qXfer_region_info;
1544 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1545
1546 if (error.Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001547 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1548 // the qXfer result as a fallback
Pavel Labath16064d32018-03-20 11:56:24 +00001549 if (qXfer_error.Success()) {
1550 region_info = qXfer_region_info;
1551 error.Clear();
1552 } else {
1553 region_info.Clear();
1554 }
1555 } else if (qXfer_error.Success()) {
1556 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
Adrian Prantl05097242018-04-30 16:49:04 +00001557 // both regions are the same range, update the result to include the flash-
1558 // memory information that is specific to the qXfer result.
Pavel Labath16064d32018-03-20 11:56:24 +00001559 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1560 region_info.SetFlash(qXfer_region_info.GetFlash());
1561 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1562 }
1563 }
1564 return error;
1565}
1566
1567Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1568 lldb::addr_t addr, MemoryRegionInfo &region) {
1569 Status error = LoadQXferMemoryMap();
1570 if (!error.Success())
1571 return error;
1572 for (const auto &map_region : m_qXfer_memory_map) {
1573 if (map_region.GetRange().Contains(addr)) {
1574 region = map_region;
1575 return error;
1576 }
1577 }
1578 error.SetErrorString("Region not found");
1579 return error;
1580}
1581
1582Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1583
1584 Status error;
1585
1586 if (m_qXfer_memory_map_loaded)
1587 // Already loaded, return success
1588 return error;
1589
1590 if (!XMLDocument::XMLEnabled()) {
1591 error.SetErrorString("XML is not supported");
1592 return error;
1593 }
1594
1595 if (!GetQXferMemoryMapReadSupported()) {
1596 error.SetErrorString("Memory map is not supported");
1597 return error;
1598 }
1599
1600 std::string xml;
1601 lldb_private::Status lldberr;
1602 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1603 lldberr)) {
1604 error.SetErrorString("Failed to read memory map");
1605 return error;
1606 }
1607
1608 XMLDocument xml_document;
1609
1610 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1611 error.SetErrorString("Failed to parse memory map xml");
1612 return error;
1613 }
1614
1615 XMLNode map_node = xml_document.GetRootElement("memory-map");
1616 if (!map_node) {
1617 error.SetErrorString("Invalid root node in memory map xml");
1618 return error;
1619 }
1620
1621 m_qXfer_memory_map.clear();
1622
1623 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1624 if (!memory_node.IsElement())
1625 return true;
1626 if (memory_node.GetName() != "memory")
1627 return true;
1628 auto type = memory_node.GetAttributeValue("type", "");
1629 uint64_t start;
1630 uint64_t length;
1631 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1632 return true;
1633 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1634 return true;
1635 MemoryRegionInfo region;
1636 region.GetRange().SetRangeBase(start);
1637 region.GetRange().SetByteSize(length);
1638 if (type == "rom") {
1639 region.SetReadable(MemoryRegionInfo::eYes);
1640 this->m_qXfer_memory_map.push_back(region);
1641 } else if (type == "ram") {
1642 region.SetReadable(MemoryRegionInfo::eYes);
1643 region.SetWritable(MemoryRegionInfo::eYes);
1644 this->m_qXfer_memory_map.push_back(region);
1645 } else if (type == "flash") {
1646 region.SetFlash(MemoryRegionInfo::eYes);
1647 memory_node.ForEachChildElement(
1648 [&region](const XMLNode &prop_node) -> bool {
1649 if (!prop_node.IsElement())
1650 return true;
1651 if (prop_node.GetName() != "property")
1652 return true;
1653 auto propname = prop_node.GetAttributeValue("name", "");
1654 if (propname == "blocksize") {
1655 uint64_t blocksize;
1656 if (prop_node.GetElementTextAsUnsigned(blocksize))
1657 region.SetBlocksize(blocksize);
1658 }
1659 return true;
1660 });
1661 this->m_qXfer_memory_map.push_back(region);
1662 }
1663 return true;
1664 });
1665
1666 m_qXfer_memory_map_loaded = true;
1667
Kate Stoneb9c1b512016-09-06 20:57:50 +00001668 return error;
1669}
1670
Zachary Turner97206d52017-05-12 04:51:55 +00001671Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1672 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001673
1674 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1675 num = m_num_supported_hardware_watchpoints;
1676 return error;
1677 }
1678
1679 // Set num to 0 first.
1680 num = 0;
1681 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1682 char packet[64];
1683 const int packet_len =
1684 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1685 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001686 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001688 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 PacketResult::Success) {
1690 m_supports_watchpoint_support_info = eLazyBoolYes;
1691 llvm::StringRef name;
1692 llvm::StringRef value;
Jason Molendac0e793d2018-11-09 22:33:26 +00001693 bool found_num_field = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001694 while (response.GetNameColonValue(name, value)) {
1695 if (name.equals("num")) {
1696 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1697 num = m_num_supported_hardware_watchpoints;
Jason Molendac0e793d2018-11-09 22:33:26 +00001698 found_num_field = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699 }
1700 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001701 if (!found_num_field) {
Jason Molendac0e793d2018-11-09 22:33:26 +00001702 m_supports_watchpoint_support_info = eLazyBoolNo;
1703 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001704 } else {
1705 m_supports_watchpoint_support_info = eLazyBoolNo;
1706 }
1707 }
1708
1709 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1710 error.SetErrorString("qWatchpointSupportInfo is not supported");
1711 }
1712 return error;
1713}
1714
Zachary Turner97206d52017-05-12 04:51:55 +00001715lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001716 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001717 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718 if (error.Success())
1719 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1720 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001721}
1722
Zachary Turner97206d52017-05-12 04:51:55 +00001723lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001724GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1725 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001726 Status error;
Fangrui Song2f677ab2019-05-16 09:07:33 +00001727 llvm::Triple triple = arch.GetTriple();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001728
Adrian Prantl05097242018-04-30 16:49:04 +00001729 // we assume watchpoints will happen after running the relevant opcode and we
1730 // only want to override this behavior if we have explicitly received a
1731 // qHostInfo telling us otherwise
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 if (m_qHostInfo_is_valid != eLazyBoolYes) {
Fangrui Song2f677ab2019-05-16 09:07:33 +00001733 // On targets like MIPS and ppc64, watchpoint exceptions are always
Adrian Prantl05097242018-04-30 16:49:04 +00001734 // generated before the instruction is executed. The connected target may
1735 // not support qHostInfo or qWatchpointSupportInfo packets.
Fangrui Song2f677ab2019-05-16 09:07:33 +00001736 after = !(triple.isMIPS() || triple.isPPC64());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737 } else {
Fangrui Song2f677ab2019-05-16 09:07:33 +00001738 // For MIPS and ppc64, set m_watchpoints_trigger_after_instruction to
Pavel Labathc51ad482017-10-27 17:02:32 +00001739 // eLazyBoolNo if it is not calculated before.
Fangrui Songddb93b62019-05-16 08:37:32 +00001740 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
Fangrui Song2f677ab2019-05-16 09:07:33 +00001741 (triple.isMIPS() || triple.isPPC64()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1743
1744 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1745 }
1746 return error;
1747}
1748
1749int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1750 if (file_spec) {
1751 std::string path{file_spec.GetPath(false)};
1752 StreamString packet;
1753 packet.PutCString("QSetSTDIN:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001754 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755
1756 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001757 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1758 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759 if (response.IsOKResponse())
1760 return 0;
1761 uint8_t error = response.GetError();
1762 if (error)
1763 return error;
1764 }
1765 }
1766 return -1;
1767}
1768
1769int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1770 if (file_spec) {
1771 std::string path{file_spec.GetPath(false)};
1772 StreamString packet;
1773 packet.PutCString("QSetSTDOUT:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001774 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001775
1776 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001777 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1778 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779 if (response.IsOKResponse())
1780 return 0;
1781 uint8_t error = response.GetError();
1782 if (error)
1783 return error;
1784 }
1785 }
1786 return -1;
1787}
1788
1789int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1790 if (file_spec) {
1791 std::string path{file_spec.GetPath(false)};
1792 StreamString packet;
1793 packet.PutCString("QSetSTDERR:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001794 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795
1796 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001797 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1798 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799 if (response.IsOKResponse())
1800 return 0;
1801 uint8_t error = response.GetError();
1802 if (error)
1803 return error;
1804 }
1805 }
1806 return -1;
1807}
1808
1809bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1810 StringExtractorGDBRemote response;
1811 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1812 PacketResult::Success) {
1813 if (response.IsUnsupportedResponse())
1814 return false;
1815 if (response.IsErrorResponse())
1816 return false;
1817 std::string cwd;
1818 response.GetHexByteString(cwd);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001819 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001820 return !cwd.empty();
1821 }
1822 return false;
1823}
1824
1825int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1826 if (working_dir) {
1827 std::string path{working_dir.GetPath(false)};
1828 StreamString packet;
1829 packet.PutCString("QSetWorkingDir:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001830 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001831
1832 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001833 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1834 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835 if (response.IsOKResponse())
1836 return 0;
1837 uint8_t error = response.GetError();
1838 if (error)
1839 return error;
1840 }
1841 }
1842 return -1;
1843}
1844
1845int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1846 char packet[32];
1847 const int packet_len =
1848 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1849 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001850 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001851 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001852 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001853 PacketResult::Success) {
1854 if (response.IsOKResponse())
1855 return 0;
1856 uint8_t error = response.GetError();
1857 if (error)
1858 return error;
1859 }
1860 return -1;
1861}
1862
1863int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1864 char packet[32];
1865 const int packet_len = ::snprintf(packet, sizeof(packet),
1866 "QSetDetachOnError:%i", enable ? 1 : 0);
1867 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001868 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001869 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001870 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001871 PacketResult::Success) {
1872 if (response.IsOKResponse())
1873 return 0;
1874 uint8_t error = response.GetError();
1875 if (error)
1876 return error;
1877 }
1878 return -1;
1879}
1880
1881bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1882 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1883 if (response.IsNormalResponse()) {
1884 llvm::StringRef name;
1885 llvm::StringRef value;
1886 StringExtractor extractor;
1887
1888 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1889 uint32_t sub = 0;
1890 std::string vendor;
1891 std::string os_type;
1892
1893 while (response.GetNameColonValue(name, value)) {
1894 if (name.equals("pid")) {
1895 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1896 value.getAsInteger(0, pid);
1897 process_info.SetProcessID(pid);
1898 } else if (name.equals("ppid")) {
1899 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1900 value.getAsInteger(0, pid);
1901 process_info.SetParentProcessID(pid);
1902 } else if (name.equals("uid")) {
1903 uint32_t uid = UINT32_MAX;
1904 value.getAsInteger(0, uid);
1905 process_info.SetUserID(uid);
1906 } else if (name.equals("euid")) {
1907 uint32_t uid = UINT32_MAX;
1908 value.getAsInteger(0, uid);
Walter Erquinigo8b6dcc12019-10-07 20:26:49 +00001909 process_info.SetEffectiveUserID(uid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001910 } else if (name.equals("gid")) {
1911 uint32_t gid = UINT32_MAX;
1912 value.getAsInteger(0, gid);
1913 process_info.SetGroupID(gid);
1914 } else if (name.equals("egid")) {
1915 uint32_t gid = UINT32_MAX;
1916 value.getAsInteger(0, gid);
1917 process_info.SetEffectiveGroupID(gid);
1918 } else if (name.equals("triple")) {
1919 StringExtractor extractor(value);
1920 std::string triple;
1921 extractor.GetHexByteString(triple);
1922 process_info.GetArchitecture().SetTriple(triple.c_str());
1923 } else if (name.equals("name")) {
1924 StringExtractor extractor(value);
Adrian Prantl05097242018-04-30 16:49:04 +00001925 // The process name from ASCII hex bytes since we can't control the
1926 // characters in a process name
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927 std::string name;
1928 extractor.GetHexByteString(name);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001929 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930 } else if (name.equals("cputype")) {
1931 value.getAsInteger(0, cpu);
1932 } else if (name.equals("cpusubtype")) {
1933 value.getAsInteger(0, sub);
1934 } else if (name.equals("vendor")) {
1935 vendor = value;
1936 } else if (name.equals("ostype")) {
1937 os_type = value;
1938 }
1939 }
1940
1941 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1942 if (vendor == "apple") {
1943 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1944 sub);
1945 process_info.GetArchitecture().GetTriple().setVendorName(
1946 llvm::StringRef(vendor));
1947 process_info.GetArchitecture().GetTriple().setOSName(
1948 llvm::StringRef(os_type));
1949 }
1950 }
1951
1952 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1953 return true;
1954 }
1955 return false;
1956}
1957
1958bool GDBRemoteCommunicationClient::GetProcessInfo(
1959 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1960 process_info.Clear();
1961
1962 if (m_supports_qProcessInfoPID) {
1963 char packet[32];
1964 const int packet_len =
1965 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1966 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001967 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001968 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001969 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001970 PacketResult::Success) {
1971 return DecodeProcessInfoResponse(response, process_info);
1972 } else {
1973 m_supports_qProcessInfoPID = false;
1974 return false;
1975 }
1976 }
1977 return false;
1978}
1979
1980bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1981 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1982 GDBR_LOG_PACKETS));
1983
1984 if (allow_lazy) {
1985 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1986 return true;
1987 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1988 return false;
1989 }
1990
1991 GetHostInfo();
1992
1993 StringExtractorGDBRemote response;
1994 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1995 PacketResult::Success) {
1996 if (response.IsNormalResponse()) {
1997 llvm::StringRef name;
1998 llvm::StringRef value;
1999 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2000 uint32_t sub = 0;
2001 std::string arch_name;
2002 std::string os_name;
Adrian Prantl24610612019-09-04 17:23:15 +00002003 std::string environment;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004 std::string vendor_name;
2005 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002006 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 uint32_t pointer_byte_size = 0;
2008 StringExtractor extractor;
2009 ByteOrder byte_order = eByteOrderInvalid;
2010 uint32_t num_keys_decoded = 0;
2011 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2012 while (response.GetNameColonValue(name, value)) {
2013 if (name.equals("cputype")) {
2014 if (!value.getAsInteger(16, cpu))
2015 ++num_keys_decoded;
2016 } else if (name.equals("cpusubtype")) {
2017 if (!value.getAsInteger(16, sub))
2018 ++num_keys_decoded;
2019 } else if (name.equals("triple")) {
2020 StringExtractor extractor(value);
2021 extractor.GetHexByteString(triple);
2022 ++num_keys_decoded;
2023 } else if (name.equals("ostype")) {
Adrian Prantl24610612019-09-04 17:23:15 +00002024 if (value.equals("maccatalyst")) {
2025 os_name = "ios";
2026 environment = "macabi";
2027 } else
2028 os_name = value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002029 ++num_keys_decoded;
2030 } else if (name.equals("vendor")) {
2031 vendor_name = value;
2032 ++num_keys_decoded;
2033 } else if (name.equals("endian")) {
2034 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2035 .Case("little", eByteOrderLittle)
2036 .Case("big", eByteOrderBig)
2037 .Case("pdp", eByteOrderPDP)
2038 .Default(eByteOrderInvalid);
2039 if (byte_order != eByteOrderInvalid)
2040 ++num_keys_decoded;
2041 } else if (name.equals("ptrsize")) {
2042 if (!value.getAsInteger(16, pointer_byte_size))
2043 ++num_keys_decoded;
2044 } else if (name.equals("pid")) {
2045 if (!value.getAsInteger(16, pid))
2046 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002047 } else if (name.equals("elf_abi")) {
2048 elf_abi = value;
2049 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002050 }
2051 }
2052 if (num_keys_decoded > 0)
2053 m_qProcessInfo_is_valid = eLazyBoolYes;
2054 if (pid != LLDB_INVALID_PROCESS_ID) {
2055 m_curr_pid_is_valid = eLazyBoolYes;
2056 m_curr_pid = pid;
2057 }
2058
2059 // Set the ArchSpec from the triple if we have it.
2060 if (!triple.empty()) {
2061 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00002062 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002063 if (pointer_byte_size) {
2064 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2065 }
2066 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2067 !vendor_name.empty()) {
2068 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
Adrian Prantl24610612019-09-04 17:23:15 +00002069 if (!environment.empty())
2070 triple.setEnvironmentName(environment);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002071
2072 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00002073 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Jason Liua03ae732019-03-12 22:01:10 +00002074 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002075 switch (triple.getObjectFormat()) {
2076 case llvm::Triple::MachO:
2077 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2078 break;
2079 case llvm::Triple::ELF:
2080 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2081 break;
2082 case llvm::Triple::COFF:
2083 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2084 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00002085 case llvm::Triple::Wasm:
Jason Liua03ae732019-03-12 22:01:10 +00002086 case llvm::Triple::XCOFF:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002087 LLDB_LOGF(log, "error: not supported target architecture");
Pavel Labath4f19fce22017-02-17 13:39:50 +00002088 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 case llvm::Triple::UnknownObjectFormat:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002090 LLDB_LOGF(log, "error: failed to determine target architecture");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002091 return false;
2092 }
2093
2094 if (pointer_byte_size) {
2095 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2096 }
2097 if (byte_order != eByteOrderInvalid) {
2098 assert(byte_order == m_process_arch.GetByteOrder());
2099 }
2100 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2101 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Adrian Prantl24610612019-09-04 17:23:15 +00002102 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002103 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2104 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Adrian Prantl24610612019-09-04 17:23:15 +00002105 m_host_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 }
2107 return true;
2108 }
2109 } else {
2110 m_qProcessInfo_is_valid = eLazyBoolNo;
2111 }
2112
2113 return false;
2114}
2115
2116uint32_t GDBRemoteCommunicationClient::FindProcesses(
2117 const ProcessInstanceInfoMatch &match_info,
2118 ProcessInstanceInfoList &process_infos) {
2119 process_infos.Clear();
2120
2121 if (m_supports_qfProcessInfo) {
2122 StreamString packet;
2123 packet.PutCString("qfProcessInfo");
2124 if (!match_info.MatchAllProcesses()) {
2125 packet.PutChar(':');
2126 const char *name = match_info.GetProcessInfo().GetName();
2127 bool has_name_match = false;
2128 if (name && name[0]) {
2129 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00002130 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002131 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00002132 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002133 has_name_match = false;
2134 break;
2135
Pavel Labathc4a33952017-02-20 11:35:33 +00002136 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002137 packet.PutCString("name_match:equals;");
2138 break;
2139
Pavel Labathc4a33952017-02-20 11:35:33 +00002140 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141 packet.PutCString("name_match:contains;");
2142 break;
2143
Pavel Labathc4a33952017-02-20 11:35:33 +00002144 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145 packet.PutCString("name_match:starts_with;");
2146 break;
2147
Pavel Labathc4a33952017-02-20 11:35:33 +00002148 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002149 packet.PutCString("name_match:ends_with;");
2150 break;
2151
Pavel Labathc4a33952017-02-20 11:35:33 +00002152 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002153 packet.PutCString("name_match:regex;");
2154 break;
2155 }
2156 if (has_name_match) {
2157 packet.PutCString("name:");
2158 packet.PutBytesAsRawHex8(name, ::strlen(name));
2159 packet.PutChar(';');
2160 }
2161 }
2162
2163 if (match_info.GetProcessInfo().ProcessIDIsValid())
2164 packet.Printf("pid:%" PRIu64 ";",
2165 match_info.GetProcessInfo().GetProcessID());
2166 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2167 packet.Printf("parent_pid:%" PRIu64 ";",
2168 match_info.GetProcessInfo().GetParentProcessID());
2169 if (match_info.GetProcessInfo().UserIDIsValid())
2170 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2171 if (match_info.GetProcessInfo().GroupIDIsValid())
2172 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2173 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2174 packet.Printf("euid:%u;",
2175 match_info.GetProcessInfo().GetEffectiveUserID());
2176 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2177 packet.Printf("egid:%u;",
2178 match_info.GetProcessInfo().GetEffectiveGroupID());
Walter Erquinigo6e1a0cf2019-10-07 17:49:32 +00002179 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2181 const ArchSpec &match_arch =
2182 match_info.GetProcessInfo().GetArchitecture();
2183 const llvm::Triple &triple = match_arch.GetTriple();
2184 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002185 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002186 packet.PutChar(';');
2187 }
2188 }
2189 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +00002190 // Increase timeout as the first qfProcessInfo packet takes a long time on
2191 // Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002192 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002193 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2194 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002195 do {
2196 ProcessInstanceInfo process_info;
2197 if (!DecodeProcessInfoResponse(response, process_info))
2198 break;
2199 process_infos.Append(process_info);
Jonas Devlieghered35b42f2019-08-21 04:55:56 +00002200 response = StringExtractorGDBRemote();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002201 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2202 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002203 } else {
2204 m_supports_qfProcessInfo = false;
2205 return 0;
2206 }
2207 }
2208 return process_infos.GetSize();
2209}
2210
2211bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2212 std::string &name) {
2213 if (m_supports_qUserName) {
2214 char packet[32];
2215 const int packet_len =
2216 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2217 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002218 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002219 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002220 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002221 PacketResult::Success) {
2222 if (response.IsNormalResponse()) {
2223 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002224 // the hex encoded user name and should make up the entire packet. If
2225 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 if (response.GetHexByteString(name) * 2 ==
2227 response.GetStringRef().size())
2228 return true;
2229 }
2230 } else {
2231 m_supports_qUserName = false;
2232 return false;
2233 }
2234 }
2235 return false;
2236}
2237
2238bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2239 std::string &name) {
2240 if (m_supports_qGroupName) {
2241 char packet[32];
2242 const int packet_len =
2243 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2244 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002245 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002247 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002248 PacketResult::Success) {
2249 if (response.IsNormalResponse()) {
2250 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002251 // the hex encoded group name and should make up the entire packet. If
2252 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002253 if (response.GetHexByteString(name) * 2 ==
2254 response.GetStringRef().size())
2255 return true;
2256 }
2257 } else {
2258 m_supports_qGroupName = false;
2259 return false;
2260 }
2261 }
2262 return false;
2263}
2264
2265bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2266 // Form non-stop packet request
2267 char packet[32];
2268 const int packet_len =
2269 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2270 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002271 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002272
2273 StringExtractorGDBRemote response;
2274 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002275 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002276 PacketResult::Success)
2277 if (response.IsOKResponse())
2278 return true;
2279
2280 // Failed or not supported
2281 return false;
2282}
2283
2284static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2285 uint32_t recv_size) {
2286 packet.Clear();
2287 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2288 uint32_t bytes_left = send_size;
2289 while (bytes_left > 0) {
2290 if (bytes_left >= 26) {
2291 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2292 bytes_left -= 26;
2293 } else {
2294 packet.Printf("%*.*s;", bytes_left, bytes_left,
2295 "abcdefghijklmnopqrstuvwxyz");
2296 bytes_left = 0;
2297 }
2298 }
2299}
2300
Pavel Labath1eff73c2016-11-24 10:54:49 +00002301duration<float>
2302calculate_standard_deviation(const std::vector<duration<float>> &v) {
2303 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002304 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2305 Dur mean = sum / v.size();
2306 float accum = 0;
2307 for (auto d : v) {
2308 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002309 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002310 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002311
Pavel Labath3aa04912016-10-31 17:19:42 +00002312 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002313}
2314
2315void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2316 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002317 uint32_t max_recv,
2318 uint64_t recv_amount,
2319 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002321 if (SendSpeedTestPacket(0, 0)) {
2322 StreamString packet;
2323 if (json)
2324 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2325 "\"results\" : [",
2326 num_packets);
2327 else
2328 strm.Printf("Testing sending %u packets of various sizes:\n",
2329 num_packets);
2330 strm.Flush();
2331
2332 uint32_t result_idx = 0;
2333 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002334 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002335
2336 for (send_size = 0; send_size <= max_send;
2337 send_size ? send_size *= 2 : send_size = 4) {
2338 for (uint32_t recv_size = 0; recv_size <= max_recv;
2339 recv_size ? recv_size *= 2 : recv_size = 4) {
2340 MakeSpeedTestPacket(packet, send_size, recv_size);
2341
2342 packet_times.clear();
2343 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002344 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002345 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002346 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002347 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002348 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002349 const auto packet_end_time = steady_clock::now();
2350 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002351 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002352 const auto end_time = steady_clock::now();
2353 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002354
2355 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002356 ((float)num_packets) / duration<float>(total_time).count();
2357 auto average_per_packet = total_time / num_packets;
2358 const duration<float> standard_deviation =
2359 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002360 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002361 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2362 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2363 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002364 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002365 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366 ++result_idx;
2367 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002368 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2369 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2370 "standard deviation of {5,10:ms+f6}\n",
2371 send_size, recv_size, duration<float>(total_time),
2372 packets_per_second, duration<float>(average_per_packet),
2373 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002374 }
2375 strm.Flush();
2376 }
2377 }
2378
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002379 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002380 if (json)
2381 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2382 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002383 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384 else
2385 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2386 "packet sizes:\n",
2387 k_recv_amount_mb);
2388 strm.Flush();
2389 send_size = 0;
2390 result_idx = 0;
2391 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2392 MakeSpeedTestPacket(packet, send_size, recv_size);
2393
2394 // If we have a receive size, test how long it takes to receive 4MB of
2395 // data
2396 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002397 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002398 uint32_t bytes_read = 0;
2399 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002400 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002402 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 bytes_read += recv_size;
2404 ++packet_count;
2405 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002406 const auto end_time = steady_clock::now();
2407 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002408 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002409 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 (1024.0 * 1024.0);
2411 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002412 ((float)packet_count) / duration<float>(total_time).count();
2413 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002414
2415 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002416 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2417 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002419 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002420 ++result_idx;
2421 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002422 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2423 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2424 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002425 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002426 duration<float>(total_time), mb_second,
2427 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002428 }
2429 strm.Flush();
2430 }
2431 }
2432 if (json)
2433 strm.Printf("\n ]\n }\n}\n");
2434 else
2435 strm.EOL();
2436 }
2437}
2438
2439bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2440 uint32_t recv_size) {
2441 StreamString packet;
2442 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2443 uint32_t bytes_left = send_size;
2444 while (bytes_left > 0) {
2445 if (bytes_left >= 26) {
2446 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2447 bytes_left -= 26;
2448 } else {
2449 packet.Printf("%*.*s;", bytes_left, bytes_left,
2450 "abcdefghijklmnopqrstuvwxyz");
2451 bytes_left = 0;
2452 }
2453 }
2454
2455 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002456 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2457 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458}
2459
2460bool GDBRemoteCommunicationClient::LaunchGDBServer(
2461 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2462 std::string &socket_name) {
2463 pid = LLDB_INVALID_PROCESS_ID;
2464 port = 0;
2465 socket_name.clear();
2466
2467 StringExtractorGDBRemote response;
2468 StreamString stream;
2469 stream.PutCString("qLaunchGDBServer;");
2470 std::string hostname;
2471 if (remote_accept_hostname && remote_accept_hostname[0])
2472 hostname = remote_accept_hostname;
2473 else {
2474 if (HostInfo::GetHostname(hostname)) {
2475 // Make the GDB server we launch only accept connections from this host
2476 stream.Printf("host:%s;", hostname.c_str());
2477 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002478 // Make the GDB server we launch accept connections from any host since
2479 // we can't figure out the hostname
Kate Stoneb9c1b512016-09-06 20:57:50 +00002480 stream.Printf("host:*;");
2481 }
2482 }
2483 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002484 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002485
2486 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2487 PacketResult::Success) {
2488 llvm::StringRef name;
2489 llvm::StringRef value;
2490 while (response.GetNameColonValue(name, value)) {
2491 if (name.equals("port"))
2492 value.getAsInteger(0, port);
2493 else if (name.equals("pid"))
2494 value.getAsInteger(0, pid);
2495 else if (name.compare("socket_name") == 0) {
2496 StringExtractor extractor(value);
2497 extractor.GetHexByteString(socket_name);
2498 }
2499 }
2500 return true;
2501 }
2502 return false;
2503}
2504
2505size_t GDBRemoteCommunicationClient::QueryGDBServer(
2506 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2507 connection_urls.clear();
2508
2509 StringExtractorGDBRemote response;
2510 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2511 PacketResult::Success)
2512 return 0;
2513
2514 StructuredData::ObjectSP data =
2515 StructuredData::ParseJSON(response.GetStringRef());
2516 if (!data)
2517 return 0;
2518
2519 StructuredData::Array *array = data->GetAsArray();
2520 if (!array)
2521 return 0;
2522
2523 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2524 StructuredData::Dictionary *element = nullptr;
2525 if (!array->GetItemAtIndexAsDictionary(i, element))
2526 continue;
2527
2528 uint16_t port = 0;
2529 if (StructuredData::ObjectSP port_osp =
2530 element->GetValueForKey(llvm::StringRef("port")))
2531 port = port_osp->GetIntegerValue(0);
2532
2533 std::string socket_name;
2534 if (StructuredData::ObjectSP socket_name_osp =
2535 element->GetValueForKey(llvm::StringRef("socket_name")))
2536 socket_name = socket_name_osp->GetStringValue();
2537
2538 if (port != 0 || !socket_name.empty())
2539 connection_urls.emplace_back(port, socket_name);
2540 }
2541 return connection_urls.size();
2542}
2543
2544bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2545 StreamString stream;
2546 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002547
2548 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002549 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002550 PacketResult::Success) {
2551 if (response.IsOKResponse())
2552 return true;
2553 }
2554 return false;
2555}
2556
2557bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2558 if (m_curr_tid == tid)
2559 return true;
2560
2561 char packet[32];
2562 int packet_len;
2563 if (tid == UINT64_MAX)
2564 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2565 else
2566 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2567 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002568 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002569 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002570 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002571 PacketResult::Success) {
2572 if (response.IsOKResponse()) {
2573 m_curr_tid = tid;
2574 return true;
2575 }
2576
2577 /*
2578 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2579 * Hg packet.
2580 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2581 * which can
2582 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2583 */
2584 if (response.IsUnsupportedResponse() && IsConnected()) {
2585 m_curr_tid = 1;
2586 return true;
2587 }
2588 }
2589 return false;
2590}
2591
2592bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2593 if (m_curr_tid_run == tid)
2594 return true;
2595
2596 char packet[32];
2597 int packet_len;
2598 if (tid == UINT64_MAX)
2599 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2600 else
2601 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2602
2603 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002604 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002605 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002606 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002607 PacketResult::Success) {
2608 if (response.IsOKResponse()) {
2609 m_curr_tid_run = tid;
2610 return true;
2611 }
2612
2613 /*
2614 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2615 * Hc packet.
2616 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2617 * which can
2618 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2619 */
2620 if (response.IsUnsupportedResponse() && IsConnected()) {
2621 m_curr_tid_run = 1;
2622 return true;
2623 }
2624 }
2625 return false;
2626}
2627
2628bool GDBRemoteCommunicationClient::GetStopReply(
2629 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002630 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002631 PacketResult::Success)
2632 return response.IsNormalResponse();
2633 return false;
2634}
2635
2636bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2637 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2638 if (m_supports_qThreadStopInfo) {
2639 char packet[256];
2640 int packet_len =
2641 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2642 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002643 UNUSED_IF_ASSERT_DISABLED(packet_len);
2644 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002645 PacketResult::Success) {
2646 if (response.IsUnsupportedResponse())
2647 m_supports_qThreadStopInfo = false;
2648 else if (response.IsNormalResponse())
2649 return true;
2650 else
2651 return false;
2652 } else {
2653 m_supports_qThreadStopInfo = false;
2654 }
2655 }
2656 return false;
2657}
2658
2659uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2660 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2661 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002662 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2663 __FUNCTION__, insert ? "add" : "remove", addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002664
2665 // Check if the stub is known not to support this breakpoint type
2666 if (!SupportsGDBStoppointPacket(type))
2667 return UINT8_MAX;
2668 // Construct the breakpoint packet
2669 char packet[64];
2670 const int packet_len =
2671 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2672 insert ? 'Z' : 'z', type, addr, length);
2673 // Check we haven't overwritten the end of the packet buffer
2674 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002675 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002676 StringExtractorGDBRemote response;
2677 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2678 // or "" (unsupported)
2679 response.SetResponseValidatorToOKErrorNotSupported();
2680 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002681 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002682 PacketResult::Success) {
2683 // Receive and OK packet when the breakpoint successfully placed
2684 if (response.IsOKResponse())
2685 return 0;
2686
Zachary Turner97206d52017-05-12 04:51:55 +00002687 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002688 if (response.IsErrorResponse())
2689 return response.GetError();
2690
2691 // Empty packet informs us that breakpoint is not supported
2692 if (response.IsUnsupportedResponse()) {
2693 // Disable this breakpoint type since it is unsupported
2694 switch (type) {
2695 case eBreakpointSoftware:
2696 m_supports_z0 = false;
2697 break;
2698 case eBreakpointHardware:
2699 m_supports_z1 = false;
2700 break;
2701 case eWatchpointWrite:
2702 m_supports_z2 = false;
2703 break;
2704 case eWatchpointRead:
2705 m_supports_z3 = false;
2706 break;
2707 case eWatchpointReadWrite:
2708 m_supports_z4 = false;
2709 break;
2710 case eStoppointInvalid:
2711 return UINT8_MAX;
2712 }
2713 }
2714 }
2715 // Signal generic failure
2716 return UINT8_MAX;
2717}
2718
2719size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2720 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2721 thread_ids.clear();
2722
2723 Lock lock(*this, false);
2724 if (lock) {
2725 sequence_mutex_unavailable = false;
2726 StringExtractorGDBRemote response;
2727
2728 PacketResult packet_result;
2729 for (packet_result =
2730 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2731 packet_result == PacketResult::Success && response.IsNormalResponse();
2732 packet_result =
2733 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2734 char ch = response.GetChar();
2735 if (ch == 'l')
2736 break;
2737 if (ch == 'm') {
2738 do {
2739 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2740
2741 if (tid != LLDB_INVALID_THREAD_ID) {
2742 thread_ids.push_back(tid);
2743 }
2744 ch = response.GetChar(); // Skip the command separator
2745 } while (ch == ','); // Make sure we got a comma separator
2746 }
2747 }
2748
2749 /*
2750 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2751 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2752 * could
2753 * be as simple as 'S05'. There is no packet which can give us pid and/or
2754 * tid.
2755 * Assume pid=tid=1 in such cases.
2756 */
Tamas Berghammer1492cb82017-09-18 10:24:48 +00002757 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2758 thread_ids.size() == 0 && IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759 thread_ids.push_back(1);
2760 }
2761 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002762#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002763 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2764 GDBR_LOG_PACKETS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002765 LLDB_LOGF(log, "error: failed to get packet sequence mutex, not sending "
2766 "packet 'qfThreadInfo'");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002767#endif
2768 sequence_mutex_unavailable = true;
2769 }
2770 return thread_ids.size();
2771}
2772
2773lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2774 StringExtractorGDBRemote response;
2775 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2776 PacketResult::Success ||
2777 !response.IsNormalResponse())
2778 return LLDB_INVALID_ADDRESS;
2779 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2780}
2781
Zachary Turner97206d52017-05-12 04:51:55 +00002782lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 const char *command, // Shouldn't be NULL
2784 const FileSpec &
2785 working_dir, // Pass empty FileSpec to use the current working directory
2786 int *status_ptr, // Pass NULL if you don't want the process exit status
2787 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2788 // process to exit
2789 std::string
2790 *command_output, // Pass NULL if you don't want the command output
Pavel Labath19dd1a02018-05-10 10:46:03 +00002791 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 lldb_private::StreamString stream;
2793 stream.PutCString("qPlatform_shell:");
2794 stream.PutBytesAsRawHex8(command, strlen(command));
2795 stream.PutChar(',');
Pavel Labath19dd1a02018-05-10 10:46:03 +00002796 uint32_t timeout_sec = UINT32_MAX;
2797 if (timeout) {
2798 // TODO: Use chrono version of std::ceil once c++17 is available.
2799 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2800 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 stream.PutHex32(timeout_sec);
2802 if (working_dir) {
2803 std::string path{working_dir.GetPath(false)};
2804 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002805 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002808 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 PacketResult::Success) {
2810 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002811 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002813 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002814 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2815 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002816 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 else if (status_ptr)
2818 *status_ptr = exitcode;
2819 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002820 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2822 if (signo_ptr)
2823 *signo_ptr = signo;
2824 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002825 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 std::string output;
2827 response.GetEscapedBinaryData(output);
2828 if (command_output)
2829 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002830 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002831 }
Zachary Turner97206d52017-05-12 04:51:55 +00002832 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833}
2834
Zachary Turner97206d52017-05-12 04:51:55 +00002835Status GDBRemoteCommunicationClient::MakeDirectory(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_mkdir:");
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", packet.str().c_str());
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", packet.str().c_str());
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
Zachary Turner97206d52017-05-12 04:51:55 +00002856Status
2857GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2858 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859 std::string path{file_spec.GetPath(false)};
2860 lldb_private::StreamString stream;
2861 stream.PutCString("qPlatform_chmod:");
2862 stream.PutHex32(file_permissions);
2863 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002864 stream.PutStringAsRawHex8(path);
Zachary Turnerc1564272016-11-16 21:15:24 +00002865 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 StringExtractorGDBRemote response;
2867
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002868 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002869 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002870 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002871
2872 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002873 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002874
Zachary Turner97206d52017-05-12 04:51:55 +00002875 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876}
2877
2878static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002879 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002880 response.SetFilePos(0);
2881 if (response.GetChar() != 'F')
2882 return fail_result;
2883 int32_t result = response.GetS32(-2);
2884 if (result == -2)
2885 return fail_result;
2886 if (response.GetChar() == ',') {
2887 int result_errno = response.GetS32(-2);
2888 if (result_errno != -2)
2889 error.SetError(result_errno, eErrorTypePOSIX);
2890 else
2891 error.SetError(-1, eErrorTypeGeneric);
2892 } else
2893 error.Clear();
2894 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002895}
2896lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002897GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2898 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002899 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002900 std::string path(file_spec.GetPath(false));
2901 lldb_private::StreamString stream;
2902 stream.PutCString("vFile:open:");
2903 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002904 return UINT64_MAX;
Pavel Labath7f815a92019-02-12 14:28:55 +00002905 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002906 stream.PutChar(',');
2907 stream.PutHex32(flags);
2908 stream.PutChar(',');
2909 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002911 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 PacketResult::Success) {
2913 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2914 }
2915 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002916}
2917
Zachary Turner97206d52017-05-12 04:51:55 +00002918bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2919 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002920 lldb_private::StreamString stream;
2921 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002922 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002923 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 PacketResult::Success) {
2925 return ParseHostIOPacketResponse(response, -1, error) == 0;
2926 }
2927 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002928}
2929
2930// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002931lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2932 const lldb_private::FileSpec &file_spec) {
2933 std::string path(file_spec.GetPath(false));
2934 lldb_private::StreamString stream;
2935 stream.PutCString("vFile:size:");
Pavel Labath7f815a92019-02-12 14:28:55 +00002936 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002937 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002938 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939 PacketResult::Success) {
2940 if (response.GetChar() != 'F')
2941 return UINT64_MAX;
2942 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2943 return retcode;
2944 }
2945 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002946}
2947
Zachary Turner97206d52017-05-12 04:51:55 +00002948Status
2949GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2950 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002952 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002953 lldb_private::StreamString stream;
2954 stream.PutCString("vFile:mode:");
Pavel Labath7f815a92019-02-12 14:28:55 +00002955 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002957 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958 PacketResult::Success) {
2959 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002960 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002961 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002962 } else {
2963 const uint32_t mode = response.GetS32(-1);
2964 if (static_cast<int32_t>(mode) == -1) {
2965 if (response.GetChar() == ',') {
2966 int response_errno = response.GetS32(-1);
2967 if (response_errno > 0)
2968 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2969 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002970 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002971 } else
2972 error.SetErrorToGenericError();
2973 } else {
2974 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2975 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002976 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002977 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002978 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002979 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002980 }
2981 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002982}
2983
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2985 uint64_t offset, void *dst,
2986 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002987 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002988 lldb_private::StreamString stream;
2989 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2990 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002992 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002993 PacketResult::Success) {
2994 if (response.GetChar() != 'F')
2995 return 0;
2996 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2997 if (retcode == UINT32_MAX)
2998 return retcode;
2999 const char next = (response.Peek() ? *response.Peek() : 0);
3000 if (next == ',')
3001 return 0;
3002 if (next == ';') {
3003 response.GetChar(); // skip the semicolon
3004 std::string buffer;
3005 if (response.GetEscapedBinaryData(buffer)) {
3006 const uint64_t data_to_write =
3007 std::min<uint64_t>(dst_len, buffer.size());
3008 if (data_to_write > 0)
3009 memcpy(dst, &buffer[0], data_to_write);
3010 return data_to_write;
3011 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003012 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003013 }
3014 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003015}
3016
Kate Stoneb9c1b512016-09-06 20:57:50 +00003017uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3018 uint64_t offset,
3019 const void *src,
3020 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003021 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003022 lldb_private::StreamGDBRemote stream;
3023 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3024 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003025 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003026 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003027 PacketResult::Success) {
3028 if (response.GetChar() != 'F') {
3029 error.SetErrorStringWithFormat("write file failed");
3030 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003031 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3033 if (bytes_written == UINT64_MAX) {
3034 error.SetErrorToGenericError();
3035 if (response.GetChar() == ',') {
3036 int response_errno = response.GetS32(-1);
3037 if (response_errno > 0)
3038 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3039 }
3040 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003041 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 return bytes_written;
3043 } else {
3044 error.SetErrorString("failed to send vFile:pwrite packet");
3045 }
3046 return 0;
3047}
3048
Zachary Turner97206d52017-05-12 04:51:55 +00003049Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3050 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003051 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003052 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003053 lldb_private::StreamGDBRemote stream;
3054 stream.PutCString("vFile:symlink:");
3055 // the unix symlink() command reverses its parameters where the dst if first,
3056 // so we follow suit here
Pavel Labath7f815a92019-02-12 14:28:55 +00003057 stream.PutStringAsRawHex8(dst_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003058 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00003059 stream.PutStringAsRawHex8(src_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003060 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003061 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062 PacketResult::Success) {
3063 if (response.GetChar() == 'F') {
3064 uint32_t result = response.GetU32(UINT32_MAX);
3065 if (result != 0) {
3066 error.SetErrorToGenericError();
3067 if (response.GetChar() == ',') {
3068 int response_errno = response.GetS32(-1);
3069 if (response_errno > 0)
3070 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3071 }
3072 }
3073 } else {
3074 // Should have returned with 'F<result>[,<errno>]'
3075 error.SetErrorStringWithFormat("symlink failed");
3076 }
3077 } else {
3078 error.SetErrorString("failed to send vFile:symlink packet");
3079 }
3080 return error;
3081}
3082
Zachary Turner97206d52017-05-12 04:51:55 +00003083Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003084 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003085 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 lldb_private::StreamGDBRemote stream;
3087 stream.PutCString("vFile:unlink:");
3088 // the unix symlink() command reverses its parameters where the dst if first,
3089 // so we follow suit here
Pavel Labath7f815a92019-02-12 14:28:55 +00003090 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003091 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003092 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 PacketResult::Success) {
3094 if (response.GetChar() == 'F') {
3095 uint32_t result = response.GetU32(UINT32_MAX);
3096 if (result != 0) {
3097 error.SetErrorToGenericError();
3098 if (response.GetChar() == ',') {
3099 int response_errno = response.GetS32(-1);
3100 if (response_errno > 0)
3101 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3102 }
3103 }
3104 } else {
3105 // Should have returned with 'F<result>[,<errno>]'
3106 error.SetErrorStringWithFormat("unlink failed");
3107 }
3108 } else {
3109 error.SetErrorString("failed to send vFile:unlink packet");
3110 }
3111 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00003112}
3113
Daniel Maleae0f8f572013-08-26 23:57:52 +00003114// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115bool GDBRemoteCommunicationClient::GetFileExists(
3116 const lldb_private::FileSpec &file_spec) {
3117 std::string path(file_spec.GetPath(false));
3118 lldb_private::StreamString stream;
3119 stream.PutCString("vFile:exists:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003120 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003121 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003122 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003123 PacketResult::Success) {
3124 if (response.GetChar() != 'F')
3125 return false;
3126 if (response.GetChar() != ',')
3127 return false;
3128 bool retcode = (response.GetChar() != '0');
3129 return retcode;
3130 }
3131 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003132}
3133
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134bool GDBRemoteCommunicationClient::CalculateMD5(
3135 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3136 std::string path(file_spec.GetPath(false));
3137 lldb_private::StreamString stream;
3138 stream.PutCString("vFile:MD5:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003139 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003141 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003142 PacketResult::Success) {
3143 if (response.GetChar() != 'F')
3144 return false;
3145 if (response.GetChar() != ',')
3146 return false;
3147 if (response.Peek() && *response.Peek() == 'x')
3148 return false;
3149 low = response.GetHexMaxU64(false, UINT64_MAX);
3150 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003151 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003152 }
3153 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003154}
3155
Kate Stoneb9c1b512016-09-06 20:57:50 +00003156bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3157 // Some targets have issues with g/G packets and we need to avoid using them
3158 if (m_avoid_g_packets == eLazyBoolCalculate) {
3159 if (process) {
3160 m_avoid_g_packets = eLazyBoolNo;
3161 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3162 if (arch.IsValid() &&
3163 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3164 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3165 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3166 m_avoid_g_packets = eLazyBoolYes;
3167 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3168 if (gdb_server_version != 0) {
3169 const char *gdb_server_name = GetGDBServerProgramName();
3170 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3171 if (gdb_server_version >= 310)
3172 m_avoid_g_packets = eLazyBoolNo;
3173 }
3174 }
3175 }
3176 }
3177 }
3178 return m_avoid_g_packets == eLazyBoolYes;
3179}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003180
Kate Stoneb9c1b512016-09-06 20:57:50 +00003181DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3182 uint32_t reg) {
3183 StreamString payload;
3184 payload.Printf("p%x", reg);
3185 StringExtractorGDBRemote response;
3186 if (SendThreadSpecificPacketAndWaitForResponse(
3187 tid, std::move(payload), response, false) != PacketResult::Success ||
3188 !response.IsNormalResponse())
3189 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003190
Kate Stoneb9c1b512016-09-06 20:57:50 +00003191 DataBufferSP buffer_sp(
3192 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3193 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3194 return buffer_sp;
3195}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003196
Kate Stoneb9c1b512016-09-06 20:57:50 +00003197DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3198 StreamString payload;
3199 payload.PutChar('g');
3200 StringExtractorGDBRemote response;
3201 if (SendThreadSpecificPacketAndWaitForResponse(
3202 tid, std::move(payload), response, false) != PacketResult::Success ||
3203 !response.IsNormalResponse())
3204 return nullptr;
3205
3206 DataBufferSP buffer_sp(
3207 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3208 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3209 return buffer_sp;
3210}
3211
3212bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3213 uint32_t reg_num,
3214 llvm::ArrayRef<uint8_t> data) {
3215 StreamString payload;
3216 payload.Printf("P%x=", reg_num);
3217 payload.PutBytesAsRawHex8(data.data(), data.size(),
3218 endian::InlHostByteOrder(),
3219 endian::InlHostByteOrder());
3220 StringExtractorGDBRemote response;
3221 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3222 response, false) ==
3223 PacketResult::Success &&
3224 response.IsOKResponse();
3225}
3226
3227bool GDBRemoteCommunicationClient::WriteAllRegisters(
3228 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3229 StreamString payload;
3230 payload.PutChar('G');
3231 payload.PutBytesAsRawHex8(data.data(), data.size(),
3232 endian::InlHostByteOrder(),
3233 endian::InlHostByteOrder());
3234 StringExtractorGDBRemote response;
3235 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3236 response, false) ==
3237 PacketResult::Success &&
3238 response.IsOKResponse();
3239}
3240
3241bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3242 uint32_t &save_id) {
3243 save_id = 0; // Set to invalid save ID
3244 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003245 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003246
3247 m_supports_QSaveRegisterState = eLazyBoolYes;
3248 StreamString payload;
3249 payload.PutCString("QSaveRegisterState");
3250 StringExtractorGDBRemote response;
3251 if (SendThreadSpecificPacketAndWaitForResponse(
3252 tid, std::move(payload), response, false) != PacketResult::Success)
3253 return false;
3254
3255 if (response.IsUnsupportedResponse())
3256 m_supports_QSaveRegisterState = eLazyBoolNo;
3257
3258 const uint32_t response_save_id = response.GetU32(0);
3259 if (response_save_id == 0)
3260 return false;
3261
3262 save_id = response_save_id;
3263 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003264}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003265
Kate Stoneb9c1b512016-09-06 20:57:50 +00003266bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3267 uint32_t save_id) {
3268 // We use the "m_supports_QSaveRegisterState" variable here because the
Adrian Prantl05097242018-04-30 16:49:04 +00003269 // QSaveRegisterState and QRestoreRegisterState packets must both be
3270 // supported in order to be useful
Kate Stoneb9c1b512016-09-06 20:57:50 +00003271 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3272 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003273
Kate Stoneb9c1b512016-09-06 20:57:50 +00003274 StreamString payload;
3275 payload.Printf("QRestoreRegisterState:%u", save_id);
3276 StringExtractorGDBRemote response;
3277 if (SendThreadSpecificPacketAndWaitForResponse(
3278 tid, std::move(payload), response, false) != PacketResult::Success)
3279 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003280
Kate Stoneb9c1b512016-09-06 20:57:50 +00003281 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003282 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003283
3284 if (response.IsUnsupportedResponse())
3285 m_supports_QSaveRegisterState = eLazyBoolNo;
3286 return false;
3287}
3288
3289bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3290 if (!GetSyncThreadStateSupported())
3291 return false;
3292
3293 StreamString packet;
3294 StringExtractorGDBRemote response;
3295 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3296 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3297 GDBRemoteCommunication::PacketResult::Success &&
3298 response.IsOKResponse();
3299}
3300
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003301lldb::user_id_t
3302GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3303 Status &error) {
3304 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3305 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3306
3307 StreamGDBRemote escaped_packet;
3308 escaped_packet.PutCString("jTraceStart:");
3309
3310 StructuredData::Dictionary json_packet;
3311 json_packet.AddIntegerItem("type", options.getType());
3312 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3313 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3314
3315 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3316 json_packet.AddIntegerItem("threadid", options.getThreadID());
3317
3318 StructuredData::DictionarySP custom_params = options.getTraceParams();
3319 if (custom_params)
3320 json_packet.AddItem("params", custom_params);
3321
3322 StreamString json_string;
3323 json_packet.Dump(json_string, false);
3324 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3325
3326 StringExtractorGDBRemote response;
3327 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3328 true) ==
3329 GDBRemoteCommunication::PacketResult::Success) {
3330 if (!response.IsNormalResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003331 error = response.GetStatus();
3332 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003333 } else {
3334 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3335 }
3336 } else {
3337 LLDB_LOG(log, "failed to send packet");
3338 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3339 escaped_packet.GetData());
3340 }
3341 return ret_uid;
3342}
3343
3344Status
3345GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3346 lldb::tid_t thread_id) {
3347 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3348 StringExtractorGDBRemote response;
3349 Status error;
3350
3351 StructuredData::Dictionary json_packet;
3352 StreamGDBRemote escaped_packet;
3353 StreamString json_string;
3354 escaped_packet.PutCString("jTraceStop:");
3355
3356 json_packet.AddIntegerItem("traceid", uid);
3357
3358 if (thread_id != LLDB_INVALID_THREAD_ID)
3359 json_packet.AddIntegerItem("threadid", thread_id);
3360
3361 json_packet.Dump(json_string, false);
3362
3363 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3364
3365 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3366 true) ==
3367 GDBRemoteCommunication::PacketResult::Success) {
3368 if (!response.IsOKResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003369 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003370 LLDB_LOG(log, "stop tracing failed");
3371 }
3372 } else {
3373 LLDB_LOG(log, "failed to send packet");
3374 error.SetErrorStringWithFormat(
3375 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3376 response.GetError());
3377 }
3378 return error;
3379}
3380
3381Status GDBRemoteCommunicationClient::SendGetDataPacket(
3382 lldb::user_id_t uid, lldb::tid_t thread_id,
3383 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003384
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003385 StreamGDBRemote escaped_packet;
3386 escaped_packet.PutCString("jTraceBufferRead:");
3387 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3388}
3389
3390Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3391 lldb::user_id_t uid, lldb::tid_t thread_id,
3392 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003393
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003394 StreamGDBRemote escaped_packet;
3395 escaped_packet.PutCString("jTraceMetaRead:");
3396 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3397}
3398
3399Status
3400GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3401 TraceOptions &options) {
3402 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3403 StringExtractorGDBRemote response;
3404 Status error;
3405
3406 StreamString json_string;
3407 StreamGDBRemote escaped_packet;
3408 escaped_packet.PutCString("jTraceConfigRead:");
3409
3410 StructuredData::Dictionary json_packet;
3411 json_packet.AddIntegerItem("traceid", uid);
3412
3413 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3414 json_packet.AddIntegerItem("threadid", options.getThreadID());
3415
3416 json_packet.Dump(json_string, false);
3417 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3418
3419 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3420 true) ==
3421 GDBRemoteCommunication::PacketResult::Success) {
3422 if (response.IsNormalResponse()) {
3423 uint64_t type = std::numeric_limits<uint64_t>::max();
3424 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3425 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3426
3427 auto json_object = StructuredData::ParseJSON(response.Peek());
3428
3429 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003430 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003431 error.SetErrorString("Invalid Configuration obtained");
3432 return error;
3433 }
3434
3435 auto json_dict = json_object->GetAsDictionary();
3436
3437 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3438 metabuffersize);
3439 options.setMetaDataBufferSize(metabuffersize);
3440
3441 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3442 options.setTraceBufferSize(buffersize);
3443
3444 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3445 options.setType(static_cast<lldb::TraceType>(type));
3446
3447 StructuredData::ObjectSP custom_params_sp =
3448 json_dict->GetValueForKey("params");
3449 if (custom_params_sp) {
3450 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003451 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003452 error.SetErrorString("Invalid Configuration obtained");
3453 return error;
3454 } else
3455 options.setTraceParams(
3456 static_pointer_cast<StructuredData::Dictionary>(
3457 custom_params_sp));
3458 }
3459 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003460 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003461 }
3462 } else {
3463 LLDB_LOG(log, "failed to send packet");
3464 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3465 escaped_packet.GetData());
3466 }
3467 return error;
3468}
3469
3470Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3471 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3472 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3473 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3474 Status error;
3475
3476 StructuredData::Dictionary json_packet;
3477
3478 json_packet.AddIntegerItem("traceid", uid);
3479 json_packet.AddIntegerItem("offset", offset);
3480 json_packet.AddIntegerItem("buffersize", buffer.size());
3481
3482 if (thread_id != LLDB_INVALID_THREAD_ID)
3483 json_packet.AddIntegerItem("threadid", thread_id);
3484
3485 StreamString json_string;
3486 json_packet.Dump(json_string, false);
3487
3488 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3489 StringExtractorGDBRemote response;
3490 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3491 GDBRemoteCommunication::PacketResult::Success) {
3492 if (response.IsNormalResponse()) {
3493 size_t filled_size = response.GetHexBytesAvail(buffer);
3494 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3495 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003496 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003497 buffer = buffer.slice(buffer.size());
3498 }
3499 } else {
3500 LLDB_LOG(log, "failed to send packet");
3501 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3502 packet.GetData());
3503 buffer = buffer.slice(buffer.size());
3504 }
3505 return error;
3506}
3507
Kate Stoneb9c1b512016-09-06 20:57:50 +00003508bool GDBRemoteCommunicationClient::GetModuleInfo(
3509 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3510 ModuleSpec &module_spec) {
3511 if (!m_supports_qModuleInfo)
3512 return false;
3513
3514 std::string module_path = module_file_spec.GetPath(false);
3515 if (module_path.empty())
3516 return false;
3517
3518 StreamString packet;
3519 packet.PutCString("qModuleInfo:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003520 packet.PutStringAsRawHex8(module_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003521 packet.PutCString(";");
3522 const auto &triple = arch_spec.GetTriple().getTriple();
Pavel Labath7f815a92019-02-12 14:28:55 +00003523 packet.PutStringAsRawHex8(triple);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003524
3525 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003526 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3527 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003528 return false;
3529
3530 if (response.IsErrorResponse())
3531 return false;
3532
3533 if (response.IsUnsupportedResponse()) {
3534 m_supports_qModuleInfo = false;
3535 return false;
3536 }
3537
3538 llvm::StringRef name;
3539 llvm::StringRef value;
3540
3541 module_spec.Clear();
3542 module_spec.GetFileSpec() = module_file_spec;
3543
3544 while (response.GetNameColonValue(name, value)) {
3545 if (name == "uuid" || name == "md5") {
3546 StringExtractor extractor(value);
3547 std::string uuid;
3548 extractor.GetHexByteString(uuid);
Pavel Labatha174bcb2018-06-21 15:24:39 +00003549 module_spec.GetUUID().SetFromStringRef(uuid, uuid.size() / 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003550 } else if (name == "triple") {
3551 StringExtractor extractor(value);
3552 std::string triple;
3553 extractor.GetHexByteString(triple);
3554 module_spec.GetArchitecture().SetTriple(triple.c_str());
3555 } else if (name == "file_offset") {
3556 uint64_t ival = 0;
3557 if (!value.getAsInteger(16, ival))
3558 module_spec.SetObjectOffset(ival);
3559 } else if (name == "file_size") {
3560 uint64_t ival = 0;
3561 if (!value.getAsInteger(16, ival))
3562 module_spec.SetObjectSize(ival);
3563 } else if (name == "file_path") {
3564 StringExtractor extractor(value);
3565 std::string path;
3566 extractor.GetHexByteString(path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003567 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003568 }
3569 }
3570
3571 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003572}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003573
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003574static llvm::Optional<ModuleSpec>
3575ParseModuleSpec(StructuredData::Dictionary *dict) {
3576 ModuleSpec result;
3577 if (!dict)
3578 return llvm::None;
3579
Zachary Turner28333212017-05-12 05:49:54 +00003580 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003581 uint64_t integer;
3582
3583 if (!dict->GetValueForKeyAsString("uuid", string))
3584 return llvm::None;
Pavel Labath8c92c892017-12-18 14:31:44 +00003585 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3586 string.size())
3587 return llvm::None;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003588
3589 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3590 return llvm::None;
3591 result.SetObjectOffset(integer);
3592
3593 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3594 return llvm::None;
3595 result.SetObjectSize(integer);
3596
3597 if (!dict->GetValueForKeyAsString("triple", string))
3598 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003599 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003600
3601 if (!dict->GetValueForKeyAsString("file_path", string))
3602 return llvm::None;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003603 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003604
3605 return result;
3606}
3607
3608llvm::Optional<std::vector<ModuleSpec>>
3609GDBRemoteCommunicationClient::GetModulesInfo(
3610 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +00003611 namespace json = llvm::json;
3612
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003613 if (!m_supports_jModulesInfo)
3614 return llvm::None;
3615
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +00003616 json::Array module_array;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003617 for (const FileSpec &module_file_spec : module_file_specs) {
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +00003618 module_array.push_back(
3619 json::Object{{"file", module_file_spec.GetPath(false)},
3620 {"triple", triple.getTriple()}});
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003621 }
3622 StreamString unescaped_payload;
3623 unescaped_payload.PutCString("jModulesInfo:");
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +00003624 unescaped_payload.AsRawOstream() << std::move(module_array);
3625
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003626 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003627 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003628 unescaped_payload.GetSize());
3629
Greg Clayton70a9f512017-04-14 17:10:04 +00003630 // Increase the timeout for jModulesInfo since this packet can take longer.
3631 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3632
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003633 StringExtractorGDBRemote response;
3634 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3635 PacketResult::Success ||
3636 response.IsErrorResponse())
3637 return llvm::None;
3638
3639 if (response.IsUnsupportedResponse()) {
3640 m_supports_jModulesInfo = false;
3641 return llvm::None;
3642 }
3643
3644 StructuredData::ObjectSP response_object_sp =
3645 StructuredData::ParseJSON(response.GetStringRef());
3646 if (!response_object_sp)
3647 return llvm::None;
3648
3649 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3650 if (!response_array)
3651 return llvm::None;
3652
3653 std::vector<ModuleSpec> result;
3654 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3655 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3656 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3657 result.push_back(*module_spec);
3658 }
3659
3660 return result;
3661}
3662
Colin Rileyc3c95b22015-04-16 15:51:33 +00003663// query the target remote for extended information using the qXfer packet
3664//
Adrian Prantl05097242018-04-30 16:49:04 +00003665// example: object='features', annex='target.xml', out=<xml output> return:
3666// 'true' on success
Colin Rileyc3c95b22015-04-16 15:51:33 +00003667// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003668bool GDBRemoteCommunicationClient::ReadExtFeature(
3669 const lldb_private::ConstString object,
3670 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003671 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003672
Kate Stoneb9c1b512016-09-06 20:57:50 +00003673 std::stringstream output;
3674 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003675
Kate Stoneb9c1b512016-09-06 20:57:50 +00003676 uint64_t size = GetRemoteMaxPacketSize();
3677 if (size == 0)
3678 size = 0x1000;
3679 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3680 int offset = 0;
3681 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003682
Kate Stoneb9c1b512016-09-06 20:57:50 +00003683 // loop until all data has been read
3684 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003685
Kate Stoneb9c1b512016-09-06 20:57:50 +00003686 // send query extended feature packet
3687 std::stringstream packet;
3688 packet << "qXfer:" << object.AsCString("")
3689 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3690 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003691
Kate Stoneb9c1b512016-09-06 20:57:50 +00003692 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003693 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003694
Kate Stoneb9c1b512016-09-06 20:57:50 +00003695 if (res != GDBRemoteCommunication::PacketResult::Success) {
3696 err.SetErrorString("Error sending $qXfer packet");
3697 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003698 }
3699
Kate Stoneb9c1b512016-09-06 20:57:50 +00003700 const std::string &str = chunk.GetStringRef();
3701 if (str.length() == 0) {
3702 // should have some data in chunk
3703 err.SetErrorString("Empty response from $qXfer packet");
3704 return false;
3705 }
3706
3707 // check packet code
3708 switch (str[0]) {
3709 // last chunk
3710 case ('l'):
3711 active = false;
3712 LLVM_FALLTHROUGH;
3713
3714 // more chunks
3715 case ('m'):
3716 if (str.length() > 1)
3717 output << &str[1];
3718 offset += size;
3719 break;
3720
3721 // unknown chunk
3722 default:
3723 err.SetErrorString("Invalid continuation code from $qXfer packet");
3724 return false;
3725 }
3726 }
3727
3728 out = output.str();
3729 err.Success();
3730 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003731}
Greg Clayton0b90be12015-06-23 21:27:50 +00003732
3733// Notify the target that gdb is prepared to serve symbol lookup requests.
3734// packet: "qSymbol::"
3735// reply:
3736// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003737// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3738// encoded).
3739// LLDB may provide the value by sending another qSymbol
3740// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003741// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003742//
3743// Three examples:
3744//
3745// lldb sends: qSymbol::
3746// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003747// Remote gdb stub does not need to know the addresses of any symbols, lldb
3748// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003749// need to ask again in this session.
3750//
3751// lldb sends: qSymbol::
3752// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3753// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3754// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003755// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3756// not know
3757// the address at this time. lldb needs to send qSymbol:: again when it has
3758// more
Jason Molenda50018d32016-01-13 04:08:10 +00003759// solibs loaded.
3760//
3761// lldb sends: qSymbol::
3762// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3763// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3764// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003765// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3766// that it
3767// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3768// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003769// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003770
Kate Stoneb9c1b512016-09-06 20:57:50 +00003771void GDBRemoteCommunicationClient::ServeSymbolLookups(
3772 lldb_private::Process *process) {
Adrian Prantl05097242018-04-30 16:49:04 +00003773 // Set to true once we've resolved a symbol to an address for the remote
3774 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3775 // any more symbols and we can stop asking.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003776 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003777
Kate Stoneb9c1b512016-09-06 20:57:50 +00003778 // Is this the initial qSymbol:: packet?
3779 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003780
Jonas Devliegherea6682a42018-12-15 00:15:33 +00003781 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003782 Lock lock(*this, false);
3783 if (lock) {
3784 StreamString packet;
3785 packet.PutCString("qSymbol::");
3786 StringExtractorGDBRemote response;
3787 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3788 PacketResult::Success) {
3789 if (response.IsOKResponse()) {
3790 if (symbol_response_provided || first_qsymbol_query) {
3791 m_qSymbol_requests_done = true;
3792 }
3793
3794 // We are done serving symbols requests
3795 return;
3796 }
3797 first_qsymbol_query = false;
3798
3799 if (response.IsUnsupportedResponse()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003800 // qSymbol is not supported by the current GDB server we are
3801 // connected to
Kate Stoneb9c1b512016-09-06 20:57:50 +00003802 m_supports_qSymbol = false;
3803 return;
3804 } else {
3805 llvm::StringRef response_str(response.GetStringRef());
3806 if (response_str.startswith("qSymbol:")) {
3807 response.SetFilePos(strlen("qSymbol:"));
3808 std::string symbol_name;
3809 if (response.GetHexByteString(symbol_name)) {
3810 if (symbol_name.empty())
3811 return;
3812
3813 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3814 lldb_private::SymbolContextList sc_list;
3815 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3816 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3817 const size_t num_scs = sc_list.GetSize();
3818 for (size_t sc_idx = 0;
3819 sc_idx < num_scs &&
3820 symbol_load_addr == LLDB_INVALID_ADDRESS;
3821 ++sc_idx) {
3822 SymbolContext sc;
3823 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3824 if (sc.symbol) {
3825 switch (sc.symbol->GetType()) {
3826 case eSymbolTypeInvalid:
3827 case eSymbolTypeAbsolute:
3828 case eSymbolTypeUndefined:
3829 case eSymbolTypeSourceFile:
3830 case eSymbolTypeHeaderFile:
3831 case eSymbolTypeObjectFile:
3832 case eSymbolTypeCommonBlock:
3833 case eSymbolTypeBlock:
3834 case eSymbolTypeLocal:
3835 case eSymbolTypeParam:
3836 case eSymbolTypeVariable:
3837 case eSymbolTypeVariableType:
3838 case eSymbolTypeLineEntry:
3839 case eSymbolTypeLineHeader:
3840 case eSymbolTypeScopeBegin:
3841 case eSymbolTypeScopeEnd:
3842 case eSymbolTypeAdditional:
3843 case eSymbolTypeCompiler:
3844 case eSymbolTypeInstrumentation:
3845 case eSymbolTypeTrampoline:
3846 break;
3847
3848 case eSymbolTypeCode:
3849 case eSymbolTypeResolver:
3850 case eSymbolTypeData:
3851 case eSymbolTypeRuntime:
3852 case eSymbolTypeException:
3853 case eSymbolTypeObjCClass:
3854 case eSymbolTypeObjCMetaClass:
3855 case eSymbolTypeObjCIVar:
3856 case eSymbolTypeReExported:
3857 symbol_load_addr =
3858 sc.symbol->GetLoadAddress(&process->GetTarget());
3859 break;
3860 }
Jason Molenda50018d32016-01-13 04:08:10 +00003861 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003862 }
Greg Clayton42b01482015-08-11 22:07:46 +00003863 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003864 }
3865 // This is the normal path where our symbol lookup was successful
Adrian Prantl05097242018-04-30 16:49:04 +00003866 // and we want to send a packet with the new symbol value and see
3867 // if another lookup needs to be done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003868
Kate Stoneb9c1b512016-09-06 20:57:50 +00003869 // Change "packet" to contain the requested symbol value and name
3870 packet.Clear();
3871 packet.PutCString("qSymbol:");
3872 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3873 packet.Printf("%" PRIx64, symbol_load_addr);
3874 symbol_response_provided = true;
3875 } else {
3876 symbol_response_provided = false;
3877 }
3878 packet.PutCString(":");
3879 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3880 continue; // go back to the while loop and send "packet" and wait
3881 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003882 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003883 }
3884 }
3885 }
3886 // If we make it here, the symbol request packet response wasn't valid or
3887 // our symbol lookup failed so we must abort
3888 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003889
Kate Stoneb9c1b512016-09-06 20:57:50 +00003890 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3891 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003892 LLDB_LOGF(log,
3893 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3894 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003895 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003896 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003897}
3898
Kate Stoneb9c1b512016-09-06 20:57:50 +00003899StructuredData::Array *
3900GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3901 if (!m_supported_async_json_packets_is_valid) {
Adrian Prantl05097242018-04-30 16:49:04 +00003902 // Query the server for the array of supported asynchronous JSON packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003903 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003904
Kate Stoneb9c1b512016-09-06 20:57:50 +00003905 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003906
Kate Stoneb9c1b512016-09-06 20:57:50 +00003907 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003908 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003909 const bool send_async = false;
3910 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3911 send_async) == PacketResult::Success) {
3912 m_supported_async_json_packets_sp =
3913 StructuredData::ParseJSON(response.GetStringRef());
3914 if (m_supported_async_json_packets_sp &&
3915 !m_supported_async_json_packets_sp->GetAsArray()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003916 // We were returned something other than a JSON array. This is
3917 // invalid. Clear it out.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003918 LLDB_LOGF(log,
3919 "GDBRemoteCommunicationClient::%s(): "
3920 "QSupportedAsyncJSONPackets returned invalid "
3921 "result: %s",
Jonas Devlieghered35b42f2019-08-21 04:55:56 +00003922 __FUNCTION__, response.GetStringRef().data());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003923 m_supported_async_json_packets_sp.reset();
3924 }
3925 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003926 LLDB_LOGF(log,
3927 "GDBRemoteCommunicationClient::%s(): "
3928 "QSupportedAsyncJSONPackets unsupported",
3929 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003930 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003931
3932 if (log && m_supported_async_json_packets_sp) {
3933 StreamString stream;
3934 m_supported_async_json_packets_sp->Dump(stream);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003935 LLDB_LOGF(log,
3936 "GDBRemoteCommunicationClient::%s(): supported async "
3937 "JSON packets: %s",
3938 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003939 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003940 }
3941
3942 return m_supported_async_json_packets_sp
3943 ? m_supported_async_json_packets_sp->GetAsArray()
3944 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003945}
3946
Zachary Turner97206d52017-05-12 04:51:55 +00003947Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003948 llvm::ArrayRef<int32_t> signals) {
3949 // Format packet:
3950 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3951 auto range = llvm::make_range(signals.begin(), signals.end());
3952 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3953
3954 StringExtractorGDBRemote response;
3955 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3956
3957 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003958 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003959
3960 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003961 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003962 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003963 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003964 }
3965}
3966
Zachary Turner97206d52017-05-12 04:51:55 +00003967Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003968 ConstString type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003969 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970
3971 if (type_name.GetLength() == 0) {
3972 error.SetErrorString("invalid type_name argument");
3973 return error;
3974 }
3975
Adrian Prantl05097242018-04-30 16:49:04 +00003976 // Build command: Configure{type_name}: serialized config data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003977 StreamGDBRemote stream;
3978 stream.PutCString("QConfigure");
3979 stream.PutCString(type_name.AsCString());
3980 stream.PutChar(':');
3981 if (config_sp) {
3982 // Gather the plain-text version of the configuration data.
3983 StreamString unescaped_stream;
3984 config_sp->Dump(unescaped_stream);
3985 unescaped_stream.Flush();
3986
3987 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003988 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003989 unescaped_stream.GetSize());
3990 }
3991 stream.Flush();
3992
3993 // Send the packet.
3994 const bool send_async = false;
3995 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003996 auto result =
3997 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003998 if (result == PacketResult::Success) {
3999 // We failed if the config result comes back other than OK.
Jonas Devlieghered35b42f2019-08-21 04:55:56 +00004000 if (strcmp(response.GetStringRef().data(), "OK") == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004001 // Okay!
4002 error.Clear();
4003 } else {
4004 error.SetErrorStringWithFormat("configuring StructuredData feature "
4005 "%s failed with error %s",
4006 type_name.AsCString(),
Jonas Devlieghered35b42f2019-08-21 04:55:56 +00004007 response.GetStringRef().data());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004008 }
4009 } else {
4010 // Can we get more data here on the failure?
4011 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4012 "failed when sending packet: "
4013 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00004014 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004015 }
4016 return error;
4017}
4018
4019void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4020 GDBRemoteClientBase::OnRunPacketSent(first);
4021 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004022}