blob: 8cfe331ee16f3605f34b8f9db6382bebe22de07c [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"))
Pavel Labathe1c716c2016-08-30 11:17:00 +00001817 {
Zachary Turner54695a32016-08-29 19:58:14 +00001818 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
Pavel Labathe1c716c2016-08-30 11:17:00 +00001819 num = m_num_supported_hardware_watchpoints;
1820 }
Johnny Chen64637202012-05-23 21:09:52 +00001821 }
1822 }
1823 else
1824 {
1825 m_supports_watchpoint_support_info = eLazyBoolNo;
1826 }
1827 }
1828
1829 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1830 {
1831 error.SetErrorString("qWatchpointSupportInfo is not supported");
1832 }
1833 return error;
1834
1835}
Greg Clayton46fb5582011-11-18 07:03:08 +00001836
Enrico Granataf04a2192012-07-13 23:18:48 +00001837lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00001838GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00001839{
1840 Error error(GetWatchpointSupportInfo(num));
1841 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00001842 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00001843 return error;
1844}
1845
1846lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00001847GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00001848{
1849 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00001850 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00001851
1852 // we assume watchpoints will happen after running the relevant opcode
1853 // and we only want to override this behavior if we have explicitly
1854 // received a qHostInfo telling us otherwise
1855 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00001856 {
1857 // On targets like MIPS, watchpoint exceptions are always generated
1858 // before the instruction is executed. The connected target may not
1859 // support qHostInfo or qWatchpointSupportInfo packets.
1860 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
1861 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1862 after = false;
1863 else
1864 after = true;
1865 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001866 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00001867 {
1868 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1869 // if it is not calculated before.
1870 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1871 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
1872 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1873 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1874
Enrico Granataf04a2192012-07-13 23:18:48 +00001875 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00001876 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001877 return error;
1878}
1879
Greg Clayton576d8832011-03-22 04:00:09 +00001880int
Chaoren Lind3173f32015-05-29 19:52:29 +00001881GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001882{
Chaoren Lind3173f32015-05-29 19:52:29 +00001883 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001884 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001885 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001886 StreamString packet;
1887 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001888 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001889
1890 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001891 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001892 {
1893 if (response.IsOKResponse())
1894 return 0;
1895 uint8_t error = response.GetError();
1896 if (error)
1897 return error;
1898 }
1899 }
1900 return -1;
1901}
1902
1903int
Chaoren Lind3173f32015-05-29 19:52:29 +00001904GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001905{
Chaoren Lind3173f32015-05-29 19:52:29 +00001906 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001907 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001908 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001909 StreamString packet;
1910 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001911 packet.PutCStringAsRawHex8(path.c_str());
1912
Greg Clayton576d8832011-03-22 04:00:09 +00001913 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001914 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001915 {
1916 if (response.IsOKResponse())
1917 return 0;
1918 uint8_t error = response.GetError();
1919 if (error)
1920 return error;
1921 }
1922 }
1923 return -1;
1924}
1925
1926int
Chaoren Lind3173f32015-05-29 19:52:29 +00001927GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001928{
Chaoren Lind3173f32015-05-29 19:52:29 +00001929 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001930 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001931 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001932 StreamString packet;
1933 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001934 packet.PutCStringAsRawHex8(path.c_str());
1935
Greg Clayton576d8832011-03-22 04:00:09 +00001936 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001937 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001938 {
1939 if (response.IsOKResponse())
1940 return 0;
1941 uint8_t error = response.GetError();
1942 if (error)
1943 return error;
1944 }
1945 }
1946 return -1;
1947}
1948
Greg Claytonfbb76342013-11-20 21:07:01 +00001949bool
Chaoren Lind3173f32015-05-29 19:52:29 +00001950GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00001951{
1952 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001953 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00001954 {
1955 if (response.IsUnsupportedResponse())
1956 return false;
1957 if (response.IsErrorResponse())
1958 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00001959 std::string cwd;
1960 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00001961 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00001962 return !cwd.empty();
1963 }
1964 return false;
1965}
1966
Greg Clayton576d8832011-03-22 04:00:09 +00001967int
Chaoren Lind3173f32015-05-29 19:52:29 +00001968GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00001969{
Chaoren Lind3173f32015-05-29 19:52:29 +00001970 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00001971 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001972 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001973 StreamString packet;
1974 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001975 packet.PutCStringAsRawHex8(path.c_str());
1976
Greg Clayton576d8832011-03-22 04:00:09 +00001977 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001978 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001979 {
1980 if (response.IsOKResponse())
1981 return 0;
1982 uint8_t error = response.GetError();
1983 if (error)
1984 return error;
1985 }
1986 }
1987 return -1;
1988}
1989
1990int
1991GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1992{
Greg Clayton32e0a752011-03-30 18:16:51 +00001993 char packet[32];
1994 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00001995 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00001996 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001997 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001998 {
1999 if (response.IsOKResponse())
2000 return 0;
2001 uint8_t error = response.GetError();
2002 if (error)
2003 return error;
2004 }
2005 return -1;
2006}
Greg Clayton32e0a752011-03-30 18:16:51 +00002007
Jim Ingham106d0282014-06-25 02:32:56 +00002008int
2009GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2010{
2011 char packet[32];
2012 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2013 assert (packet_len < (int)sizeof(packet));
2014 StringExtractorGDBRemote response;
2015 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2016 {
2017 if (response.IsOKResponse())
2018 return 0;
2019 uint8_t error = response.GetError();
2020 if (error)
2021 return error;
2022 }
2023 return -1;
2024}
2025
2026
Greg Clayton32e0a752011-03-30 18:16:51 +00002027bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002028GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002029{
2030 if (response.IsNormalResponse())
2031 {
Zachary Turner54695a32016-08-29 19:58:14 +00002032 llvm::StringRef name;
2033 llvm::StringRef value;
Greg Clayton32e0a752011-03-30 18:16:51 +00002034 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002035
2036 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2037 uint32_t sub = 0;
2038 std::string vendor;
2039 std::string os_type;
Zachary Turner54695a32016-08-29 19:58:14 +00002040
Greg Clayton32e0a752011-03-30 18:16:51 +00002041 while (response.GetNameColonValue(name, value))
2042 {
Zachary Turner54695a32016-08-29 19:58:14 +00002043 if (name.equals("pid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002044 {
Zachary Turner54695a32016-08-29 19:58:14 +00002045 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2046 value.getAsInteger(0, pid);
2047 process_info.SetProcessID(pid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002048 }
Zachary Turner54695a32016-08-29 19:58:14 +00002049 else if (name.equals("ppid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002050 {
Zachary Turner54695a32016-08-29 19:58:14 +00002051 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2052 value.getAsInteger(0, pid);
2053 process_info.SetParentProcessID(pid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002054 }
Zachary Turner54695a32016-08-29 19:58:14 +00002055 else if (name.equals("uid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002056 {
Zachary Turner54695a32016-08-29 19:58:14 +00002057 uint32_t uid = UINT32_MAX;
2058 value.getAsInteger(0, uid);
2059 process_info.SetUserID(uid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002060 }
Zachary Turner54695a32016-08-29 19:58:14 +00002061 else if (name.equals("euid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002062 {
Zachary Turner54695a32016-08-29 19:58:14 +00002063 uint32_t uid = UINT32_MAX;
2064 value.getAsInteger(0, uid);
2065 process_info.SetEffectiveGroupID(uid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002066 }
Zachary Turner54695a32016-08-29 19:58:14 +00002067 else if (name.equals("gid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002068 {
Zachary Turner54695a32016-08-29 19:58:14 +00002069 uint32_t gid = UINT32_MAX;
2070 value.getAsInteger(0, gid);
2071 process_info.SetGroupID(gid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002072 }
Zachary Turner54695a32016-08-29 19:58:14 +00002073 else if (name.equals("egid"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002074 {
Zachary Turner54695a32016-08-29 19:58:14 +00002075 uint32_t gid = UINT32_MAX;
2076 value.getAsInteger(0, gid);
2077 process_info.SetEffectiveGroupID(gid);
Greg Clayton32e0a752011-03-30 18:16:51 +00002078 }
Zachary Turner54695a32016-08-29 19:58:14 +00002079 else if (name.equals("triple"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002080 {
Zachary Turner54695a32016-08-29 19:58:14 +00002081 StringExtractor extractor(value);
2082 std::string triple;
2083 extractor.GetHexByteString(triple);
2084 process_info.GetArchitecture().SetTriple(triple.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002085 }
Zachary Turner54695a32016-08-29 19:58:14 +00002086 else if (name.equals("name"))
Greg Clayton32e0a752011-03-30 18:16:51 +00002087 {
Zachary Turner54695a32016-08-29 19:58:14 +00002088 StringExtractor extractor(value);
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002089 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002090 // control the characters in a process name
Zachary Turner54695a32016-08-29 19:58:14 +00002091 std::string name;
2092 extractor.GetHexByteString(name);
2093 process_info.GetExecutableFile().SetFile(name.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002094 }
Zachary Turner54695a32016-08-29 19:58:14 +00002095 else if (name.equals("cputype"))
Jason Molenda89c37492014-01-27 22:23:20 +00002096 {
Zachary Turner54695a32016-08-29 19:58:14 +00002097 value.getAsInteger(0, cpu);
Jason Molenda89c37492014-01-27 22:23:20 +00002098 }
Zachary Turner54695a32016-08-29 19:58:14 +00002099 else if (name.equals("cpusubtype"))
Jason Molenda89c37492014-01-27 22:23:20 +00002100 {
Zachary Turner54695a32016-08-29 19:58:14 +00002101 value.getAsInteger(0, sub);
Jason Molenda89c37492014-01-27 22:23:20 +00002102 }
Zachary Turner54695a32016-08-29 19:58:14 +00002103 else if (name.equals("vendor"))
Jason Molenda89c37492014-01-27 22:23:20 +00002104 {
2105 vendor = value;
2106 }
Zachary Turner54695a32016-08-29 19:58:14 +00002107 else if (name.equals("ostype"))
Jason Molenda89c37492014-01-27 22:23:20 +00002108 {
2109 os_type = value;
2110 }
2111 }
2112
2113 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2114 {
2115 if (vendor == "apple")
2116 {
2117 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2118 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2119 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2120 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002121 }
2122
2123 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2124 return true;
2125 }
2126 return false;
2127}
2128
2129bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002130GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002131{
2132 process_info.Clear();
2133
2134 if (m_supports_qProcessInfoPID)
2135 {
2136 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002137 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002138 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002139 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002140 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002141 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002142 return DecodeProcessInfoResponse (response, process_info);
2143 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002144 else
2145 {
2146 m_supports_qProcessInfoPID = false;
2147 return false;
2148 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002149 }
2150 return false;
2151}
2152
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002153bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002154GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002155{
Todd Fiala3daa1762014-09-15 16:01:29 +00002156 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2157
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002158 if (allow_lazy)
2159 {
2160 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2161 return true;
2162 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2163 return false;
2164 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002165
2166 GetHostInfo ();
2167
2168 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002169 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002170 {
2171 if (response.IsNormalResponse())
2172 {
Zachary Turner54695a32016-08-29 19:58:14 +00002173 llvm::StringRef name;
2174 llvm::StringRef value;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002175 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2176 uint32_t sub = 0;
2177 std::string arch_name;
2178 std::string os_name;
2179 std::string vendor_name;
2180 std::string triple;
2181 uint32_t pointer_byte_size = 0;
2182 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002183 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002184 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002185 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002186 while (response.GetNameColonValue(name, value))
2187 {
Zachary Turner54695a32016-08-29 19:58:14 +00002188 if (name.equals("cputype"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002189 {
Zachary Turner54695a32016-08-29 19:58:14 +00002190 if (!value.getAsInteger(16, cpu))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002191 ++num_keys_decoded;
2192 }
Zachary Turner54695a32016-08-29 19:58:14 +00002193 else if (name.equals("cpusubtype"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002194 {
Zachary Turner54695a32016-08-29 19:58:14 +00002195 if (!value.getAsInteger(16, sub))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002196 ++num_keys_decoded;
2197 }
Zachary Turner54695a32016-08-29 19:58:14 +00002198 else if (name.equals("triple"))
Todd Fialac540dd02014-08-26 18:21:02 +00002199 {
Zachary Turner54695a32016-08-29 19:58:14 +00002200 StringExtractor extractor(value);
Greg Clayton44272a42014-09-18 00:18:32 +00002201 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002202 ++num_keys_decoded;
2203 }
Zachary Turner54695a32016-08-29 19:58:14 +00002204 else if (name.equals("ostype"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002205 {
Zachary Turner54695a32016-08-29 19:58:14 +00002206 os_name = value;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002207 ++num_keys_decoded;
2208 }
Zachary Turner54695a32016-08-29 19:58:14 +00002209 else if (name.equals("vendor"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002210 {
Zachary Turner54695a32016-08-29 19:58:14 +00002211 vendor_name = value;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002212 ++num_keys_decoded;
2213 }
Zachary Turner54695a32016-08-29 19:58:14 +00002214 else if (name.equals("endian"))
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002215 {
Zachary Turner54695a32016-08-29 19:58:14 +00002216 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2217 .Case("little", eByteOrderLittle)
2218 .Case("big", eByteOrderBig)
2219 .Case("pdp", eByteOrderPDP)
2220 .Default(eByteOrderInvalid);
2221 if (byte_order != eByteOrderInvalid)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002222 ++num_keys_decoded;
2223 }
Zachary Turner54695a32016-08-29 19:58:14 +00002224 else if (name.equals("ptrsize"))
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002225 {
Zachary Turner54695a32016-08-29 19:58:14 +00002226 if (!value.getAsInteger(16, pointer_byte_size))
2227 ++num_keys_decoded;
2228 }
2229 else if (name.equals("pid"))
2230 {
2231 if (!value.getAsInteger(16, pid))
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002232 ++num_keys_decoded;
2233 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002234 }
2235 if (num_keys_decoded > 0)
2236 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002237 if (pid != LLDB_INVALID_PROCESS_ID)
2238 {
2239 m_curr_pid_is_valid = eLazyBoolYes;
2240 m_curr_pid = pid;
2241 }
Todd Fialac540dd02014-08-26 18:21:02 +00002242
2243 // Set the ArchSpec from the triple if we have it.
2244 if (!triple.empty ())
2245 {
2246 m_process_arch.SetTriple (triple.c_str ());
2247 if (pointer_byte_size)
2248 {
2249 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2250 }
2251 }
2252 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002253 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002254 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2255
2256 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2257 switch (triple.getObjectFormat()) {
2258 case llvm::Triple::MachO:
2259 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2260 break;
2261 case llvm::Triple::ELF:
2262 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2263 break;
2264 case llvm::Triple::COFF:
2265 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2266 break;
2267 case llvm::Triple::UnknownObjectFormat:
2268 if (log)
2269 log->Printf("error: failed to determine target architecture");
2270 return false;
2271 }
2272
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002273 if (pointer_byte_size)
2274 {
2275 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2276 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002277 if (byte_order != eByteOrderInvalid)
2278 {
2279 assert (byte_order == m_process_arch.GetByteOrder());
2280 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002281 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002282 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002283 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2284 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002285 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002286 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002287 }
2288 }
2289 else
2290 {
2291 m_qProcessInfo_is_valid = eLazyBoolNo;
2292 }
2293
2294 return false;
2295}
2296
2297
Greg Clayton32e0a752011-03-30 18:16:51 +00002298uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002299GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2300 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002301{
2302 process_infos.Clear();
2303
2304 if (m_supports_qfProcessInfo)
2305 {
2306 StreamString packet;
2307 packet.PutCString ("qfProcessInfo");
2308 if (!match_info.MatchAllProcesses())
2309 {
2310 packet.PutChar (':');
2311 const char *name = match_info.GetProcessInfo().GetName();
2312 bool has_name_match = false;
2313 if (name && name[0])
2314 {
2315 has_name_match = true;
2316 NameMatchType name_match_type = match_info.GetNameMatchType();
2317 switch (name_match_type)
2318 {
2319 case eNameMatchIgnore:
2320 has_name_match = false;
2321 break;
2322
2323 case eNameMatchEquals:
2324 packet.PutCString ("name_match:equals;");
2325 break;
2326
2327 case eNameMatchContains:
2328 packet.PutCString ("name_match:contains;");
2329 break;
2330
2331 case eNameMatchStartsWith:
2332 packet.PutCString ("name_match:starts_with;");
2333 break;
2334
2335 case eNameMatchEndsWith:
2336 packet.PutCString ("name_match:ends_with;");
2337 break;
2338
2339 case eNameMatchRegularExpression:
2340 packet.PutCString ("name_match:regex;");
2341 break;
2342 }
2343 if (has_name_match)
2344 {
2345 packet.PutCString ("name:");
2346 packet.PutBytesAsRawHex8(name, ::strlen(name));
2347 packet.PutChar (';');
2348 }
2349 }
2350
2351 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002352 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002353 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002354 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002355 if (match_info.GetProcessInfo().UserIDIsValid())
2356 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2357 if (match_info.GetProcessInfo().GroupIDIsValid())
2358 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002359 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2360 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2361 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2362 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2363 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2364 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2365 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2366 {
2367 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2368 const llvm::Triple &triple = match_arch.GetTriple();
2369 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00002370 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002371 packet.PutChar (';');
2372 }
2373 }
2374 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00002375 // Increase timeout as the first qfProcessInfo packet takes a long time
2376 // on Android. The value of 1min was arrived at empirically.
2377 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00002378 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002379 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002380 do
2381 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002382 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002383 if (!DecodeProcessInfoResponse (response, process_info))
2384 break;
2385 process_infos.Append(process_info);
2386 response.GetStringRef().clear();
2387 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002388 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002389 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002390 else
2391 {
2392 m_supports_qfProcessInfo = false;
2393 return 0;
2394 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002395 }
2396 return process_infos.GetSize();
2397
2398}
2399
2400bool
2401GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2402{
2403 if (m_supports_qUserName)
2404 {
2405 char packet[32];
2406 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002407 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002408 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002409 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002410 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002411 if (response.IsNormalResponse())
2412 {
2413 // Make sure we parsed the right number of characters. The response is
2414 // the hex encoded user name and should make up the entire packet.
2415 // If there are any non-hex ASCII bytes, the length won't match below..
2416 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2417 return true;
2418 }
2419 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002420 else
2421 {
2422 m_supports_qUserName = false;
2423 return false;
2424 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002425 }
2426 return false;
2427
2428}
2429
2430bool
2431GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2432{
2433 if (m_supports_qGroupName)
2434 {
2435 char packet[32];
2436 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002437 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002438 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002439 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002440 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002441 if (response.IsNormalResponse())
2442 {
2443 // Make sure we parsed the right number of characters. The response is
2444 // the hex encoded group name and should make up the entire packet.
2445 // If there are any non-hex ASCII bytes, the length won't match below..
2446 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2447 return true;
2448 }
2449 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002450 else
2451 {
2452 m_supports_qGroupName = false;
2453 return false;
2454 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002455 }
2456 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002457}
Greg Clayton32e0a752011-03-30 18:16:51 +00002458
Ewan Crawford78baa192015-05-13 09:18:18 +00002459bool
2460GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
2461{
2462 // Form non-stop packet request
2463 char packet[32];
2464 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2465 assert(packet_len < (int)sizeof(packet));
2466
2467 StringExtractorGDBRemote response;
2468 // Send to target
2469 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2470 if (response.IsOKResponse())
2471 return true;
2472
2473 // Failed or not supported
2474 return false;
2475
2476}
2477
Greg Claytone034a042015-05-21 20:52:06 +00002478static void
2479MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
2480{
2481 packet.Clear();
2482 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2483 uint32_t bytes_left = send_size;
2484 while (bytes_left > 0)
2485 {
2486 if (bytes_left >= 26)
2487 {
2488 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2489 bytes_left -= 26;
2490 }
2491 else
2492 {
2493 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2494 bytes_left = 0;
2495 }
2496 }
2497}
2498
2499template<typename T>
2500T calculate_standard_deviation(const std::vector<T> &v)
2501{
2502 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
2503 T mean = sum / (T)v.size();
2504 T accum = T(0);
2505 std::for_each (std::begin(v), std::end(v), [&](const T d) {
2506 T delta = d - mean;
2507 accum += delta * delta;
2508 });
2509
2510 T stdev = sqrt(accum / (v.size()-1));
2511 return stdev;
2512}
2513
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002514void
Greg Claytone034a042015-05-21 20:52:06 +00002515GDBRemoteCommunicationClient::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 +00002516{
2517 uint32_t i;
2518 TimeValue start_time, end_time;
2519 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002520 if (SendSpeedTestPacket (0, 0))
2521 {
Greg Claytone034a042015-05-21 20:52:06 +00002522 StreamString packet;
2523 if (json)
2524 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
2525 else
2526 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
2527 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00002528
Greg Claytone034a042015-05-21 20:52:06 +00002529 uint32_t result_idx = 0;
2530 uint32_t send_size;
2531 std::vector<float> packet_times;
2532
2533 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
2534 {
2535 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
2536 {
2537 MakeSpeedTestPacket (packet, send_size, recv_size);
2538
2539 packet_times.clear();
2540 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00002541 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00002542 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00002543 {
Greg Claytone034a042015-05-21 20:52:06 +00002544 TimeValue packet_start_time = TimeValue::Now();
2545 StringExtractorGDBRemote response;
2546 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2547 TimeValue packet_end_time = TimeValue::Now();
2548 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
2549 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002550 }
2551 end_time = TimeValue::Now();
2552 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00002553
2554 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2555 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2556 float average_ms_per_packet = total_ms / num_packets;
2557 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
2558 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00002559 {
Greg Claytone034a042015-05-21 20:52:06 +00002560 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);
2561 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00002562 }
2563 else
2564 {
Greg Claytone034a042015-05-21 20:52:06 +00002565 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",
2566 send_size,
2567 recv_size,
2568 total_time_nsec / TimeValue::NanoSecPerSec,
2569 total_time_nsec % TimeValue::NanoSecPerSec,
2570 packets_per_second,
2571 average_ms_per_packet,
2572 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00002573 }
Greg Claytone034a042015-05-21 20:52:06 +00002574 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002575 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002576 }
Greg Claytone034a042015-05-21 20:52:06 +00002577
2578 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
2579
2580 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
2581 if (json)
2582 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
2583 else
2584 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
2585 strm.Flush();
2586 send_size = 0;
2587 result_idx = 0;
2588 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
2589 {
2590 MakeSpeedTestPacket (packet, send_size, recv_size);
2591
2592 // If we have a receive size, test how long it takes to receive 4MB of data
2593 if (recv_size > 0)
2594 {
2595 start_time = TimeValue::Now();
2596 uint32_t bytes_read = 0;
2597 uint32_t packet_count = 0;
2598 while (bytes_read < k_recv_amount)
2599 {
2600 StringExtractorGDBRemote response;
2601 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2602 bytes_read += recv_size;
2603 ++packet_count;
2604 }
2605 end_time = TimeValue::Now();
2606 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2607 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2608 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2609 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2610 float average_ms_per_packet = total_ms / packet_count;
2611
2612 if (json)
2613 {
2614 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);
2615 ++result_idx;
2616 }
2617 else
2618 {
2619 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",
2620 send_size,
2621 recv_size,
2622 packet_count,
2623 k_recv_amount_mb,
2624 total_time_nsec / TimeValue::NanoSecPerSec,
2625 total_time_nsec % TimeValue::NanoSecPerSec,
2626 mb_second,
2627 packets_per_second,
2628 average_ms_per_packet);
2629 }
2630 strm.Flush();
2631 }
2632 }
2633 if (json)
2634 strm.Printf("\n ]\n }\n}\n");
2635 else
2636 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002637 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002638}
2639
2640bool
2641GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2642{
2643 StreamString packet;
2644 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2645 uint32_t bytes_left = send_size;
2646 while (bytes_left > 0)
2647 {
2648 if (bytes_left >= 26)
2649 {
2650 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2651 bytes_left -= 26;
2652 }
2653 else
2654 {
2655 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2656 bytes_left = 0;
2657 }
2658 }
2659
2660 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002661 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00002662}
Greg Clayton8b82f082011-04-12 05:54:46 +00002663
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002664bool
2665GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
2666 lldb::pid_t &pid,
2667 uint16_t &port,
2668 std::string &socket_name)
Greg Clayton8b82f082011-04-12 05:54:46 +00002669{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002670 pid = LLDB_INVALID_PROCESS_ID;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002671 port = 0;
2672 socket_name.clear();
2673
Greg Clayton8b82f082011-04-12 05:54:46 +00002674 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002675 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002676 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002677 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00002678 if (remote_accept_hostname && remote_accept_hostname[0])
2679 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002680 else
2681 {
Zachary Turner97a14e62014-08-19 17:18:29 +00002682 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00002683 {
2684 // Make the GDB server we launch only accept connections from this host
2685 stream.Printf("host:%s;", hostname.c_str());
2686 }
2687 else
2688 {
2689 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2690 stream.Printf("host:*;");
2691 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002692 }
Vince Harron1b5a74e2015-01-21 22:42:49 +00002693 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00002694 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002695
Zachary Turner54695a32016-08-29 19:58:14 +00002696 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002697 {
Zachary Turner54695a32016-08-29 19:58:14 +00002698 llvm::StringRef name;
2699 llvm::StringRef value;
Greg Clayton8b82f082011-04-12 05:54:46 +00002700 while (response.GetNameColonValue(name, value))
2701 {
Zachary Turner54695a32016-08-29 19:58:14 +00002702 if (name.equals("port"))
2703 value.getAsInteger(0, port);
2704 else if (name.equals("pid"))
2705 value.getAsInteger(0, pid);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002706 else if (name.compare("socket_name") == 0)
2707 {
Zachary Turner54695a32016-08-29 19:58:14 +00002708 StringExtractor extractor(value);
2709 extractor.GetHexByteString(socket_name);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002710 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002711 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002712 return true;
Greg Clayton8b82f082011-04-12 05:54:46 +00002713 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002714 return false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002715}
2716
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00002717size_t
2718GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls)
2719{
2720 connection_urls.clear();
2721
2722 StringExtractorGDBRemote response;
2723 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success)
2724 return 0;
2725
2726 StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef());
2727 if (!data)
2728 return 0;
2729
2730 StructuredData::Array* array = data->GetAsArray();
2731 if (!array)
2732 return 0;
2733
2734 for (size_t i = 0, count = array->GetSize(); i < count; ++i)
2735 {
2736 StructuredData::Dictionary* element = nullptr;
2737 if (!array->GetItemAtIndexAsDictionary(i, element))
2738 continue;
2739
2740 uint16_t port = 0;
2741 if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port")))
2742 port = port_osp->GetIntegerValue(0);
2743
2744 std::string socket_name;
2745 if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name")))
2746 socket_name = socket_name_osp->GetStringValue();
2747
2748 if (port != 0 || !socket_name.empty())
2749 connection_urls.emplace_back(port, socket_name);
2750 }
2751 return connection_urls.size();
2752}
2753
Greg Clayton8b82f082011-04-12 05:54:46 +00002754bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002755GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2756{
2757 StreamString stream;
2758 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2759 const char *packet = stream.GetData();
2760 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002761
Daniel Maleae0f8f572013-08-26 23:57:52 +00002762 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002763 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002764 {
2765 if (response.IsOKResponse())
2766 return true;
2767 }
2768 return false;
2769}
2770
2771bool
Pavel Labath0faf3732016-08-25 08:34:57 +00002772GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid, const Lock &lock)
Greg Clayton8b82f082011-04-12 05:54:46 +00002773{
2774 if (m_curr_tid == tid)
2775 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002776
Greg Clayton8b82f082011-04-12 05:54:46 +00002777 char packet[32];
2778 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002779 if (tid == UINT64_MAX)
2780 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002781 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002782 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002783 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002784 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00002785 if (SendPacketAndWaitForResponse(llvm::StringRef(packet, packet_len), response, lock) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002786 {
2787 if (response.IsOKResponse())
2788 {
2789 m_curr_tid = tid;
2790 return true;
2791 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002792
2793 /*
2794 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
2795 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
2796 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2797 */
2798 if (response.IsUnsupportedResponse() && IsConnected())
2799 {
2800 m_curr_tid = 1;
2801 return true;
2802 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002803 }
2804 return false;
2805}
2806
2807bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002808GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002809{
2810 if (m_curr_tid_run == tid)
2811 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002812
Greg Clayton8b82f082011-04-12 05:54:46 +00002813 char packet[32];
2814 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002815 if (tid == UINT64_MAX)
2816 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002817 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002818 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2819
Andy Gibbsa297a972013-06-19 19:04:53 +00002820 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002821 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002822 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002823 {
2824 if (response.IsOKResponse())
2825 {
2826 m_curr_tid_run = tid;
2827 return true;
2828 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002829
2830 /*
2831 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
2832 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
2833 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2834 */
2835 if (response.IsUnsupportedResponse() && IsConnected())
2836 {
2837 m_curr_tid_run = 1;
2838 return true;
2839 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002840 }
2841 return false;
2842}
2843
2844bool
2845GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2846{
Greg Clayton3dedae12013-12-06 21:45:27 +00002847 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002848 return response.IsNormalResponse();
2849 return false;
2850}
2851
2852bool
Greg Claytonf402f782012-10-13 02:11:55 +00002853GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002854{
2855 if (m_supports_qThreadStopInfo)
2856 {
2857 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002858 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002859 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002860 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002861 {
Greg Claytonef8180a2013-10-15 00:14:28 +00002862 if (response.IsUnsupportedResponse())
2863 m_supports_qThreadStopInfo = false;
2864 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002865 return true;
2866 else
2867 return false;
2868 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002869 else
2870 {
2871 m_supports_qThreadStopInfo = false;
2872 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002873 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002874 return false;
2875}
2876
2877
2878uint8_t
2879GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2880{
Todd Fiala616b8272014-10-09 00:55:04 +00002881 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2882 if (log)
2883 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2884 __FUNCTION__, insert ? "add" : "remove", addr);
2885
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002886 // Check if the stub is known not to support this breakpoint type
2887 if (!SupportsGDBStoppointPacket(type))
2888 return UINT8_MAX;
2889 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00002890 char packet[64];
2891 const int packet_len = ::snprintf (packet,
2892 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002893 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002894 insert ? 'Z' : 'z',
2895 type,
2896 addr,
2897 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002898 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00002899 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002900 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00002901 // Make sure the response is either "OK", "EXX" where XX are two hex digits, or "" (unsupported)
2902 response.SetResponseValidatorToOKErrorNotSupported();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002903 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00002904 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002905 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002906 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00002907 if (response.IsOKResponse())
2908 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002909
2910 // Error while setting breakpoint, send back specific error
2911 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002912 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002913
2914 // Empty packet informs us that breakpoint is not supported
2915 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00002916 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002917 // Disable this breakpoint type since it is unsupported
2918 switch (type)
2919 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002920 case eBreakpointSoftware: m_supports_z0 = false; break;
2921 case eBreakpointHardware: m_supports_z1 = false; break;
2922 case eWatchpointWrite: m_supports_z2 = false; break;
2923 case eWatchpointRead: m_supports_z3 = false; break;
2924 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00002925 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002926 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002927 }
2928 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002929 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00002930 return UINT8_MAX;
2931}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002932
2933size_t
2934GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2935 bool &sequence_mutex_unavailable)
2936{
Greg Claytonadc00cb2011-05-20 23:38:13 +00002937 thread_ids.clear();
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002938
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00002939 Lock lock(*this, false);
2940 if (lock)
Greg Claytonadc00cb2011-05-20 23:38:13 +00002941 {
2942 sequence_mutex_unavailable = false;
2943 StringExtractorGDBRemote response;
2944
Greg Clayton3dedae12013-12-06 21:45:27 +00002945 PacketResult packet_result;
Pavel Labath0faf3732016-08-25 08:34:57 +00002946 for (packet_result = SendPacketAndWaitForResponse("qfThreadInfo", response, lock);
Greg Clayton3dedae12013-12-06 21:45:27 +00002947 packet_result == PacketResult::Success && response.IsNormalResponse();
Pavel Labath0faf3732016-08-25 08:34:57 +00002948 packet_result = SendPacketAndWaitForResponse("qsThreadInfo", response, lock))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002949 {
2950 char ch = response.GetChar();
2951 if (ch == 'l')
2952 break;
2953 if (ch == 'm')
2954 {
2955 do
2956 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002957 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002958
2959 if (tid != LLDB_INVALID_THREAD_ID)
2960 {
2961 thread_ids.push_back (tid);
2962 }
2963 ch = response.GetChar(); // Skip the command separator
2964 } while (ch == ','); // Make sure we got a comma separator
2965 }
2966 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002967
2968 /*
2969 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2970 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
2971 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
2972 * Assume pid=tid=1 in such cases.
2973 */
2974 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
2975 {
2976 thread_ids.push_back (1);
2977 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00002978 }
2979 else
2980 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002981#if defined (LLDB_CONFIGURATION_DEBUG)
2982 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2983#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002984 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002985 if (log)
2986 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002987#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002988 sequence_mutex_unavailable = true;
2989 }
2990 return thread_ids.size();
2991}
Greg Clayton37a0a242012-04-11 00:24:49 +00002992
2993lldb::addr_t
2994GDBRemoteCommunicationClient::GetShlibInfoAddr()
2995{
Pavel Labath83082a02016-08-18 14:33:55 +00002996 StringExtractorGDBRemote response;
2997 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) != PacketResult::Success || !response.IsNormalResponse())
2998 return LLDB_INVALID_ADDRESS;
2999 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
Greg Clayton37a0a242012-04-11 00:24:49 +00003000}
3001
Daniel Maleae0f8f572013-08-26 23:57:52 +00003002lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003003GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3004 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3005 int *status_ptr, // Pass NULL if you don't want the process exit status
3006 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3007 std::string *command_output, // Pass NULL if you don't want the command output
3008 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003009{
3010 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003011 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003012 stream.PutBytesAsRawHex8(command, strlen(command));
3013 stream.PutChar(',');
3014 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003015 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003016 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003017 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003018 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003019 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003020 }
3021 const char *packet = stream.GetData();
3022 int packet_len = stream.GetSize();
3023 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003024 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003025 {
3026 if (response.GetChar() != 'F')
3027 return Error("malformed reply");
3028 if (response.GetChar() != ',')
3029 return Error("malformed reply");
3030 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3031 if (exitcode == UINT32_MAX)
3032 return Error("unable to run remote process");
3033 else if (status_ptr)
3034 *status_ptr = exitcode;
3035 if (response.GetChar() != ',')
3036 return Error("malformed reply");
3037 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3038 if (signo_ptr)
3039 *signo_ptr = signo;
3040 if (response.GetChar() != ',')
3041 return Error("malformed reply");
3042 std::string output;
3043 response.GetEscapedBinaryData(output);
3044 if (command_output)
3045 command_output->assign(output);
3046 return Error();
3047 }
3048 return Error("unable to send packet");
3049}
3050
Greg Claytonfbb76342013-11-20 21:07:01 +00003051Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003052GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3053 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003054{
Chaoren Lind3173f32015-05-29 19:52:29 +00003055 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003056 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003057 stream.PutCString("qPlatform_mkdir:");
3058 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003059 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003060 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003061 const char *packet = stream.GetData();
3062 int packet_len = stream.GetSize();
3063 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003064
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003065 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3066 return Error("failed to send '%s' packet", packet);
3067
3068 if (response.GetChar() != 'F')
3069 return Error("invalid response to '%s' packet", packet);
3070
3071 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003072}
3073
Greg Claytonfbb76342013-11-20 21:07:01 +00003074Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003075GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3076 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003077{
Chaoren Lind3173f32015-05-29 19:52:29 +00003078 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003079 lldb_private::StreamString stream;
3080 stream.PutCString("qPlatform_chmod:");
3081 stream.PutHex32(file_permissions);
3082 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003083 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003084 const char *packet = stream.GetData();
3085 int packet_len = stream.GetSize();
3086 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003087
3088 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3089 return Error("failed to send '%s' packet", packet);
3090
3091 if (response.GetChar() != 'F')
3092 return Error("invalid response to '%s' packet", packet);
3093
Chaoren Lince36c4c2015-05-05 18:43:19 +00003094 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003095}
3096
Daniel Maleae0f8f572013-08-26 23:57:52 +00003097static uint64_t
3098ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3099 uint64_t fail_result,
3100 Error &error)
3101{
3102 response.SetFilePos(0);
3103 if (response.GetChar() != 'F')
3104 return fail_result;
3105 int32_t result = response.GetS32 (-2);
3106 if (result == -2)
3107 return fail_result;
3108 if (response.GetChar() == ',')
3109 {
3110 int result_errno = response.GetS32 (-2);
3111 if (result_errno != -2)
3112 error.SetError(result_errno, eErrorTypePOSIX);
3113 else
3114 error.SetError(-1, eErrorTypeGeneric);
3115 }
3116 else
3117 error.Clear();
3118 return result;
3119}
3120lldb::user_id_t
3121GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3122 uint32_t flags,
3123 mode_t mode,
3124 Error &error)
3125{
Chaoren Lind3173f32015-05-29 19:52:29 +00003126 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003127 lldb_private::StreamString stream;
3128 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003129 if (path.empty())
3130 return UINT64_MAX;
3131 stream.PutCStringAsRawHex8(path.c_str());
3132 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003133 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003134 stream.PutChar(',');
3135 stream.PutHex32(mode);
3136 const char* packet = stream.GetData();
3137 int packet_len = stream.GetSize();
3138 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003139 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003140 {
3141 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3142 }
3143 return UINT64_MAX;
3144}
3145
3146bool
3147GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3148 Error &error)
3149{
3150 lldb_private::StreamString stream;
3151 stream.Printf("vFile:close:%i", (int)fd);
3152 const char* packet = stream.GetData();
3153 int packet_len = stream.GetSize();
3154 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003155 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003156 {
3157 return ParseHostIOPacketResponse (response, -1, error) == 0;
3158 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003159 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003160}
3161
3162// Extension of host I/O packets to get the file size.
3163lldb::user_id_t
3164GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3165{
Chaoren Lind3173f32015-05-29 19:52:29 +00003166 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003167 lldb_private::StreamString stream;
3168 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003169 stream.PutCStringAsRawHex8(path.c_str());
3170 const char* packet = stream.GetData();
3171 int packet_len = stream.GetSize();
3172 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003173 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003174 {
3175 if (response.GetChar() != 'F')
3176 return UINT64_MAX;
3177 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3178 return retcode;
3179 }
3180 return UINT64_MAX;
3181}
3182
Greg Claytonfbb76342013-11-20 21:07:01 +00003183Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003184GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3185 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003186{
Chaoren Lind3173f32015-05-29 19:52:29 +00003187 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003188 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003189 lldb_private::StreamString stream;
3190 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003191 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003192 const char* packet = stream.GetData();
3193 int packet_len = stream.GetSize();
3194 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003195 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003196 {
3197 if (response.GetChar() != 'F')
3198 {
3199 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003200 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003201 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003202 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003203 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003204 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003205 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003206 if (response.GetChar() == ',')
3207 {
3208 int response_errno = response.GetS32(-1);
3209 if (response_errno > 0)
3210 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3211 else
3212 error.SetErrorToGenericError();
3213 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003214 else
3215 error.SetErrorToGenericError();
3216 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003217 else
3218 {
3219 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3220 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003221 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003222 }
3223 else
3224 {
3225 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3226 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003227 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003228}
3229
3230uint64_t
3231GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3232 uint64_t offset,
3233 void *dst,
3234 uint64_t dst_len,
3235 Error &error)
3236{
3237 lldb_private::StreamString stream;
3238 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3239 const char* packet = stream.GetData();
3240 int packet_len = stream.GetSize();
3241 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003242 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003243 {
3244 if (response.GetChar() != 'F')
3245 return 0;
3246 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3247 if (retcode == UINT32_MAX)
3248 return retcode;
3249 const char next = (response.Peek() ? *response.Peek() : 0);
3250 if (next == ',')
3251 return 0;
3252 if (next == ';')
3253 {
3254 response.GetChar(); // skip the semicolon
3255 std::string buffer;
3256 if (response.GetEscapedBinaryData(buffer))
3257 {
3258 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3259 if (data_to_write > 0)
3260 memcpy(dst, &buffer[0], data_to_write);
3261 return data_to_write;
3262 }
3263 }
3264 }
3265 return 0;
3266}
3267
3268uint64_t
3269GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3270 uint64_t offset,
3271 const void* src,
3272 uint64_t src_len,
3273 Error &error)
3274{
3275 lldb_private::StreamGDBRemote stream;
3276 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3277 stream.PutEscapedBytes(src, src_len);
3278 const char* packet = stream.GetData();
3279 int packet_len = stream.GetSize();
3280 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003281 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003282 {
3283 if (response.GetChar() != 'F')
3284 {
3285 error.SetErrorStringWithFormat("write file failed");
3286 return 0;
3287 }
3288 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3289 if (bytes_written == UINT64_MAX)
3290 {
3291 error.SetErrorToGenericError();
3292 if (response.GetChar() == ',')
3293 {
3294 int response_errno = response.GetS32(-1);
3295 if (response_errno > 0)
3296 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3297 }
3298 return 0;
3299 }
3300 return bytes_written;
3301 }
3302 else
3303 {
3304 error.SetErrorString ("failed to send vFile:pwrite packet");
3305 }
3306 return 0;
3307}
3308
Greg Claytonfbb76342013-11-20 21:07:01 +00003309Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003310GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003311{
Chaoren Lind3173f32015-05-29 19:52:29 +00003312 std::string src_path{src.GetPath(false)},
3313 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003314 Error error;
3315 lldb_private::StreamGDBRemote stream;
3316 stream.PutCString("vFile:symlink:");
3317 // the unix symlink() command reverses its parameters where the dst if first,
3318 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003319 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003320 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003321 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003322 const char* packet = stream.GetData();
3323 int packet_len = stream.GetSize();
3324 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003325 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003326 {
3327 if (response.GetChar() == 'F')
3328 {
3329 uint32_t result = response.GetU32(UINT32_MAX);
3330 if (result != 0)
3331 {
3332 error.SetErrorToGenericError();
3333 if (response.GetChar() == ',')
3334 {
3335 int response_errno = response.GetS32(-1);
3336 if (response_errno > 0)
3337 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3338 }
3339 }
3340 }
3341 else
3342 {
3343 // Should have returned with 'F<result>[,<errno>]'
3344 error.SetErrorStringWithFormat("symlink failed");
3345 }
3346 }
3347 else
3348 {
3349 error.SetErrorString ("failed to send vFile:symlink packet");
3350 }
3351 return error;
3352}
3353
3354Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003355GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00003356{
Chaoren Lind3173f32015-05-29 19:52:29 +00003357 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003358 Error error;
3359 lldb_private::StreamGDBRemote stream;
3360 stream.PutCString("vFile:unlink:");
3361 // the unix symlink() command reverses its parameters where the dst if first,
3362 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003363 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003364 const char* packet = stream.GetData();
3365 int packet_len = stream.GetSize();
3366 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003367 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003368 {
3369 if (response.GetChar() == 'F')
3370 {
3371 uint32_t result = response.GetU32(UINT32_MAX);
3372 if (result != 0)
3373 {
3374 error.SetErrorToGenericError();
3375 if (response.GetChar() == ',')
3376 {
3377 int response_errno = response.GetS32(-1);
3378 if (response_errno > 0)
3379 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3380 }
3381 }
3382 }
3383 else
3384 {
3385 // Should have returned with 'F<result>[,<errno>]'
3386 error.SetErrorStringWithFormat("unlink failed");
3387 }
3388 }
3389 else
3390 {
3391 error.SetErrorString ("failed to send vFile:unlink packet");
3392 }
3393 return error;
3394}
3395
Daniel Maleae0f8f572013-08-26 23:57:52 +00003396// Extension of host I/O packets to get whether a file exists.
3397bool
3398GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3399{
Chaoren Lind3173f32015-05-29 19:52:29 +00003400 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003401 lldb_private::StreamString stream;
3402 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003403 stream.PutCStringAsRawHex8(path.c_str());
3404 const char* packet = stream.GetData();
3405 int packet_len = stream.GetSize();
3406 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003407 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003408 {
3409 if (response.GetChar() != 'F')
3410 return false;
3411 if (response.GetChar() != ',')
3412 return false;
3413 bool retcode = (response.GetChar() != '0');
3414 return retcode;
3415 }
3416 return false;
3417}
3418
3419bool
3420GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3421 uint64_t &high,
3422 uint64_t &low)
3423{
Chaoren Lind3173f32015-05-29 19:52:29 +00003424 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003425 lldb_private::StreamString stream;
3426 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003427 stream.PutCStringAsRawHex8(path.c_str());
3428 const char* packet = stream.GetData();
3429 int packet_len = stream.GetSize();
3430 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003431 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003432 {
3433 if (response.GetChar() != 'F')
3434 return false;
3435 if (response.GetChar() != ',')
3436 return false;
3437 if (response.Peek() && *response.Peek() == 'x')
3438 return false;
3439 low = response.GetHexMaxU64(false, UINT64_MAX);
3440 high = response.GetHexMaxU64(false, UINT64_MAX);
3441 return true;
3442 }
3443 return false;
3444}
Greg Claytonf74cf862013-11-13 23:28:31 +00003445
3446bool
Jason Molendaa3329782014-03-29 18:54:20 +00003447GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3448{
3449 // Some targets have issues with g/G packets and we need to avoid using them
3450 if (m_avoid_g_packets == eLazyBoolCalculate)
3451 {
3452 if (process)
3453 {
3454 m_avoid_g_packets = eLazyBoolNo;
3455 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3456 if (arch.IsValid()
3457 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3458 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00003459 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00003460 {
3461 m_avoid_g_packets = eLazyBoolYes;
3462 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3463 if (gdb_server_version != 0)
3464 {
3465 const char *gdb_server_name = GetGDBServerProgramName();
3466 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3467 {
3468 if (gdb_server_version >= 310)
3469 m_avoid_g_packets = eLazyBoolNo;
3470 }
3471 }
3472 }
3473 }
3474 }
3475 return m_avoid_g_packets == eLazyBoolYes;
3476}
3477
Pavel Labathb42b48e2016-08-19 12:31:49 +00003478DataBufferSP
Pavel Labath0faf3732016-08-25 08:34:57 +00003479GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, const Lock &lock)
Greg Claytonf74cf862013-11-13 23:28:31 +00003480{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003481 StreamString payload;
3482 payload.Printf("p%x", reg);
Pavel Labathb42b48e2016-08-19 12:31:49 +00003483 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003484 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) != PacketResult::Success ||
Pavel Labathb42b48e2016-08-19 12:31:49 +00003485 !response.IsNormalResponse())
3486 return nullptr;
3487
3488 DataBufferSP buffer_sp(new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3489 response.GetHexBytes(buffer_sp->GetBytes(), buffer_sp->GetByteSize(), '\xcc');
3490 return buffer_sp;
Greg Claytonf74cf862013-11-13 23:28:31 +00003491}
3492
Pavel Labathb42b48e2016-08-19 12:31:49 +00003493DataBufferSP
Pavel Labath0faf3732016-08-25 08:34:57 +00003494GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid, const Lock &lock)
Greg Claytonf74cf862013-11-13 23:28:31 +00003495{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003496 StreamString payload;
3497 payload.PutChar('g');
Pavel Labathb42b48e2016-08-19 12:31:49 +00003498 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003499 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) != PacketResult::Success ||
Pavel Labathb42b48e2016-08-19 12:31:49 +00003500 !response.IsNormalResponse())
3501 return nullptr;
3502
3503 DataBufferSP buffer_sp(new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3504 response.GetHexBytes(buffer_sp->GetBytes(), buffer_sp->GetByteSize(), '\xcc');
3505 return buffer_sp;
Greg Claytonf74cf862013-11-13 23:28:31 +00003506}
Pavel Labath56d72622016-08-17 08:53:31 +00003507
3508bool
Pavel Labath0faf3732016-08-25 08:34:57 +00003509GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid, uint32_t reg_num, llvm::ArrayRef<uint8_t> data,
3510 const Lock &lock)
Pavel Labath56d72622016-08-17 08:53:31 +00003511{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003512 StreamString payload;
3513 payload.Printf("P%x=", reg_num);
3514 payload.PutBytesAsRawHex8(data.data(), data.size(), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Pavel Labath56d72622016-08-17 08:53:31 +00003515 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003516 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) ==
Pavel Labathb42b48e2016-08-19 12:31:49 +00003517 PacketResult::Success &&
3518 response.IsOKResponse();
Pavel Labath56d72622016-08-17 08:53:31 +00003519}
3520
3521bool
Pavel Labath0faf3732016-08-25 08:34:57 +00003522GDBRemoteCommunicationClient::WriteAllRegisters(lldb::tid_t tid, llvm::ArrayRef<uint8_t> data, const Lock &lock)
Pavel Labath56d72622016-08-17 08:53:31 +00003523{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003524 StreamString payload;
3525 payload.PutChar('G');
Pavel Labathb42b48e2016-08-19 12:31:49 +00003526 payload.PutBytesAsRawHex8(data.data(), data.size(), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Pavel Labath56d72622016-08-17 08:53:31 +00003527 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003528 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) ==
Pavel Labathb42b48e2016-08-19 12:31:49 +00003529 PacketResult::Success &&
3530 response.IsOKResponse();
Pavel Labath56d72622016-08-17 08:53:31 +00003531}
3532
Greg Claytonf74cf862013-11-13 23:28:31 +00003533bool
3534GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3535{
3536 save_id = 0; // Set to invalid save ID
3537 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3538 return false;
Pavel Labath0faf3732016-08-25 08:34:57 +00003539
3540 Lock lock(*this, false);
3541 if (!lock)
3542 {
3543 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3544 if (log)
3545 log->Printf("GDBRemoteCommunicationClient::%s failed to get sequence mutex", __FUNCTION__);
3546 return false;
3547 }
3548
Greg Claytonf74cf862013-11-13 23:28:31 +00003549 m_supports_QSaveRegisterState = eLazyBoolYes;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003550 StreamString payload;
3551 payload.PutCString("QSaveRegisterState");
3552 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003553 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) != PacketResult::Success)
Pavel Labath4b6f9592016-08-18 08:30:03 +00003554 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003555
Pavel Labath4b6f9592016-08-18 08:30:03 +00003556 if (response.IsUnsupportedResponse())
3557 m_supports_QSaveRegisterState = eLazyBoolNo;
3558
3559 const uint32_t response_save_id = response.GetU32(0);
3560 if (response_save_id == 0)
3561 return false;
3562
3563 save_id = response_save_id;
3564 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003565}
3566
3567bool
3568GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3569{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003570 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00003571 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3572 // order to be useful
3573 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3574 return false;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003575
Pavel Labath0faf3732016-08-25 08:34:57 +00003576 Lock lock(*this, false);
3577 if (!lock)
3578 {
3579 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
3580 if (log)
3581 log->Printf("GDBRemoteCommunicationClient::%s failed to get sequence mutex", __FUNCTION__);
3582 return false;
3583 }
3584
Pavel Labath4b6f9592016-08-18 08:30:03 +00003585 StreamString payload;
3586 payload.Printf("QRestoreRegisterState:%u", save_id);
3587 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003588 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, lock) != PacketResult::Success)
Pavel Labath4b6f9592016-08-18 08:30:03 +00003589 return false;
3590
3591 if (response.IsOKResponse())
3592 return true;
3593
3594 if (response.IsUnsupportedResponse())
3595 m_supports_QSaveRegisterState = eLazyBoolNo;
Greg Claytonf74cf862013-11-13 23:28:31 +00003596 return false;
3597}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003598
3599bool
Pavel Labath27402d22016-08-18 12:32:41 +00003600GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid)
3601{
3602 if (!GetSyncThreadStateSupported())
3603 return false;
3604
3605 StreamString packet;
3606 StringExtractorGDBRemote response;
3607 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3608 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3609 GDBRemoteCommunication::PacketResult::Success &&
3610 response.IsOKResponse();
3611}
3612
3613bool
3614GDBRemoteCommunicationClient::GetModuleInfo(const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3615 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003616{
Stephane Sezer6f455292016-01-08 00:00:17 +00003617 if (!m_supports_qModuleInfo)
3618 return false;
3619
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00003620 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003621 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003622 return false;
3623
3624 StreamString packet;
3625 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003626 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003627 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00003628 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00003629 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003630
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003631 StringExtractorGDBRemote response;
3632 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
3633 return false;
3634
Stephane Sezer6f455292016-01-08 00:00:17 +00003635 if (response.IsErrorResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003636 return false;
3637
Stephane Sezer6f455292016-01-08 00:00:17 +00003638 if (response.IsUnsupportedResponse ())
3639 {
3640 m_supports_qModuleInfo = false;
3641 return false;
3642 }
3643
Zachary Turner54695a32016-08-29 19:58:14 +00003644 llvm::StringRef name;
3645 llvm::StringRef value;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003646
3647 module_spec.Clear ();
3648 module_spec.GetFileSpec () = module_file_spec;
3649
3650 while (response.GetNameColonValue (name, value))
3651 {
3652 if (name == "uuid" || name == "md5")
3653 {
Zachary Turner54695a32016-08-29 19:58:14 +00003654 StringExtractor extractor(value);
3655 std::string uuid;
3656 extractor.GetHexByteString(uuid);
3657 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003658 }
3659 else if (name == "triple")
3660 {
Zachary Turner54695a32016-08-29 19:58:14 +00003661 StringExtractor extractor(value);
3662 std::string triple;
3663 extractor.GetHexByteString(triple);
3664 module_spec.GetArchitecture().SetTriple(triple.c_str());
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003665 }
3666 else if (name == "file_offset")
3667 {
Zachary Turner54695a32016-08-29 19:58:14 +00003668 uint64_t ival = 0;
3669 if (!value.getAsInteger(16, ival))
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003670 module_spec.SetObjectOffset (ival);
3671 }
3672 else if (name == "file_size")
3673 {
Zachary Turner54695a32016-08-29 19:58:14 +00003674 uint64_t ival = 0;
3675 if (!value.getAsInteger(16, ival))
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003676 module_spec.SetObjectSize (ival);
3677 }
3678 else if (name == "file_path")
3679 {
Zachary Turner54695a32016-08-29 19:58:14 +00003680 StringExtractor extractor(value);
3681 std::string path;
3682 extractor.GetHexByteString(path);
3683 module_spec.GetFileSpec() = FileSpec(path.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003684 }
3685 }
3686
3687 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003688}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003689
3690// query the target remote for extended information using the qXfer packet
3691//
3692// example: object='features', annex='target.xml', out=<xml output>
3693// return: 'true' on success
3694// 'false' on failure (err set)
3695bool
3696GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
3697 const lldb_private::ConstString annex,
3698 std::string & out,
3699 lldb_private::Error & err) {
3700
3701 std::stringstream output;
3702 StringExtractorGDBRemote chunk;
3703
Greg Claytond04f0ed2015-05-26 18:00:51 +00003704 uint64_t size = GetRemoteMaxPacketSize();
3705 if (size == 0)
3706 size = 0x1000;
3707 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3708 int offset = 0;
3709 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003710
3711 // loop until all data has been read
3712 while ( active ) {
3713
3714 // send query extended feature packet
3715 std::stringstream packet;
3716 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00003717 << object.AsCString("") << ":read:"
3718 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00003719 << std::hex << offset << ","
3720 << std::hex << size;
3721
3722 GDBRemoteCommunication::PacketResult res =
3723 SendPacketAndWaitForResponse( packet.str().c_str(),
3724 chunk,
3725 false );
3726
3727 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
3728 err.SetErrorString( "Error sending $qXfer packet" );
3729 return false;
3730 }
3731
3732 const std::string & str = chunk.GetStringRef( );
3733 if ( str.length() == 0 ) {
3734 // should have some data in chunk
3735 err.SetErrorString( "Empty response from $qXfer packet" );
3736 return false;
3737 }
3738
3739 // check packet code
3740 switch ( str[0] ) {
3741 // last chunk
3742 case ( 'l' ):
3743 active = false;
Jason Molenda62e06812016-02-16 04:14:33 +00003744 LLVM_FALLTHROUGH;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003745
3746 // more chunks
3747 case ( 'm' ) :
3748 if ( str.length() > 1 )
3749 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00003750 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003751 break;
3752
3753 // unknown chunk
3754 default:
3755 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
3756 return false;
3757 }
3758 }
3759
3760 out = output.str( );
3761 err.Success( );
3762 return true;
3763}
Greg Clayton0b90be12015-06-23 21:27:50 +00003764
3765// Notify the target that gdb is prepared to serve symbol lookup requests.
3766// packet: "qSymbol::"
3767// reply:
3768// OK The target does not need to look up any (more) symbols.
3769// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
3770// LLDB may provide the value by sending another qSymbol packet
3771// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003772//
3773// Three examples:
3774//
3775// lldb sends: qSymbol::
3776// lldb receives: OK
3777// Remote gdb stub does not need to know the addresses of any symbols, lldb does not
3778// need to ask again in this session.
3779//
3780// lldb sends: qSymbol::
3781// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3782// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3783// lldb receives: OK
3784// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does not know
3785// the address at this time. lldb needs to send qSymbol:: again when it has more
3786// solibs loaded.
3787//
3788// lldb sends: qSymbol::
3789// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3790// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3791// lldb receives: OK
3792// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says that it
3793// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it does not
3794// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003795
3796void
3797GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
3798{
Jason Molenda50018d32016-01-13 04:08:10 +00003799 // Set to true once we've resolved a symbol to an address for the remote stub.
3800 // If we get an 'OK' response after this, the remote stub doesn't need any more
3801 // symbols and we can stop asking.
3802 bool symbol_response_provided = false;
3803
Ed Maste75500e72016-07-19 15:28:02 +00003804 // Is this the initial qSymbol:: packet?
Jason Molenda50018d32016-01-13 04:08:10 +00003805 bool first_qsymbol_query = true;
3806
3807 if (m_supports_qSymbol && m_qSymbol_requests_done == false)
Greg Clayton0b90be12015-06-23 21:27:50 +00003808 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003809 Lock lock(*this, false);
3810 if (lock)
Greg Clayton0b90be12015-06-23 21:27:50 +00003811 {
3812 StreamString packet;
3813 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00003814 StringExtractorGDBRemote response;
Pavel Labath0faf3732016-08-25 08:34:57 +00003815 while (SendPacketAndWaitForResponse(packet.GetString(), response, lock) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00003816 {
Greg Clayton42b01482015-08-11 22:07:46 +00003817 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00003818 {
Jason Molenda50018d32016-01-13 04:08:10 +00003819 if (symbol_response_provided || first_qsymbol_query)
3820 {
3821 m_qSymbol_requests_done = true;
3822 }
3823
Greg Clayton42b01482015-08-11 22:07:46 +00003824 // We are done serving symbols requests
3825 return;
3826 }
Jason Molenda50018d32016-01-13 04:08:10 +00003827 first_qsymbol_query = false;
Greg Clayton0b90be12015-06-23 21:27:50 +00003828
Greg Clayton42b01482015-08-11 22:07:46 +00003829 if (response.IsUnsupportedResponse())
3830 {
3831 // qSymbol is not supported by the current GDB server we are connected to
3832 m_supports_qSymbol = false;
3833 return;
3834 }
3835 else
3836 {
3837 llvm::StringRef response_str(response.GetStringRef());
3838 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00003839 {
Greg Clayton42b01482015-08-11 22:07:46 +00003840 response.SetFilePos(strlen("qSymbol:"));
3841 std::string symbol_name;
3842 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00003843 {
Greg Clayton42b01482015-08-11 22:07:46 +00003844 if (symbol_name.empty())
3845 return;
3846
3847 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3848 lldb_private::SymbolContextList sc_list;
3849 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00003850 {
Greg Clayton42b01482015-08-11 22:07:46 +00003851 const size_t num_scs = sc_list.GetSize();
3852 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 +00003853 {
Greg Clayton42b01482015-08-11 22:07:46 +00003854 SymbolContext sc;
3855 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00003856 {
Greg Clayton42b01482015-08-11 22:07:46 +00003857 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00003858 {
Greg Clayton42b01482015-08-11 22:07:46 +00003859 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00003860 {
Greg Clayton42b01482015-08-11 22:07:46 +00003861 case eSymbolTypeInvalid:
3862 case eSymbolTypeAbsolute:
3863 case eSymbolTypeUndefined:
3864 case eSymbolTypeSourceFile:
3865 case eSymbolTypeHeaderFile:
3866 case eSymbolTypeObjectFile:
3867 case eSymbolTypeCommonBlock:
3868 case eSymbolTypeBlock:
3869 case eSymbolTypeLocal:
3870 case eSymbolTypeParam:
3871 case eSymbolTypeVariable:
3872 case eSymbolTypeVariableType:
3873 case eSymbolTypeLineEntry:
3874 case eSymbolTypeLineHeader:
3875 case eSymbolTypeScopeBegin:
3876 case eSymbolTypeScopeEnd:
3877 case eSymbolTypeAdditional:
3878 case eSymbolTypeCompiler:
3879 case eSymbolTypeInstrumentation:
3880 case eSymbolTypeTrampoline:
3881 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00003882
Greg Clayton42b01482015-08-11 22:07:46 +00003883 case eSymbolTypeCode:
3884 case eSymbolTypeResolver:
3885 case eSymbolTypeData:
3886 case eSymbolTypeRuntime:
3887 case eSymbolTypeException:
3888 case eSymbolTypeObjCClass:
3889 case eSymbolTypeObjCMetaClass:
3890 case eSymbolTypeObjCIVar:
3891 case eSymbolTypeReExported:
3892 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
3893 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00003894 }
3895 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003896 }
3897 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003898 }
Greg Clayton42b01482015-08-11 22:07:46 +00003899 // This is the normal path where our symbol lookup was successful and we want
3900 // to send a packet with the new symbol value and see if another lookup needs to be
3901 // done.
3902
3903 // Change "packet" to contain the requested symbol value and name
3904 packet.Clear();
3905 packet.PutCString("qSymbol:");
3906 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
Jason Molenda50018d32016-01-13 04:08:10 +00003907 {
Greg Clayton42b01482015-08-11 22:07:46 +00003908 packet.Printf("%" PRIx64, symbol_load_addr);
Jason Molenda50018d32016-01-13 04:08:10 +00003909 symbol_response_provided = true;
3910 }
3911 else
3912 {
3913 symbol_response_provided = false;
3914 }
Greg Clayton42b01482015-08-11 22:07:46 +00003915 packet.PutCString(":");
3916 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3917 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003918 }
3919 }
3920 }
3921 }
3922 // If we make it here, the symbol request packet response wasn't valid or
3923 // our symbol lookup failed so we must abort
3924 return;
3925
3926 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003927 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
3928 {
3929 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.", __FUNCTION__);
3930 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003931 }
3932}
3933
Todd Fiala75930012016-08-19 04:21:48 +00003934StructuredData::Array*
3935GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins()
3936{
3937 if (!m_supported_async_json_packets_is_valid)
3938 {
3939 // Query the server for the array of supported asynchronous JSON
3940 // packets.
3941 m_supported_async_json_packets_is_valid = true;
3942
3943 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
3944 GDBR_LOG_PROCESS));
3945
3946 // Poll it now.
3947 StringExtractorGDBRemote response;
3948 const bool send_async = false;
3949 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3950 send_async) == PacketResult::Success)
3951 {
3952 m_supported_async_json_packets_sp = StructuredData::ParseJSON(
3953 response.GetStringRef());
3954 if (m_supported_async_json_packets_sp &&
3955 !m_supported_async_json_packets_sp->GetAsArray())
3956 {
3957 // We were returned something other than a JSON array. This
3958 // is invalid. Clear it out.
3959 if (log)
3960 log->Printf("GDBRemoteCommunicationClient::%s(): "
3961 "QSupportedAsyncJSONPackets returned invalid "
3962 "result: %s", __FUNCTION__,
3963 response.GetStringRef().c_str());
3964 m_supported_async_json_packets_sp.reset();
3965 }
3966 }
3967 else
3968 {
3969 if (log)
3970 log->Printf("GDBRemoteCommunicationClient::%s(): "
3971 "QSupportedAsyncJSONPackets unsupported",
3972 __FUNCTION__);
3973 }
3974
Pavel Labath849cc1a2016-08-23 12:10:09 +00003975 if (log && m_supported_async_json_packets_sp)
Todd Fiala75930012016-08-19 04:21:48 +00003976 {
3977 StreamString stream;
3978 m_supported_async_json_packets_sp->Dump(stream);
3979 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3980 "JSON packets: %s", __FUNCTION__,
3981 stream.GetString().c_str());
3982 }
3983 }
3984
3985 return m_supported_async_json_packets_sp
3986 ? m_supported_async_json_packets_sp->GetAsArray()
3987 : nullptr;
3988}
3989
3990Error
3991GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3992 const ConstString &type_name,
3993 const StructuredData::ObjectSP &config_sp)
3994{
3995 Error error;
3996
3997 if (type_name.GetLength() == 0)
3998 {
3999 error.SetErrorString("invalid type_name argument");
4000 return error;
4001 }
4002
4003 // Build command: Configure{type_name}: serialized config
4004 // data.
4005 StreamGDBRemote stream;
4006 stream.PutCString("QConfigure");
4007 stream.PutCString(type_name.AsCString());
4008 stream.PutChar(':');
4009 if (config_sp)
4010 {
4011 // Gather the plain-text version of the configuration data.
4012 StreamString unescaped_stream;
4013 config_sp->Dump(unescaped_stream);
4014 unescaped_stream.Flush();
4015
4016 // Add it to the stream in escaped fashion.
4017 stream.PutEscapedBytes(unescaped_stream.GetData(),
4018 unescaped_stream.GetSize());
4019 }
4020 stream.Flush();
4021
4022 // Send the packet.
4023 const bool send_async = false;
4024 StringExtractorGDBRemote response;
4025 auto result = SendPacketAndWaitForResponse(stream.GetString().c_str(),
4026 response, send_async);
4027 if (result == PacketResult::Success)
4028 {
4029 // We failed if the config result comes back other than OK.
4030 if (strcmp(response.GetStringRef().c_str(), "OK") == 0)
4031 {
4032 // Okay!
4033 error.Clear();
4034 }
4035 else
4036 {
4037 error.SetErrorStringWithFormat("configuring StructuredData feature "
4038 "%s failed with error %s",
4039 type_name.AsCString(),
4040 response.GetStringRef().c_str());
4041 }
4042 }
4043 else
4044 {
4045 // Can we get more data here on the failure?
4046 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4047 "failed when sending packet: "
4048 "PacketResult=%d", type_name.AsCString(),
4049 result);
4050 }
4051 return error;
4052}
4053
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004054void
4055GDBRemoteCommunicationClient::OnRunPacketSent(bool first)
4056{
4057 GDBRemoteClientBase::OnRunPacketSent(first);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004058 m_curr_tid = LLDB_INVALID_THREAD_ID;
4059}