blob: 939cc2b9fa0eabc8f476688676ca7f1552459aea [file] [log] [blame]
Raphael Isemann80814282020-01-24 08:23:27 +01001//===-- GDBRemoteCommunicationClient.cpp ----------------------------------===//
Greg Clayton576d8832011-03-22 04:00:09 +00002//
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
Tatyana Krasnukhafaf6b252019-10-17 15:16:21 +0000342 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips,arc"};
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 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) {
Guilherme Andradeb1b70f62019-11-07 10:38:25 +0100546 if (m_supports_p == eLazyBoolCalculate)
547 m_supports_p = GetThreadPacketSupported(tid, "p0");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000549}
Greg Clayton576d8832011-03-22 04:00:09 +0000550
Guilherme Andradeb1b70f62019-11-07 10:38:25 +0100551LazyBool GDBRemoteCommunicationClient::GetThreadPacketSupported(
552 lldb::tid_t tid, llvm::StringRef packetStr) {
553 StreamString payload;
554 payload.PutCString(packetStr);
555 StringExtractorGDBRemote response;
556 if (SendThreadSpecificPacketAndWaitForResponse(
557 tid, std::move(payload), response, false) == PacketResult::Success &&
558 response.IsNormalResponse()) {
559 return eLazyBoolYes;
560 }
561 return eLazyBoolNo;
562}
563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
565 // Get information on all threads at one using the "jThreadsInfo" packet
566 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000567
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 if (m_supports_jThreadsInfo) {
569 StringExtractorGDBRemote response;
570 response.SetResponseValidatorToJSON();
571 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
572 PacketResult::Success) {
573 if (response.IsUnsupportedResponse()) {
574 m_supports_jThreadsInfo = false;
575 } else if (!response.Empty()) {
576 object_sp = StructuredData::ParseJSON(response.GetStringRef());
577 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 }
580 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000581}
582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
584 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
585 StringExtractorGDBRemote response;
586 m_supports_jThreadExtendedInfo = eLazyBoolNo;
587 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
588 PacketResult::Success) {
589 if (response.IsOKResponse()) {
590 m_supports_jThreadExtendedInfo = eLazyBoolYes;
591 }
Jason Molenda705b1802014-06-13 02:37:02 +0000592 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593 }
594 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000595}
596
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000597void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
598 if (m_supports_error_string_reply == eLazyBoolCalculate) {
599 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +0000600 // We try to enable error strings in remote packets but if we fail, we just
601 // work in the older way.
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000602 m_supports_error_string_reply = eLazyBoolNo;
603 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
604 PacketResult::Success) {
605 if (response.IsOKResponse()) {
606 m_supports_error_string_reply = eLazyBoolYes;
607 }
608 }
609 }
610}
611
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
613 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
614 StringExtractorGDBRemote response;
615 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
616 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
617 response,
618 false) == PacketResult::Success) {
619 if (response.IsOKResponse()) {
620 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
621 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000622 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 }
624 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000625}
626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
628 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
629 StringExtractorGDBRemote response;
630 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
631 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
632 PacketResult::Success) {
633 if (response.IsOKResponse()) {
634 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
635 }
Jason Molenda37397352016-07-22 00:17:55 +0000636 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 }
638 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000639}
640
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641bool GDBRemoteCommunicationClient::GetxPacketSupported() {
642 if (m_supports_x == eLazyBoolCalculate) {
643 StringExtractorGDBRemote response;
644 m_supports_x = eLazyBoolNo;
645 char packet[256];
646 snprintf(packet, sizeof(packet), "x0,0");
647 if (SendPacketAndWaitForResponse(packet, response, false) ==
648 PacketResult::Success) {
649 if (response.IsOKResponse())
650 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000651 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652 }
653 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000654}
655
Greg Clayton3dedae12013-12-06 21:45:27 +0000656GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
658 const char *payload_prefix, std::string &response_string) {
659 Lock lock(*this, false);
660 if (!lock) {
661 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
662 GDBR_LOG_PACKETS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000663 LLDB_LOGF(log,
664 "error: failed to get packet sequence mutex, not sending "
665 "packets with prefix '%s'",
666 payload_prefix);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000667 return PacketResult::ErrorNoSequenceLock;
668 }
669
670 response_string = "";
671 std::string payload_prefix_str(payload_prefix);
672 unsigned int response_size = 0x1000;
673 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
674 response_size = GetRemoteMaxPacketSize();
675 }
676
677 for (unsigned int offset = 0; true; offset += response_size) {
678 StringExtractorGDBRemote this_response;
679 // Construct payload
680 char sizeDescriptor[128];
681 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
682 response_size);
683 PacketResult result = SendPacketAndWaitForResponseNoLock(
684 payload_prefix_str + sizeDescriptor, this_response);
685 if (result != PacketResult::Success)
686 return result;
687
688 const std::string &this_string = this_response.GetStringRef();
689
690 // Check for m or l as first character; l seems to mean this is the last
691 // chunk
692 char first_char = *this_string.c_str();
693 if (first_char != 'm' && first_char != 'l') {
694 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 // Concatenate the result so far (skipping 'm' or 'l')
697 response_string.append(this_string, 1, std::string::npos);
698 if (first_char == 'l')
699 // We're done
700 return PacketResult::Success;
701 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000702}
703
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
705 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
706 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000707
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 // First try to retrieve the pid via the qProcessInfo request.
709 GetCurrentProcessInfo(allow_lazy);
710 if (m_curr_pid_is_valid == eLazyBoolYes) {
711 // We really got it.
712 return m_curr_pid;
713 } else {
714 // If we don't get a response for qProcessInfo, check if $qC gives us a
Adrian Prantl05097242018-04-30 16:49:04 +0000715 // result. $qC only returns a real process id on older debugserver and
716 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
717 // the thread id, which newer debugserver and lldb-gdbserver stubs return
718 // correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000719 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000720 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 PacketResult::Success) {
722 if (response.GetChar() == 'Q') {
723 if (response.GetChar() == 'C') {
724 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
725 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
726 m_curr_pid_is_valid = eLazyBoolYes;
727 return m_curr_pid;
728 }
Greg Clayton576d8832011-03-22 04:00:09 +0000729 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 }
Greg Clayton576d8832011-03-22 04:00:09 +0000731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732
733 // If we don't get a response for $qC, check if $qfThreadID gives us a
734 // result.
735 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
736 std::vector<lldb::tid_t> thread_ids;
737 bool sequence_mutex_unavailable;
738 size_t size;
739 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000740 if (size && !sequence_mutex_unavailable) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 m_curr_pid = thread_ids.front();
742 m_curr_pid_is_valid = eLazyBoolYes;
743 return m_curr_pid;
744 }
Greg Clayton576d8832011-03-22 04:00:09 +0000745 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 }
747
748 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000749}
750
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
752 error_str.clear();
753 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000754 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
755 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 if (response.IsOKResponse())
757 return true;
758 if (response.GetChar() == 'E') {
759 // A string the describes what failed when launching...
760 error_str = response.GetStringRef().substr(1);
761 } else {
762 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000763 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 } else {
765 error_str.assign("timed out waiting for app to launch");
766 }
767 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000768}
769
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770int GDBRemoteCommunicationClient::SendArgumentsPacket(
771 const ProcessLaunchInfo &launch_info) {
772 // Since we don't get the send argv0 separate from the executable path, we
Adrian Prantl05097242018-04-30 16:49:04 +0000773 // need to make sure to use the actual executable path found in the
774 // launch_info...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 std::vector<const char *> argv;
776 FileSpec exe_file = launch_info.GetExecutableFile();
777 std::string exe_path;
Konrad Kleine248a1302019-05-23 11:14:47 +0000778 const char *arg = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 const Args &launch_args = launch_info.GetArguments();
780 if (exe_file)
781 exe_path = exe_file.GetPath(false);
782 else {
783 arg = launch_args.GetArgumentAtIndex(0);
784 if (arg)
785 exe_path = arg;
786 }
787 if (!exe_path.empty()) {
788 argv.push_back(exe_path.c_str());
Konrad Kleine248a1302019-05-23 11:14:47 +0000789 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 ++i) {
791 if (arg)
792 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000793 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 }
795 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000796 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 packet.PutChar('A');
798 for (size_t i = 0, n = argv.size(); i < n; ++i) {
799 arg = argv[i];
800 const int arg_len = strlen(arg);
801 if (i > 0)
802 packet.PutChar(',');
803 packet.Printf("%i,%i,", arg_len * 2, (int)i);
804 packet.PutBytesAsRawHex8(arg, arg_len);
805 }
806
Vince Harrone0be4252015-02-06 18:32:57 +0000807 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000808 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
809 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000811 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 uint8_t error = response.GetError();
813 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000814 return error;
815 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 }
817 return -1;
818}
Johnny Chen64637202012-05-23 21:09:52 +0000819
Pavel Labath62930e52018-01-10 11:57:31 +0000820int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
821 for (const auto &KV : env) {
822 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
823 if (r != 0)
824 return r;
825 }
826 return 0;
827}
828
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829int GDBRemoteCommunicationClient::SendEnvironmentPacket(
830 char const *name_equal_value) {
831 if (name_equal_value && name_equal_value[0]) {
832 StreamString packet;
833 bool send_hex_encoding = false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000834 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
835 ++p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836 if (isprint(*p)) {
837 switch (*p) {
838 case '$':
839 case '#':
840 case '*':
841 case '}':
842 send_hex_encoding = true;
843 break;
844 default:
845 break;
Johnny Chen64637202012-05-23 21:09:52 +0000846 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 } else {
848 // We have non printable characters, lets hex encode this...
849 send_hex_encoding = true;
850 }
Johnny Chen64637202012-05-23 21:09:52 +0000851 }
852
Greg Claytonfbb76342013-11-20 21:07:01 +0000853 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 if (send_hex_encoding) {
855 if (m_supports_QEnvironmentHexEncoded) {
856 packet.PutCString("QEnvironmentHexEncoded:");
857 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000858 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
859 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 if (response.IsOKResponse())
861 return 0;
862 uint8_t error = response.GetError();
863 if (error)
864 return error;
865 if (response.IsUnsupportedResponse())
866 m_supports_QEnvironmentHexEncoded = false;
867 }
868 }
869
870 } else if (m_supports_QEnvironment) {
871 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000872 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
873 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874 if (response.IsOKResponse())
875 return 0;
876 uint8_t error = response.GetError();
877 if (error)
878 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000879 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 m_supports_QEnvironment = false;
881 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000882 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 }
884 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000885}
886
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
888 if (arch && arch[0]) {
889 StreamString packet;
890 packet.Printf("QLaunchArch:%s", arch);
891 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000892 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
893 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 if (response.IsOKResponse())
895 return 0;
896 uint8_t error = response.GetError();
897 if (error)
898 return error;
899 }
900 }
901 return -1;
902}
Chaoren Lind3173f32015-05-29 19:52:29 +0000903
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
905 char const *data, bool *was_supported) {
906 if (data && *data != '\0') {
907 StreamString packet;
908 packet.Printf("QSetProcessEvent:%s", data);
909 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000910 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
911 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 if (response.IsOKResponse()) {
913 if (was_supported)
914 *was_supported = true;
915 return 0;
916 } else if (response.IsUnsupportedResponse()) {
917 if (was_supported)
918 *was_supported = false;
919 return -1;
920 } else {
921 uint8_t error = response.GetError();
922 if (was_supported)
923 *was_supported = true;
924 if (error)
925 return error;
926 }
927 }
928 }
929 return -1;
930}
931
Pavel Labath2272c482018-06-18 15:02:23 +0000932llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() {
933 GetHostInfo();
934 return m_os_version;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935}
936
Adrian Prantl24610612019-09-04 17:23:15 +0000937llvm::VersionTuple GDBRemoteCommunicationClient::GetMacCatalystVersion() {
938 GetHostInfo();
939 return m_maccatalyst_version;
940}
941
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
943 if (GetHostInfo()) {
944 if (!m_os_build.empty()) {
945 s = m_os_build;
946 return true;
947 }
948 }
949 s.clear();
950 return false;
951}
952
953bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
954 if (GetHostInfo()) {
955 if (!m_os_kernel.empty()) {
956 s = m_os_kernel;
957 return true;
958 }
959 }
960 s.clear();
961 return false;
962}
963
964bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
965 if (GetHostInfo()) {
966 if (!m_hostname.empty()) {
967 s = m_hostname;
968 return true;
969 }
970 }
971 s.clear();
972 return false;
973}
974
975ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
976 if (GetHostInfo())
977 return m_host_arch;
978 return ArchSpec();
979}
980
981const lldb_private::ArchSpec &
982GDBRemoteCommunicationClient::GetProcessArchitecture() {
983 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
984 GetCurrentProcessInfo();
985 return m_process_arch;
986}
987
988bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
989 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
990 m_gdb_server_name.clear();
991 m_gdb_server_version = 0;
992 m_qGDBServerVersion_is_valid = eLazyBoolNo;
993
994 StringExtractorGDBRemote response;
995 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
996 PacketResult::Success) {
997 if (response.IsNormalResponse()) {
998 llvm::StringRef name, value;
999 bool success = false;
1000 while (response.GetNameColonValue(name, value)) {
1001 if (name.equals("name")) {
1002 success = true;
1003 m_gdb_server_name = value;
1004 } else if (name.equals("version")) {
1005 llvm::StringRef major, minor;
1006 std::tie(major, minor) = value.split('.');
1007 if (!major.getAsInteger(0, m_gdb_server_version))
1008 success = true;
1009 }
Greg Clayton576d8832011-03-22 04:00:09 +00001010 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 if (success)
1012 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1013 }
Greg Clayton576d8832011-03-22 04:00:09 +00001014 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 }
1016 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001017}
1018
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019void GDBRemoteCommunicationClient::MaybeEnableCompression(
1020 std::vector<std::string> supported_compressions) {
1021 CompressionType avail_type = CompressionType::None;
1022 std::string avail_name;
1023
1024#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001025 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026 for (auto compression : supported_compressions) {
1027 if (compression == "lzfse") {
1028 avail_type = CompressionType::LZFSE;
1029 avail_name = compression;
1030 break;
1031 }
1032 }
1033 }
1034#endif
1035
1036#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001037 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 for (auto compression : supported_compressions) {
1039 if (compression == "zlib-deflate") {
1040 avail_type = CompressionType::ZlibDeflate;
1041 avail_name = compression;
1042 break;
1043 }
1044 }
1045 }
1046#endif
1047
Saleem Abdulrasoolabb00752020-01-01 15:01:04 -08001048#if LLVM_ENABLE_ZLIB
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 if (avail_type == CompressionType::None) {
1050 for (auto compression : supported_compressions) {
1051 if (compression == "zlib-deflate") {
1052 avail_type = CompressionType::ZlibDeflate;
1053 avail_name = compression;
1054 break;
1055 }
1056 }
1057 }
1058#endif
1059
1060#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001061 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 for (auto compression : supported_compressions) {
1063 if (compression == "lz4") {
1064 avail_type = CompressionType::LZ4;
1065 avail_name = compression;
1066 break;
1067 }
1068 }
1069 }
1070#endif
1071
1072#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001073 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 for (auto compression : supported_compressions) {
1075 if (compression == "lzma") {
1076 avail_type = CompressionType::LZMA;
1077 avail_name = compression;
1078 break;
1079 }
1080 }
1081 }
1082#endif
1083
1084 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001085 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001087 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 PacketResult::Success)
1089 return;
1090
1091 if (response.IsOKResponse()) {
1092 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001093 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094 }
Greg Clayton576d8832011-03-22 04:00:09 +00001095}
Greg Clayton32e0a752011-03-30 18:16:51 +00001096
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1098 if (GetGDBServerVersion()) {
1099 if (!m_gdb_server_name.empty())
1100 return m_gdb_server_name.c_str();
1101 }
Konrad Kleine248a1302019-05-23 11:14:47 +00001102 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103}
1104
1105uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1106 if (GetGDBServerVersion())
1107 return m_gdb_server_version;
1108 return 0;
1109}
1110
1111bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1112 StringExtractorGDBRemote response;
1113 if (SendPacketAndWaitForResponse("qC", response, false) !=
1114 PacketResult::Success)
1115 return false;
1116
1117 if (!response.IsNormalResponse())
1118 return false;
1119
1120 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1121 tid = response.GetHexMaxU32(true, -1);
1122
1123 return true;
1124}
1125
1126bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1127 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1128
1129 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
Pavel Labathe7ec0832018-08-31 05:34:03 +00001130 // host info computation can require DNS traffic and shelling out to external processes.
1131 // Increase the timeout to account for that.
1132 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001134 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1136 PacketResult::Success) {
1137 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001138 llvm::StringRef name;
1139 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001140 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1141 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001142 std::string arch_name;
1143 std::string os_name;
Adrian Prantl24610612019-09-04 17:23:15 +00001144 std::string environment;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145 std::string vendor_name;
1146 std::string triple;
1147 std::string distribution_id;
1148 uint32_t pointer_byte_size = 0;
1149 ByteOrder byte_order = eByteOrderInvalid;
1150 uint32_t num_keys_decoded = 0;
1151 while (response.GetNameColonValue(name, value)) {
1152 if (name.equals("cputype")) {
1153 // exception type in big endian hex
1154 if (!value.getAsInteger(0, cpu))
1155 ++num_keys_decoded;
1156 } else if (name.equals("cpusubtype")) {
1157 // exception count in big endian hex
1158 if (!value.getAsInteger(0, sub))
1159 ++num_keys_decoded;
1160 } else if (name.equals("arch")) {
1161 arch_name = value;
1162 ++num_keys_decoded;
1163 } else if (name.equals("triple")) {
1164 StringExtractor extractor(value);
1165 extractor.GetHexByteString(triple);
1166 ++num_keys_decoded;
1167 } else if (name.equals("distribution_id")) {
1168 StringExtractor extractor(value);
1169 extractor.GetHexByteString(distribution_id);
1170 ++num_keys_decoded;
1171 } else if (name.equals("os_build")) {
1172 StringExtractor extractor(value);
1173 extractor.GetHexByteString(m_os_build);
1174 ++num_keys_decoded;
1175 } else if (name.equals("hostname")) {
1176 StringExtractor extractor(value);
1177 extractor.GetHexByteString(m_hostname);
1178 ++num_keys_decoded;
1179 } else if (name.equals("os_kernel")) {
1180 StringExtractor extractor(value);
1181 extractor.GetHexByteString(m_os_kernel);
1182 ++num_keys_decoded;
1183 } else if (name.equals("ostype")) {
Adrian Prantl24610612019-09-04 17:23:15 +00001184 if (value.equals("maccatalyst")) {
1185 os_name = "ios";
1186 environment = "macabi";
1187 } else
1188 os_name = value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001189 ++num_keys_decoded;
1190 } else if (name.equals("vendor")) {
1191 vendor_name = value;
1192 ++num_keys_decoded;
1193 } else if (name.equals("endian")) {
1194 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1195 .Case("little", eByteOrderLittle)
1196 .Case("big", eByteOrderBig)
1197 .Case("pdp", eByteOrderPDP)
1198 .Default(eByteOrderInvalid);
1199 if (byte_order != eByteOrderInvalid)
1200 ++num_keys_decoded;
1201 } else if (name.equals("ptrsize")) {
1202 if (!value.getAsInteger(0, pointer_byte_size))
1203 ++num_keys_decoded;
1204 } else if (name.equals("os_version") ||
1205 name.equals(
1206 "version")) // Older debugserver binaries used the
1207 // "version" key instead of
1208 // "os_version"...
1209 {
Pavel Labath2272c482018-06-18 15:02:23 +00001210 if (!m_os_version.tryParse(value))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 ++num_keys_decoded;
Adrian Prantl24610612019-09-04 17:23:15 +00001212 } else if (name.equals("maccatalyst_version")) {
1213 if (!m_maccatalyst_version.tryParse(value))
1214 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 } else if (name.equals("watchpoint_exceptions_received")) {
1216 m_watchpoints_trigger_after_instruction =
1217 llvm::StringSwitch<LazyBool>(value)
1218 .Case("before", eLazyBoolNo)
1219 .Case("after", eLazyBoolYes)
1220 .Default(eLazyBoolCalculate);
1221 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1222 ++num_keys_decoded;
1223 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001224 uint32_t timeout_seconds;
1225 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001226 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227 SetPacketTimeout(m_default_packet_timeout);
1228 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001229 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 }
Jason Molenda89c37492014-01-27 22:23:20 +00001231 }
1232
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 if (num_keys_decoded > 0)
1234 m_qHostInfo_is_valid = eLazyBoolYes;
1235
1236 if (triple.empty()) {
1237 if (arch_name.empty()) {
1238 if (cpu != LLDB_INVALID_CPUTYPE) {
1239 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1240 if (pointer_byte_size) {
1241 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1242 }
1243 if (byte_order != eByteOrderInvalid) {
1244 assert(byte_order == m_host_arch.GetByteOrder());
1245 }
1246
1247 if (!vendor_name.empty())
1248 m_host_arch.GetTriple().setVendorName(
1249 llvm::StringRef(vendor_name));
1250 if (!os_name.empty())
1251 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Adrian Prantl24610612019-09-04 17:23:15 +00001252 if (!environment.empty())
1253 m_host_arch.GetTriple().setEnvironmentName(environment);
Jason Molenda89c37492014-01-27 22:23:20 +00001254 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001256 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 triple += arch_name;
1258 if (!vendor_name.empty() || !os_name.empty()) {
1259 triple += '-';
1260 if (vendor_name.empty())
1261 triple += "unknown";
1262 else
1263 triple += vendor_name;
1264 triple += '-';
1265 if (os_name.empty())
1266 triple += "unknown";
1267 else
1268 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001269 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001271
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 llvm::Triple &host_triple = m_host_arch.GetTriple();
1273 if (host_triple.getVendor() == llvm::Triple::Apple &&
1274 host_triple.getOS() == llvm::Triple::Darwin) {
1275 switch (m_host_arch.GetMachine()) {
1276 case llvm::Triple::aarch64:
Jason Molenda7dd7a362019-10-16 19:14:49 +00001277 case llvm::Triple::aarch64_32:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 case llvm::Triple::arm:
1279 case llvm::Triple::thumb:
1280 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001281 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 default:
1283 host_triple.setOS(llvm::Triple::MacOSX);
1284 break;
1285 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001286 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 if (pointer_byte_size) {
1288 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1289 }
1290 if (byte_order != eByteOrderInvalid) {
1291 assert(byte_order == m_host_arch.GetByteOrder());
1292 }
1293 }
1294 } else {
1295 m_host_arch.SetTriple(triple.c_str());
1296 if (pointer_byte_size) {
1297 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1298 }
1299 if (byte_order != eByteOrderInvalid) {
1300 assert(byte_order == m_host_arch.GetByteOrder());
1301 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001302
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001303 LLDB_LOGF(log,
1304 "GDBRemoteCommunicationClient::%s parsed host "
1305 "architecture as %s, triple as %s from triple text %s",
1306 __FUNCTION__,
1307 m_host_arch.GetArchitectureName()
1308 ? m_host_arch.GetArchitectureName()
1309 : "<null-arch-name>",
1310 m_host_arch.GetTriple().getTriple().c_str(),
1311 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001312 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 if (!distribution_id.empty())
1314 m_host_arch.SetDistributionId(distribution_id.c_str());
1315 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001316 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 }
1318 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001319}
Greg Clayton37a0a242012-04-11 00:24:49 +00001320
Kate Stoneb9c1b512016-09-06 20:57:50 +00001321int GDBRemoteCommunicationClient::SendAttach(
1322 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1323 if (pid != LLDB_INVALID_PROCESS_ID) {
1324 char packet[64];
1325 const int packet_len =
1326 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001327 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001329 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 PacketResult::Success) {
1331 if (response.IsErrorResponse())
1332 return response.GetError();
1333 return 0;
1334 }
1335 }
1336 return -1;
1337}
1338
1339int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1340 size_t data_len) {
1341 StreamString packet;
1342 packet.PutCString("I");
1343 packet.PutBytesAsRawHex8(data, data_len);
1344 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001345 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1346 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001347 return 0;
1348 }
1349 return response.GetError();
1350}
1351
1352const lldb_private::ArchSpec &
1353GDBRemoteCommunicationClient::GetHostArchitecture() {
1354 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1355 GetHostInfo();
1356 return m_host_arch;
1357}
1358
Pavel Labath1eff73c2016-11-24 10:54:49 +00001359seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001360 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1361 GetHostInfo();
1362 return m_default_packet_timeout;
1363}
1364
1365addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1366 uint32_t permissions) {
1367 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1368 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1369 char packet[64];
1370 const int packet_len = ::snprintf(
1371 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1372 permissions & lldb::ePermissionsReadable ? "r" : "",
1373 permissions & lldb::ePermissionsWritable ? "w" : "",
1374 permissions & lldb::ePermissionsExecutable ? "x" : "");
1375 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001376 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001377 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001378 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379 PacketResult::Success) {
1380 if (response.IsUnsupportedResponse())
1381 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1382 else if (!response.IsErrorResponse())
1383 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1384 } else {
1385 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1386 }
1387 }
1388 return LLDB_INVALID_ADDRESS;
1389}
1390
1391bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1392 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1393 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1394 char packet[64];
1395 const int packet_len =
1396 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1397 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001398 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001400 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001401 PacketResult::Success) {
1402 if (response.IsUnsupportedResponse())
1403 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1404 else if (response.IsOKResponse())
1405 return true;
1406 } else {
1407 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1408 }
1409 }
1410 return false;
1411}
1412
Zachary Turner97206d52017-05-12 04:51:55 +00001413Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1414 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001415
1416 if (keep_stopped) {
1417 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1418 char packet[64];
1419 const int packet_len =
1420 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1421 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001422 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001423 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001424 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 PacketResult::Success &&
1426 response.IsOKResponse()) {
1427 m_supports_detach_stay_stopped = eLazyBoolYes;
1428 } else {
1429 m_supports_detach_stay_stopped = eLazyBoolNo;
1430 }
1431 }
1432
1433 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1434 error.SetErrorString("Stays stopped not supported by this target.");
1435 return error;
1436 } else {
1437 StringExtractorGDBRemote response;
1438 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001439 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 if (packet_result != PacketResult::Success)
1441 error.SetErrorString("Sending extended disconnect packet failed.");
1442 }
1443 } else {
1444 StringExtractorGDBRemote response;
1445 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001446 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447 if (packet_result != PacketResult::Success)
1448 error.SetErrorString("Sending disconnect packet failed.");
1449 }
1450 return error;
1451}
1452
Zachary Turner97206d52017-05-12 04:51:55 +00001453Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001455 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001456 region_info.Clear();
1457
1458 if (m_supports_memory_region_info != eLazyBoolNo) {
1459 m_supports_memory_region_info = eLazyBoolYes;
1460 char packet[64];
1461 const int packet_len = ::snprintf(
1462 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1463 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001464 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001466 if (SendPacketAndWaitForResponse(packet, response, false) ==
Pavel Labath16064d32018-03-20 11:56:24 +00001467 PacketResult::Success &&
1468 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469 llvm::StringRef name;
1470 llvm::StringRef value;
1471 addr_t addr_value = LLDB_INVALID_ADDRESS;
1472 bool success = true;
1473 bool saw_permissions = false;
1474 while (success && response.GetNameColonValue(name, value)) {
1475 if (name.equals("start")) {
1476 if (!value.getAsInteger(16, addr_value))
1477 region_info.GetRange().SetRangeBase(addr_value);
1478 } else if (name.equals("size")) {
1479 if (!value.getAsInteger(16, addr_value))
1480 region_info.GetRange().SetByteSize(addr_value);
1481 } else if (name.equals("permissions") &&
1482 region_info.GetRange().IsValid()) {
1483 saw_permissions = true;
1484 if (region_info.GetRange().Contains(addr)) {
1485 if (value.find('r') != llvm::StringRef::npos)
1486 region_info.SetReadable(MemoryRegionInfo::eYes);
1487 else
1488 region_info.SetReadable(MemoryRegionInfo::eNo);
1489
1490 if (value.find('w') != llvm::StringRef::npos)
1491 region_info.SetWritable(MemoryRegionInfo::eYes);
1492 else
1493 region_info.SetWritable(MemoryRegionInfo::eNo);
1494
1495 if (value.find('x') != llvm::StringRef::npos)
1496 region_info.SetExecutable(MemoryRegionInfo::eYes);
1497 else
1498 region_info.SetExecutable(MemoryRegionInfo::eNo);
1499
1500 region_info.SetMapped(MemoryRegionInfo::eYes);
1501 } else {
1502 // The reported region does not contain this address -- we're
1503 // looking at an unmapped page
1504 region_info.SetReadable(MemoryRegionInfo::eNo);
1505 region_info.SetWritable(MemoryRegionInfo::eNo);
1506 region_info.SetExecutable(MemoryRegionInfo::eNo);
1507 region_info.SetMapped(MemoryRegionInfo::eNo);
1508 }
1509 } else if (name.equals("name")) {
1510 StringExtractorGDBRemote name_extractor(value);
1511 std::string name;
1512 name_extractor.GetHexByteString(name);
1513 region_info.SetName(name.c_str());
1514 } else if (name.equals("error")) {
1515 StringExtractorGDBRemote error_extractor(value);
1516 std::string error_string;
1517 // Now convert the HEX bytes into a string value
1518 error_extractor.GetHexByteString(error_string);
1519 error.SetErrorString(error_string.c_str());
1520 }
1521 }
1522
Stephane Sezer48d14272017-03-31 18:00:48 +00001523 if (region_info.GetRange().IsValid()) {
1524 // We got a valid address range back but no permissions -- which means
1525 // this is an unmapped page
1526 if (!saw_permissions) {
1527 region_info.SetReadable(MemoryRegionInfo::eNo);
1528 region_info.SetWritable(MemoryRegionInfo::eNo);
1529 region_info.SetExecutable(MemoryRegionInfo::eNo);
1530 region_info.SetMapped(MemoryRegionInfo::eNo);
1531 }
1532 } else {
1533 // We got an invalid address range back
1534 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001535 }
1536 } else {
1537 m_supports_memory_region_info = eLazyBoolNo;
1538 }
1539 }
1540
1541 if (m_supports_memory_region_info == eLazyBoolNo) {
1542 error.SetErrorString("qMemoryRegionInfo is not supported");
1543 }
Pavel Labath16064d32018-03-20 11:56:24 +00001544
1545 // Try qXfer:memory-map:read to get region information not included in
1546 // qMemoryRegionInfo
1547 MemoryRegionInfo qXfer_region_info;
1548 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1549
1550 if (error.Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001551 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1552 // the qXfer result as a fallback
Pavel Labath16064d32018-03-20 11:56:24 +00001553 if (qXfer_error.Success()) {
1554 region_info = qXfer_region_info;
1555 error.Clear();
1556 } else {
1557 region_info.Clear();
1558 }
1559 } else if (qXfer_error.Success()) {
1560 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
Adrian Prantl05097242018-04-30 16:49:04 +00001561 // both regions are the same range, update the result to include the flash-
1562 // memory information that is specific to the qXfer result.
Pavel Labath16064d32018-03-20 11:56:24 +00001563 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1564 region_info.SetFlash(qXfer_region_info.GetFlash());
1565 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1566 }
1567 }
1568 return error;
1569}
1570
1571Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1572 lldb::addr_t addr, MemoryRegionInfo &region) {
1573 Status error = LoadQXferMemoryMap();
1574 if (!error.Success())
1575 return error;
1576 for (const auto &map_region : m_qXfer_memory_map) {
1577 if (map_region.GetRange().Contains(addr)) {
1578 region = map_region;
1579 return error;
1580 }
1581 }
1582 error.SetErrorString("Region not found");
1583 return error;
1584}
1585
1586Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1587
1588 Status error;
1589
1590 if (m_qXfer_memory_map_loaded)
1591 // Already loaded, return success
1592 return error;
1593
1594 if (!XMLDocument::XMLEnabled()) {
1595 error.SetErrorString("XML is not supported");
1596 return error;
1597 }
1598
1599 if (!GetQXferMemoryMapReadSupported()) {
1600 error.SetErrorString("Memory map is not supported");
1601 return error;
1602 }
1603
1604 std::string xml;
1605 lldb_private::Status lldberr;
1606 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1607 lldberr)) {
1608 error.SetErrorString("Failed to read memory map");
1609 return error;
1610 }
1611
1612 XMLDocument xml_document;
1613
1614 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1615 error.SetErrorString("Failed to parse memory map xml");
1616 return error;
1617 }
1618
1619 XMLNode map_node = xml_document.GetRootElement("memory-map");
1620 if (!map_node) {
1621 error.SetErrorString("Invalid root node in memory map xml");
1622 return error;
1623 }
1624
1625 m_qXfer_memory_map.clear();
1626
1627 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1628 if (!memory_node.IsElement())
1629 return true;
1630 if (memory_node.GetName() != "memory")
1631 return true;
1632 auto type = memory_node.GetAttributeValue("type", "");
1633 uint64_t start;
1634 uint64_t length;
1635 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1636 return true;
1637 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1638 return true;
1639 MemoryRegionInfo region;
1640 region.GetRange().SetRangeBase(start);
1641 region.GetRange().SetByteSize(length);
1642 if (type == "rom") {
1643 region.SetReadable(MemoryRegionInfo::eYes);
1644 this->m_qXfer_memory_map.push_back(region);
1645 } else if (type == "ram") {
1646 region.SetReadable(MemoryRegionInfo::eYes);
1647 region.SetWritable(MemoryRegionInfo::eYes);
1648 this->m_qXfer_memory_map.push_back(region);
1649 } else if (type == "flash") {
1650 region.SetFlash(MemoryRegionInfo::eYes);
1651 memory_node.ForEachChildElement(
1652 [&region](const XMLNode &prop_node) -> bool {
1653 if (!prop_node.IsElement())
1654 return true;
1655 if (prop_node.GetName() != "property")
1656 return true;
1657 auto propname = prop_node.GetAttributeValue("name", "");
1658 if (propname == "blocksize") {
1659 uint64_t blocksize;
1660 if (prop_node.GetElementTextAsUnsigned(blocksize))
1661 region.SetBlocksize(blocksize);
1662 }
1663 return true;
1664 });
1665 this->m_qXfer_memory_map.push_back(region);
1666 }
1667 return true;
1668 });
1669
1670 m_qXfer_memory_map_loaded = true;
1671
Kate Stoneb9c1b512016-09-06 20:57:50 +00001672 return error;
1673}
1674
Zachary Turner97206d52017-05-12 04:51:55 +00001675Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1676 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677
1678 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1679 num = m_num_supported_hardware_watchpoints;
1680 return error;
1681 }
1682
1683 // Set num to 0 first.
1684 num = 0;
1685 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1686 char packet[64];
1687 const int packet_len =
1688 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1689 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001690 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001692 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001693 PacketResult::Success) {
1694 m_supports_watchpoint_support_info = eLazyBoolYes;
1695 llvm::StringRef name;
1696 llvm::StringRef value;
Jason Molendac0e793d2018-11-09 22:33:26 +00001697 bool found_num_field = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001698 while (response.GetNameColonValue(name, value)) {
1699 if (name.equals("num")) {
1700 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1701 num = m_num_supported_hardware_watchpoints;
Jason Molendac0e793d2018-11-09 22:33:26 +00001702 found_num_field = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 }
1704 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001705 if (!found_num_field) {
Jason Molendac0e793d2018-11-09 22:33:26 +00001706 m_supports_watchpoint_support_info = eLazyBoolNo;
1707 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001708 } else {
1709 m_supports_watchpoint_support_info = eLazyBoolNo;
1710 }
1711 }
1712
1713 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1714 error.SetErrorString("qWatchpointSupportInfo is not supported");
1715 }
1716 return error;
1717}
1718
Zachary Turner97206d52017-05-12 04:51:55 +00001719lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001721 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722 if (error.Success())
1723 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1724 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001725}
1726
Zachary Turner97206d52017-05-12 04:51:55 +00001727lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1729 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001730 Status error;
Fangrui Song2f677ab2019-05-16 09:07:33 +00001731 llvm::Triple triple = arch.GetTriple();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001732
Adrian Prantl05097242018-04-30 16:49:04 +00001733 // we assume watchpoints will happen after running the relevant opcode and we
1734 // only want to override this behavior if we have explicitly received a
1735 // qHostInfo telling us otherwise
Kate Stoneb9c1b512016-09-06 20:57:50 +00001736 if (m_qHostInfo_is_valid != eLazyBoolYes) {
Fangrui Song2f677ab2019-05-16 09:07:33 +00001737 // On targets like MIPS and ppc64, watchpoint exceptions are always
Adrian Prantl05097242018-04-30 16:49:04 +00001738 // generated before the instruction is executed. The connected target may
1739 // not support qHostInfo or qWatchpointSupportInfo packets.
Fangrui Song2f677ab2019-05-16 09:07:33 +00001740 after = !(triple.isMIPS() || triple.isPPC64());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001741 } else {
Fangrui Song2f677ab2019-05-16 09:07:33 +00001742 // For MIPS and ppc64, set m_watchpoints_trigger_after_instruction to
Pavel Labathc51ad482017-10-27 17:02:32 +00001743 // eLazyBoolNo if it is not calculated before.
Fangrui Songddb93b62019-05-16 08:37:32 +00001744 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
Fangrui Song2f677ab2019-05-16 09:07:33 +00001745 (triple.isMIPS() || triple.isPPC64()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1747
1748 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1749 }
1750 return error;
1751}
1752
1753int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1754 if (file_spec) {
1755 std::string path{file_spec.GetPath(false)};
1756 StreamString packet;
1757 packet.PutCString("QSetSTDIN:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001758 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759
1760 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001761 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1762 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001763 if (response.IsOKResponse())
1764 return 0;
1765 uint8_t error = response.GetError();
1766 if (error)
1767 return error;
1768 }
1769 }
1770 return -1;
1771}
1772
1773int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1774 if (file_spec) {
1775 std::string path{file_spec.GetPath(false)};
1776 StreamString packet;
1777 packet.PutCString("QSetSTDOUT:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001778 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779
1780 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001781 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1782 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001783 if (response.IsOKResponse())
1784 return 0;
1785 uint8_t error = response.GetError();
1786 if (error)
1787 return error;
1788 }
1789 }
1790 return -1;
1791}
1792
1793int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1794 if (file_spec) {
1795 std::string path{file_spec.GetPath(false)};
1796 StreamString packet;
1797 packet.PutCString("QSetSTDERR:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001798 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799
1800 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001801 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1802 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001803 if (response.IsOKResponse())
1804 return 0;
1805 uint8_t error = response.GetError();
1806 if (error)
1807 return error;
1808 }
1809 }
1810 return -1;
1811}
1812
1813bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1814 StringExtractorGDBRemote response;
1815 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1816 PacketResult::Success) {
1817 if (response.IsUnsupportedResponse())
1818 return false;
1819 if (response.IsErrorResponse())
1820 return false;
1821 std::string cwd;
1822 response.GetHexByteString(cwd);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001823 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001824 return !cwd.empty();
1825 }
1826 return false;
1827}
1828
1829int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1830 if (working_dir) {
1831 std::string path{working_dir.GetPath(false)};
1832 StreamString packet;
1833 packet.PutCString("QSetWorkingDir:");
Pavel Labath7f815a92019-02-12 14:28:55 +00001834 packet.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835
1836 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001837 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1838 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001839 if (response.IsOKResponse())
1840 return 0;
1841 uint8_t error = response.GetError();
1842 if (error)
1843 return error;
1844 }
1845 }
1846 return -1;
1847}
1848
1849int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1850 char packet[32];
1851 const int packet_len =
1852 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1853 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001854 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001855 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001856 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001857 PacketResult::Success) {
1858 if (response.IsOKResponse())
1859 return 0;
1860 uint8_t error = response.GetError();
1861 if (error)
1862 return error;
1863 }
1864 return -1;
1865}
1866
1867int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1868 char packet[32];
1869 const int packet_len = ::snprintf(packet, sizeof(packet),
1870 "QSetDetachOnError:%i", enable ? 1 : 0);
1871 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001872 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001873 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001874 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875 PacketResult::Success) {
1876 if (response.IsOKResponse())
1877 return 0;
1878 uint8_t error = response.GetError();
1879 if (error)
1880 return error;
1881 }
1882 return -1;
1883}
1884
1885bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1886 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1887 if (response.IsNormalResponse()) {
1888 llvm::StringRef name;
1889 llvm::StringRef value;
1890 StringExtractor extractor;
1891
1892 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1893 uint32_t sub = 0;
1894 std::string vendor;
1895 std::string os_type;
1896
1897 while (response.GetNameColonValue(name, value)) {
1898 if (name.equals("pid")) {
1899 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1900 value.getAsInteger(0, pid);
1901 process_info.SetProcessID(pid);
1902 } else if (name.equals("ppid")) {
1903 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1904 value.getAsInteger(0, pid);
1905 process_info.SetParentProcessID(pid);
1906 } else if (name.equals("uid")) {
1907 uint32_t uid = UINT32_MAX;
1908 value.getAsInteger(0, uid);
1909 process_info.SetUserID(uid);
1910 } else if (name.equals("euid")) {
1911 uint32_t uid = UINT32_MAX;
1912 value.getAsInteger(0, uid);
Walter Erquinigo8b6dcc12019-10-07 20:26:49 +00001913 process_info.SetEffectiveUserID(uid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001914 } else if (name.equals("gid")) {
1915 uint32_t gid = UINT32_MAX;
1916 value.getAsInteger(0, gid);
1917 process_info.SetGroupID(gid);
1918 } else if (name.equals("egid")) {
1919 uint32_t gid = UINT32_MAX;
1920 value.getAsInteger(0, gid);
1921 process_info.SetEffectiveGroupID(gid);
1922 } else if (name.equals("triple")) {
1923 StringExtractor extractor(value);
1924 std::string triple;
1925 extractor.GetHexByteString(triple);
1926 process_info.GetArchitecture().SetTriple(triple.c_str());
1927 } else if (name.equals("name")) {
1928 StringExtractor extractor(value);
Adrian Prantl05097242018-04-30 16:49:04 +00001929 // The process name from ASCII hex bytes since we can't control the
1930 // characters in a process name
Kate Stoneb9c1b512016-09-06 20:57:50 +00001931 std::string name;
1932 extractor.GetHexByteString(name);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001933 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
Walter Erquinigo48a50ee2019-10-16 18:47:05 +00001934 } else if (name.equals("args")) {
1935 llvm::StringRef encoded_args(value), hex_arg;
1936
1937 bool is_arg0 = true;
1938 while (!encoded_args.empty()) {
1939 std::tie(hex_arg, encoded_args) = encoded_args.split('-');
1940 std::string arg;
1941 StringExtractor extractor(hex_arg);
1942 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) {
1943 // In case of wrong encoding, we discard all the arguments
1944 process_info.GetArguments().Clear();
1945 process_info.SetArg0("");
1946 break;
1947 }
1948 if (is_arg0)
1949 process_info.SetArg0(arg);
1950 else
1951 process_info.GetArguments().AppendArgument(arg);
1952 is_arg0 = false;
1953 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001954 } else if (name.equals("cputype")) {
1955 value.getAsInteger(0, cpu);
1956 } else if (name.equals("cpusubtype")) {
1957 value.getAsInteger(0, sub);
1958 } else if (name.equals("vendor")) {
1959 vendor = value;
1960 } else if (name.equals("ostype")) {
1961 os_type = value;
1962 }
1963 }
1964
1965 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1966 if (vendor == "apple") {
1967 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1968 sub);
1969 process_info.GetArchitecture().GetTriple().setVendorName(
1970 llvm::StringRef(vendor));
1971 process_info.GetArchitecture().GetTriple().setOSName(
1972 llvm::StringRef(os_type));
1973 }
1974 }
1975
1976 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1977 return true;
1978 }
1979 return false;
1980}
1981
1982bool GDBRemoteCommunicationClient::GetProcessInfo(
1983 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1984 process_info.Clear();
1985
1986 if (m_supports_qProcessInfoPID) {
1987 char packet[32];
1988 const int packet_len =
1989 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1990 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001991 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001992 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001993 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 PacketResult::Success) {
1995 return DecodeProcessInfoResponse(response, process_info);
1996 } else {
1997 m_supports_qProcessInfoPID = false;
1998 return false;
1999 }
2000 }
2001 return false;
2002}
2003
2004bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
2005 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2006 GDBR_LOG_PACKETS));
2007
2008 if (allow_lazy) {
2009 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2010 return true;
2011 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2012 return false;
2013 }
2014
2015 GetHostInfo();
2016
2017 StringExtractorGDBRemote response;
2018 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
2019 PacketResult::Success) {
2020 if (response.IsNormalResponse()) {
2021 llvm::StringRef name;
2022 llvm::StringRef value;
2023 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2024 uint32_t sub = 0;
2025 std::string arch_name;
2026 std::string os_name;
Adrian Prantl24610612019-09-04 17:23:15 +00002027 std::string environment;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002028 std::string vendor_name;
2029 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002030 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002031 uint32_t pointer_byte_size = 0;
2032 StringExtractor extractor;
2033 ByteOrder byte_order = eByteOrderInvalid;
2034 uint32_t num_keys_decoded = 0;
2035 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2036 while (response.GetNameColonValue(name, value)) {
2037 if (name.equals("cputype")) {
2038 if (!value.getAsInteger(16, cpu))
2039 ++num_keys_decoded;
2040 } else if (name.equals("cpusubtype")) {
2041 if (!value.getAsInteger(16, sub))
2042 ++num_keys_decoded;
2043 } else if (name.equals("triple")) {
2044 StringExtractor extractor(value);
2045 extractor.GetHexByteString(triple);
2046 ++num_keys_decoded;
2047 } else if (name.equals("ostype")) {
Adrian Prantl24610612019-09-04 17:23:15 +00002048 if (value.equals("maccatalyst")) {
2049 os_name = "ios";
2050 environment = "macabi";
2051 } else
2052 os_name = value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002053 ++num_keys_decoded;
2054 } else if (name.equals("vendor")) {
2055 vendor_name = value;
2056 ++num_keys_decoded;
2057 } else if (name.equals("endian")) {
2058 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2059 .Case("little", eByteOrderLittle)
2060 .Case("big", eByteOrderBig)
2061 .Case("pdp", eByteOrderPDP)
2062 .Default(eByteOrderInvalid);
2063 if (byte_order != eByteOrderInvalid)
2064 ++num_keys_decoded;
2065 } else if (name.equals("ptrsize")) {
2066 if (!value.getAsInteger(16, pointer_byte_size))
2067 ++num_keys_decoded;
2068 } else if (name.equals("pid")) {
2069 if (!value.getAsInteger(16, pid))
2070 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00002071 } else if (name.equals("elf_abi")) {
2072 elf_abi = value;
2073 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002074 }
2075 }
2076 if (num_keys_decoded > 0)
2077 m_qProcessInfo_is_valid = eLazyBoolYes;
2078 if (pid != LLDB_INVALID_PROCESS_ID) {
2079 m_curr_pid_is_valid = eLazyBoolYes;
2080 m_curr_pid = pid;
2081 }
2082
2083 // Set the ArchSpec from the triple if we have it.
2084 if (!triple.empty()) {
2085 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00002086 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002087 if (pointer_byte_size) {
2088 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2089 }
2090 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2091 !vendor_name.empty()) {
2092 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
Adrian Prantl24610612019-09-04 17:23:15 +00002093 if (!environment.empty())
2094 triple.setEnvironmentName(environment);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002095
2096 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00002097 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Jason Liua03ae732019-03-12 22:01:10 +00002098 assert(triple.getObjectFormat() != llvm::Triple::XCOFF);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099 switch (triple.getObjectFormat()) {
2100 case llvm::Triple::MachO:
2101 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2102 break;
2103 case llvm::Triple::ELF:
2104 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2105 break;
2106 case llvm::Triple::COFF:
2107 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2108 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00002109 case llvm::Triple::Wasm:
Jason Liua03ae732019-03-12 22:01:10 +00002110 case llvm::Triple::XCOFF:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002111 LLDB_LOGF(log, "error: not supported target architecture");
Pavel Labath4f19fce22017-02-17 13:39:50 +00002112 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002113 case llvm::Triple::UnknownObjectFormat:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002114 LLDB_LOGF(log, "error: failed to determine target architecture");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002115 return false;
2116 }
2117
2118 if (pointer_byte_size) {
2119 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2120 }
2121 if (byte_order != eByteOrderInvalid) {
2122 assert(byte_order == m_process_arch.GetByteOrder());
2123 }
2124 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2125 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Adrian Prantl24610612019-09-04 17:23:15 +00002126 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002127 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2128 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Adrian Prantl24610612019-09-04 17:23:15 +00002129 m_host_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002130 }
2131 return true;
2132 }
2133 } else {
2134 m_qProcessInfo_is_valid = eLazyBoolNo;
2135 }
2136
2137 return false;
2138}
2139
2140uint32_t GDBRemoteCommunicationClient::FindProcesses(
2141 const ProcessInstanceInfoMatch &match_info,
2142 ProcessInstanceInfoList &process_infos) {
2143 process_infos.Clear();
2144
2145 if (m_supports_qfProcessInfo) {
2146 StreamString packet;
2147 packet.PutCString("qfProcessInfo");
2148 if (!match_info.MatchAllProcesses()) {
2149 packet.PutChar(':');
2150 const char *name = match_info.GetProcessInfo().GetName();
2151 bool has_name_match = false;
2152 if (name && name[0]) {
2153 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00002154 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002155 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00002156 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157 has_name_match = false;
2158 break;
2159
Pavel Labathc4a33952017-02-20 11:35:33 +00002160 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002161 packet.PutCString("name_match:equals;");
2162 break;
2163
Pavel Labathc4a33952017-02-20 11:35:33 +00002164 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002165 packet.PutCString("name_match:contains;");
2166 break;
2167
Pavel Labathc4a33952017-02-20 11:35:33 +00002168 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 packet.PutCString("name_match:starts_with;");
2170 break;
2171
Pavel Labathc4a33952017-02-20 11:35:33 +00002172 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002173 packet.PutCString("name_match:ends_with;");
2174 break;
2175
Pavel Labathc4a33952017-02-20 11:35:33 +00002176 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002177 packet.PutCString("name_match:regex;");
2178 break;
2179 }
2180 if (has_name_match) {
2181 packet.PutCString("name:");
2182 packet.PutBytesAsRawHex8(name, ::strlen(name));
2183 packet.PutChar(';');
2184 }
2185 }
2186
2187 if (match_info.GetProcessInfo().ProcessIDIsValid())
2188 packet.Printf("pid:%" PRIu64 ";",
2189 match_info.GetProcessInfo().GetProcessID());
2190 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2191 packet.Printf("parent_pid:%" PRIu64 ";",
2192 match_info.GetProcessInfo().GetParentProcessID());
2193 if (match_info.GetProcessInfo().UserIDIsValid())
2194 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2195 if (match_info.GetProcessInfo().GroupIDIsValid())
2196 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2197 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2198 packet.Printf("euid:%u;",
2199 match_info.GetProcessInfo().GetEffectiveUserID());
2200 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2201 packet.Printf("egid:%u;",
2202 match_info.GetProcessInfo().GetEffectiveGroupID());
Walter Erquinigoaf1d27e2019-10-12 02:36:16 +00002203 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2205 const ArchSpec &match_arch =
2206 match_info.GetProcessInfo().GetArchitecture();
2207 const llvm::Triple &triple = match_arch.GetTriple();
2208 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002209 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002210 packet.PutChar(';');
2211 }
2212 }
2213 StringExtractorGDBRemote response;
Adrian Prantl05097242018-04-30 16:49:04 +00002214 // Increase timeout as the first qfProcessInfo packet takes a long time on
2215 // Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002216 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002217 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2218 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002219 do {
2220 ProcessInstanceInfo process_info;
2221 if (!DecodeProcessInfoResponse(response, process_info))
2222 break;
2223 process_infos.Append(process_info);
Jonas Devlieghered35b42f2019-08-21 04:55:56 +00002224 response = StringExtractorGDBRemote();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002225 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2226 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002227 } else {
2228 m_supports_qfProcessInfo = false;
2229 return 0;
2230 }
2231 }
2232 return process_infos.GetSize();
2233}
2234
2235bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2236 std::string &name) {
2237 if (m_supports_qUserName) {
2238 char packet[32];
2239 const int packet_len =
2240 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2241 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002242 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002244 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002245 PacketResult::Success) {
2246 if (response.IsNormalResponse()) {
2247 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002248 // the hex encoded user name and should make up the entire packet. If
2249 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002250 if (response.GetHexByteString(name) * 2 ==
2251 response.GetStringRef().size())
2252 return true;
2253 }
2254 } else {
2255 m_supports_qUserName = false;
2256 return false;
2257 }
2258 }
2259 return false;
2260}
2261
2262bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2263 std::string &name) {
2264 if (m_supports_qGroupName) {
2265 char packet[32];
2266 const int packet_len =
2267 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2268 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002269 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002271 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002272 PacketResult::Success) {
2273 if (response.IsNormalResponse()) {
2274 // Make sure we parsed the right number of characters. The response is
Adrian Prantl05097242018-04-30 16:49:04 +00002275 // the hex encoded group name and should make up the entire packet. If
2276 // there are any non-hex ASCII bytes, the length won't match below..
Kate Stoneb9c1b512016-09-06 20:57:50 +00002277 if (response.GetHexByteString(name) * 2 ==
2278 response.GetStringRef().size())
2279 return true;
2280 }
2281 } else {
2282 m_supports_qGroupName = false;
2283 return false;
2284 }
2285 }
2286 return false;
2287}
2288
2289bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2290 // Form non-stop packet request
2291 char packet[32];
2292 const int packet_len =
2293 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2294 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002295 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002296
2297 StringExtractorGDBRemote response;
2298 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002299 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002300 PacketResult::Success)
2301 if (response.IsOKResponse())
2302 return true;
2303
2304 // Failed or not supported
2305 return false;
2306}
2307
2308static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2309 uint32_t recv_size) {
2310 packet.Clear();
2311 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2312 uint32_t bytes_left = send_size;
2313 while (bytes_left > 0) {
2314 if (bytes_left >= 26) {
2315 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2316 bytes_left -= 26;
2317 } else {
2318 packet.Printf("%*.*s;", bytes_left, bytes_left,
2319 "abcdefghijklmnopqrstuvwxyz");
2320 bytes_left = 0;
2321 }
2322 }
2323}
2324
Pavel Labath1eff73c2016-11-24 10:54:49 +00002325duration<float>
2326calculate_standard_deviation(const std::vector<duration<float>> &v) {
2327 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002328 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2329 Dur mean = sum / v.size();
2330 float accum = 0;
2331 for (auto d : v) {
2332 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002333 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002334 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002335
Pavel Labath3aa04912016-10-31 17:19:42 +00002336 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002337}
2338
2339void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2340 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002341 uint32_t max_recv,
2342 uint64_t recv_amount,
2343 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002345 if (SendSpeedTestPacket(0, 0)) {
2346 StreamString packet;
2347 if (json)
2348 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2349 "\"results\" : [",
2350 num_packets);
2351 else
2352 strm.Printf("Testing sending %u packets of various sizes:\n",
2353 num_packets);
2354 strm.Flush();
2355
2356 uint32_t result_idx = 0;
2357 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002358 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359
2360 for (send_size = 0; send_size <= max_send;
2361 send_size ? send_size *= 2 : send_size = 4) {
2362 for (uint32_t recv_size = 0; recv_size <= max_recv;
2363 recv_size ? recv_size *= 2 : recv_size = 4) {
2364 MakeSpeedTestPacket(packet, send_size, recv_size);
2365
2366 packet_times.clear();
2367 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002368 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002369 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002370 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002371 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002372 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002373 const auto packet_end_time = steady_clock::now();
2374 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002375 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002376 const auto end_time = steady_clock::now();
2377 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002378
2379 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002380 ((float)num_packets) / duration<float>(total_time).count();
2381 auto average_per_packet = total_time / num_packets;
2382 const duration<float> standard_deviation =
2383 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002385 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2386 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2387 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002388 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002389 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002390 ++result_idx;
2391 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002392 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2393 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2394 "standard deviation of {5,10:ms+f6}\n",
2395 send_size, recv_size, duration<float>(total_time),
2396 packets_per_second, duration<float>(average_per_packet),
2397 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002398 }
2399 strm.Flush();
2400 }
2401 }
2402
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002403 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002404 if (json)
2405 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2406 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002407 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408 else
2409 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2410 "packet sizes:\n",
2411 k_recv_amount_mb);
2412 strm.Flush();
2413 send_size = 0;
2414 result_idx = 0;
2415 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2416 MakeSpeedTestPacket(packet, send_size, recv_size);
2417
2418 // If we have a receive size, test how long it takes to receive 4MB of
2419 // data
2420 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002421 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002422 uint32_t bytes_read = 0;
2423 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002424 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002425 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002426 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002427 bytes_read += recv_size;
2428 ++packet_count;
2429 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002430 const auto end_time = steady_clock::now();
2431 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002432 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002433 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002434 (1024.0 * 1024.0);
2435 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002436 ((float)packet_count) / duration<float>(total_time).count();
2437 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438
2439 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002440 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2441 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002442 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002443 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002444 ++result_idx;
2445 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002446 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2447 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2448 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002450 duration<float>(total_time), mb_second,
2451 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002452 }
2453 strm.Flush();
2454 }
2455 }
2456 if (json)
2457 strm.Printf("\n ]\n }\n}\n");
2458 else
2459 strm.EOL();
2460 }
2461}
2462
2463bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2464 uint32_t recv_size) {
2465 StreamString packet;
2466 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2467 uint32_t bytes_left = send_size;
2468 while (bytes_left > 0) {
2469 if (bytes_left >= 26) {
2470 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2471 bytes_left -= 26;
2472 } else {
2473 packet.Printf("%*.*s;", bytes_left, bytes_left,
2474 "abcdefghijklmnopqrstuvwxyz");
2475 bytes_left = 0;
2476 }
2477 }
2478
2479 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002480 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2481 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002482}
2483
2484bool GDBRemoteCommunicationClient::LaunchGDBServer(
2485 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2486 std::string &socket_name) {
2487 pid = LLDB_INVALID_PROCESS_ID;
2488 port = 0;
2489 socket_name.clear();
2490
2491 StringExtractorGDBRemote response;
2492 StreamString stream;
2493 stream.PutCString("qLaunchGDBServer;");
2494 std::string hostname;
2495 if (remote_accept_hostname && remote_accept_hostname[0])
2496 hostname = remote_accept_hostname;
2497 else {
2498 if (HostInfo::GetHostname(hostname)) {
2499 // Make the GDB server we launch only accept connections from this host
2500 stream.Printf("host:%s;", hostname.c_str());
2501 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00002502 // Make the GDB server we launch accept connections from any host since
2503 // we can't figure out the hostname
Kate Stoneb9c1b512016-09-06 20:57:50 +00002504 stream.Printf("host:*;");
2505 }
2506 }
2507 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002508 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002509
2510 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2511 PacketResult::Success) {
2512 llvm::StringRef name;
2513 llvm::StringRef value;
2514 while (response.GetNameColonValue(name, value)) {
2515 if (name.equals("port"))
2516 value.getAsInteger(0, port);
2517 else if (name.equals("pid"))
2518 value.getAsInteger(0, pid);
2519 else if (name.compare("socket_name") == 0) {
2520 StringExtractor extractor(value);
2521 extractor.GetHexByteString(socket_name);
2522 }
2523 }
2524 return true;
2525 }
2526 return false;
2527}
2528
2529size_t GDBRemoteCommunicationClient::QueryGDBServer(
2530 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2531 connection_urls.clear();
2532
2533 StringExtractorGDBRemote response;
2534 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2535 PacketResult::Success)
2536 return 0;
2537
2538 StructuredData::ObjectSP data =
2539 StructuredData::ParseJSON(response.GetStringRef());
2540 if (!data)
2541 return 0;
2542
2543 StructuredData::Array *array = data->GetAsArray();
2544 if (!array)
2545 return 0;
2546
2547 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2548 StructuredData::Dictionary *element = nullptr;
2549 if (!array->GetItemAtIndexAsDictionary(i, element))
2550 continue;
2551
2552 uint16_t port = 0;
2553 if (StructuredData::ObjectSP port_osp =
2554 element->GetValueForKey(llvm::StringRef("port")))
2555 port = port_osp->GetIntegerValue(0);
2556
2557 std::string socket_name;
2558 if (StructuredData::ObjectSP socket_name_osp =
2559 element->GetValueForKey(llvm::StringRef("socket_name")))
2560 socket_name = socket_name_osp->GetStringValue();
2561
2562 if (port != 0 || !socket_name.empty())
2563 connection_urls.emplace_back(port, socket_name);
2564 }
2565 return connection_urls.size();
2566}
2567
2568bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2569 StreamString stream;
2570 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002571
2572 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002573 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002574 PacketResult::Success) {
2575 if (response.IsOKResponse())
2576 return true;
2577 }
2578 return false;
2579}
2580
2581bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2582 if (m_curr_tid == tid)
2583 return true;
2584
2585 char packet[32];
2586 int packet_len;
2587 if (tid == UINT64_MAX)
2588 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2589 else
2590 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2591 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002592 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002594 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002595 PacketResult::Success) {
2596 if (response.IsOKResponse()) {
2597 m_curr_tid = tid;
2598 return true;
2599 }
2600
2601 /*
2602 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2603 * Hg packet.
2604 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2605 * which can
2606 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2607 */
2608 if (response.IsUnsupportedResponse() && IsConnected()) {
2609 m_curr_tid = 1;
2610 return true;
2611 }
2612 }
2613 return false;
2614}
2615
2616bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2617 if (m_curr_tid_run == tid)
2618 return true;
2619
2620 char packet[32];
2621 int packet_len;
2622 if (tid == UINT64_MAX)
2623 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2624 else
2625 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2626
2627 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002628 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002629 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002630 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002631 PacketResult::Success) {
2632 if (response.IsOKResponse()) {
2633 m_curr_tid_run = tid;
2634 return true;
2635 }
2636
2637 /*
2638 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2639 * Hc packet.
2640 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2641 * which can
2642 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2643 */
2644 if (response.IsUnsupportedResponse() && IsConnected()) {
2645 m_curr_tid_run = 1;
2646 return true;
2647 }
2648 }
2649 return false;
2650}
2651
2652bool GDBRemoteCommunicationClient::GetStopReply(
2653 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002654 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002655 PacketResult::Success)
2656 return response.IsNormalResponse();
2657 return false;
2658}
2659
2660bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2661 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2662 if (m_supports_qThreadStopInfo) {
2663 char packet[256];
2664 int packet_len =
2665 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2666 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002667 UNUSED_IF_ASSERT_DISABLED(packet_len);
2668 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002669 PacketResult::Success) {
2670 if (response.IsUnsupportedResponse())
2671 m_supports_qThreadStopInfo = false;
2672 else if (response.IsNormalResponse())
2673 return true;
2674 else
2675 return false;
2676 } else {
2677 m_supports_qThreadStopInfo = false;
2678 }
2679 }
2680 return false;
2681}
2682
2683uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2684 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2685 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002686 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2687 __FUNCTION__, insert ? "add" : "remove", addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002688
2689 // Check if the stub is known not to support this breakpoint type
2690 if (!SupportsGDBStoppointPacket(type))
2691 return UINT8_MAX;
2692 // Construct the breakpoint packet
2693 char packet[64];
2694 const int packet_len =
2695 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2696 insert ? 'Z' : 'z', type, addr, length);
2697 // Check we haven't overwritten the end of the packet buffer
2698 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002699 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002700 StringExtractorGDBRemote response;
2701 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2702 // or "" (unsupported)
2703 response.SetResponseValidatorToOKErrorNotSupported();
2704 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002705 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706 PacketResult::Success) {
2707 // Receive and OK packet when the breakpoint successfully placed
2708 if (response.IsOKResponse())
2709 return 0;
2710
Zachary Turner97206d52017-05-12 04:51:55 +00002711 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712 if (response.IsErrorResponse())
2713 return response.GetError();
2714
2715 // Empty packet informs us that breakpoint is not supported
2716 if (response.IsUnsupportedResponse()) {
2717 // Disable this breakpoint type since it is unsupported
2718 switch (type) {
2719 case eBreakpointSoftware:
2720 m_supports_z0 = false;
2721 break;
2722 case eBreakpointHardware:
2723 m_supports_z1 = false;
2724 break;
2725 case eWatchpointWrite:
2726 m_supports_z2 = false;
2727 break;
2728 case eWatchpointRead:
2729 m_supports_z3 = false;
2730 break;
2731 case eWatchpointReadWrite:
2732 m_supports_z4 = false;
2733 break;
2734 case eStoppointInvalid:
2735 return UINT8_MAX;
2736 }
2737 }
2738 }
2739 // Signal generic failure
2740 return UINT8_MAX;
2741}
2742
2743size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2744 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2745 thread_ids.clear();
2746
2747 Lock lock(*this, false);
2748 if (lock) {
2749 sequence_mutex_unavailable = false;
2750 StringExtractorGDBRemote response;
2751
2752 PacketResult packet_result;
2753 for (packet_result =
2754 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2755 packet_result == PacketResult::Success && response.IsNormalResponse();
2756 packet_result =
2757 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2758 char ch = response.GetChar();
2759 if (ch == 'l')
2760 break;
2761 if (ch == 'm') {
2762 do {
2763 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2764
2765 if (tid != LLDB_INVALID_THREAD_ID) {
2766 thread_ids.push_back(tid);
2767 }
2768 ch = response.GetChar(); // Skip the command separator
2769 } while (ch == ','); // Make sure we got a comma separator
2770 }
2771 }
2772
2773 /*
2774 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2775 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2776 * could
2777 * be as simple as 'S05'. There is no packet which can give us pid and/or
2778 * tid.
2779 * Assume pid=tid=1 in such cases.
2780 */
Tamas Berghammer1492cb82017-09-18 10:24:48 +00002781 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2782 thread_ids.size() == 0 && IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 thread_ids.push_back(1);
2784 }
2785 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002786#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002787 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2788 GDBR_LOG_PACKETS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002789 LLDB_LOGF(log, "error: failed to get packet sequence mutex, not sending "
2790 "packet 'qfThreadInfo'");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791#endif
2792 sequence_mutex_unavailable = true;
2793 }
2794 return thread_ids.size();
2795}
2796
2797lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2798 StringExtractorGDBRemote response;
2799 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2800 PacketResult::Success ||
2801 !response.IsNormalResponse())
2802 return LLDB_INVALID_ADDRESS;
2803 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2804}
2805
Zachary Turner97206d52017-05-12 04:51:55 +00002806lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 const char *command, // Shouldn't be NULL
2808 const FileSpec &
2809 working_dir, // Pass empty FileSpec to use the current working directory
2810 int *status_ptr, // Pass NULL if you don't want the process exit status
2811 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2812 // process to exit
2813 std::string
2814 *command_output, // Pass NULL if you don't want the command output
Pavel Labath19dd1a02018-05-10 10:46:03 +00002815 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002816 lldb_private::StreamString stream;
2817 stream.PutCString("qPlatform_shell:");
2818 stream.PutBytesAsRawHex8(command, strlen(command));
2819 stream.PutChar(',');
Pavel Labath19dd1a02018-05-10 10:46:03 +00002820 uint32_t timeout_sec = UINT32_MAX;
2821 if (timeout) {
2822 // TODO: Use chrono version of std::ceil once c++17 is available.
2823 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2824 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002825 stream.PutHex32(timeout_sec);
2826 if (working_dir) {
2827 std::string path{working_dir.GetPath(false)};
2828 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002829 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002831 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002832 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833 PacketResult::Success) {
2834 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002835 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002837 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2839 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002840 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 else if (status_ptr)
2842 *status_ptr = exitcode;
2843 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002844 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2846 if (signo_ptr)
2847 *signo_ptr = signo;
2848 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002849 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 std::string output;
2851 response.GetEscapedBinaryData(output);
2852 if (command_output)
2853 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002854 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 }
Zachary Turner97206d52017-05-12 04:51:55 +00002856 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857}
2858
Zachary Turner97206d52017-05-12 04:51:55 +00002859Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2860 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002861 std::string path{file_spec.GetPath(false)};
2862 lldb_private::StreamString stream;
2863 stream.PutCString("qPlatform_mkdir:");
2864 stream.PutHex32(file_permissions);
2865 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002866 stream.PutStringAsRawHex8(path);
Zachary Turnerc1564272016-11-16 21:15:24 +00002867 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868 StringExtractorGDBRemote response;
2869
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002870 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002871 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002872 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002873
2874 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002875 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876
Zachary Turner97206d52017-05-12 04:51:55 +00002877 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878}
2879
Zachary Turner97206d52017-05-12 04:51:55 +00002880Status
2881GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2882 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002883 std::string path{file_spec.GetPath(false)};
2884 lldb_private::StreamString stream;
2885 stream.PutCString("qPlatform_chmod:");
2886 stream.PutHex32(file_permissions);
2887 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00002888 stream.PutStringAsRawHex8(path);
Zachary Turnerc1564272016-11-16 21:15:24 +00002889 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 StringExtractorGDBRemote response;
2891
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002892 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002893 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002894 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895
2896 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002897 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002898
Zachary Turner97206d52017-05-12 04:51:55 +00002899 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002900}
2901
2902static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002903 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002904 response.SetFilePos(0);
2905 if (response.GetChar() != 'F')
2906 return fail_result;
2907 int32_t result = response.GetS32(-2);
2908 if (result == -2)
2909 return fail_result;
2910 if (response.GetChar() == ',') {
2911 int result_errno = response.GetS32(-2);
2912 if (result_errno != -2)
2913 error.SetError(result_errno, eErrorTypePOSIX);
2914 else
2915 error.SetError(-1, eErrorTypeGeneric);
2916 } else
2917 error.Clear();
2918 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002919}
2920lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
Lawrence D'Anna62c9fe42019-10-14 20:15:34 +00002922 File::OpenOptions flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002923 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 std::string path(file_spec.GetPath(false));
2925 lldb_private::StreamString stream;
2926 stream.PutCString("vFile:open:");
2927 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002928 return UINT64_MAX;
Pavel Labath7f815a92019-02-12 14:28:55 +00002929 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002930 stream.PutChar(',');
2931 stream.PutHex32(flags);
2932 stream.PutChar(',');
2933 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002934 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002935 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002936 PacketResult::Success) {
2937 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2938 }
2939 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002940}
2941
Zachary Turner97206d52017-05-12 04:51:55 +00002942bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2943 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002944 lldb_private::StreamString stream;
2945 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002946 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002947 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 PacketResult::Success) {
2949 return ParseHostIOPacketResponse(response, -1, error) == 0;
2950 }
2951 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002952}
2953
2954// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002955lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2956 const lldb_private::FileSpec &file_spec) {
2957 std::string path(file_spec.GetPath(false));
2958 lldb_private::StreamString stream;
2959 stream.PutCString("vFile:size:");
Pavel Labath7f815a92019-02-12 14:28:55 +00002960 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002961 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002962 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002963 PacketResult::Success) {
2964 if (response.GetChar() != 'F')
2965 return UINT64_MAX;
2966 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2967 return retcode;
2968 }
2969 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002970}
2971
Zachary Turner97206d52017-05-12 04:51:55 +00002972Status
2973GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2974 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002976 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002977 lldb_private::StreamString stream;
2978 stream.PutCString("vFile:mode:");
Pavel Labath7f815a92019-02-12 14:28:55 +00002979 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002980 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002981 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 PacketResult::Success) {
2983 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002984 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002985 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002986 } else {
2987 const uint32_t mode = response.GetS32(-1);
2988 if (static_cast<int32_t>(mode) == -1) {
2989 if (response.GetChar() == ',') {
2990 int response_errno = response.GetS32(-1);
2991 if (response_errno > 0)
2992 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2993 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002994 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 } else
2996 error.SetErrorToGenericError();
2997 } else {
2998 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2999 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003000 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003001 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003002 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00003003 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003004 }
3005 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003006}
3007
Kate Stoneb9c1b512016-09-06 20:57:50 +00003008uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
3009 uint64_t offset, void *dst,
3010 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003011 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003012 lldb_private::StreamString stream;
3013 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
3014 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003016 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003017 PacketResult::Success) {
3018 if (response.GetChar() != 'F')
3019 return 0;
3020 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3021 if (retcode == UINT32_MAX)
3022 return retcode;
3023 const char next = (response.Peek() ? *response.Peek() : 0);
3024 if (next == ',')
3025 return 0;
3026 if (next == ';') {
3027 response.GetChar(); // skip the semicolon
3028 std::string buffer;
3029 if (response.GetEscapedBinaryData(buffer)) {
3030 const uint64_t data_to_write =
3031 std::min<uint64_t>(dst_len, buffer.size());
3032 if (data_to_write > 0)
3033 memcpy(dst, &buffer[0], data_to_write);
3034 return data_to_write;
3035 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003036 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 }
3038 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003039}
3040
Kate Stoneb9c1b512016-09-06 20:57:50 +00003041uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3042 uint64_t offset,
3043 const void *src,
3044 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003045 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046 lldb_private::StreamGDBRemote stream;
3047 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3048 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003050 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003051 PacketResult::Success) {
3052 if (response.GetChar() != 'F') {
3053 error.SetErrorStringWithFormat("write file failed");
3054 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003055 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003056 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3057 if (bytes_written == UINT64_MAX) {
3058 error.SetErrorToGenericError();
3059 if (response.GetChar() == ',') {
3060 int response_errno = response.GetS32(-1);
3061 if (response_errno > 0)
3062 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3063 }
3064 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00003065 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003066 return bytes_written;
3067 } else {
3068 error.SetErrorString("failed to send vFile:pwrite packet");
3069 }
3070 return 0;
3071}
3072
Zachary Turner97206d52017-05-12 04:51:55 +00003073Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3074 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003075 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003076 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003077 lldb_private::StreamGDBRemote stream;
3078 stream.PutCString("vFile:symlink:");
3079 // the unix symlink() command reverses its parameters where the dst if first,
3080 // so we follow suit here
Pavel Labath7f815a92019-02-12 14:28:55 +00003081 stream.PutStringAsRawHex8(dst_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082 stream.PutChar(',');
Pavel Labath7f815a92019-02-12 14:28:55 +00003083 stream.PutStringAsRawHex8(src_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003084 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003085 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 PacketResult::Success) {
3087 if (response.GetChar() == 'F') {
3088 uint32_t result = response.GetU32(UINT32_MAX);
3089 if (result != 0) {
3090 error.SetErrorToGenericError();
3091 if (response.GetChar() == ',') {
3092 int response_errno = response.GetS32(-1);
3093 if (response_errno > 0)
3094 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3095 }
3096 }
3097 } else {
3098 // Should have returned with 'F<result>[,<errno>]'
3099 error.SetErrorStringWithFormat("symlink failed");
3100 }
3101 } else {
3102 error.SetErrorString("failed to send vFile:symlink packet");
3103 }
3104 return error;
3105}
3106
Zachary Turner97206d52017-05-12 04:51:55 +00003107Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003108 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00003109 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 lldb_private::StreamGDBRemote stream;
3111 stream.PutCString("vFile:unlink:");
3112 // the unix symlink() command reverses its parameters where the dst if first,
3113 // so we follow suit here
Pavel Labath7f815a92019-02-12 14:28:55 +00003114 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003116 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117 PacketResult::Success) {
3118 if (response.GetChar() == 'F') {
3119 uint32_t result = response.GetU32(UINT32_MAX);
3120 if (result != 0) {
3121 error.SetErrorToGenericError();
3122 if (response.GetChar() == ',') {
3123 int response_errno = response.GetS32(-1);
3124 if (response_errno > 0)
3125 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3126 }
3127 }
3128 } else {
3129 // Should have returned with 'F<result>[,<errno>]'
3130 error.SetErrorStringWithFormat("unlink failed");
3131 }
3132 } else {
3133 error.SetErrorString("failed to send vFile:unlink packet");
3134 }
3135 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00003136}
3137
Daniel Maleae0f8f572013-08-26 23:57:52 +00003138// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139bool GDBRemoteCommunicationClient::GetFileExists(
3140 const lldb_private::FileSpec &file_spec) {
3141 std::string path(file_spec.GetPath(false));
3142 lldb_private::StreamString stream;
3143 stream.PutCString("vFile:exists:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003144 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003145 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003146 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003147 PacketResult::Success) {
3148 if (response.GetChar() != 'F')
3149 return false;
3150 if (response.GetChar() != ',')
3151 return false;
3152 bool retcode = (response.GetChar() != '0');
3153 return retcode;
3154 }
3155 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003156}
3157
Kate Stoneb9c1b512016-09-06 20:57:50 +00003158bool GDBRemoteCommunicationClient::CalculateMD5(
3159 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3160 std::string path(file_spec.GetPath(false));
3161 lldb_private::StreamString stream;
3162 stream.PutCString("vFile:MD5:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003163 stream.PutStringAsRawHex8(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003164 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003165 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003166 PacketResult::Success) {
3167 if (response.GetChar() != 'F')
3168 return false;
3169 if (response.GetChar() != ',')
3170 return false;
3171 if (response.Peek() && *response.Peek() == 'x')
3172 return false;
3173 low = response.GetHexMaxU64(false, UINT64_MAX);
3174 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003175 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003176 }
3177 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003178}
3179
Kate Stoneb9c1b512016-09-06 20:57:50 +00003180bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3181 // Some targets have issues with g/G packets and we need to avoid using them
3182 if (m_avoid_g_packets == eLazyBoolCalculate) {
3183 if (process) {
3184 m_avoid_g_packets = eLazyBoolNo;
3185 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3186 if (arch.IsValid() &&
3187 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3188 arch.GetTriple().getOS() == llvm::Triple::IOS &&
Jason Molenda7dd7a362019-10-16 19:14:49 +00003189 (arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
3190 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003191 m_avoid_g_packets = eLazyBoolYes;
3192 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3193 if (gdb_server_version != 0) {
3194 const char *gdb_server_name = GetGDBServerProgramName();
3195 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3196 if (gdb_server_version >= 310)
3197 m_avoid_g_packets = eLazyBoolNo;
3198 }
3199 }
3200 }
3201 }
3202 }
3203 return m_avoid_g_packets == eLazyBoolYes;
3204}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003205
Kate Stoneb9c1b512016-09-06 20:57:50 +00003206DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3207 uint32_t reg) {
3208 StreamString payload;
3209 payload.Printf("p%x", reg);
3210 StringExtractorGDBRemote response;
3211 if (SendThreadSpecificPacketAndWaitForResponse(
3212 tid, std::move(payload), response, false) != PacketResult::Success ||
3213 !response.IsNormalResponse())
3214 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003215
Kate Stoneb9c1b512016-09-06 20:57:50 +00003216 DataBufferSP buffer_sp(
3217 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3218 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3219 return buffer_sp;
3220}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003221
Kate Stoneb9c1b512016-09-06 20:57:50 +00003222DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3223 StreamString payload;
3224 payload.PutChar('g');
3225 StringExtractorGDBRemote response;
3226 if (SendThreadSpecificPacketAndWaitForResponse(
3227 tid, std::move(payload), response, false) != PacketResult::Success ||
3228 !response.IsNormalResponse())
3229 return nullptr;
3230
3231 DataBufferSP buffer_sp(
3232 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3233 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3234 return buffer_sp;
3235}
3236
3237bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3238 uint32_t reg_num,
3239 llvm::ArrayRef<uint8_t> data) {
3240 StreamString payload;
3241 payload.Printf("P%x=", reg_num);
3242 payload.PutBytesAsRawHex8(data.data(), data.size(),
3243 endian::InlHostByteOrder(),
3244 endian::InlHostByteOrder());
3245 StringExtractorGDBRemote response;
3246 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3247 response, false) ==
3248 PacketResult::Success &&
3249 response.IsOKResponse();
3250}
3251
3252bool GDBRemoteCommunicationClient::WriteAllRegisters(
3253 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3254 StreamString payload;
3255 payload.PutChar('G');
3256 payload.PutBytesAsRawHex8(data.data(), data.size(),
3257 endian::InlHostByteOrder(),
3258 endian::InlHostByteOrder());
3259 StringExtractorGDBRemote response;
3260 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3261 response, false) ==
3262 PacketResult::Success &&
3263 response.IsOKResponse();
3264}
3265
3266bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3267 uint32_t &save_id) {
3268 save_id = 0; // Set to invalid save ID
3269 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003270 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003271
3272 m_supports_QSaveRegisterState = eLazyBoolYes;
3273 StreamString payload;
3274 payload.PutCString("QSaveRegisterState");
3275 StringExtractorGDBRemote response;
3276 if (SendThreadSpecificPacketAndWaitForResponse(
3277 tid, std::move(payload), response, false) != PacketResult::Success)
3278 return false;
3279
3280 if (response.IsUnsupportedResponse())
3281 m_supports_QSaveRegisterState = eLazyBoolNo;
3282
3283 const uint32_t response_save_id = response.GetU32(0);
3284 if (response_save_id == 0)
3285 return false;
3286
3287 save_id = response_save_id;
3288 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003289}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003290
Kate Stoneb9c1b512016-09-06 20:57:50 +00003291bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3292 uint32_t save_id) {
3293 // We use the "m_supports_QSaveRegisterState" variable here because the
Adrian Prantl05097242018-04-30 16:49:04 +00003294 // QSaveRegisterState and QRestoreRegisterState packets must both be
3295 // supported in order to be useful
Kate Stoneb9c1b512016-09-06 20:57:50 +00003296 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3297 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003298
Kate Stoneb9c1b512016-09-06 20:57:50 +00003299 StreamString payload;
3300 payload.Printf("QRestoreRegisterState:%u", save_id);
3301 StringExtractorGDBRemote response;
3302 if (SendThreadSpecificPacketAndWaitForResponse(
3303 tid, std::move(payload), response, false) != PacketResult::Success)
3304 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003305
Kate Stoneb9c1b512016-09-06 20:57:50 +00003306 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003307 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003308
3309 if (response.IsUnsupportedResponse())
3310 m_supports_QSaveRegisterState = eLazyBoolNo;
3311 return false;
3312}
3313
3314bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3315 if (!GetSyncThreadStateSupported())
3316 return false;
3317
3318 StreamString packet;
3319 StringExtractorGDBRemote response;
3320 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3321 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3322 GDBRemoteCommunication::PacketResult::Success &&
3323 response.IsOKResponse();
3324}
3325
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003326lldb::user_id_t
3327GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3328 Status &error) {
3329 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3330 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3331
3332 StreamGDBRemote escaped_packet;
3333 escaped_packet.PutCString("jTraceStart:");
3334
3335 StructuredData::Dictionary json_packet;
3336 json_packet.AddIntegerItem("type", options.getType());
3337 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3338 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3339
3340 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3341 json_packet.AddIntegerItem("threadid", options.getThreadID());
3342
3343 StructuredData::DictionarySP custom_params = options.getTraceParams();
3344 if (custom_params)
3345 json_packet.AddItem("params", custom_params);
3346
3347 StreamString json_string;
3348 json_packet.Dump(json_string, false);
3349 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3350
3351 StringExtractorGDBRemote response;
3352 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3353 true) ==
3354 GDBRemoteCommunication::PacketResult::Success) {
3355 if (!response.IsNormalResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003356 error = response.GetStatus();
3357 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003358 } else {
3359 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3360 }
3361 } else {
3362 LLDB_LOG(log, "failed to send packet");
3363 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3364 escaped_packet.GetData());
3365 }
3366 return ret_uid;
3367}
3368
3369Status
3370GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3371 lldb::tid_t thread_id) {
3372 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3373 StringExtractorGDBRemote response;
3374 Status error;
3375
3376 StructuredData::Dictionary json_packet;
3377 StreamGDBRemote escaped_packet;
3378 StreamString json_string;
3379 escaped_packet.PutCString("jTraceStop:");
3380
3381 json_packet.AddIntegerItem("traceid", uid);
3382
3383 if (thread_id != LLDB_INVALID_THREAD_ID)
3384 json_packet.AddIntegerItem("threadid", thread_id);
3385
3386 json_packet.Dump(json_string, false);
3387
3388 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3389
3390 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3391 true) ==
3392 GDBRemoteCommunication::PacketResult::Success) {
3393 if (!response.IsOKResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003394 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003395 LLDB_LOG(log, "stop tracing failed");
3396 }
3397 } else {
3398 LLDB_LOG(log, "failed to send packet");
3399 error.SetErrorStringWithFormat(
3400 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3401 response.GetError());
3402 }
3403 return error;
3404}
3405
3406Status GDBRemoteCommunicationClient::SendGetDataPacket(
3407 lldb::user_id_t uid, lldb::tid_t thread_id,
3408 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003409
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003410 StreamGDBRemote escaped_packet;
3411 escaped_packet.PutCString("jTraceBufferRead:");
3412 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3413}
3414
3415Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3416 lldb::user_id_t uid, lldb::tid_t thread_id,
3417 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003418
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003419 StreamGDBRemote escaped_packet;
3420 escaped_packet.PutCString("jTraceMetaRead:");
3421 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3422}
3423
3424Status
3425GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3426 TraceOptions &options) {
3427 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3428 StringExtractorGDBRemote response;
3429 Status error;
3430
3431 StreamString json_string;
3432 StreamGDBRemote escaped_packet;
3433 escaped_packet.PutCString("jTraceConfigRead:");
3434
3435 StructuredData::Dictionary json_packet;
3436 json_packet.AddIntegerItem("traceid", uid);
3437
3438 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3439 json_packet.AddIntegerItem("threadid", options.getThreadID());
3440
3441 json_packet.Dump(json_string, false);
3442 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3443
3444 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3445 true) ==
3446 GDBRemoteCommunication::PacketResult::Success) {
3447 if (response.IsNormalResponse()) {
3448 uint64_t type = std::numeric_limits<uint64_t>::max();
3449 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3450 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3451
3452 auto json_object = StructuredData::ParseJSON(response.Peek());
3453
3454 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003455 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003456 error.SetErrorString("Invalid Configuration obtained");
3457 return error;
3458 }
3459
3460 auto json_dict = json_object->GetAsDictionary();
3461
3462 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3463 metabuffersize);
3464 options.setMetaDataBufferSize(metabuffersize);
3465
3466 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3467 options.setTraceBufferSize(buffersize);
3468
3469 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3470 options.setType(static_cast<lldb::TraceType>(type));
3471
3472 StructuredData::ObjectSP custom_params_sp =
3473 json_dict->GetValueForKey("params");
3474 if (custom_params_sp) {
3475 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003476 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003477 error.SetErrorString("Invalid Configuration obtained");
3478 return error;
3479 } else
3480 options.setTraceParams(
3481 static_pointer_cast<StructuredData::Dictionary>(
3482 custom_params_sp));
3483 }
3484 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003485 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003486 }
3487 } else {
3488 LLDB_LOG(log, "failed to send packet");
3489 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3490 escaped_packet.GetData());
3491 }
3492 return error;
3493}
3494
3495Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3496 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3497 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3498 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3499 Status error;
3500
3501 StructuredData::Dictionary json_packet;
3502
3503 json_packet.AddIntegerItem("traceid", uid);
3504 json_packet.AddIntegerItem("offset", offset);
3505 json_packet.AddIntegerItem("buffersize", buffer.size());
3506
3507 if (thread_id != LLDB_INVALID_THREAD_ID)
3508 json_packet.AddIntegerItem("threadid", thread_id);
3509
3510 StreamString json_string;
3511 json_packet.Dump(json_string, false);
3512
3513 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3514 StringExtractorGDBRemote response;
3515 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3516 GDBRemoteCommunication::PacketResult::Success) {
3517 if (response.IsNormalResponse()) {
3518 size_t filled_size = response.GetHexBytesAvail(buffer);
3519 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3520 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003521 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003522 buffer = buffer.slice(buffer.size());
3523 }
3524 } else {
3525 LLDB_LOG(log, "failed to send packet");
3526 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3527 packet.GetData());
3528 buffer = buffer.slice(buffer.size());
3529 }
3530 return error;
3531}
3532
Kate Stoneb9c1b512016-09-06 20:57:50 +00003533bool GDBRemoteCommunicationClient::GetModuleInfo(
3534 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3535 ModuleSpec &module_spec) {
3536 if (!m_supports_qModuleInfo)
3537 return false;
3538
3539 std::string module_path = module_file_spec.GetPath(false);
3540 if (module_path.empty())
3541 return false;
3542
3543 StreamString packet;
3544 packet.PutCString("qModuleInfo:");
Pavel Labath7f815a92019-02-12 14:28:55 +00003545 packet.PutStringAsRawHex8(module_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003546 packet.PutCString(";");
3547 const auto &triple = arch_spec.GetTriple().getTriple();
Pavel Labath7f815a92019-02-12 14:28:55 +00003548 packet.PutStringAsRawHex8(triple);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003549
3550 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003551 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3552 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003553 return false;
3554
3555 if (response.IsErrorResponse())
3556 return false;
3557
3558 if (response.IsUnsupportedResponse()) {
3559 m_supports_qModuleInfo = false;
3560 return false;
3561 }
3562
3563 llvm::StringRef name;
3564 llvm::StringRef value;
3565
3566 module_spec.Clear();
3567 module_spec.GetFileSpec() = module_file_spec;
3568
3569 while (response.GetNameColonValue(name, value)) {
3570 if (name == "uuid" || name == "md5") {
3571 StringExtractor extractor(value);
3572 std::string uuid;
3573 extractor.GetHexByteString(uuid);
Pavel Labatha174bcb2018-06-21 15:24:39 +00003574 module_spec.GetUUID().SetFromStringRef(uuid, uuid.size() / 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003575 } else if (name == "triple") {
3576 StringExtractor extractor(value);
3577 std::string triple;
3578 extractor.GetHexByteString(triple);
3579 module_spec.GetArchitecture().SetTriple(triple.c_str());
3580 } else if (name == "file_offset") {
3581 uint64_t ival = 0;
3582 if (!value.getAsInteger(16, ival))
3583 module_spec.SetObjectOffset(ival);
3584 } else if (name == "file_size") {
3585 uint64_t ival = 0;
3586 if (!value.getAsInteger(16, ival))
3587 module_spec.SetObjectSize(ival);
3588 } else if (name == "file_path") {
3589 StringExtractor extractor(value);
3590 std::string path;
3591 extractor.GetHexByteString(path);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003592 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003593 }
3594 }
3595
3596 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003597}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003598
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003599static llvm::Optional<ModuleSpec>
3600ParseModuleSpec(StructuredData::Dictionary *dict) {
3601 ModuleSpec result;
3602 if (!dict)
3603 return llvm::None;
3604
Zachary Turner28333212017-05-12 05:49:54 +00003605 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003606 uint64_t integer;
3607
3608 if (!dict->GetValueForKeyAsString("uuid", string))
3609 return llvm::None;
Pavel Labath8c92c892017-12-18 14:31:44 +00003610 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3611 string.size())
3612 return llvm::None;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003613
3614 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3615 return llvm::None;
3616 result.SetObjectOffset(integer);
3617
3618 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3619 return llvm::None;
3620 result.SetObjectSize(integer);
3621
3622 if (!dict->GetValueForKeyAsString("triple", string))
3623 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003624 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003625
3626 if (!dict->GetValueForKeyAsString("file_path", string))
3627 return llvm::None;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00003628 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003629
3630 return result;
3631}
3632
3633llvm::Optional<std::vector<ModuleSpec>>
3634GDBRemoteCommunicationClient::GetModulesInfo(
3635 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +00003636 namespace json = llvm::json;
3637
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003638 if (!m_supports_jModulesInfo)
3639 return llvm::None;
3640
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +00003641 json::Array module_array;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003642 for (const FileSpec &module_file_spec : module_file_specs) {
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +00003643 module_array.push_back(
3644 json::Object{{"file", module_file_spec.GetPath(false)},
3645 {"triple", triple.getTriple()}});
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003646 }
3647 StreamString unescaped_payload;
3648 unescaped_payload.PutCString("jModulesInfo:");
Jonas Devlieghere2a5a9062019-10-02 18:02:26 +00003649 unescaped_payload.AsRawOstream() << std::move(module_array);
3650
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003651 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003652 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003653 unescaped_payload.GetSize());
3654
Greg Clayton70a9f512017-04-14 17:10:04 +00003655 // Increase the timeout for jModulesInfo since this packet can take longer.
3656 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3657
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003658 StringExtractorGDBRemote response;
3659 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3660 PacketResult::Success ||
3661 response.IsErrorResponse())
3662 return llvm::None;
3663
3664 if (response.IsUnsupportedResponse()) {
3665 m_supports_jModulesInfo = false;
3666 return llvm::None;
3667 }
3668
3669 StructuredData::ObjectSP response_object_sp =
3670 StructuredData::ParseJSON(response.GetStringRef());
3671 if (!response_object_sp)
3672 return llvm::None;
3673
3674 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3675 if (!response_array)
3676 return llvm::None;
3677
3678 std::vector<ModuleSpec> result;
3679 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3680 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3681 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3682 result.push_back(*module_spec);
3683 }
3684
3685 return result;
3686}
3687
Colin Rileyc3c95b22015-04-16 15:51:33 +00003688// query the target remote for extended information using the qXfer packet
3689//
Adrian Prantl05097242018-04-30 16:49:04 +00003690// example: object='features', annex='target.xml', out=<xml output> return:
3691// 'true' on success
Colin Rileyc3c95b22015-04-16 15:51:33 +00003692// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003693bool GDBRemoteCommunicationClient::ReadExtFeature(
3694 const lldb_private::ConstString object,
3695 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003696 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003697
Kate Stoneb9c1b512016-09-06 20:57:50 +00003698 std::stringstream output;
3699 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003700
Kate Stoneb9c1b512016-09-06 20:57:50 +00003701 uint64_t size = GetRemoteMaxPacketSize();
3702 if (size == 0)
3703 size = 0x1000;
3704 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3705 int offset = 0;
3706 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003707
Kate Stoneb9c1b512016-09-06 20:57:50 +00003708 // loop until all data has been read
3709 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003710
Kate Stoneb9c1b512016-09-06 20:57:50 +00003711 // send query extended feature packet
3712 std::stringstream packet;
3713 packet << "qXfer:" << object.AsCString("")
3714 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3715 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003716
Kate Stoneb9c1b512016-09-06 20:57:50 +00003717 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003718 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003719
Kate Stoneb9c1b512016-09-06 20:57:50 +00003720 if (res != GDBRemoteCommunication::PacketResult::Success) {
3721 err.SetErrorString("Error sending $qXfer packet");
3722 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003723 }
3724
Kate Stoneb9c1b512016-09-06 20:57:50 +00003725 const std::string &str = chunk.GetStringRef();
3726 if (str.length() == 0) {
3727 // should have some data in chunk
3728 err.SetErrorString("Empty response from $qXfer packet");
3729 return false;
3730 }
3731
3732 // check packet code
3733 switch (str[0]) {
3734 // last chunk
3735 case ('l'):
3736 active = false;
3737 LLVM_FALLTHROUGH;
3738
3739 // more chunks
3740 case ('m'):
3741 if (str.length() > 1)
3742 output << &str[1];
Jason Molenda02113912020-01-09 16:05:38 -08003743 offset += str.length() - 1;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003744 break;
3745
3746 // unknown chunk
3747 default:
3748 err.SetErrorString("Invalid continuation code from $qXfer packet");
3749 return false;
3750 }
3751 }
3752
3753 out = output.str();
3754 err.Success();
3755 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003756}
Greg Clayton0b90be12015-06-23 21:27:50 +00003757
3758// Notify the target that gdb is prepared to serve symbol lookup requests.
3759// packet: "qSymbol::"
3760// reply:
3761// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003762// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3763// encoded).
3764// LLDB may provide the value by sending another qSymbol
3765// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003766// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003767//
3768// Three examples:
3769//
3770// lldb sends: qSymbol::
3771// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003772// Remote gdb stub does not need to know the addresses of any symbols, lldb
3773// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003774// need to ask again in this session.
3775//
3776// lldb sends: qSymbol::
3777// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3778// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3779// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003780// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3781// not know
3782// the address at this time. lldb needs to send qSymbol:: again when it has
3783// more
Jason Molenda50018d32016-01-13 04:08:10 +00003784// solibs loaded.
3785//
3786// lldb sends: qSymbol::
3787// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3788// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3789// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003790// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3791// that it
3792// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3793// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003794// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003795
Kate Stoneb9c1b512016-09-06 20:57:50 +00003796void GDBRemoteCommunicationClient::ServeSymbolLookups(
3797 lldb_private::Process *process) {
Adrian Prantl05097242018-04-30 16:49:04 +00003798 // Set to true once we've resolved a symbol to an address for the remote
3799 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3800 // any more symbols and we can stop asking.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003801 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003802
Kate Stoneb9c1b512016-09-06 20:57:50 +00003803 // Is this the initial qSymbol:: packet?
3804 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003805
Jonas Devliegherea6682a42018-12-15 00:15:33 +00003806 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003807 Lock lock(*this, false);
3808 if (lock) {
3809 StreamString packet;
3810 packet.PutCString("qSymbol::");
3811 StringExtractorGDBRemote response;
3812 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3813 PacketResult::Success) {
3814 if (response.IsOKResponse()) {
3815 if (symbol_response_provided || first_qsymbol_query) {
3816 m_qSymbol_requests_done = true;
3817 }
3818
3819 // We are done serving symbols requests
3820 return;
3821 }
3822 first_qsymbol_query = false;
3823
3824 if (response.IsUnsupportedResponse()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003825 // qSymbol is not supported by the current GDB server we are
3826 // connected to
Kate Stoneb9c1b512016-09-06 20:57:50 +00003827 m_supports_qSymbol = false;
3828 return;
3829 } else {
3830 llvm::StringRef response_str(response.GetStringRef());
3831 if (response_str.startswith("qSymbol:")) {
3832 response.SetFilePos(strlen("qSymbol:"));
3833 std::string symbol_name;
3834 if (response.GetHexByteString(symbol_name)) {
3835 if (symbol_name.empty())
3836 return;
3837
3838 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3839 lldb_private::SymbolContextList sc_list;
Adrian Prantl1ad655e2019-10-17 19:56:40 +00003840 process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3841 ConstString(symbol_name), eSymbolTypeAny, sc_list);
3842 if (!sc_list.IsEmpty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003843 const size_t num_scs = sc_list.GetSize();
3844 for (size_t sc_idx = 0;
3845 sc_idx < num_scs &&
3846 symbol_load_addr == LLDB_INVALID_ADDRESS;
3847 ++sc_idx) {
3848 SymbolContext sc;
3849 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3850 if (sc.symbol) {
3851 switch (sc.symbol->GetType()) {
3852 case eSymbolTypeInvalid:
3853 case eSymbolTypeAbsolute:
3854 case eSymbolTypeUndefined:
3855 case eSymbolTypeSourceFile:
3856 case eSymbolTypeHeaderFile:
3857 case eSymbolTypeObjectFile:
3858 case eSymbolTypeCommonBlock:
3859 case eSymbolTypeBlock:
3860 case eSymbolTypeLocal:
3861 case eSymbolTypeParam:
3862 case eSymbolTypeVariable:
3863 case eSymbolTypeVariableType:
3864 case eSymbolTypeLineEntry:
3865 case eSymbolTypeLineHeader:
3866 case eSymbolTypeScopeBegin:
3867 case eSymbolTypeScopeEnd:
3868 case eSymbolTypeAdditional:
3869 case eSymbolTypeCompiler:
3870 case eSymbolTypeInstrumentation:
3871 case eSymbolTypeTrampoline:
3872 break;
3873
3874 case eSymbolTypeCode:
3875 case eSymbolTypeResolver:
3876 case eSymbolTypeData:
3877 case eSymbolTypeRuntime:
3878 case eSymbolTypeException:
3879 case eSymbolTypeObjCClass:
3880 case eSymbolTypeObjCMetaClass:
3881 case eSymbolTypeObjCIVar:
3882 case eSymbolTypeReExported:
3883 symbol_load_addr =
3884 sc.symbol->GetLoadAddress(&process->GetTarget());
3885 break;
3886 }
Jason Molenda50018d32016-01-13 04:08:10 +00003887 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003888 }
Greg Clayton42b01482015-08-11 22:07:46 +00003889 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003890 }
3891 // This is the normal path where our symbol lookup was successful
Adrian Prantl05097242018-04-30 16:49:04 +00003892 // and we want to send a packet with the new symbol value and see
3893 // if another lookup needs to be done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003894
Kate Stoneb9c1b512016-09-06 20:57:50 +00003895 // Change "packet" to contain the requested symbol value and name
3896 packet.Clear();
3897 packet.PutCString("qSymbol:");
3898 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3899 packet.Printf("%" PRIx64, symbol_load_addr);
3900 symbol_response_provided = true;
3901 } else {
3902 symbol_response_provided = false;
3903 }
3904 packet.PutCString(":");
3905 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3906 continue; // go back to the while loop and send "packet" and wait
3907 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003908 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003909 }
3910 }
3911 }
3912 // If we make it here, the symbol request packet response wasn't valid or
3913 // our symbol lookup failed so we must abort
3914 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003915
Kate Stoneb9c1b512016-09-06 20:57:50 +00003916 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3917 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003918 LLDB_LOGF(log,
3919 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3920 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003921 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003922 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003923}
3924
Kate Stoneb9c1b512016-09-06 20:57:50 +00003925StructuredData::Array *
3926GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3927 if (!m_supported_async_json_packets_is_valid) {
Adrian Prantl05097242018-04-30 16:49:04 +00003928 // Query the server for the array of supported asynchronous JSON packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003929 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003930
Kate Stoneb9c1b512016-09-06 20:57:50 +00003931 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003932
Kate Stoneb9c1b512016-09-06 20:57:50 +00003933 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003934 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003935 const bool send_async = false;
3936 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3937 send_async) == PacketResult::Success) {
3938 m_supported_async_json_packets_sp =
3939 StructuredData::ParseJSON(response.GetStringRef());
3940 if (m_supported_async_json_packets_sp &&
3941 !m_supported_async_json_packets_sp->GetAsArray()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003942 // We were returned something other than a JSON array. This is
3943 // invalid. Clear it out.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003944 LLDB_LOGF(log,
3945 "GDBRemoteCommunicationClient::%s(): "
3946 "QSupportedAsyncJSONPackets returned invalid "
3947 "result: %s",
Jonas Devlieghered35b42f2019-08-21 04:55:56 +00003948 __FUNCTION__, response.GetStringRef().data());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003949 m_supported_async_json_packets_sp.reset();
3950 }
3951 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003952 LLDB_LOGF(log,
3953 "GDBRemoteCommunicationClient::%s(): "
3954 "QSupportedAsyncJSONPackets unsupported",
3955 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003956 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003957
3958 if (log && m_supported_async_json_packets_sp) {
3959 StreamString stream;
3960 m_supported_async_json_packets_sp->Dump(stream);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003961 LLDB_LOGF(log,
3962 "GDBRemoteCommunicationClient::%s(): supported async "
3963 "JSON packets: %s",
3964 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003965 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003966 }
3967
3968 return m_supported_async_json_packets_sp
3969 ? m_supported_async_json_packets_sp->GetAsArray()
3970 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003971}
3972
Zachary Turner97206d52017-05-12 04:51:55 +00003973Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003974 llvm::ArrayRef<int32_t> signals) {
3975 // Format packet:
3976 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3977 auto range = llvm::make_range(signals.begin(), signals.end());
3978 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3979
3980 StringExtractorGDBRemote response;
3981 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3982
3983 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003984 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003985
3986 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003987 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003988 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003989 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003990 }
3991}
3992
Zachary Turner97206d52017-05-12 04:51:55 +00003993Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003994 ConstString type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003995 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003996
3997 if (type_name.GetLength() == 0) {
3998 error.SetErrorString("invalid type_name argument");
3999 return error;
4000 }
4001
Adrian Prantl05097242018-04-30 16:49:04 +00004002 // Build command: Configure{type_name}: serialized config data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004003 StreamGDBRemote stream;
4004 stream.PutCString("QConfigure");
4005 stream.PutCString(type_name.AsCString());
4006 stream.PutChar(':');
4007 if (config_sp) {
4008 // Gather the plain-text version of the configuration data.
4009 StreamString unescaped_stream;
4010 config_sp->Dump(unescaped_stream);
4011 unescaped_stream.Flush();
4012
4013 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00004014 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00004015 unescaped_stream.GetSize());
4016 }
4017 stream.Flush();
4018
4019 // Send the packet.
4020 const bool send_async = false;
4021 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00004022 auto result =
4023 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004024 if (result == PacketResult::Success) {
4025 // We failed if the config result comes back other than OK.
Jonas Devlieghered35b42f2019-08-21 04:55:56 +00004026 if (strcmp(response.GetStringRef().data(), "OK") == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004027 // Okay!
4028 error.Clear();
4029 } else {
4030 error.SetErrorStringWithFormat("configuring StructuredData feature "
4031 "%s failed with error %s",
4032 type_name.AsCString(),
Jonas Devlieghered35b42f2019-08-21 04:55:56 +00004033 response.GetStringRef().data());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004034 }
4035 } else {
4036 // Can we get more data here on the failure?
4037 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4038 "failed when sending packet: "
4039 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00004040 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004041 }
4042 return error;
4043}
4044
4045void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4046 GDBRemoteClientBase::OnRunPacketSent(first);
4047 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004048}