blob: ebeba059f36d53e33682870f29acdea3479bc68e [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#include "GDBRemoteCommunicationClient.h"
12
13// C Includes
Greg Claytone034a042015-05-21 20:52:06 +000014#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000015#include <sys/stat.h>
16
Greg Clayton576d8832011-03-22 04:00:09 +000017// C++ Includes
Han Ming Ong4b6459f2013-01-18 23:11:53 +000018#include <sstream>
Greg Claytone034a042015-05-21 20:52:06 +000019#include <numeric>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000020
Greg Clayton576d8832011-03-22 04:00:09 +000021// Other libraries and framework includes
Greg Clayton576d8832011-03-22 04:00:09 +000022#include "lldb/Core/Log.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000023#include "lldb/Core/ModuleSpec.h"
Greg Clayton576d8832011-03-22 04:00:09 +000024#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000025#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000026#include "lldb/Core/StreamString.h"
Pavel Labathb42b48e2016-08-19 12:31:49 +000027#include "lldb/Core/DataBufferHeap.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000028#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000029#include "lldb/Host/StringConvert.h"
Greg Clayton576d8832011-03-22 04:00:09 +000030#include "lldb/Host/TimeValue.h"
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000031#include "lldb/Interpreter/Args.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000032#include "lldb/Symbol/Symbol.h"
Pavel Labath4cb69922016-07-29 15:41:52 +000033#include "lldb/Target/MemoryRegionInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000034#include "lldb/Target/UnixSignals.h"
35#include "lldb/Utility/LLDBAssert.h"
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000036#include "lldb/Target/Target.h"
Greg Clayton576d8832011-03-22 04:00:09 +000037
38// Project includes
39#include "Utility/StringExtractorGDBRemote.h"
40#include "ProcessGDBRemote.h"
41#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000042#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000043
Zachary Turner54695a32016-08-29 19:58:14 +000044#include "llvm/ADT/StringSwitch.h"
45
Jason Molenda91ffe0a2015-06-18 21:46:06 +000046#if defined (HAVE_LIBCOMPRESSION)
47#include <compression.h>
48#endif
49
Greg Clayton576d8832011-03-22 04:00:09 +000050using namespace lldb;
51using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000052using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000053
54//----------------------------------------------------------------------
55// GDBRemoteCommunicationClient constructor
56//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000057GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000058 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000059 m_supports_not_sending_acks(eLazyBoolCalculate),
60 m_supports_thread_suffix(eLazyBoolCalculate),
61 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
62 m_supports_vCont_all(eLazyBoolCalculate),
63 m_supports_vCont_any(eLazyBoolCalculate),
64 m_supports_vCont_c(eLazyBoolCalculate),
65 m_supports_vCont_C(eLazyBoolCalculate),
66 m_supports_vCont_s(eLazyBoolCalculate),
67 m_supports_vCont_S(eLazyBoolCalculate),
68 m_qHostInfo_is_valid(eLazyBoolCalculate),
69 m_curr_pid_is_valid(eLazyBoolCalculate),
70 m_qProcessInfo_is_valid(eLazyBoolCalculate),
71 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
72 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
73 m_supports_memory_region_info(eLazyBoolCalculate),
74 m_supports_watchpoint_support_info(eLazyBoolCalculate),
75 m_supports_detach_stay_stopped(eLazyBoolCalculate),
76 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
77 m_attach_or_wait_reply(eLazyBoolCalculate),
78 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
79 m_supports_p(eLazyBoolCalculate),
80 m_supports_x(eLazyBoolCalculate),
81 m_avoid_g_packets(eLazyBoolCalculate),
82 m_supports_QSaveRegisterState(eLazyBoolCalculate),
83 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
84 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
85 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
86 m_supports_qXfer_features_read(eLazyBoolCalculate),
87 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
88 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
89 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000090 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000091 m_supports_qProcessInfoPID(true),
92 m_supports_qfProcessInfo(true),
93 m_supports_qUserName(true),
94 m_supports_qGroupName(true),
95 m_supports_qThreadStopInfo(true),
96 m_supports_z0(true),
97 m_supports_z1(true),
98 m_supports_z2(true),
99 m_supports_z3(true),
100 m_supports_z4(true),
101 m_supports_QEnvironment(true),
102 m_supports_QEnvironmentHexEncoded(true),
103 m_supports_qSymbol(true),
104 m_qSymbol_requests_done(false),
105 m_supports_qModuleInfo(true),
106 m_supports_jThreadsInfo(true),
107 m_curr_pid(LLDB_INVALID_PROCESS_ID),
108 m_curr_tid(LLDB_INVALID_THREAD_ID),
109 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
110 m_num_supported_hardware_watchpoints(0),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000111 m_host_arch(),
112 m_process_arch(),
113 m_os_version_major(UINT32_MAX),
114 m_os_version_minor(UINT32_MAX),
115 m_os_version_update(UINT32_MAX),
116 m_os_build(),
117 m_os_kernel(),
118 m_hostname(),
119 m_gdb_server_name(),
120 m_gdb_server_version(UINT32_MAX),
121 m_default_packet_timeout(0),
Todd Fiala75930012016-08-19 04:21:48 +0000122 m_max_packet_size(0),
123 m_qSupported_response(),
124 m_supported_async_json_packets_is_valid(false),
125 m_supported_async_json_packets_sp()
Greg Clayton576d8832011-03-22 04:00:09 +0000126{
Greg Clayton576d8832011-03-22 04:00:09 +0000127}
128
129//----------------------------------------------------------------------
130// Destructor
131//----------------------------------------------------------------------
132GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
133{
Greg Clayton576d8832011-03-22 04:00:09 +0000134 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000135 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000136}
137
138bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000139GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
140{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000141 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000142
Greg Clayton1cb64962011-03-24 04:28:38 +0000143 // Start the read thread after we send the handshake ack since if we
144 // fail to send the handshake ack, there is no reason to continue...
145 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000146 {
Ed Maste48f986f2013-12-18 15:31:45 +0000147 // Wait for any responses that might have been queued up in the remote
148 // GDB server and flush them all
149 StringExtractorGDBRemote response;
150 PacketResult packet_result = PacketResult::Success;
151 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
152 while (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000153 packet_result = ReadPacket (response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000154
Greg Claytonfb909312013-11-23 01:58:15 +0000155 // The return value from QueryNoAckModeSupported() is true if the packet
156 // was sent and _any_ response (including UNIMPLEMENTED) was received),
157 // or false if no response was received. This quickly tells us if we have
158 // a live connection to a remote GDB server...
159 if (QueryNoAckModeSupported())
160 {
161 return true;
162 }
163 else
164 {
165 if (error_ptr)
166 error_ptr->SetErrorString("failed to get reply to handshake packet");
167 }
168 }
169 else
170 {
171 if (error_ptr)
172 error_ptr->SetErrorString("failed to send the handshake ack");
173 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000174 return false;
175}
176
Greg Claytonfb909312013-11-23 01:58:15 +0000177bool
Greg Claytonb30c50c2015-05-29 00:01:55 +0000178GDBRemoteCommunicationClient::GetEchoSupported ()
179{
180 if (m_supports_qEcho == eLazyBoolCalculate)
181 {
182 GetRemoteQSupported();
183 }
184 return m_supports_qEcho == eLazyBoolYes;
185}
186
187
188bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000189GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
190{
191 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
192 {
193 GetRemoteQSupported();
194 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000195 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000196}
197
198bool
199GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
200{
201 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
202 {
203 GetRemoteQSupported();
204 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000205 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000206}
207
208bool
209GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
210{
211 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
212 {
213 GetRemoteQSupported();
214 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000215 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000216}
217
Steve Pucci03904ac2014-03-04 23:18:46 +0000218bool
219GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
220{
221 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
222 {
223 GetRemoteQSupported();
224 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000225 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000226}
227
Colin Rileyc3c95b22015-04-16 15:51:33 +0000228bool
229GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
230{
231 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
232 {
233 GetRemoteQSupported();
234 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000235 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000236}
237
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000238uint64_t
239GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
240{
241 if (m_max_packet_size == 0)
242 {
243 GetRemoteQSupported();
244 }
245 return m_max_packet_size;
246}
247
248bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000249GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000250{
251 if (m_supports_not_sending_acks == eLazyBoolCalculate)
252 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000253 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000254 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000255
Jason Molenda36a216e2014-07-24 01:36:24 +0000256 // This is the first real packet that we'll send in a debug session and it may take a little
257 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
258
259 const uint32_t minimum_timeout = 6;
260 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000261 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000262
Greg Clayton1cb64962011-03-24 04:28:38 +0000263 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000264 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000265 {
266 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000267 {
268 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000269 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000270 }
Greg Claytonfb909312013-11-23 01:58:15 +0000271 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000272 }
273 }
Greg Claytonfb909312013-11-23 01:58:15 +0000274 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000275}
276
277void
Greg Clayton44633992012-04-10 03:22:03 +0000278GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
279{
280 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
281 {
282 m_supports_threads_in_stop_reply = eLazyBoolNo;
283
284 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000285 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000286 {
287 if (response.IsOKResponse())
288 m_supports_threads_in_stop_reply = eLazyBoolYes;
289 }
290 }
291}
292
Jim Inghamcd16df92012-07-20 21:37:13 +0000293bool
294GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
295{
296 if (m_attach_or_wait_reply == eLazyBoolCalculate)
297 {
298 m_attach_or_wait_reply = eLazyBoolNo;
299
300 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000301 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000302 {
303 if (response.IsOKResponse())
304 m_attach_or_wait_reply = eLazyBoolYes;
305 }
306 }
307 if (m_attach_or_wait_reply == eLazyBoolYes)
308 return true;
309 else
310 return false;
311}
312
Jim Ingham279ceec2012-07-25 21:12:43 +0000313bool
314GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
315{
316 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
317 {
318 m_prepare_for_reg_writing_reply = eLazyBoolNo;
319
320 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000321 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000322 {
323 if (response.IsOKResponse())
324 m_prepare_for_reg_writing_reply = eLazyBoolYes;
325 }
326 }
327 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
328 return true;
329 else
330 return false;
331}
332
Greg Clayton44633992012-04-10 03:22:03 +0000333
334void
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000335GDBRemoteCommunicationClient::ResetDiscoverableSettings (bool did_exec)
Greg Clayton576d8832011-03-22 04:00:09 +0000336{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000337 if (did_exec == false)
338 {
339 // Hard reset everything, this is when we first connect to a GDB server
340 m_supports_not_sending_acks = eLazyBoolCalculate;
341 m_supports_thread_suffix = eLazyBoolCalculate;
342 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
343 m_supports_vCont_c = eLazyBoolCalculate;
344 m_supports_vCont_C = eLazyBoolCalculate;
345 m_supports_vCont_s = eLazyBoolCalculate;
346 m_supports_vCont_S = eLazyBoolCalculate;
347 m_supports_p = eLazyBoolCalculate;
348 m_supports_x = eLazyBoolCalculate;
349 m_supports_QSaveRegisterState = eLazyBoolCalculate;
350 m_qHostInfo_is_valid = eLazyBoolCalculate;
351 m_curr_pid_is_valid = eLazyBoolCalculate;
352 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
353 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
354 m_supports_memory_region_info = eLazyBoolCalculate;
355 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
356 m_attach_or_wait_reply = eLazyBoolCalculate;
357 m_avoid_g_packets = eLazyBoolCalculate;
358 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
359 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
360 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
361 m_supports_qXfer_features_read = eLazyBoolCalculate;
362 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
363 m_supports_qProcessInfoPID = true;
364 m_supports_qfProcessInfo = true;
365 m_supports_qUserName = true;
366 m_supports_qGroupName = true;
367 m_supports_qThreadStopInfo = true;
368 m_supports_z0 = true;
369 m_supports_z1 = true;
370 m_supports_z2 = true;
371 m_supports_z3 = true;
372 m_supports_z4 = true;
373 m_supports_QEnvironment = true;
374 m_supports_QEnvironmentHexEncoded = true;
375 m_supports_qSymbol = true;
Jason Molenda50018d32016-01-13 04:08:10 +0000376 m_qSymbol_requests_done = false;
Stephane Sezer6f455292016-01-08 00:00:17 +0000377 m_supports_qModuleInfo = true;
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000378 m_host_arch.Clear();
379 m_os_version_major = UINT32_MAX;
380 m_os_version_minor = UINT32_MAX;
381 m_os_version_update = UINT32_MAX;
382 m_os_build.clear();
383 m_os_kernel.clear();
384 m_hostname.clear();
385 m_gdb_server_name.clear();
386 m_gdb_server_version = UINT32_MAX;
387 m_default_packet_timeout = 0;
388 m_max_packet_size = 0;
Todd Fiala75930012016-08-19 04:21:48 +0000389 m_qSupported_response.clear();
390 m_supported_async_json_packets_is_valid = false;
391 m_supported_async_json_packets_sp.reset();
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000392 }
393
394 // These flags should be reset when we first connect to a GDB server
395 // and when our inferior process execs
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000396 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000397 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000398}
399
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000400void
401GDBRemoteCommunicationClient::GetRemoteQSupported ()
402{
403 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000404 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000405 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000406 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000407 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000408 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000409 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
410
Colin Rileyc3c95b22015-04-16 15:51:33 +0000411 // build the qSupported packet
412 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
413 StreamString packet;
414 packet.PutCString( "qSupported" );
415 for ( uint32_t i = 0; i < features.size( ); ++i )
416 {
417 packet.PutCString( i==0 ? ":" : ";");
418 packet.PutCString( features[i].c_str( ) );
419 }
420
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000421 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000422 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000423 response,
424 /*send_async=*/false) == PacketResult::Success)
425 {
426 const char *response_cstr = response.GetStringRef().c_str();
Todd Fiala75930012016-08-19 04:21:48 +0000427
428 // Hang on to the qSupported packet, so that platforms can do custom
429 // configuration of the transport before attaching/launching the
430 // process.
431 m_qSupported_response = response_cstr;
432
Steve Pucci03904ac2014-03-04 23:18:46 +0000433 if (::strstr (response_cstr, "qXfer:auxv:read+"))
434 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000435 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
436 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
437 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
438 {
439 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
440 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
441 }
442 if (::strstr (response_cstr, "qXfer:libraries:read+"))
443 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000444 if (::strstr (response_cstr, "qXfer:features:read+"))
445 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000446
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000447
448 // Look for a list of compressions in the features list e.g.
449 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
450 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
451 if (features_list)
452 {
453 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
454 if (compressions)
455 {
456 std::vector<std::string> supported_compressions;
457 compressions += sizeof ("SupportedCompressions=") - 1;
458 const char *end_of_compressions = strchr (compressions, ';');
459 if (end_of_compressions == NULL)
460 {
461 end_of_compressions = strchr (compressions, '\0');
462 }
463 const char *current_compression = compressions;
464 while (current_compression < end_of_compressions)
465 {
466 const char *next_compression_name = strchr (current_compression, ',');
467 const char *end_of_this_word = next_compression_name;
468 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
469 {
470 end_of_this_word = end_of_compressions;
471 }
472
473 if (end_of_this_word)
474 {
475 if (end_of_this_word == current_compression)
476 {
477 current_compression++;
478 }
479 else
480 {
481 std::string this_compression (current_compression, end_of_this_word - current_compression);
482 supported_compressions.push_back (this_compression);
483 current_compression = end_of_this_word + 1;
484 }
485 }
486 else
487 {
488 supported_compressions.push_back (current_compression);
489 current_compression = end_of_compressions;
490 }
491 }
492
493 if (supported_compressions.size() > 0)
494 {
495 MaybeEnableCompression (supported_compressions);
496 }
497 }
498 }
499
Greg Claytonb30c50c2015-05-29 00:01:55 +0000500 if (::strstr (response_cstr, "qEcho"))
501 m_supports_qEcho = eLazyBoolYes;
502 else
503 m_supports_qEcho = eLazyBoolNo;
504
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000505 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
506 if (packet_size_str)
507 {
508 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
509 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
510 if (m_max_packet_size == 0)
511 {
512 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
513 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
514 if (log)
515 log->Printf ("Garbled PacketSize spec in qSupported response");
516 }
517 }
518 }
519}
Greg Clayton576d8832011-03-22 04:00:09 +0000520
Pavel Labath0faf3732016-08-25 08:34:57 +0000521void
522GDBRemoteCommunicationClient::ComputeThreadSuffixSupport()
Greg Clayton576d8832011-03-22 04:00:09 +0000523{
Pavel Labath0faf3732016-08-25 08:34:57 +0000524 if (m_supports_thread_suffix != eLazyBoolCalculate)
525 return;
526
527 StringExtractorGDBRemote response;
528 m_supports_thread_suffix = eLazyBoolNo;
529 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000530 {
Pavel Labath0faf3732016-08-25 08:34:57 +0000531 if (response.IsOKResponse())
532 m_supports_thread_suffix = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000533 }
Greg Clayton576d8832011-03-22 04:00:09 +0000534}
Pavel Labath0faf3732016-08-25 08:34:57 +0000535
536bool
537GDBRemoteCommunicationClient::GetThreadSuffixSupported()
538{
539 return m_supports_thread_suffix == eLazyBoolYes;
540}
541
Greg Clayton576d8832011-03-22 04:00:09 +0000542bool
543GDBRemoteCommunicationClient::GetVContSupported (char flavor)
544{
545 if (m_supports_vCont_c == eLazyBoolCalculate)
546 {
547 StringExtractorGDBRemote response;
548 m_supports_vCont_any = eLazyBoolNo;
549 m_supports_vCont_all = eLazyBoolNo;
550 m_supports_vCont_c = eLazyBoolNo;
551 m_supports_vCont_C = eLazyBoolNo;
552 m_supports_vCont_s = eLazyBoolNo;
553 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000554 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000555 {
556 const char *response_cstr = response.GetStringRef().c_str();
557 if (::strstr (response_cstr, ";c"))
558 m_supports_vCont_c = eLazyBoolYes;
559
560 if (::strstr (response_cstr, ";C"))
561 m_supports_vCont_C = eLazyBoolYes;
562
563 if (::strstr (response_cstr, ";s"))
564 m_supports_vCont_s = eLazyBoolYes;
565
566 if (::strstr (response_cstr, ";S"))
567 m_supports_vCont_S = eLazyBoolYes;
568
569 if (m_supports_vCont_c == eLazyBoolYes &&
570 m_supports_vCont_C == eLazyBoolYes &&
571 m_supports_vCont_s == eLazyBoolYes &&
572 m_supports_vCont_S == eLazyBoolYes)
573 {
574 m_supports_vCont_all = eLazyBoolYes;
575 }
576
577 if (m_supports_vCont_c == eLazyBoolYes ||
578 m_supports_vCont_C == eLazyBoolYes ||
579 m_supports_vCont_s == eLazyBoolYes ||
580 m_supports_vCont_S == eLazyBoolYes)
581 {
582 m_supports_vCont_any = eLazyBoolYes;
583 }
584 }
585 }
586
587 switch (flavor)
588 {
589 case 'a': return m_supports_vCont_any;
590 case 'A': return m_supports_vCont_all;
591 case 'c': return m_supports_vCont_c;
592 case 'C': return m_supports_vCont_C;
593 case 's': return m_supports_vCont_s;
594 case 'S': return m_supports_vCont_S;
595 default: break;
596 }
597 return false;
598}
599
Pavel Labath4b6f9592016-08-18 08:30:03 +0000600GDBRemoteCommunication::PacketResult
601GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(lldb::tid_t tid, StreamString &&payload,
602 StringExtractorGDBRemote &response,
Pavel Labath0faf3732016-08-25 08:34:57 +0000603 const Lock &lock)
Pavel Labath4b6f9592016-08-18 08:30:03 +0000604{
Pavel Labath4b6f9592016-08-18 08:30:03 +0000605 if (GetThreadSuffixSupported())
606 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
607 else
608 {
Pavel Labath0faf3732016-08-25 08:34:57 +0000609 if (!SetCurrentThread(tid, lock))
Pavel Labath4b6f9592016-08-18 08:30:03 +0000610 return PacketResult::ErrorSendFailed;
611 }
612
Pavel Labath0faf3732016-08-25 08:34:57 +0000613 return SendPacketAndWaitForResponse(payload.GetString(), response, lock);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000614}
615
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000616// Check if the target supports 'p' packet. It sends out a 'p'
617// packet and checks the response. A normal packet will tell us
618// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000619//
620// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000621bool
Sean Callananb1de1142013-09-04 23:24:15 +0000622GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000623{
624 if (m_supports_p == eLazyBoolCalculate)
625 {
Pavel Labath0faf3732016-08-25 08:34:57 +0000626 Lock lock(*this, false);
627 if (!lock)
628 {
629 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
630 if (log)
631 log->Printf("GDBRemoteCommunicationClient::%s failed to get sequence mutex", __FUNCTION__);
632 return false;
633 }
634
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000635 m_supports_p = eLazyBoolNo;
Pavel Labath4b6f9592016-08-18 08:30:03 +0000636 StreamString payload;
637 payload.PutCString("p0");
638 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +0000639 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) ==
Pavel Labath4b6f9592016-08-18 08:30:03 +0000640 PacketResult::Success &&
641 response.IsNormalResponse())
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000642 {
Pavel Labath4b6f9592016-08-18 08:30:03 +0000643 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000644 }
645 }
646 return m_supports_p;
647}
Greg Clayton576d8832011-03-22 04:00:09 +0000648
Greg Clayton358cf1e2015-06-25 21:46:34 +0000649StructuredData::ObjectSP
650GDBRemoteCommunicationClient::GetThreadsInfo()
651{
652 // Get information on all threads at one using the "jThreadsInfo" packet
653 StructuredData::ObjectSP object_sp;
654
655 if (m_supports_jThreadsInfo)
656 {
657 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +0000658 response.SetResponseValidatorToJSON();
Greg Clayton358cf1e2015-06-25 21:46:34 +0000659 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
660 {
661 if (response.IsUnsupportedResponse())
662 {
663 m_supports_jThreadsInfo = false;
664 }
665 else if (!response.Empty())
666 {
667 object_sp = StructuredData::ParseJSON (response.GetStringRef());
668 }
669 }
670 }
671 return object_sp;
672}
673
674
Jason Molendabdc4f122014-05-06 02:59:39 +0000675bool
Jason Molenda705b1802014-06-13 02:37:02 +0000676GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
677{
678 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
679 {
680 StringExtractorGDBRemote response;
681 m_supports_jThreadExtendedInfo = eLazyBoolNo;
682 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
683 {
684 if (response.IsOKResponse())
685 {
686 m_supports_jThreadExtendedInfo = eLazyBoolYes;
687 }
688 }
689 }
690 return m_supports_jThreadExtendedInfo;
691}
692
693bool
Jason Molenda20ee21b2015-07-10 23:15:22 +0000694GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported ()
695{
696 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate)
697 {
698 StringExtractorGDBRemote response;
699 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
700 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", response, false) == PacketResult::Success)
701 {
702 if (response.IsOKResponse())
703 {
704 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
705 }
706 }
707 }
708 return m_supports_jLoadedDynamicLibrariesInfos;
709}
710
711bool
Jason Molenda37397352016-07-22 00:17:55 +0000712GDBRemoteCommunicationClient::GetSharedCacheInfoSupported ()
713{
714 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate)
715 {
716 StringExtractorGDBRemote response;
717 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
718 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) == PacketResult::Success)
719 {
720 if (response.IsOKResponse())
721 {
722 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
723 }
724 }
725 }
726 return m_supports_jGetSharedCacheInfo;
727}
728
729bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000730GDBRemoteCommunicationClient::GetxPacketSupported ()
731{
732 if (m_supports_x == eLazyBoolCalculate)
733 {
734 StringExtractorGDBRemote response;
735 m_supports_x = eLazyBoolNo;
736 char packet[256];
737 snprintf (packet, sizeof (packet), "x0,0");
738 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
739 {
740 if (response.IsOKResponse())
741 m_supports_x = eLazyBoolYes;
742 }
743 }
744 return m_supports_x;
745}
746
Greg Clayton3dedae12013-12-06 21:45:27 +0000747GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000748GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
749(
750 const char *payload_prefix,
751 std::string &response_string
752)
753{
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000754 Lock lock(*this, false);
755 if (!lock)
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000756 {
757 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
758 if (log)
759 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
760 payload_prefix);
761 return PacketResult::ErrorNoSequenceLock;
762 }
763
764 response_string = "";
765 std::string payload_prefix_str(payload_prefix);
766 unsigned int response_size = 0x1000;
767 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
768 response_size = GetRemoteMaxPacketSize();
769 }
770
771 for (unsigned int offset = 0; true; offset += response_size)
772 {
773 StringExtractorGDBRemote this_response;
774 // Construct payload
775 char sizeDescriptor[128];
776 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
Pavel Labath0faf3732016-08-25 08:34:57 +0000777 PacketResult result = SendPacketAndWaitForResponse(payload_prefix_str + sizeDescriptor, this_response, lock);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000778 if (result != PacketResult::Success)
779 return result;
780
781 const std::string &this_string = this_response.GetStringRef();
782
783 // Check for m or l as first character; l seems to mean this is the last chunk
784 char first_char = *this_string.c_str();
785 if (first_char != 'm' && first_char != 'l')
786 {
787 return PacketResult::ErrorReplyInvalid;
788 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000789 // Concatenate the result so far (skipping 'm' or 'l')
790 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000791 if (first_char == 'l')
792 // We're done
793 return PacketResult::Success;
794 }
795}
796
Greg Clayton576d8832011-03-22 04:00:09 +0000797lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000798GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +0000799{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000800 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000801 return m_curr_pid;
802
803 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000804 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000805 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +0000806 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000807 // We really got it.
808 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +0000809 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000810 else
811 {
Todd Fialae24614f2014-05-14 00:15:32 +0000812 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
813 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
814 // The gdb remote protocol documents $qC as returning the thread id, which newer
815 // debugserver and lldb-gdbserver stubs return correctly.
816 StringExtractorGDBRemote response;
817 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000818 {
Todd Fialae24614f2014-05-14 00:15:32 +0000819 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000820 {
Todd Fialae24614f2014-05-14 00:15:32 +0000821 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000822 {
Todd Fialae24614f2014-05-14 00:15:32 +0000823 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
824 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000825 {
Todd Fialae24614f2014-05-14 00:15:32 +0000826 m_curr_pid_is_valid = eLazyBoolYes;
827 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000828 }
829 }
830 }
831 }
Jaydeep Patil1142f832015-08-13 03:46:36 +0000832
833 // If we don't get a response for $qC, check if $qfThreadID gives us a result.
834 if (m_curr_pid == LLDB_INVALID_PROCESS_ID)
835 {
836 std::vector<lldb::tid_t> thread_ids;
837 bool sequence_mutex_unavailable;
838 size_t size;
839 size = GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
840 if (size && sequence_mutex_unavailable == false)
841 {
842 m_curr_pid = thread_ids.front();
843 m_curr_pid_is_valid = eLazyBoolYes;
844 return m_curr_pid;
845 }
846 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000847 }
848
Greg Clayton576d8832011-03-22 04:00:09 +0000849 return LLDB_INVALID_PROCESS_ID;
850}
851
852bool
853GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
854{
855 error_str.clear();
856 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000857 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000858 {
859 if (response.IsOKResponse())
860 return true;
861 if (response.GetChar() == 'E')
862 {
863 // A string the describes what failed when launching...
864 error_str = response.GetStringRef().substr(1);
865 }
866 else
867 {
868 error_str.assign ("unknown error occurred launching process");
869 }
870 }
871 else
872 {
Jim Ingham98d6da52012-06-28 20:30:23 +0000873 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +0000874 }
875 return false;
876}
877
878int
Greg Claytonfbb76342013-11-20 21:07:01 +0000879GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +0000880{
Greg Claytonfbb76342013-11-20 21:07:01 +0000881 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000882 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +0000883 std::vector<const char *> argv;
884 FileSpec exe_file = launch_info.GetExecutableFile();
885 std::string exe_path;
886 const char *arg = NULL;
887 const Args &launch_args = launch_info.GetArguments();
888 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +0000889 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +0000890 else
891 {
892 arg = launch_args.GetArgumentAtIndex(0);
893 if (arg)
894 exe_path = arg;
895 }
896 if (!exe_path.empty())
897 {
898 argv.push_back(exe_path.c_str());
899 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
900 {
901 if (arg)
902 argv.push_back(arg);
903 }
904 }
905 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +0000906 {
907 StreamString packet;
908 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +0000909 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +0000910 {
Greg Claytonfbb76342013-11-20 21:07:01 +0000911 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +0000912 const int arg_len = strlen(arg);
913 if (i > 0)
914 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +0000915 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +0000916 packet.PutBytesAsRawHex8 (arg, arg_len);
917 }
918
919 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000920 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000921 {
922 if (response.IsOKResponse())
923 return 0;
924 uint8_t error = response.GetError();
925 if (error)
926 return error;
927 }
928 }
929 return -1;
930}
931
932int
933GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
934{
935 if (name_equal_value && name_equal_value[0])
936 {
937 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +0000938 bool send_hex_encoding = false;
939 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +0000940 {
Greg Clayton89600582013-10-10 17:53:50 +0000941 if (isprint(*p))
942 {
943 switch (*p)
944 {
945 case '$':
946 case '#':
Jason Molenda60bdafb2015-11-05 23:51:05 +0000947 case '*':
Tim Northover974ff612015-11-09 22:05:05 +0000948 case '}':
Greg Clayton89600582013-10-10 17:53:50 +0000949 send_hex_encoding = true;
950 break;
951 default:
952 break;
953 }
954 }
955 else
956 {
957 // We have non printable characters, lets hex encode this...
958 send_hex_encoding = true;
959 }
960 }
961
962 StringExtractorGDBRemote response;
963 if (send_hex_encoding)
964 {
965 if (m_supports_QEnvironmentHexEncoded)
966 {
967 packet.PutCString("QEnvironmentHexEncoded:");
968 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +0000969 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +0000970 {
971 if (response.IsOKResponse())
972 return 0;
973 uint8_t error = response.GetError();
974 if (error)
975 return error;
976 if (response.IsUnsupportedResponse())
977 m_supports_QEnvironmentHexEncoded = false;
978 }
979 }
980
981 }
982 else if (m_supports_QEnvironment)
983 {
984 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +0000985 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +0000986 {
987 if (response.IsOKResponse())
988 return 0;
989 uint8_t error = response.GetError();
990 if (error)
991 return error;
992 if (response.IsUnsupportedResponse())
993 m_supports_QEnvironment = false;
994 }
Greg Clayton576d8832011-03-22 04:00:09 +0000995 }
996 }
997 return -1;
998}
999
Greg Claytonc4103b32011-05-08 04:53:50 +00001000int
1001GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1002{
1003 if (arch && arch[0])
1004 {
1005 StreamString packet;
1006 packet.Printf("QLaunchArch:%s", arch);
1007 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001008 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001009 {
1010 if (response.IsOKResponse())
1011 return 0;
1012 uint8_t error = response.GetError();
1013 if (error)
1014 return error;
1015 }
1016 }
1017 return -1;
1018}
1019
Jason Molendaa3329782014-03-29 18:54:20 +00001020int
1021GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1022{
1023 if (data && *data != '\0')
1024 {
1025 StreamString packet;
1026 packet.Printf("QSetProcessEvent:%s", data);
1027 StringExtractorGDBRemote response;
1028 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1029 {
1030 if (response.IsOKResponse())
1031 {
1032 if (was_supported)
1033 *was_supported = true;
1034 return 0;
1035 }
1036 else if (response.IsUnsupportedResponse())
1037 {
1038 if (was_supported)
1039 *was_supported = false;
1040 return -1;
1041 }
1042 else
1043 {
1044 uint8_t error = response.GetError();
1045 if (was_supported)
1046 *was_supported = true;
1047 if (error)
1048 return error;
1049 }
1050 }
1051 }
1052 return -1;
1053}
1054
Greg Clayton576d8832011-03-22 04:00:09 +00001055bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001056GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1057 uint32_t &minor,
1058 uint32_t &update)
1059{
1060 if (GetHostInfo ())
1061 {
1062 if (m_os_version_major != UINT32_MAX)
1063 {
1064 major = m_os_version_major;
1065 minor = m_os_version_minor;
1066 update = m_os_version_update;
1067 return true;
1068 }
1069 }
1070 return false;
1071}
1072
1073bool
1074GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1075{
1076 if (GetHostInfo ())
1077 {
1078 if (!m_os_build.empty())
1079 {
1080 s = m_os_build;
1081 return true;
1082 }
1083 }
1084 s.clear();
1085 return false;
1086}
1087
1088
1089bool
1090GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1091{
1092 if (GetHostInfo ())
1093 {
1094 if (!m_os_kernel.empty())
1095 {
1096 s = m_os_kernel;
1097 return true;
1098 }
1099 }
1100 s.clear();
1101 return false;
1102}
1103
1104bool
1105GDBRemoteCommunicationClient::GetHostname (std::string &s)
1106{
1107 if (GetHostInfo ())
1108 {
1109 if (!m_hostname.empty())
1110 {
1111 s = m_hostname;
1112 return true;
1113 }
1114 }
1115 s.clear();
1116 return false;
1117}
1118
1119ArchSpec
1120GDBRemoteCommunicationClient::GetSystemArchitecture ()
1121{
1122 if (GetHostInfo ())
1123 return m_host_arch;
1124 return ArchSpec();
1125}
1126
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001127const lldb_private::ArchSpec &
1128GDBRemoteCommunicationClient::GetProcessArchitecture ()
1129{
1130 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1131 GetCurrentProcessInfo ();
1132 return m_process_arch;
1133}
1134
Jason Molendaa3329782014-03-29 18:54:20 +00001135bool
1136GDBRemoteCommunicationClient::GetGDBServerVersion()
1137{
1138 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1139 {
1140 m_gdb_server_name.clear();
1141 m_gdb_server_version = 0;
1142 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1143
1144 StringExtractorGDBRemote response;
1145 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1146 {
1147 if (response.IsNormalResponse())
1148 {
Zachary Turner54695a32016-08-29 19:58:14 +00001149 llvm::StringRef name, value;
Jason Molendaa3329782014-03-29 18:54:20 +00001150 bool success = false;
1151 while (response.GetNameColonValue(name, value))
1152 {
Zachary Turner54695a32016-08-29 19:58:14 +00001153 if (name.equals("name"))
Jason Molendaa3329782014-03-29 18:54:20 +00001154 {
1155 success = true;
Zachary Turner54695a32016-08-29 19:58:14 +00001156 m_gdb_server_name = value;
Jason Molendaa3329782014-03-29 18:54:20 +00001157 }
Zachary Turner54695a32016-08-29 19:58:14 +00001158 else if (name.equals("version"))
Jason Molendaa3329782014-03-29 18:54:20 +00001159 {
Zachary Turner54695a32016-08-29 19:58:14 +00001160 llvm::StringRef major, minor;
1161 std::tie(major, minor) = value.split('.');
1162 if (!major.getAsInteger(0, m_gdb_server_version))
Jason Molendaa3329782014-03-29 18:54:20 +00001163 success = true;
Jason Molendaa3329782014-03-29 18:54:20 +00001164 }
1165 }
1166 if (success)
1167 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1168 }
1169 }
1170 }
1171 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1172}
1173
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001174void
1175GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1176{
1177 CompressionType avail_type = CompressionType::None;
1178 std::string avail_name;
1179
1180#if defined (HAVE_LIBCOMPRESSION)
1181 // libcompression is weak linked so test if compression_decode_buffer() is available
1182 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1183 {
1184 for (auto compression : supported_compressions)
1185 {
1186 if (compression == "lzfse")
1187 {
1188 avail_type = CompressionType::LZFSE;
1189 avail_name = compression;
1190 break;
1191 }
1192 }
1193 }
1194#endif
1195
1196#if defined (HAVE_LIBCOMPRESSION)
1197 // libcompression is weak linked so test if compression_decode_buffer() is available
1198 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1199 {
1200 for (auto compression : supported_compressions)
1201 {
1202 if (compression == "zlib-deflate")
1203 {
1204 avail_type = CompressionType::ZlibDeflate;
1205 avail_name = compression;
1206 break;
1207 }
1208 }
1209 }
1210#endif
1211
1212#if defined (HAVE_LIBZ)
1213 if (avail_type == CompressionType::None)
1214 {
1215 for (auto compression : supported_compressions)
1216 {
1217 if (compression == "zlib-deflate")
1218 {
1219 avail_type = CompressionType::ZlibDeflate;
1220 avail_name = compression;
1221 break;
1222 }
1223 }
1224 }
1225#endif
1226
1227#if defined (HAVE_LIBCOMPRESSION)
1228 // libcompression is weak linked so test if compression_decode_buffer() is available
1229 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1230 {
1231 for (auto compression : supported_compressions)
1232 {
1233 if (compression == "lz4")
1234 {
1235 avail_type = CompressionType::LZ4;
1236 avail_name = compression;
1237 break;
1238 }
1239 }
1240 }
1241#endif
1242
1243#if defined (HAVE_LIBCOMPRESSION)
1244 // libcompression is weak linked so test if compression_decode_buffer() is available
1245 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1246 {
1247 for (auto compression : supported_compressions)
1248 {
1249 if (compression == "lzma")
1250 {
1251 avail_type = CompressionType::LZMA;
1252 avail_name = compression;
1253 break;
1254 }
1255 }
1256 }
1257#endif
1258
1259 if (avail_type != CompressionType::None)
1260 {
1261 StringExtractorGDBRemote response;
1262 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1263 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1264 return;
1265
1266 if (response.IsOKResponse())
1267 {
1268 m_compression_type = avail_type;
1269 }
1270 }
1271}
1272
Jason Molendaa3329782014-03-29 18:54:20 +00001273const char *
1274GDBRemoteCommunicationClient::GetGDBServerProgramName()
1275{
1276 if (GetGDBServerVersion())
1277 {
1278 if (!m_gdb_server_name.empty())
1279 return m_gdb_server_name.c_str();
1280 }
1281 return NULL;
1282}
1283
1284uint32_t
1285GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1286{
1287 if (GetGDBServerVersion())
1288 return m_gdb_server_version;
1289 return 0;
1290}
Greg Clayton1cb64962011-03-24 04:28:38 +00001291
1292bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001293GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1294{
1295 StringExtractorGDBRemote response;
1296 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1297 return false;
1298
1299 if (!response.IsNormalResponse())
1300 return false;
1301
1302 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1303 tid = response.GetHexMaxU32(true, -1);
1304
1305 return true;
1306}
1307
1308bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001309GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001310{
Todd Fialaaf245d12014-06-30 21:05:18 +00001311 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1312
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001313 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001314 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001315 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001316 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001317 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001318 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001319 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001320 {
Zachary Turner54695a32016-08-29 19:58:14 +00001321 llvm::StringRef name;
1322 llvm::StringRef value;
Greg Clayton32e0a752011-03-30 18:16:51 +00001323 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1324 uint32_t sub = 0;
1325 std::string arch_name;
1326 std::string os_name;
1327 std::string vendor_name;
1328 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001329 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001330 uint32_t pointer_byte_size = 0;
Greg Clayton32e0a752011-03-30 18:16:51 +00001331 ByteOrder byte_order = eByteOrderInvalid;
1332 uint32_t num_keys_decoded = 0;
1333 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001334 {
Zachary Turner54695a32016-08-29 19:58:14 +00001335 if (name.equals("cputype"))
Greg Clayton1cb64962011-03-24 04:28:38 +00001336 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001337 // exception type in big endian hex
Zachary Turner54695a32016-08-29 19:58:14 +00001338 if (!value.getAsInteger(0, cpu))
Greg Clayton32e0a752011-03-30 18:16:51 +00001339 ++num_keys_decoded;
1340 }
Zachary Turner54695a32016-08-29 19:58:14 +00001341 else if (name.equals("cpusubtype"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001342 {
1343 // exception count in big endian hex
Zachary Turner54695a32016-08-29 19:58:14 +00001344 if (!value.getAsInteger(0, sub))
Greg Clayton32e0a752011-03-30 18:16:51 +00001345 ++num_keys_decoded;
1346 }
Zachary Turner54695a32016-08-29 19:58:14 +00001347 else if (name.equals("arch"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001348 {
Zachary Turner54695a32016-08-29 19:58:14 +00001349 arch_name = value;
Greg Clayton32e0a752011-03-30 18:16:51 +00001350 ++num_keys_decoded;
1351 }
Zachary Turner54695a32016-08-29 19:58:14 +00001352 else if (name.equals("triple"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001353 {
Zachary Turner54695a32016-08-29 19:58:14 +00001354 StringExtractor extractor(value);
Greg Clayton44272a42014-09-18 00:18:32 +00001355 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001356 ++num_keys_decoded;
1357 }
Zachary Turner54695a32016-08-29 19:58:14 +00001358 else if (name.equals("distribution_id"))
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001359 {
Zachary Turner54695a32016-08-29 19:58:14 +00001360 StringExtractor extractor(value);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001361 extractor.GetHexByteString (distribution_id);
1362 ++num_keys_decoded;
1363 }
Zachary Turner54695a32016-08-29 19:58:14 +00001364 else if (name.equals("os_build"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001365 {
Zachary Turner54695a32016-08-29 19:58:14 +00001366 StringExtractor extractor(value);
Greg Clayton32e0a752011-03-30 18:16:51 +00001367 extractor.GetHexByteString (m_os_build);
1368 ++num_keys_decoded;
1369 }
Zachary Turner54695a32016-08-29 19:58:14 +00001370 else if (name.equals("hostname"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001371 {
Zachary Turner54695a32016-08-29 19:58:14 +00001372 StringExtractor extractor(value);
Greg Clayton32e0a752011-03-30 18:16:51 +00001373 extractor.GetHexByteString (m_hostname);
1374 ++num_keys_decoded;
1375 }
Zachary Turner54695a32016-08-29 19:58:14 +00001376 else if (name.equals("os_kernel"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001377 {
Zachary Turner54695a32016-08-29 19:58:14 +00001378 StringExtractor extractor(value);
Greg Clayton32e0a752011-03-30 18:16:51 +00001379 extractor.GetHexByteString (m_os_kernel);
1380 ++num_keys_decoded;
1381 }
Zachary Turner54695a32016-08-29 19:58:14 +00001382 else if (name.equals("ostype"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001383 {
Zachary Turner54695a32016-08-29 19:58:14 +00001384 os_name = value;
Greg Clayton32e0a752011-03-30 18:16:51 +00001385 ++num_keys_decoded;
1386 }
Zachary Turner54695a32016-08-29 19:58:14 +00001387 else if (name.equals("vendor"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001388 {
Zachary Turner54695a32016-08-29 19:58:14 +00001389 vendor_name = value;
Greg Clayton32e0a752011-03-30 18:16:51 +00001390 ++num_keys_decoded;
1391 }
Zachary Turner54695a32016-08-29 19:58:14 +00001392 else if (name.equals("endian"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001393 {
Zachary Turner54695a32016-08-29 19:58:14 +00001394 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1395 .Case("little", eByteOrderLittle)
1396 .Case("big", eByteOrderBig)
1397 .Case("pdp", eByteOrderPDP)
1398 .Default(eByteOrderInvalid);
1399 if (byte_order != eByteOrderInvalid)
Greg Clayton32e0a752011-03-30 18:16:51 +00001400 ++num_keys_decoded;
1401 }
Zachary Turner54695a32016-08-29 19:58:14 +00001402 else if (name.equals("ptrsize"))
Greg Clayton32e0a752011-03-30 18:16:51 +00001403 {
Zachary Turner54695a32016-08-29 19:58:14 +00001404 if (!value.getAsInteger(0, pointer_byte_size))
1405 ++num_keys_decoded;
1406 }
1407 else if (name.equals("os_version") || name.equals("version")) // Older debugserver binaries used the
1408 // "version" key instead of
1409 // "os_version"...
1410 {
1411 Args::StringToVersion(value.str().c_str(), m_os_version_major, m_os_version_minor,
1412 m_os_version_update);
Greg Clayton32e0a752011-03-30 18:16:51 +00001413 if (m_os_version_major != UINT32_MAX)
1414 ++num_keys_decoded;
1415 }
Zachary Turner54695a32016-08-29 19:58:14 +00001416 else if (name.equals("watchpoint_exceptions_received"))
Enrico Granataf04a2192012-07-13 23:18:48 +00001417 {
Zachary Turner54695a32016-08-29 19:58:14 +00001418 m_watchpoints_trigger_after_instruction = llvm::StringSwitch<LazyBool>(value)
1419 .Case("before", eLazyBoolNo)
1420 .Case("after", eLazyBoolYes)
1421 .Default(eLazyBoolCalculate);
1422 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1423 ++num_keys_decoded;
Enrico Granataf04a2192012-07-13 23:18:48 +00001424 }
Zachary Turner54695a32016-08-29 19:58:14 +00001425 else if (name.equals("default_packet_timeout"))
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001426 {
Zachary Turner54695a32016-08-29 19:58:14 +00001427 if (!value.getAsInteger(0, m_default_packet_timeout))
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001428 {
1429 SetPacketTimeout(m_default_packet_timeout);
1430 ++num_keys_decoded;
1431 }
1432 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001433
Greg Clayton32e0a752011-03-30 18:16:51 +00001434 }
1435
1436 if (num_keys_decoded > 0)
1437 m_qHostInfo_is_valid = eLazyBoolYes;
1438
1439 if (triple.empty())
1440 {
1441 if (arch_name.empty())
1442 {
1443 if (cpu != LLDB_INVALID_CPUTYPE)
1444 {
1445 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1446 if (pointer_byte_size)
1447 {
1448 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1449 }
1450 if (byte_order != eByteOrderInvalid)
1451 {
1452 assert (byte_order == m_host_arch.GetByteOrder());
1453 }
Greg Clayton70512312012-05-08 01:45:38 +00001454
Greg Clayton32e0a752011-03-30 18:16:51 +00001455 if (!vendor_name.empty())
1456 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1457 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001458 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001459
1460 }
1461 }
1462 else
1463 {
1464 std::string triple;
1465 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001466 if (!vendor_name.empty() || !os_name.empty())
1467 {
1468 triple += '-';
1469 if (vendor_name.empty())
1470 triple += "unknown";
1471 else
1472 triple += vendor_name;
1473 triple += '-';
1474 if (os_name.empty())
1475 triple += "unknown";
1476 else
1477 triple += os_name;
1478 }
1479 m_host_arch.SetTriple (triple.c_str());
1480
1481 llvm::Triple &host_triple = m_host_arch.GetTriple();
1482 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1483 {
1484 switch (m_host_arch.GetMachine())
1485 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001486 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001487 case llvm::Triple::arm:
1488 case llvm::Triple::thumb:
1489 host_triple.setOS(llvm::Triple::IOS);
1490 break;
1491 default:
1492 host_triple.setOS(llvm::Triple::MacOSX);
1493 break;
1494 }
1495 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001496 if (pointer_byte_size)
1497 {
1498 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1499 }
1500 if (byte_order != eByteOrderInvalid)
1501 {
1502 assert (byte_order == m_host_arch.GetByteOrder());
1503 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001504
Greg Clayton1cb64962011-03-24 04:28:38 +00001505 }
1506 }
1507 else
1508 {
Greg Clayton70512312012-05-08 01:45:38 +00001509 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001510 if (pointer_byte_size)
1511 {
1512 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1513 }
1514 if (byte_order != eByteOrderInvalid)
1515 {
1516 assert (byte_order == m_host_arch.GetByteOrder());
1517 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001518
1519 if (log)
1520 log->Printf ("GDBRemoteCommunicationClient::%s parsed host architecture as %s, triple as %s from triple text %s", __FUNCTION__, m_host_arch.GetArchitectureName () ? m_host_arch.GetArchitectureName () : "<null-arch-name>", m_host_arch.GetTriple ().getTriple ().c_str(), triple.c_str ());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001521 }
1522 if (!distribution_id.empty ())
1523 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00001524 }
Greg Clayton576d8832011-03-22 04:00:09 +00001525 }
1526 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001527 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001528}
1529
1530int
1531GDBRemoteCommunicationClient::SendAttach
1532(
1533 lldb::pid_t pid,
1534 StringExtractorGDBRemote& response
1535)
1536{
1537 if (pid != LLDB_INVALID_PROCESS_ID)
1538 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001539 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001540 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001541 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00001542 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001543 {
1544 if (response.IsErrorResponse())
1545 return response.GetError();
1546 return 0;
1547 }
1548 }
1549 return -1;
1550}
1551
Vince Harrone0be4252015-02-06 18:32:57 +00001552int
1553GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
1554{
1555 StreamString packet;
1556 packet.PutCString("I");
1557 packet.PutBytesAsRawHex8(data, data_len);
1558 StringExtractorGDBRemote response;
1559 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1560 {
1561 return 0;
1562 }
1563 return response.GetError();
1564
1565}
1566
Greg Clayton576d8832011-03-22 04:00:09 +00001567const lldb_private::ArchSpec &
1568GDBRemoteCommunicationClient::GetHostArchitecture ()
1569{
Greg Clayton32e0a752011-03-30 18:16:51 +00001570 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001571 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001572 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001573}
1574
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001575uint32_t
1576GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1577{
1578 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1579 GetHostInfo ();
1580 return m_default_packet_timeout;
1581}
1582
Greg Clayton576d8832011-03-22 04:00:09 +00001583addr_t
1584GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1585{
Greg Clayton70b57652011-05-15 01:25:55 +00001586 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001587 {
Greg Clayton70b57652011-05-15 01:25:55 +00001588 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001589 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001590 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001591 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001592 permissions & lldb::ePermissionsReadable ? "r" : "",
1593 permissions & lldb::ePermissionsWritable ? "w" : "",
1594 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001595 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001596 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001597 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001598 {
Todd Fialaf105f582014-06-21 00:48:09 +00001599 if (response.IsUnsupportedResponse())
1600 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1601 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001602 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1603 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001604 else
1605 {
1606 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1607 }
Greg Clayton576d8832011-03-22 04:00:09 +00001608 }
1609 return LLDB_INVALID_ADDRESS;
1610}
1611
1612bool
1613GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1614{
Greg Clayton70b57652011-05-15 01:25:55 +00001615 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001616 {
Greg Clayton70b57652011-05-15 01:25:55 +00001617 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001618 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001619 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001620 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001621 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001622 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001623 {
Todd Fialaf105f582014-06-21 00:48:09 +00001624 if (response.IsUnsupportedResponse())
1625 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1626 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001627 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001628 }
1629 else
1630 {
1631 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001632 }
Greg Clayton576d8832011-03-22 04:00:09 +00001633 }
1634 return false;
1635}
1636
Jim Inghamacff8952013-05-02 00:27:30 +00001637Error
1638GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001639{
Jim Inghamacff8952013-05-02 00:27:30 +00001640 Error error;
1641
1642 if (keep_stopped)
1643 {
1644 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1645 {
1646 char packet[64];
1647 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001648 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001649 StringExtractorGDBRemote response;
Jim Ingham4920a4e2015-07-15 00:59:25 +00001650 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success
1651 && response.IsOKResponse())
Jim Inghamacff8952013-05-02 00:27:30 +00001652 {
1653 m_supports_detach_stay_stopped = eLazyBoolYes;
1654 }
1655 else
1656 {
1657 m_supports_detach_stay_stopped = eLazyBoolNo;
1658 }
1659 }
1660
1661 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1662 {
1663 error.SetErrorString("Stays stopped not supported by this target.");
1664 return error;
1665 }
1666 else
1667 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001668 StringExtractorGDBRemote response;
Jason Molenda2a667382015-07-15 00:16:09 +00001669 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001670 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001671 error.SetErrorString ("Sending extended disconnect packet failed.");
1672 }
1673 }
1674 else
1675 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001676 StringExtractorGDBRemote response;
1677 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001678 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001679 error.SetErrorString ("Sending disconnect packet failed.");
1680 }
1681 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001682}
1683
Greg Clayton46fb5582011-11-18 07:03:08 +00001684Error
1685GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1686 lldb_private::MemoryRegionInfo &region_info)
1687{
1688 Error error;
1689 region_info.Clear();
1690
1691 if (m_supports_memory_region_info != eLazyBoolNo)
1692 {
1693 m_supports_memory_region_info = eLazyBoolYes;
1694 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001695 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001696 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001697 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001698 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00001699 {
Zachary Turner54695a32016-08-29 19:58:14 +00001700 llvm::StringRef name;
1701 llvm::StringRef value;
1702 addr_t addr_value = LLDB_INVALID_ADDRESS;
Greg Clayton46fb5582011-11-18 07:03:08 +00001703 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001704 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001705 while (success && response.GetNameColonValue(name, value))
1706 {
Zachary Turner54695a32016-08-29 19:58:14 +00001707 if (name.equals("start"))
Greg Clayton46fb5582011-11-18 07:03:08 +00001708 {
Zachary Turner54695a32016-08-29 19:58:14 +00001709 if (!value.getAsInteger(16, addr_value))
Greg Clayton46fb5582011-11-18 07:03:08 +00001710 region_info.GetRange().SetRangeBase(addr_value);
1711 }
Zachary Turner54695a32016-08-29 19:58:14 +00001712 else if (name.equals("size"))
Greg Clayton46fb5582011-11-18 07:03:08 +00001713 {
Zachary Turner54695a32016-08-29 19:58:14 +00001714 if (!value.getAsInteger(16, addr_value))
1715 region_info.GetRange().SetByteSize(addr_value);
Greg Clayton46fb5582011-11-18 07:03:08 +00001716 }
Zachary Turner54695a32016-08-29 19:58:14 +00001717 else if (name.equals("permissions") && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001718 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001719 saw_permissions = true;
1720 if (region_info.GetRange().Contains (addr))
1721 {
Zachary Turner54695a32016-08-29 19:58:14 +00001722 if (value.find('r') != llvm::StringRef::npos)
Jason Molendacb349ee2011-12-13 05:39:38 +00001723 region_info.SetReadable (MemoryRegionInfo::eYes);
1724 else
1725 region_info.SetReadable (MemoryRegionInfo::eNo);
1726
Zachary Turner54695a32016-08-29 19:58:14 +00001727 if (value.find('w') != llvm::StringRef::npos)
Jason Molendacb349ee2011-12-13 05:39:38 +00001728 region_info.SetWritable (MemoryRegionInfo::eYes);
1729 else
1730 region_info.SetWritable (MemoryRegionInfo::eNo);
1731
Zachary Turner54695a32016-08-29 19:58:14 +00001732 if (value.find('x') != llvm::StringRef::npos)
Jason Molendacb349ee2011-12-13 05:39:38 +00001733 region_info.SetExecutable (MemoryRegionInfo::eYes);
1734 else
1735 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00001736
1737 region_info.SetMapped(MemoryRegionInfo::eYes);
Jason Molendacb349ee2011-12-13 05:39:38 +00001738 }
1739 else
1740 {
1741 // The reported region does not contain this address -- we're looking at an unmapped page
1742 region_info.SetReadable (MemoryRegionInfo::eNo);
1743 region_info.SetWritable (MemoryRegionInfo::eNo);
1744 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00001745 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00001746 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001747 }
Zachary Turner54695a32016-08-29 19:58:14 +00001748 else if (name.equals("name"))
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001749 {
Zachary Turner54695a32016-08-29 19:58:14 +00001750 StringExtractorGDBRemote name_extractor(value);
1751 std::string name;
1752 name_extractor.GetHexByteString(name);
1753 region_info.SetName(name.c_str());
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001754 }
Zachary Turner54695a32016-08-29 19:58:14 +00001755 else if (name.equals("error"))
Greg Clayton46fb5582011-11-18 07:03:08 +00001756 {
Zachary Turner54695a32016-08-29 19:58:14 +00001757 StringExtractorGDBRemote error_extractor(value);
1758 std::string error_string;
Greg Clayton46fb5582011-11-18 07:03:08 +00001759 // Now convert the HEX bytes into a string value
Zachary Turner54695a32016-08-29 19:58:14 +00001760 error_extractor.GetHexByteString(error_string);
1761 error.SetErrorString(error_string.c_str());
Greg Clayton46fb5582011-11-18 07:03:08 +00001762 }
1763 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001764
1765 // We got a valid address range back but no permissions -- which means this is an unmapped page
1766 if (region_info.GetRange().IsValid() && saw_permissions == false)
1767 {
1768 region_info.SetReadable (MemoryRegionInfo::eNo);
1769 region_info.SetWritable (MemoryRegionInfo::eNo);
1770 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00001771 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00001772 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001773 }
1774 else
1775 {
1776 m_supports_memory_region_info = eLazyBoolNo;
1777 }
1778 }
1779
1780 if (m_supports_memory_region_info == eLazyBoolNo)
1781 {
1782 error.SetErrorString("qMemoryRegionInfo is not supported");
1783 }
1784 if (error.Fail())
1785 region_info.Clear();
1786 return error;
1787
1788}
1789
Johnny Chen64637202012-05-23 21:09:52 +00001790Error
1791GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1792{
1793 Error error;
1794
1795 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1796 {
1797 num = m_num_supported_hardware_watchpoints;
1798 return error;
1799 }
1800
1801 // Set num to 0 first.
1802 num = 0;
1803 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1804 {
1805 char packet[64];
1806 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001807 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00001808 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001809 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00001810 {
Zachary Turner54695a32016-08-29 19:58:14 +00001811 m_supports_watchpoint_support_info = eLazyBoolYes;
1812 llvm::StringRef name;
1813 llvm::StringRef value;
Johnny Chen64637202012-05-23 21:09:52 +00001814 while (response.GetNameColonValue(name, value))
1815 {
Zachary Turner54695a32016-08-29 19:58:14 +00001816 if (name.equals("num"))
1817 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
Johnny Chen64637202012-05-23 21:09:52 +00001818 }
1819 }
1820 else
1821 {
1822 m_supports_watchpoint_support_info = eLazyBoolNo;
1823 }
1824 }
1825
1826 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1827 {
1828 error.SetErrorString("qWatchpointSupportInfo is not supported");
1829 }
1830 return error;
1831
1832}
Greg Clayton46fb5582011-11-18 07:03:08 +00001833
Enrico Granataf04a2192012-07-13 23:18:48 +00001834lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00001835GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00001836{
1837 Error error(GetWatchpointSupportInfo(num));
1838 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00001839 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00001840 return error;
1841}
1842
1843lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00001844GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00001845{
1846 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00001847 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00001848
1849 // we assume watchpoints will happen after running the relevant opcode
1850 // and we only want to override this behavior if we have explicitly
1851 // received a qHostInfo telling us otherwise
1852 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00001853 {
1854 // On targets like MIPS, watchpoint exceptions are always generated
1855 // before the instruction is executed. The connected target may not
1856 // support qHostInfo or qWatchpointSupportInfo packets.
1857 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
1858 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1859 after = false;
1860 else
1861 after = true;
1862 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001863 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00001864 {
1865 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1866 // if it is not calculated before.
1867 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1868 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
1869 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1870 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1871
Enrico Granataf04a2192012-07-13 23:18:48 +00001872 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00001873 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001874 return error;
1875}
1876
Greg Clayton576d8832011-03-22 04:00:09 +00001877int
Chaoren Lind3173f32015-05-29 19:52:29 +00001878GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001879{
Chaoren Lind3173f32015-05-29 19:52:29 +00001880 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001881 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001882 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001883 StreamString packet;
1884 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001885 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001886
1887 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001888 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001889 {
1890 if (response.IsOKResponse())
1891 return 0;
1892 uint8_t error = response.GetError();
1893 if (error)
1894 return error;
1895 }
1896 }
1897 return -1;
1898}
1899
1900int
Chaoren Lind3173f32015-05-29 19:52:29 +00001901GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001902{
Chaoren Lind3173f32015-05-29 19:52:29 +00001903 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001904 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001905 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001906 StreamString packet;
1907 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001908 packet.PutCStringAsRawHex8(path.c_str());
1909
Greg Clayton576d8832011-03-22 04:00:09 +00001910 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001911 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001912 {
1913 if (response.IsOKResponse())
1914 return 0;
1915 uint8_t error = response.GetError();
1916 if (error)
1917 return error;
1918 }
1919 }
1920 return -1;
1921}
1922
1923int
Chaoren Lind3173f32015-05-29 19:52:29 +00001924GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001925{
Chaoren Lind3173f32015-05-29 19:52:29 +00001926 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001927 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001928 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001929 StreamString packet;
1930 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001931 packet.PutCStringAsRawHex8(path.c_str());
1932
Greg Clayton576d8832011-03-22 04:00:09 +00001933 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001934 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001935 {
1936 if (response.IsOKResponse())
1937 return 0;
1938 uint8_t error = response.GetError();
1939 if (error)
1940 return error;
1941 }
1942 }
1943 return -1;
1944}
1945
Greg Claytonfbb76342013-11-20 21:07:01 +00001946bool
Chaoren Lind3173f32015-05-29 19:52:29 +00001947GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00001948{
1949 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001950 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00001951 {
1952 if (response.IsUnsupportedResponse())
1953 return false;
1954 if (response.IsErrorResponse())
1955 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00001956 std::string cwd;
1957 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00001958 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00001959 return !cwd.empty();
1960 }
1961 return false;
1962}
1963
Greg Clayton576d8832011-03-22 04:00:09 +00001964int
Chaoren Lind3173f32015-05-29 19:52:29 +00001965GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00001966{
Chaoren Lind3173f32015-05-29 19:52:29 +00001967 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00001968 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001969 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001970 StreamString packet;
1971 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001972 packet.PutCStringAsRawHex8(path.c_str());
1973
Greg Clayton576d8832011-03-22 04:00:09 +00001974 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001975 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001976 {
1977 if (response.IsOKResponse())
1978 return 0;
1979 uint8_t error = response.GetError();
1980 if (error)
1981 return error;
1982 }
1983 }
1984 return -1;
1985}
1986
1987int
1988GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1989{
Greg Clayton32e0a752011-03-30 18:16:51 +00001990 char packet[32];
1991 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00001992 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00001993 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001994 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001995 {
1996 if (response.IsOKResponse())
1997 return 0;
1998 uint8_t error = response.GetError();
1999 if (error)
2000 return error;
2001 }
2002 return -1;
2003}
Greg Clayton32e0a752011-03-30 18:16:51 +00002004
Jim Ingham106d0282014-06-25 02:32:56 +00002005int
2006GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2007{
2008 char packet[32];
2009 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2010 assert (packet_len < (int)sizeof(packet));
2011 StringExtractorGDBRemote response;
2012 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2013 {
2014 if (response.IsOKResponse())
2015 return 0;
2016 uint8_t error = response.GetError();
2017 if (error)
2018 return error;
2019 }
2020 return -1;
2021}
2022
2023
Greg Clayton32e0a752011-03-30 18:16:51 +00002024bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002025GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002026{
2027 if (response.IsNormalResponse())
2028 {
Zachary Turner54695a32016-08-29 19:58:14 +00002029 llvm::StringRef name;
2030 llvm::StringRef value;
Greg Clayton32e0a752011-03-30 18:16:51 +00002031 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002032
2033 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2034 uint32_t sub = 0;
2035 std::string vendor;
2036 std::string os_type;
Zachary Turner54695a32016-08-29 19:58:14 +00002037
Greg Clayton32e0a752011-03-30 18:16:51 +00002038 while (response.GetNameColonValue(name, value))
2039 {
Zachary Turner54695a32016-08-29 19:58:14 +00002040 if (name.equals("pid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002041 {
Zachary Turner54695a32016-08-29 19:58:14 +00002042 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2043 value.getAsInteger(0, pid);
2044 process_info.SetProcessID(pid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002045 }
Zachary Turner54695a32016-08-29 19:58:14 +00002046 else if (name.equals("ppid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002047 {
Zachary Turner54695a32016-08-29 19:58:14 +00002048 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2049 value.getAsInteger(0, pid);
2050 process_info.SetParentProcessID(pid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002051 }
Zachary Turner54695a32016-08-29 19:58:14 +00002052 else if (name.equals("uid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002053 {
Zachary Turner54695a32016-08-29 19:58:14 +00002054 uint32_t uid = UINT32_MAX;
2055 value.getAsInteger(0, uid);
2056 process_info.SetUserID(uid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002057 }
Zachary Turner54695a32016-08-29 19:58:14 +00002058 else if (name.equals("euid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002059 {
Zachary Turner54695a32016-08-29 19:58:14 +00002060 uint32_t uid = UINT32_MAX;
2061 value.getAsInteger(0, uid);
2062 process_info.SetEffectiveGroupID(uid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002063 }
Zachary Turner54695a32016-08-29 19:58:14 +00002064 else if (name.equals("gid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002065 {
Zachary Turner54695a32016-08-29 19:58:14 +00002066 uint32_t gid = UINT32_MAX;
2067 value.getAsInteger(0, gid);
2068 process_info.SetGroupID(gid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002069 }
Zachary Turner54695a32016-08-29 19:58:14 +00002070 else if (name.equals("egid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002071 {
Zachary Turner54695a32016-08-29 19:58:14 +00002072 uint32_t gid = UINT32_MAX;
2073 value.getAsInteger(0, gid);
2074 process_info.SetEffectiveGroupID(gid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002075 }
Zachary Turner54695a32016-08-29 19:58:14 +00002076 else if (name.equals("triple"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002077 {
Zachary Turner54695a32016-08-29 19:58:14 +00002078 StringExtractor extractor(value);
2079 std::string triple;
2080 extractor.GetHexByteString(triple);
2081 process_info.GetArchitecture().SetTriple(triple.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002082 }
Zachary Turner54695a32016-08-29 19:58:14 +00002083 else if (name.equals("name"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002084 {
Zachary Turner54695a32016-08-29 19:58:14 +00002085 StringExtractor extractor(value);
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002086 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002087 // control the characters in a process name
Zachary Turner54695a32016-08-29 19:58:14 +00002088 std::string name;
2089 extractor.GetHexByteString(name);
2090 process_info.GetExecutableFile().SetFile(name.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002091 }
Zachary Turner54695a32016-08-29 19:58:14 +00002092 else if (name.equals("cputype"))
Jason Molenda89c37492014-01-27 22:23:20 +00002093 {
Zachary Turner54695a32016-08-29 19:58:14 +00002094 value.getAsInteger(0, cpu);
Jason Molenda89c37492014-01-27 22:23:20 +00002095 }
Zachary Turner54695a32016-08-29 19:58:14 +00002096 else if (name.equals("cpusubtype"))
Jason Molenda89c37492014-01-27 22:23:20 +00002097 {
Zachary Turner54695a32016-08-29 19:58:14 +00002098 value.getAsInteger(0, sub);
Jason Molenda89c37492014-01-27 22:23:20 +00002099 }
Zachary Turner54695a32016-08-29 19:58:14 +00002100 else if (name.equals("vendor"))
Jason Molenda89c37492014-01-27 22:23:20 +00002101 {
2102 vendor = value;
2103 }
Zachary Turner54695a32016-08-29 19:58:14 +00002104 else if (name.equals("ostype"))
Jason Molenda89c37492014-01-27 22:23:20 +00002105 {
2106 os_type = value;
2107 }
2108 }
2109
2110 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2111 {
2112 if (vendor == "apple")
2113 {
2114 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2115 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2116 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2117 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002118 }
2119
2120 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2121 return true;
2122 }
2123 return false;
2124}
2125
2126bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002127GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002128{
2129 process_info.Clear();
2130
2131 if (m_supports_qProcessInfoPID)
2132 {
2133 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002134 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002135 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002136 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002137 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002138 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002139 return DecodeProcessInfoResponse (response, process_info);
2140 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002141 else
2142 {
2143 m_supports_qProcessInfoPID = false;
2144 return false;
2145 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002146 }
2147 return false;
2148}
2149
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002150bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002151GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002152{
Todd Fiala3daa1762014-09-15 16:01:29 +00002153 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2154
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002155 if (allow_lazy)
2156 {
2157 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2158 return true;
2159 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2160 return false;
2161 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002162
2163 GetHostInfo ();
2164
2165 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002166 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002167 {
2168 if (response.IsNormalResponse())
2169 {
Zachary Turner54695a32016-08-29 19:58:14 +00002170 llvm::StringRef name;
2171 llvm::StringRef value;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002172 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2173 uint32_t sub = 0;
2174 std::string arch_name;
2175 std::string os_name;
2176 std::string vendor_name;
2177 std::string triple;
2178 uint32_t pointer_byte_size = 0;
2179 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002180 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002181 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002182 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002183 while (response.GetNameColonValue(name, value))
2184 {
Zachary Turner54695a32016-08-29 19:58:14 +00002185 if (name.equals("cputype"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002186 {
Zachary Turner54695a32016-08-29 19:58:14 +00002187 if (!value.getAsInteger(16, cpu))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002188 ++num_keys_decoded;
2189 }
Zachary Turner54695a32016-08-29 19:58:14 +00002190 else if (name.equals("cpusubtype"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002191 {
Zachary Turner54695a32016-08-29 19:58:14 +00002192 if (!value.getAsInteger(16, sub))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002193 ++num_keys_decoded;
2194 }
Zachary Turner54695a32016-08-29 19:58:14 +00002195 else if (name.equals("triple"))
Todd Fialac540dd02014-08-26 18:21:02 +00002196 {
Zachary Turner54695a32016-08-29 19:58:14 +00002197 StringExtractor extractor(value);
Greg Clayton44272a42014-09-18 00:18:32 +00002198 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002199 ++num_keys_decoded;
2200 }
Zachary Turner54695a32016-08-29 19:58:14 +00002201 else if (name.equals("ostype"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002202 {
Zachary Turner54695a32016-08-29 19:58:14 +00002203 os_name = value;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002204 ++num_keys_decoded;
2205 }
Zachary Turner54695a32016-08-29 19:58:14 +00002206 else if (name.equals("vendor"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002207 {
Zachary Turner54695a32016-08-29 19:58:14 +00002208 vendor_name = value;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002209 ++num_keys_decoded;
2210 }
Zachary Turner54695a32016-08-29 19:58:14 +00002211 else if (name.equals("endian"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002212 {
Zachary Turner54695a32016-08-29 19:58:14 +00002213 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2214 .Case("little", eByteOrderLittle)
2215 .Case("big", eByteOrderBig)
2216 .Case("pdp", eByteOrderPDP)
2217 .Default(eByteOrderInvalid);
2218 if (byte_order != eByteOrderInvalid)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002219 ++num_keys_decoded;
2220 }
Zachary Turner54695a32016-08-29 19:58:14 +00002221 else if (name.equals("ptrsize"))
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002222 {
Zachary Turner54695a32016-08-29 19:58:14 +00002223 if (!value.getAsInteger(16, pointer_byte_size))
2224 ++num_keys_decoded;
2225 }
2226 else if (name.equals("pid"))
2227 {
2228 if (!value.getAsInteger(16, pid))
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002229 ++num_keys_decoded;
2230 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002231 }
2232 if (num_keys_decoded > 0)
2233 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002234 if (pid != LLDB_INVALID_PROCESS_ID)
2235 {
2236 m_curr_pid_is_valid = eLazyBoolYes;
2237 m_curr_pid = pid;
2238 }
Todd Fialac540dd02014-08-26 18:21:02 +00002239
2240 // Set the ArchSpec from the triple if we have it.
2241 if (!triple.empty ())
2242 {
2243 m_process_arch.SetTriple (triple.c_str ());
2244 if (pointer_byte_size)
2245 {
2246 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2247 }
2248 }
2249 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002250 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002251 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2252
2253 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2254 switch (triple.getObjectFormat()) {
2255 case llvm::Triple::MachO:
2256 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2257 break;
2258 case llvm::Triple::ELF:
2259 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2260 break;
2261 case llvm::Triple::COFF:
2262 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2263 break;
2264 case llvm::Triple::UnknownObjectFormat:
2265 if (log)
2266 log->Printf("error: failed to determine target architecture");
2267 return false;
2268 }
2269
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002270 if (pointer_byte_size)
2271 {
2272 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2273 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002274 if (byte_order != eByteOrderInvalid)
2275 {
2276 assert (byte_order == m_process_arch.GetByteOrder());
2277 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002278 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002279 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002280 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2281 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002282 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002283 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002284 }
2285 }
2286 else
2287 {
2288 m_qProcessInfo_is_valid = eLazyBoolNo;
2289 }
2290
2291 return false;
2292}
2293
2294
Greg Clayton32e0a752011-03-30 18:16:51 +00002295uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002296GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2297 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002298{
2299 process_infos.Clear();
2300
2301 if (m_supports_qfProcessInfo)
2302 {
2303 StreamString packet;
2304 packet.PutCString ("qfProcessInfo");
2305 if (!match_info.MatchAllProcesses())
2306 {
2307 packet.PutChar (':');
2308 const char *name = match_info.GetProcessInfo().GetName();
2309 bool has_name_match = false;
2310 if (name && name[0])
2311 {
2312 has_name_match = true;
2313 NameMatchType name_match_type = match_info.GetNameMatchType();
2314 switch (name_match_type)
2315 {
2316 case eNameMatchIgnore:
2317 has_name_match = false;
2318 break;
2319
2320 case eNameMatchEquals:
2321 packet.PutCString ("name_match:equals;");
2322 break;
2323
2324 case eNameMatchContains:
2325 packet.PutCString ("name_match:contains;");
2326 break;
2327
2328 case eNameMatchStartsWith:
2329 packet.PutCString ("name_match:starts_with;");
2330 break;
2331
2332 case eNameMatchEndsWith:
2333 packet.PutCString ("name_match:ends_with;");
2334 break;
2335
2336 case eNameMatchRegularExpression:
2337 packet.PutCString ("name_match:regex;");
2338 break;
2339 }
2340 if (has_name_match)
2341 {
2342 packet.PutCString ("name:");
2343 packet.PutBytesAsRawHex8(name, ::strlen(name));
2344 packet.PutChar (';');
2345 }
2346 }
2347
2348 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002349 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002350 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002351 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002352 if (match_info.GetProcessInfo().UserIDIsValid())
2353 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2354 if (match_info.GetProcessInfo().GroupIDIsValid())
2355 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002356 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2357 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2358 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2359 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2360 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2361 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2362 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2363 {
2364 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2365 const llvm::Triple &triple = match_arch.GetTriple();
2366 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00002367 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002368 packet.PutChar (';');
2369 }
2370 }
2371 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00002372 // Increase timeout as the first qfProcessInfo packet takes a long time
2373 // on Android. The value of 1min was arrived at empirically.
2374 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00002375 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002376 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002377 do
2378 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002379 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002380 if (!DecodeProcessInfoResponse (response, process_info))
2381 break;
2382 process_infos.Append(process_info);
2383 response.GetStringRef().clear();
2384 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002385 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002386 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002387 else
2388 {
2389 m_supports_qfProcessInfo = false;
2390 return 0;
2391 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002392 }
2393 return process_infos.GetSize();
2394
2395}
2396
2397bool
2398GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2399{
2400 if (m_supports_qUserName)
2401 {
2402 char packet[32];
2403 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002404 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002405 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002406 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002407 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002408 if (response.IsNormalResponse())
2409 {
2410 // Make sure we parsed the right number of characters. The response is
2411 // the hex encoded user name and should make up the entire packet.
2412 // If there are any non-hex ASCII bytes, the length won't match below..
2413 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2414 return true;
2415 }
2416 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002417 else
2418 {
2419 m_supports_qUserName = false;
2420 return false;
2421 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002422 }
2423 return false;
2424
2425}
2426
2427bool
2428GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2429{
2430 if (m_supports_qGroupName)
2431 {
2432 char packet[32];
2433 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002434 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002435 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002436 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002437 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002438 if (response.IsNormalResponse())
2439 {
2440 // Make sure we parsed the right number of characters. The response is
2441 // the hex encoded group name and should make up the entire packet.
2442 // If there are any non-hex ASCII bytes, the length won't match below..
2443 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2444 return true;
2445 }
2446 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002447 else
2448 {
2449 m_supports_qGroupName = false;
2450 return false;
2451 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002452 }
2453 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002454}
Greg Clayton32e0a752011-03-30 18:16:51 +00002455
Ewan Crawford78baa192015-05-13 09:18:18 +00002456bool
2457GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
2458{
2459 // Form non-stop packet request
2460 char packet[32];
2461 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2462 assert(packet_len < (int)sizeof(packet));
2463
2464 StringExtractorGDBRemote response;
2465 // Send to target
2466 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2467 if (response.IsOKResponse())
2468 return true;
2469
2470 // Failed or not supported
2471 return false;
2472
2473}
2474
Greg Claytone034a042015-05-21 20:52:06 +00002475static void
2476MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
2477{
2478 packet.Clear();
2479 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2480 uint32_t bytes_left = send_size;
2481 while (bytes_left > 0)
2482 {
2483 if (bytes_left >= 26)
2484 {
2485 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2486 bytes_left -= 26;
2487 }
2488 else
2489 {
2490 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2491 bytes_left = 0;
2492 }
2493 }
2494}
2495
2496template<typename T>
2497T calculate_standard_deviation(const std::vector<T> &v)
2498{
2499 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
2500 T mean = sum / (T)v.size();
2501 T accum = T(0);
2502 std::for_each (std::begin(v), std::end(v), [&](const T d) {
2503 T delta = d - mean;
2504 accum += delta * delta;
2505 });
2506
2507 T stdev = sqrt(accum / (v.size()-1));
2508 return stdev;
2509}
2510
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002511void
Greg Claytone034a042015-05-21 20:52:06 +00002512GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, bool json, Stream &strm)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002513{
2514 uint32_t i;
2515 TimeValue start_time, end_time;
2516 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002517 if (SendSpeedTestPacket (0, 0))
2518 {
Greg Claytone034a042015-05-21 20:52:06 +00002519 StreamString packet;
2520 if (json)
2521 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
2522 else
2523 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
2524 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00002525
Greg Claytone034a042015-05-21 20:52:06 +00002526 uint32_t result_idx = 0;
2527 uint32_t send_size;
2528 std::vector<float> packet_times;
2529
2530 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
2531 {
2532 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
2533 {
2534 MakeSpeedTestPacket (packet, send_size, recv_size);
2535
2536 packet_times.clear();
2537 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00002538 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00002539 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00002540 {
Greg Claytone034a042015-05-21 20:52:06 +00002541 TimeValue packet_start_time = TimeValue::Now();
2542 StringExtractorGDBRemote response;
2543 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2544 TimeValue packet_end_time = TimeValue::Now();
2545 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
2546 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002547 }
2548 end_time = TimeValue::Now();
2549 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00002550
2551 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2552 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2553 float average_ms_per_packet = total_ms / num_packets;
2554 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
2555 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00002556 {
Greg Claytone034a042015-05-21 20:52:06 +00002557 strm.Printf ("%s\n {\"send_size\" : %6" PRIu32 ", \"recv_size\" : %6" PRIu32 ", \"total_time_nsec\" : %12" PRIu64 ", \"standard_deviation_nsec\" : %9" PRIu64 " }", result_idx > 0 ? "," : "", send_size, recv_size, total_time_nsec, (uint64_t)standard_deviation);
2558 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00002559 }
2560 else
2561 {
Greg Claytone034a042015-05-21 20:52:06 +00002562 strm.Printf ("qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %9.2f packets/sec (%10.6f ms per packet) with standard deviation of %10.6f ms\n",
2563 send_size,
2564 recv_size,
2565 total_time_nsec / TimeValue::NanoSecPerSec,
2566 total_time_nsec % TimeValue::NanoSecPerSec,
2567 packets_per_second,
2568 average_ms_per_packet,
2569 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00002570 }
Greg Claytone034a042015-05-21 20:52:06 +00002571 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002572 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002573 }
Greg Claytone034a042015-05-21 20:52:06 +00002574
2575 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
2576
2577 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
2578 if (json)
2579 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
2580 else
2581 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
2582 strm.Flush();
2583 send_size = 0;
2584 result_idx = 0;
2585 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
2586 {
2587 MakeSpeedTestPacket (packet, send_size, recv_size);
2588
2589 // If we have a receive size, test how long it takes to receive 4MB of data
2590 if (recv_size > 0)
2591 {
2592 start_time = TimeValue::Now();
2593 uint32_t bytes_read = 0;
2594 uint32_t packet_count = 0;
2595 while (bytes_read < k_recv_amount)
2596 {
2597 StringExtractorGDBRemote response;
2598 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2599 bytes_read += recv_size;
2600 ++packet_count;
2601 }
2602 end_time = TimeValue::Now();
2603 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2604 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2605 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2606 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2607 float average_ms_per_packet = total_ms / packet_count;
2608
2609 if (json)
2610 {
2611 strm.Printf ("%s\n {\"send_size\" : %6" PRIu32 ", \"recv_size\" : %6" PRIu32 ", \"total_time_nsec\" : %12" PRIu64 " }", result_idx > 0 ? "," : "", send_size, recv_size, total_time_nsec);
2612 ++result_idx;
2613 }
2614 else
2615 {
2616 strm.Printf ("qSpeedTest(send=%-7u, recv=%-7u) %6u packets needed to receive %2.1fMB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec for %9.2f packets/sec (%10.6f ms per packet)\n",
2617 send_size,
2618 recv_size,
2619 packet_count,
2620 k_recv_amount_mb,
2621 total_time_nsec / TimeValue::NanoSecPerSec,
2622 total_time_nsec % TimeValue::NanoSecPerSec,
2623 mb_second,
2624 packets_per_second,
2625 average_ms_per_packet);
2626 }
2627 strm.Flush();
2628 }
2629 }
2630 if (json)
2631 strm.Printf("\n ]\n }\n}\n");
2632 else
2633 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002634 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002635}
2636
2637bool
2638GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2639{
2640 StreamString packet;
2641 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2642 uint32_t bytes_left = send_size;
2643 while (bytes_left > 0)
2644 {
2645 if (bytes_left >= 26)
2646 {
2647 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2648 bytes_left -= 26;
2649 }
2650 else
2651 {
2652 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2653 bytes_left = 0;
2654 }
2655 }
2656
2657 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002658 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00002659}
Greg Clayton8b82f082011-04-12 05:54:46 +00002660
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002661bool
2662GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
2663 lldb::pid_t &pid,
2664 uint16_t &port,
2665 std::string &socket_name)
Greg Clayton8b82f082011-04-12 05:54:46 +00002666{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002667 pid = LLDB_INVALID_PROCESS_ID;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002668 port = 0;
2669 socket_name.clear();
2670
Greg Clayton8b82f082011-04-12 05:54:46 +00002671 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002672 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002673 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002674 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00002675 if (remote_accept_hostname && remote_accept_hostname[0])
2676 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002677 else
2678 {
Zachary Turner97a14e62014-08-19 17:18:29 +00002679 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00002680 {
2681 // Make the GDB server we launch only accept connections from this host
2682 stream.Printf("host:%s;", hostname.c_str());
2683 }
2684 else
2685 {
2686 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2687 stream.Printf("host:*;");
2688 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002689 }
Vince Harron1b5a74e2015-01-21 22:42:49 +00002690 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00002691 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002692
Zachary Turner54695a32016-08-29 19:58:14 +00002693 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002694 {
Zachary Turner54695a32016-08-29 19:58:14 +00002695 llvm::StringRef name;
2696 llvm::StringRef value;
Greg Clayton8b82f082011-04-12 05:54:46 +00002697 while (response.GetNameColonValue(name, value))
2698 {
Zachary Turner54695a32016-08-29 19:58:14 +00002699 if (name.equals("port"))
2700 value.getAsInteger(0, port);
2701 else if (name.equals("pid"))
2702 value.getAsInteger(0, pid);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002703 else if (name.compare("socket_name") == 0)
2704 {
Zachary Turner54695a32016-08-29 19:58:14 +00002705 StringExtractor extractor(value);
2706 extractor.GetHexByteString(socket_name);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002707 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002708 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002709 return true;
Greg Clayton8b82f082011-04-12 05:54:46 +00002710 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002711 return false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002712}
2713
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00002714size_t
2715GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls)
2716{
2717 connection_urls.clear();
2718
2719 StringExtractorGDBRemote response;
2720 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success)
2721 return 0;
2722
2723 StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef());
2724 if (!data)
2725 return 0;
2726
2727 StructuredData::Array* array = data->GetAsArray();
2728 if (!array)
2729 return 0;
2730
2731 for (size_t i = 0, count = array->GetSize(); i < count; ++i)
2732 {
2733 StructuredData::Dictionary* element = nullptr;
2734 if (!array->GetItemAtIndexAsDictionary(i, element))
2735 continue;
2736
2737 uint16_t port = 0;
2738 if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port")))
2739 port = port_osp->GetIntegerValue(0);
2740
2741 std::string socket_name;
2742 if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name")))
2743 socket_name = socket_name_osp->GetStringValue();
2744
2745 if (port != 0 || !socket_name.empty())
2746 connection_urls.emplace_back(port, socket_name);
2747 }
2748 return connection_urls.size();
2749}
2750
Greg Clayton8b82f082011-04-12 05:54:46 +00002751bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002752GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2753{
2754 StreamString stream;
2755 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2756 const char *packet = stream.GetData();
2757 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002758
Daniel Maleae0f8f572013-08-26 23:57:52 +00002759 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002760 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002761 {
2762 if (response.IsOKResponse())
2763 return true;
2764 }
2765 return false;
2766}
2767
2768bool
Pavel Labath0faf3732016-08-25 08:34:57 +00002769GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid, const Lock &lock)
Greg Clayton8b82f082011-04-12 05:54:46 +00002770{
2771 if (m_curr_tid == tid)
2772 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002773
Greg Clayton8b82f082011-04-12 05:54:46 +00002774 char packet[32];
2775 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002776 if (tid == UINT64_MAX)
2777 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002778 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002779 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002780 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002781 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00002782 if (SendPacketAndWaitForResponse(llvm::StringRef(packet, packet_len), response, lock) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002783 {
2784 if (response.IsOKResponse())
2785 {
2786 m_curr_tid = tid;
2787 return true;
2788 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002789
2790 /*
2791 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
2792 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
2793 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2794 */
2795 if (response.IsUnsupportedResponse() && IsConnected())
2796 {
2797 m_curr_tid = 1;
2798 return true;
2799 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002800 }
2801 return false;
2802}
2803
2804bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002805GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002806{
2807 if (m_curr_tid_run == tid)
2808 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002809
Greg Clayton8b82f082011-04-12 05:54:46 +00002810 char packet[32];
2811 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002812 if (tid == UINT64_MAX)
2813 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002814 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002815 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2816
Andy Gibbsa297a972013-06-19 19:04:53 +00002817 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002818 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002819 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002820 {
2821 if (response.IsOKResponse())
2822 {
2823 m_curr_tid_run = tid;
2824 return true;
2825 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002826
2827 /*
2828 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
2829 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
2830 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2831 */
2832 if (response.IsUnsupportedResponse() && IsConnected())
2833 {
2834 m_curr_tid_run = 1;
2835 return true;
2836 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002837 }
2838 return false;
2839}
2840
2841bool
2842GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2843{
Greg Clayton3dedae12013-12-06 21:45:27 +00002844 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002845 return response.IsNormalResponse();
2846 return false;
2847}
2848
2849bool
Greg Claytonf402f782012-10-13 02:11:55 +00002850GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002851{
2852 if (m_supports_qThreadStopInfo)
2853 {
2854 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002855 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002856 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002857 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002858 {
Greg Claytonef8180a2013-10-15 00:14:28 +00002859 if (response.IsUnsupportedResponse())
2860 m_supports_qThreadStopInfo = false;
2861 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002862 return true;
2863 else
2864 return false;
2865 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002866 else
2867 {
2868 m_supports_qThreadStopInfo = false;
2869 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002870 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002871 return false;
2872}
2873
2874
2875uint8_t
2876GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2877{
Todd Fiala616b8272014-10-09 00:55:04 +00002878 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2879 if (log)
2880 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2881 __FUNCTION__, insert ? "add" : "remove", addr);
2882
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002883 // Check if the stub is known not to support this breakpoint type
2884 if (!SupportsGDBStoppointPacket(type))
2885 return UINT8_MAX;
2886 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00002887 char packet[64];
2888 const int packet_len = ::snprintf (packet,
2889 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002890 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002891 insert ? 'Z' : 'z',
2892 type,
2893 addr,
2894 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002895 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00002896 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002897 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00002898 // Make sure the response is either "OK", "EXX" where XX are two hex digits, or "" (unsupported)
2899 response.SetResponseValidatorToOKErrorNotSupported();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002900 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00002901 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002902 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002903 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00002904 if (response.IsOKResponse())
2905 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002906
2907 // Error while setting breakpoint, send back specific error
2908 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002909 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002910
2911 // Empty packet informs us that breakpoint is not supported
2912 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00002913 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002914 // Disable this breakpoint type since it is unsupported
2915 switch (type)
2916 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002917 case eBreakpointSoftware: m_supports_z0 = false; break;
2918 case eBreakpointHardware: m_supports_z1 = false; break;
2919 case eWatchpointWrite: m_supports_z2 = false; break;
2920 case eWatchpointRead: m_supports_z3 = false; break;
2921 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00002922 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002923 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002924 }
2925 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002926 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00002927 return UINT8_MAX;
2928}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002929
2930size_t
2931GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2932 bool &sequence_mutex_unavailable)
2933{
Greg Claytonadc00cb2011-05-20 23:38:13 +00002934 thread_ids.clear();
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002935
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00002936 Lock lock(*this, false);
2937 if (lock)
Greg Claytonadc00cb2011-05-20 23:38:13 +00002938 {
2939 sequence_mutex_unavailable = false;
2940 StringExtractorGDBRemote response;
2941
Greg Clayton3dedae12013-12-06 21:45:27 +00002942 PacketResult packet_result;
Pavel Labath0faf3732016-08-25 08:34:57 +00002943 for (packet_result = SendPacketAndWaitForResponse("qfThreadInfo", response, lock);
Greg Clayton3dedae12013-12-06 21:45:27 +00002944 packet_result == PacketResult::Success && response.IsNormalResponse();
Pavel Labath0faf3732016-08-25 08:34:57 +00002945 packet_result = SendPacketAndWaitForResponse("qsThreadInfo", response, lock))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002946 {
2947 char ch = response.GetChar();
2948 if (ch == 'l')
2949 break;
2950 if (ch == 'm')
2951 {
2952 do
2953 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002954 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002955
2956 if (tid != LLDB_INVALID_THREAD_ID)
2957 {
2958 thread_ids.push_back (tid);
2959 }
2960 ch = response.GetChar(); // Skip the command separator
2961 } while (ch == ','); // Make sure we got a comma separator
2962 }
2963 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002964
2965 /*
2966 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2967 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
2968 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
2969 * Assume pid=tid=1 in such cases.
2970 */
2971 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
2972 {
2973 thread_ids.push_back (1);
2974 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00002975 }
2976 else
2977 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002978#if defined (LLDB_CONFIGURATION_DEBUG)
2979 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2980#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002981 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002982 if (log)
2983 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002984#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002985 sequence_mutex_unavailable = true;
2986 }
2987 return thread_ids.size();
2988}
Greg Clayton37a0a242012-04-11 00:24:49 +00002989
2990lldb::addr_t
2991GDBRemoteCommunicationClient::GetShlibInfoAddr()
2992{
Pavel Labath83082a02016-08-18 14:33:55 +00002993 StringExtractorGDBRemote response;
2994 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) != PacketResult::Success || !response.IsNormalResponse())
2995 return LLDB_INVALID_ADDRESS;
2996 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
Greg Clayton37a0a242012-04-11 00:24:49 +00002997}
2998
Daniel Maleae0f8f572013-08-26 23:57:52 +00002999lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003000GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3001 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3002 int *status_ptr, // Pass NULL if you don't want the process exit status
3003 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3004 std::string *command_output, // Pass NULL if you don't want the command output
3005 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003006{
3007 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003008 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003009 stream.PutBytesAsRawHex8(command, strlen(command));
3010 stream.PutChar(',');
3011 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003012 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003013 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003014 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003015 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003016 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003017 }
3018 const char *packet = stream.GetData();
3019 int packet_len = stream.GetSize();
3020 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003021 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003022 {
3023 if (response.GetChar() != 'F')
3024 return Error("malformed reply");
3025 if (response.GetChar() != ',')
3026 return Error("malformed reply");
3027 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3028 if (exitcode == UINT32_MAX)
3029 return Error("unable to run remote process");
3030 else if (status_ptr)
3031 *status_ptr = exitcode;
3032 if (response.GetChar() != ',')
3033 return Error("malformed reply");
3034 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3035 if (signo_ptr)
3036 *signo_ptr = signo;
3037 if (response.GetChar() != ',')
3038 return Error("malformed reply");
3039 std::string output;
3040 response.GetEscapedBinaryData(output);
3041 if (command_output)
3042 command_output->assign(output);
3043 return Error();
3044 }
3045 return Error("unable to send packet");
3046}
3047
Greg Claytonfbb76342013-11-20 21:07:01 +00003048Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003049GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3050 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003051{
Chaoren Lind3173f32015-05-29 19:52:29 +00003052 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003053 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003054 stream.PutCString("qPlatform_mkdir:");
3055 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003056 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003057 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003058 const char *packet = stream.GetData();
3059 int packet_len = stream.GetSize();
3060 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003061
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003062 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3063 return Error("failed to send '%s' packet", packet);
3064
3065 if (response.GetChar() != 'F')
3066 return Error("invalid response to '%s' packet", packet);
3067
3068 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003069}
3070
Greg Claytonfbb76342013-11-20 21:07:01 +00003071Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003072GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3073 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003074{
Chaoren Lind3173f32015-05-29 19:52:29 +00003075 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003076 lldb_private::StreamString stream;
3077 stream.PutCString("qPlatform_chmod:");
3078 stream.PutHex32(file_permissions);
3079 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003080 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003081 const char *packet = stream.GetData();
3082 int packet_len = stream.GetSize();
3083 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003084
3085 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3086 return Error("failed to send '%s' packet", packet);
3087
3088 if (response.GetChar() != 'F')
3089 return Error("invalid response to '%s' packet", packet);
3090
Chaoren Lince36c4c2015-05-05 18:43:19 +00003091 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003092}
3093
Daniel Maleae0f8f572013-08-26 23:57:52 +00003094static uint64_t
3095ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3096 uint64_t fail_result,
3097 Error &error)
3098{
3099 response.SetFilePos(0);
3100 if (response.GetChar() != 'F')
3101 return fail_result;
3102 int32_t result = response.GetS32 (-2);
3103 if (result == -2)
3104 return fail_result;
3105 if (response.GetChar() == ',')
3106 {
3107 int result_errno = response.GetS32 (-2);
3108 if (result_errno != -2)
3109 error.SetError(result_errno, eErrorTypePOSIX);
3110 else
3111 error.SetError(-1, eErrorTypeGeneric);
3112 }
3113 else
3114 error.Clear();
3115 return result;
3116}
3117lldb::user_id_t
3118GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3119 uint32_t flags,
3120 mode_t mode,
3121 Error &error)
3122{
Chaoren Lind3173f32015-05-29 19:52:29 +00003123 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003124 lldb_private::StreamString stream;
3125 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003126 if (path.empty())
3127 return UINT64_MAX;
3128 stream.PutCStringAsRawHex8(path.c_str());
3129 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003130 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003131 stream.PutChar(',');
3132 stream.PutHex32(mode);
3133 const char* packet = stream.GetData();
3134 int packet_len = stream.GetSize();
3135 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003136 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003137 {
3138 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3139 }
3140 return UINT64_MAX;
3141}
3142
3143bool
3144GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3145 Error &error)
3146{
3147 lldb_private::StreamString stream;
3148 stream.Printf("vFile:close:%i", (int)fd);
3149 const char* packet = stream.GetData();
3150 int packet_len = stream.GetSize();
3151 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003152 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003153 {
3154 return ParseHostIOPacketResponse (response, -1, error) == 0;
3155 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003156 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003157}
3158
3159// Extension of host I/O packets to get the file size.
3160lldb::user_id_t
3161GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3162{
Chaoren Lind3173f32015-05-29 19:52:29 +00003163 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003164 lldb_private::StreamString stream;
3165 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003166 stream.PutCStringAsRawHex8(path.c_str());
3167 const char* packet = stream.GetData();
3168 int packet_len = stream.GetSize();
3169 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003170 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003171 {
3172 if (response.GetChar() != 'F')
3173 return UINT64_MAX;
3174 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3175 return retcode;
3176 }
3177 return UINT64_MAX;
3178}
3179
Greg Claytonfbb76342013-11-20 21:07:01 +00003180Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003181GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3182 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003183{
Chaoren Lind3173f32015-05-29 19:52:29 +00003184 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003185 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003186 lldb_private::StreamString stream;
3187 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003188 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003189 const char* packet = stream.GetData();
3190 int packet_len = stream.GetSize();
3191 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003192 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003193 {
3194 if (response.GetChar() != 'F')
3195 {
3196 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003197 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003198 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003199 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003200 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003201 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003202 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003203 if (response.GetChar() == ',')
3204 {
3205 int response_errno = response.GetS32(-1);
3206 if (response_errno > 0)
3207 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3208 else
3209 error.SetErrorToGenericError();
3210 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003211 else
3212 error.SetErrorToGenericError();
3213 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003214 else
3215 {
3216 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3217 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003218 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003219 }
3220 else
3221 {
3222 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3223 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003224 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003225}
3226
3227uint64_t
3228GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3229 uint64_t offset,
3230 void *dst,
3231 uint64_t dst_len,
3232 Error &error)
3233{
3234 lldb_private::StreamString stream;
3235 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3236 const char* packet = stream.GetData();
3237 int packet_len = stream.GetSize();
3238 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003239 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003240 {
3241 if (response.GetChar() != 'F')
3242 return 0;
3243 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3244 if (retcode == UINT32_MAX)
3245 return retcode;
3246 const char next = (response.Peek() ? *response.Peek() : 0);
3247 if (next == ',')
3248 return 0;
3249 if (next == ';')
3250 {
3251 response.GetChar(); // skip the semicolon
3252 std::string buffer;
3253 if (response.GetEscapedBinaryData(buffer))
3254 {
3255 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3256 if (data_to_write > 0)
3257 memcpy(dst, &buffer[0], data_to_write);
3258 return data_to_write;
3259 }
3260 }
3261 }
3262 return 0;
3263}
3264
3265uint64_t
3266GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3267 uint64_t offset,
3268 const void* src,
3269 uint64_t src_len,
3270 Error &error)
3271{
3272 lldb_private::StreamGDBRemote stream;
3273 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3274 stream.PutEscapedBytes(src, src_len);
3275 const char* packet = stream.GetData();
3276 int packet_len = stream.GetSize();
3277 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003278 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003279 {
3280 if (response.GetChar() != 'F')
3281 {
3282 error.SetErrorStringWithFormat("write file failed");
3283 return 0;
3284 }
3285 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3286 if (bytes_written == UINT64_MAX)
3287 {
3288 error.SetErrorToGenericError();
3289 if (response.GetChar() == ',')
3290 {
3291 int response_errno = response.GetS32(-1);
3292 if (response_errno > 0)
3293 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3294 }
3295 return 0;
3296 }
3297 return bytes_written;
3298 }
3299 else
3300 {
3301 error.SetErrorString ("failed to send vFile:pwrite packet");
3302 }
3303 return 0;
3304}
3305
Greg Claytonfbb76342013-11-20 21:07:01 +00003306Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003307GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003308{
Chaoren Lind3173f32015-05-29 19:52:29 +00003309 std::string src_path{src.GetPath(false)},
3310 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003311 Error error;
3312 lldb_private::StreamGDBRemote stream;
3313 stream.PutCString("vFile:symlink:");
3314 // the unix symlink() command reverses its parameters where the dst if first,
3315 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003316 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003317 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003318 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003319 const char* packet = stream.GetData();
3320 int packet_len = stream.GetSize();
3321 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003322 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003323 {
3324 if (response.GetChar() == 'F')
3325 {
3326 uint32_t result = response.GetU32(UINT32_MAX);
3327 if (result != 0)
3328 {
3329 error.SetErrorToGenericError();
3330 if (response.GetChar() == ',')
3331 {
3332 int response_errno = response.GetS32(-1);
3333 if (response_errno > 0)
3334 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3335 }
3336 }
3337 }
3338 else
3339 {
3340 // Should have returned with 'F<result>[,<errno>]'
3341 error.SetErrorStringWithFormat("symlink failed");
3342 }
3343 }
3344 else
3345 {
3346 error.SetErrorString ("failed to send vFile:symlink packet");
3347 }
3348 return error;
3349}
3350
3351Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003352GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00003353{
Chaoren Lind3173f32015-05-29 19:52:29 +00003354 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003355 Error error;
3356 lldb_private::StreamGDBRemote stream;
3357 stream.PutCString("vFile:unlink:");
3358 // the unix symlink() command reverses its parameters where the dst if first,
3359 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003360 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003361 const char* packet = stream.GetData();
3362 int packet_len = stream.GetSize();
3363 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003364 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003365 {
3366 if (response.GetChar() == 'F')
3367 {
3368 uint32_t result = response.GetU32(UINT32_MAX);
3369 if (result != 0)
3370 {
3371 error.SetErrorToGenericError();
3372 if (response.GetChar() == ',')
3373 {
3374 int response_errno = response.GetS32(-1);
3375 if (response_errno > 0)
3376 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3377 }
3378 }
3379 }
3380 else
3381 {
3382 // Should have returned with 'F<result>[,<errno>]'
3383 error.SetErrorStringWithFormat("unlink failed");
3384 }
3385 }
3386 else
3387 {
3388 error.SetErrorString ("failed to send vFile:unlink packet");
3389 }
3390 return error;
3391}
3392
Daniel Maleae0f8f572013-08-26 23:57:52 +00003393// Extension of host I/O packets to get whether a file exists.
3394bool
3395GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3396{
Chaoren Lind3173f32015-05-29 19:52:29 +00003397 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003398 lldb_private::StreamString stream;
3399 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003400 stream.PutCStringAsRawHex8(path.c_str());
3401 const char* packet = stream.GetData();
3402 int packet_len = stream.GetSize();
3403 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003404 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003405 {
3406 if (response.GetChar() != 'F')
3407 return false;
3408 if (response.GetChar() != ',')
3409 return false;
3410 bool retcode = (response.GetChar() != '0');
3411 return retcode;
3412 }
3413 return false;
3414}
3415
3416bool
3417GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3418 uint64_t &high,
3419 uint64_t &low)
3420{
Chaoren Lind3173f32015-05-29 19:52:29 +00003421 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003422 lldb_private::StreamString stream;
3423 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003424 stream.PutCStringAsRawHex8(path.c_str());
3425 const char* packet = stream.GetData();
3426 int packet_len = stream.GetSize();
3427 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003428 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003429 {
3430 if (response.GetChar() != 'F')
3431 return false;
3432 if (response.GetChar() != ',')
3433 return false;
3434 if (response.Peek() && *response.Peek() == 'x')
3435 return false;
3436 low = response.GetHexMaxU64(false, UINT64_MAX);
3437 high = response.GetHexMaxU64(false, UINT64_MAX);
3438 return true;
3439 }
3440 return false;
3441}
Greg Claytonf74cf862013-11-13 23:28:31 +00003442
3443bool
Jason Molendaa3329782014-03-29 18:54:20 +00003444GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3445{
3446 // Some targets have issues with g/G packets and we need to avoid using them
3447 if (m_avoid_g_packets == eLazyBoolCalculate)
3448 {
3449 if (process)
3450 {
3451 m_avoid_g_packets = eLazyBoolNo;
3452 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3453 if (arch.IsValid()
3454 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3455 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00003456 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00003457 {
3458 m_avoid_g_packets = eLazyBoolYes;
3459 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3460 if (gdb_server_version != 0)
3461 {
3462 const char *gdb_server_name = GetGDBServerProgramName();
3463 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3464 {
3465 if (gdb_server_version >= 310)
3466 m_avoid_g_packets = eLazyBoolNo;
3467 }
3468 }
3469 }
3470 }
3471 }
3472 return m_avoid_g_packets == eLazyBoolYes;
3473}
3474
Pavel Labathb42b48e2016-08-19 12:31:49 +00003475DataBufferSP
Pavel Labath0faf3732016-08-25 08:34:57 +00003476GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, const Lock &lock)
Greg Claytonf74cf862013-11-13 23:28:31 +00003477{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003478 StreamString payload;
3479 payload.Printf("p%x", reg);
Pavel Labathb42b48e2016-08-19 12:31:49 +00003480 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003481 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) != PacketResult::Success ||
Pavel Labathb42b48e2016-08-19 12:31:49 +00003482 !response.IsNormalResponse())
3483 return nullptr;
3484
3485 DataBufferSP buffer_sp(new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3486 response.GetHexBytes(buffer_sp->GetBytes(), buffer_sp->GetByteSize(), '\xcc');
3487 return buffer_sp;
Greg Claytonf74cf862013-11-13 23:28:31 +00003488}
3489
Pavel Labathb42b48e2016-08-19 12:31:49 +00003490DataBufferSP
Pavel Labath0faf3732016-08-25 08:34:57 +00003491GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid, const Lock &lock)
Greg Claytonf74cf862013-11-13 23:28:31 +00003492{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003493 StreamString payload;
3494 payload.PutChar('g');
Pavel Labathb42b48e2016-08-19 12:31:49 +00003495 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003496 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) != PacketResult::Success ||
Pavel Labathb42b48e2016-08-19 12:31:49 +00003497 !response.IsNormalResponse())
3498 return nullptr;
3499
3500 DataBufferSP buffer_sp(new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3501 response.GetHexBytes(buffer_sp->GetBytes(), buffer_sp->GetByteSize(), '\xcc');
3502 return buffer_sp;
Greg Claytonf74cf862013-11-13 23:28:31 +00003503}
Pavel Labath56d72622016-08-17 08:53:31 +00003504
3505bool
Pavel Labath0faf3732016-08-25 08:34:57 +00003506GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid, uint32_t reg_num, llvm::ArrayRef<uint8_t> data,
3507 const Lock &lock)
Pavel Labath56d72622016-08-17 08:53:31 +00003508{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003509 StreamString payload;
3510 payload.Printf("P%x=", reg_num);
3511 payload.PutBytesAsRawHex8(data.data(), data.size(), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Pavel Labath56d72622016-08-17 08:53:31 +00003512 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003513 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) ==
Pavel Labathb42b48e2016-08-19 12:31:49 +00003514 PacketResult::Success &&
3515 response.IsOKResponse();
Pavel Labath56d72622016-08-17 08:53:31 +00003516}
3517
3518bool
Pavel Labath0faf3732016-08-25 08:34:57 +00003519GDBRemoteCommunicationClient::WriteAllRegisters(lldb::tid_t tid, llvm::ArrayRef<uint8_t> data, const Lock &lock)
Pavel Labath56d72622016-08-17 08:53:31 +00003520{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003521 StreamString payload;
3522 payload.PutChar('G');
Pavel Labathb42b48e2016-08-19 12:31:49 +00003523 payload.PutBytesAsRawHex8(data.data(), data.size(), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Pavel Labath56d72622016-08-17 08:53:31 +00003524 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003525 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) ==
Pavel Labathb42b48e2016-08-19 12:31:49 +00003526 PacketResult::Success &&
3527 response.IsOKResponse();
Pavel Labath56d72622016-08-17 08:53:31 +00003528}
3529
Greg Claytonf74cf862013-11-13 23:28:31 +00003530bool
3531GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3532{
3533 save_id = 0; // Set to invalid save ID
3534 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3535 return false;
Pavel Labath0faf3732016-08-25 08:34:57 +00003536
3537 Lock lock(*this, false);
3538 if (!lock)
3539 {
3540 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3541 if (log)
3542 log->Printf("GDBRemoteCommunicationClient::%s failed to get sequence mutex", __FUNCTION__);
3543 return false;
3544 }
3545
Greg Claytonf74cf862013-11-13 23:28:31 +00003546 m_supports_QSaveRegisterState = eLazyBoolYes;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003547 StreamString payload;
3548 payload.PutCString("QSaveRegisterState");
3549 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003550 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) != PacketResult::Success)
Pavel Labath4b6f9592016-08-18 08:30:03 +00003551 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003552
Pavel Labath4b6f9592016-08-18 08:30:03 +00003553 if (response.IsUnsupportedResponse())
3554 m_supports_QSaveRegisterState = eLazyBoolNo;
3555
3556 const uint32_t response_save_id = response.GetU32(0);
3557 if (response_save_id == 0)
3558 return false;
3559
3560 save_id = response_save_id;
3561 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003562}
3563
3564bool
3565GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3566{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003567 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00003568 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3569 // order to be useful
3570 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3571 return false;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003572
Pavel Labath0faf3732016-08-25 08:34:57 +00003573 Lock lock(*this, false);
3574 if (!lock)
3575 {
3576 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3577 if (log)
3578 log->Printf("GDBRemoteCommunicationClient::%s failed to get sequence mutex", __FUNCTION__);
3579 return false;
3580 }
3581
Pavel Labath4b6f9592016-08-18 08:30:03 +00003582 StreamString payload;
3583 payload.Printf("QRestoreRegisterState:%u", save_id);
3584 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003585 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) != PacketResult::Success)
Pavel Labath4b6f9592016-08-18 08:30:03 +00003586 return false;
3587
3588 if (response.IsOKResponse())
3589 return true;
3590
3591 if (response.IsUnsupportedResponse())
3592 m_supports_QSaveRegisterState = eLazyBoolNo;
Greg Claytonf74cf862013-11-13 23:28:31 +00003593 return false;
3594}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003595
3596bool
Pavel Labath27402d22016-08-18 12:32:41 +00003597GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid)
3598{
3599 if (!GetSyncThreadStateSupported())
3600 return false;
3601
3602 StreamString packet;
3603 StringExtractorGDBRemote response;
3604 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3605 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3606 GDBRemoteCommunication::PacketResult::Success &&
3607 response.IsOKResponse();
3608}
3609
3610bool
3611GDBRemoteCommunicationClient::GetModuleInfo(const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3612 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003613{
Stephane Sezer6f455292016-01-08 00:00:17 +00003614 if (!m_supports_qModuleInfo)
3615 return false;
3616
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00003617 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003618 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003619 return false;
3620
3621 StreamString packet;
3622 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003623 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003624 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00003625 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00003626 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003627
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003628 StringExtractorGDBRemote response;
3629 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
3630 return false;
3631
Stephane Sezer6f455292016-01-08 00:00:17 +00003632 if (response.IsErrorResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003633 return false;
3634
Stephane Sezer6f455292016-01-08 00:00:17 +00003635 if (response.IsUnsupportedResponse ())
3636 {
3637 m_supports_qModuleInfo = false;
3638 return false;
3639 }
3640
Zachary Turner54695a32016-08-29 19:58:14 +00003641 llvm::StringRef name;
3642 llvm::StringRef value;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003643
3644 module_spec.Clear ();
3645 module_spec.GetFileSpec () = module_file_spec;
3646
3647 while (response.GetNameColonValue (name, value))
3648 {
3649 if (name == "uuid" || name == "md5")
3650 {
Zachary Turner54695a32016-08-29 19:58:14 +00003651 StringExtractor extractor(value);
3652 std::string uuid;
3653 extractor.GetHexByteString(uuid);
3654 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003655 }
3656 else if (name == "triple")
3657 {
Zachary Turner54695a32016-08-29 19:58:14 +00003658 StringExtractor extractor(value);
3659 std::string triple;
3660 extractor.GetHexByteString(triple);
3661 module_spec.GetArchitecture().SetTriple(triple.c_str());
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003662 }
3663 else if (name == "file_offset")
3664 {
Zachary Turner54695a32016-08-29 19:58:14 +00003665 uint64_t ival = 0;
3666 if (!value.getAsInteger(16, ival))
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003667 module_spec.SetObjectOffset (ival);
3668 }
3669 else if (name == "file_size")
3670 {
Zachary Turner54695a32016-08-29 19:58:14 +00003671 uint64_t ival = 0;
3672 if (!value.getAsInteger(16, ival))
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003673 module_spec.SetObjectSize (ival);
3674 }
3675 else if (name == "file_path")
3676 {
Zachary Turner54695a32016-08-29 19:58:14 +00003677 StringExtractor extractor(value);
3678 std::string path;
3679 extractor.GetHexByteString(path);
3680 module_spec.GetFileSpec() = FileSpec(path.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003681 }
3682 }
3683
3684 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003685}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003686
3687// query the target remote for extended information using the qXfer packet
3688//
3689// example: object='features', annex='target.xml', out=<xml output>
3690// return: 'true' on success
3691// 'false' on failure (err set)
3692bool
3693GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
3694 const lldb_private::ConstString annex,
3695 std::string & out,
3696 lldb_private::Error & err) {
3697
3698 std::stringstream output;
3699 StringExtractorGDBRemote chunk;
3700
Greg Claytond04f0ed2015-05-26 18:00:51 +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
3708 // loop until all data has been read
3709 while ( active ) {
3710
3711 // send query extended feature packet
3712 std::stringstream packet;
3713 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00003714 << object.AsCString("") << ":read:"
3715 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00003716 << std::hex << offset << ","
3717 << std::hex << size;
3718
3719 GDBRemoteCommunication::PacketResult res =
3720 SendPacketAndWaitForResponse( packet.str().c_str(),
3721 chunk,
3722 false );
3723
3724 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
3725 err.SetErrorString( "Error sending $qXfer packet" );
3726 return false;
3727 }
3728
3729 const std::string & str = chunk.GetStringRef( );
3730 if ( str.length() == 0 ) {
3731 // should have some data in chunk
3732 err.SetErrorString( "Empty response from $qXfer packet" );
3733 return false;
3734 }
3735
3736 // check packet code
3737 switch ( str[0] ) {
3738 // last chunk
3739 case ( 'l' ):
3740 active = false;
Jason Molenda62e06812016-02-16 04:14:33 +00003741 LLVM_FALLTHROUGH;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003742
3743 // more chunks
3744 case ( 'm' ) :
3745 if ( str.length() > 1 )
3746 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00003747 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003748 break;
3749
3750 // unknown chunk
3751 default:
3752 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
3753 return false;
3754 }
3755 }
3756
3757 out = output.str( );
3758 err.Success( );
3759 return true;
3760}
Greg Clayton0b90be12015-06-23 21:27:50 +00003761
3762// Notify the target that gdb is prepared to serve symbol lookup requests.
3763// packet: "qSymbol::"
3764// reply:
3765// OK The target does not need to look up any (more) symbols.
3766// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
3767// LLDB may provide the value by sending another qSymbol packet
3768// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003769//
3770// Three examples:
3771//
3772// lldb sends: qSymbol::
3773// lldb receives: OK
3774// Remote gdb stub does not need to know the addresses of any symbols, lldb does not
3775// need to ask again in this session.
3776//
3777// lldb sends: qSymbol::
3778// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3779// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3780// lldb receives: OK
3781// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does not know
3782// the address at this time. lldb needs to send qSymbol:: again when it has more
3783// solibs loaded.
3784//
3785// lldb sends: qSymbol::
3786// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3787// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3788// lldb receives: OK
3789// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says that it
3790// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it does not
3791// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003792
3793void
3794GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
3795{
Jason Molenda50018d32016-01-13 04:08:10 +00003796 // Set to true once we've resolved a symbol to an address for the remote stub.
3797 // If we get an 'OK' response after this, the remote stub doesn't need any more
3798 // symbols and we can stop asking.
3799 bool symbol_response_provided = false;
3800
Ed Maste75500e72016-07-19 15:28:02 +00003801 // Is this the initial qSymbol:: packet?
Jason Molenda50018d32016-01-13 04:08:10 +00003802 bool first_qsymbol_query = true;
3803
3804 if (m_supports_qSymbol && m_qSymbol_requests_done == false)
Greg Clayton0b90be12015-06-23 21:27:50 +00003805 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003806 Lock lock(*this, false);
3807 if (lock)
Greg Clayton0b90be12015-06-23 21:27:50 +00003808 {
3809 StreamString packet;
3810 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00003811 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003812 while (SendPacketAndWaitForResponse(packet.GetString(), response, lock) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00003813 {
Greg Clayton42b01482015-08-11 22:07:46 +00003814 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00003815 {
Jason Molenda50018d32016-01-13 04:08:10 +00003816 if (symbol_response_provided || first_qsymbol_query)
3817 {
3818 m_qSymbol_requests_done = true;
3819 }
3820
Greg Clayton42b01482015-08-11 22:07:46 +00003821 // We are done serving symbols requests
3822 return;
3823 }
Jason Molenda50018d32016-01-13 04:08:10 +00003824 first_qsymbol_query = false;
Greg Clayton0b90be12015-06-23 21:27:50 +00003825
Greg Clayton42b01482015-08-11 22:07:46 +00003826 if (response.IsUnsupportedResponse())
3827 {
3828 // qSymbol is not supported by the current GDB server we are connected to
3829 m_supports_qSymbol = false;
3830 return;
3831 }
3832 else
3833 {
3834 llvm::StringRef response_str(response.GetStringRef());
3835 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00003836 {
Greg Clayton42b01482015-08-11 22:07:46 +00003837 response.SetFilePos(strlen("qSymbol:"));
3838 std::string symbol_name;
3839 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00003840 {
Greg Clayton42b01482015-08-11 22:07:46 +00003841 if (symbol_name.empty())
3842 return;
3843
3844 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3845 lldb_private::SymbolContextList sc_list;
3846 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00003847 {
Greg Clayton42b01482015-08-11 22:07:46 +00003848 const size_t num_scs = sc_list.GetSize();
3849 for (size_t sc_idx=0; sc_idx<num_scs && symbol_load_addr == LLDB_INVALID_ADDRESS; ++sc_idx)
Greg Clayton0b90be12015-06-23 21:27:50 +00003850 {
Greg Clayton42b01482015-08-11 22:07:46 +00003851 SymbolContext sc;
3852 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00003853 {
Greg Clayton42b01482015-08-11 22:07:46 +00003854 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00003855 {
Greg Clayton42b01482015-08-11 22:07:46 +00003856 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00003857 {
Greg Clayton42b01482015-08-11 22:07:46 +00003858 case eSymbolTypeInvalid:
3859 case eSymbolTypeAbsolute:
3860 case eSymbolTypeUndefined:
3861 case eSymbolTypeSourceFile:
3862 case eSymbolTypeHeaderFile:
3863 case eSymbolTypeObjectFile:
3864 case eSymbolTypeCommonBlock:
3865 case eSymbolTypeBlock:
3866 case eSymbolTypeLocal:
3867 case eSymbolTypeParam:
3868 case eSymbolTypeVariable:
3869 case eSymbolTypeVariableType:
3870 case eSymbolTypeLineEntry:
3871 case eSymbolTypeLineHeader:
3872 case eSymbolTypeScopeBegin:
3873 case eSymbolTypeScopeEnd:
3874 case eSymbolTypeAdditional:
3875 case eSymbolTypeCompiler:
3876 case eSymbolTypeInstrumentation:
3877 case eSymbolTypeTrampoline:
3878 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00003879
Greg Clayton42b01482015-08-11 22:07:46 +00003880 case eSymbolTypeCode:
3881 case eSymbolTypeResolver:
3882 case eSymbolTypeData:
3883 case eSymbolTypeRuntime:
3884 case eSymbolTypeException:
3885 case eSymbolTypeObjCClass:
3886 case eSymbolTypeObjCMetaClass:
3887 case eSymbolTypeObjCIVar:
3888 case eSymbolTypeReExported:
3889 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
3890 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00003891 }
3892 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003893 }
3894 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003895 }
Greg Clayton42b01482015-08-11 22:07:46 +00003896 // This is the normal path where our symbol lookup was successful and we want
3897 // to send a packet with the new symbol value and see if another lookup needs to be
3898 // done.
3899
3900 // Change "packet" to contain the requested symbol value and name
3901 packet.Clear();
3902 packet.PutCString("qSymbol:");
3903 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
Jason Molenda50018d32016-01-13 04:08:10 +00003904 {
Greg Clayton42b01482015-08-11 22:07:46 +00003905 packet.Printf("%" PRIx64, symbol_load_addr);
Jason Molenda50018d32016-01-13 04:08:10 +00003906 symbol_response_provided = true;
3907 }
3908 else
3909 {
3910 symbol_response_provided = false;
3911 }
Greg Clayton42b01482015-08-11 22:07:46 +00003912 packet.PutCString(":");
3913 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3914 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003915 }
3916 }
3917 }
3918 }
3919 // If we make it here, the symbol request packet response wasn't valid or
3920 // our symbol lookup failed so we must abort
3921 return;
3922
3923 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003924 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
3925 {
3926 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.", __FUNCTION__);
3927 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003928 }
3929}
3930
Todd Fiala75930012016-08-19 04:21:48 +00003931StructuredData::Array*
3932GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins()
3933{
3934 if (!m_supported_async_json_packets_is_valid)
3935 {
3936 // Query the server for the array of supported asynchronous JSON
3937 // packets.
3938 m_supported_async_json_packets_is_valid = true;
3939
3940 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
3941 GDBR_LOG_PROCESS));
3942
3943 // Poll it now.
3944 StringExtractorGDBRemote response;
3945 const bool send_async = false;
3946 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3947 send_async) == PacketResult::Success)
3948 {
3949 m_supported_async_json_packets_sp = StructuredData::ParseJSON(
3950 response.GetStringRef());
3951 if (m_supported_async_json_packets_sp &&
3952 !m_supported_async_json_packets_sp->GetAsArray())
3953 {
3954 // We were returned something other than a JSON array. This
3955 // is invalid. Clear it out.
3956 if (log)
3957 log->Printf("GDBRemoteCommunicationClient::%s(): "
3958 "QSupportedAsyncJSONPackets returned invalid "
3959 "result: %s", __FUNCTION__,
3960 response.GetStringRef().c_str());
3961 m_supported_async_json_packets_sp.reset();
3962 }
3963 }
3964 else
3965 {
3966 if (log)
3967 log->Printf("GDBRemoteCommunicationClient::%s(): "
3968 "QSupportedAsyncJSONPackets unsupported",
3969 __FUNCTION__);
3970 }
3971
Pavel Labath849cc1a2016-08-23 12:10:09 +00003972 if (log && m_supported_async_json_packets_sp)
Todd Fiala75930012016-08-19 04:21:48 +00003973 {
3974 StreamString stream;
3975 m_supported_async_json_packets_sp->Dump(stream);
3976 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3977 "JSON packets: %s", __FUNCTION__,
3978 stream.GetString().c_str());
3979 }
3980 }
3981
3982 return m_supported_async_json_packets_sp
3983 ? m_supported_async_json_packets_sp->GetAsArray()
3984 : nullptr;
3985}
3986
3987Error
3988GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3989 const ConstString &type_name,
3990 const StructuredData::ObjectSP &config_sp)
3991{
3992 Error error;
3993
3994 if (type_name.GetLength() == 0)
3995 {
3996 error.SetErrorString("invalid type_name argument");
3997 return error;
3998 }
3999
4000 // Build command: Configure{type_name}: serialized config
4001 // data.
4002 StreamGDBRemote stream;
4003 stream.PutCString("QConfigure");
4004 stream.PutCString(type_name.AsCString());
4005 stream.PutChar(':');
4006 if (config_sp)
4007 {
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.
4014 stream.PutEscapedBytes(unescaped_stream.GetData(),
4015 unescaped_stream.GetSize());
4016 }
4017 stream.Flush();
4018
4019 // Send the packet.
4020 const bool send_async = false;
4021 StringExtractorGDBRemote response;
4022 auto result = SendPacketAndWaitForResponse(stream.GetString().c_str(),
4023 response, send_async);
4024 if (result == PacketResult::Success)
4025 {
4026 // We failed if the config result comes back other than OK.
4027 if (strcmp(response.GetStringRef().c_str(), "OK") == 0)
4028 {
4029 // Okay!
4030 error.Clear();
4031 }
4032 else
4033 {
4034 error.SetErrorStringWithFormat("configuring StructuredData feature "
4035 "%s failed with error %s",
4036 type_name.AsCString(),
4037 response.GetStringRef().c_str());
4038 }
4039 }
4040 else
4041 {
4042 // Can we get more data here on the failure?
4043 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4044 "failed when sending packet: "
4045 "PacketResult=%d", type_name.AsCString(),
4046 result);
4047 }
4048 return error;
4049}
4050
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004051void
4052GDBRemoteCommunicationClient::OnRunPacketSent(bool first)
4053{
4054 GDBRemoteClientBase::OnRunPacketSent(first);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004055 m_curr_tid = LLDB_INVALID_THREAD_ID;
4056}