blob: a6fcd14cba4aea7e52c3ab472096f14993e3fe98 [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
Saleem Abdulrasool28606952014-06-27 05:17:41 +000022#include "llvm/ADT/STLExtras.h"
Greg Clayton576d8832011-03-22 04:00:09 +000023#include "llvm/ADT/Triple.h"
24#include "lldb/Interpreter/Args.h"
Greg Clayton576d8832011-03-22 04:00:09 +000025#include "lldb/Core/Log.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000026#include "lldb/Core/ModuleSpec.h"
Greg Clayton576d8832011-03-22 04:00:09 +000027#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000028#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000029#include "lldb/Core/StreamString.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000030#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton576d8832011-03-22 04:00:09 +000031#include "lldb/Host/Endian.h"
32#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000033#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000034#include "lldb/Host/StringConvert.h"
Greg Clayton576d8832011-03-22 04:00:09 +000035#include "lldb/Host/TimeValue.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000036#include "lldb/Symbol/Symbol.h"
Jason Molendaa3329782014-03-29 18:54:20 +000037#include "lldb/Target/Target.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000038#include "lldb/Target/MemoryRegionInfo.h"
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +000039#include "lldb/Target/UnixSignals.h"
Greg Clayton576d8832011-03-22 04:00:09 +000040
41// Project includes
42#include "Utility/StringExtractorGDBRemote.h"
43#include "ProcessGDBRemote.h"
44#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000045#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000046
Jason Molenda91ffe0a2015-06-18 21:46:06 +000047#if defined (HAVE_LIBCOMPRESSION)
48#include <compression.h>
49#endif
50
Greg Clayton576d8832011-03-22 04:00:09 +000051using namespace lldb;
52using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000053using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000054
55//----------------------------------------------------------------------
56// GDBRemoteCommunicationClient constructor
57//----------------------------------------------------------------------
Tamas Berghammere13c2732015-02-11 10:29:30 +000058GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() :
59 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet"),
Greg Clayton576d8832011-03-22 04:00:09 +000060 m_supports_not_sending_acks (eLazyBoolCalculate),
61 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000062 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000063 m_supports_vCont_all (eLazyBoolCalculate),
64 m_supports_vCont_any (eLazyBoolCalculate),
65 m_supports_vCont_c (eLazyBoolCalculate),
66 m_supports_vCont_C (eLazyBoolCalculate),
67 m_supports_vCont_s (eLazyBoolCalculate),
68 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000069 m_qHostInfo_is_valid (eLazyBoolCalculate),
Todd Fiala9f72b3a2014-05-07 19:28:21 +000070 m_curr_pid_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000071 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000072 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000073 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000074 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000075 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000076 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000077 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000078 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000079 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000080 m_supports_p (eLazyBoolCalculate),
Jason Molendabdc4f122014-05-06 02:59:39 +000081 m_supports_x (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000082 m_avoid_g_packets (eLazyBoolCalculate),
Greg Claytonf74cf862013-11-13 23:28:31 +000083 m_supports_QSaveRegisterState (eLazyBoolCalculate),
Steve Pucci03904ac2014-03-04 23:18:46 +000084 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000085 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
86 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
Greg Clayton253204e2015-04-16 23:11:06 +000087 m_supports_qXfer_features_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000088 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
Jason Molenda705b1802014-06-13 02:37:02 +000089 m_supports_jThreadExtendedInfo (eLazyBoolCalculate),
Jason Molenda20ee21b2015-07-10 23:15:22 +000090 m_supports_jLoadedDynamicLibrariesInfos (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000091 m_supports_qProcessInfoPID (true),
92 m_supports_qfProcessInfo (true),
93 m_supports_qUserName (true),
94 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000095 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),
Greg Clayton89600582013-10-10 17:53:50 +0000101 m_supports_QEnvironment (true),
102 m_supports_QEnvironmentHexEncoded (true),
Greg Clayton0b90be12015-06-23 21:27:50 +0000103 m_supports_qSymbol (true),
Greg Clayton358cf1e2015-06-25 21:46:34 +0000104 m_supports_jThreadsInfo (true),
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000105 m_curr_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton8b82f082011-04-12 05:54:46 +0000106 m_curr_tid (LLDB_INVALID_THREAD_ID),
107 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +0000108 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +0000109 m_async_mutex (Mutex::eMutexTypeRecursive),
110 m_async_packet_predicate (false),
111 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +0000112 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +0000113 m_async_response (),
114 m_async_signal (-1),
Jim Inghamb8cd5752014-04-16 02:24:17 +0000115 m_interrupt_sent (false),
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000116 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +0000117 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000118 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +0000119 m_os_version_major (UINT32_MAX),
120 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000121 m_os_version_update (UINT32_MAX),
122 m_os_build (),
123 m_os_kernel (),
124 m_hostname (),
Jason Molendaa3329782014-03-29 18:54:20 +0000125 m_gdb_server_name(),
126 m_gdb_server_version(UINT32_MAX),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000127 m_default_packet_timeout (0),
128 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000129{
Greg Clayton576d8832011-03-22 04:00:09 +0000130}
131
132//----------------------------------------------------------------------
133// Destructor
134//----------------------------------------------------------------------
135GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
136{
Greg Clayton576d8832011-03-22 04:00:09 +0000137 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000138 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000139}
140
141bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000142GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
143{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000144 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000145
Greg Clayton1cb64962011-03-24 04:28:38 +0000146 // Start the read thread after we send the handshake ack since if we
147 // fail to send the handshake ack, there is no reason to continue...
148 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000149 {
Ed Maste48f986f2013-12-18 15:31:45 +0000150 // Wait for any responses that might have been queued up in the remote
151 // GDB server and flush them all
152 StringExtractorGDBRemote response;
153 PacketResult packet_result = PacketResult::Success;
154 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
155 while (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000156 packet_result = ReadPacket (response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000157
Greg Claytonfb909312013-11-23 01:58:15 +0000158 // The return value from QueryNoAckModeSupported() is true if the packet
159 // was sent and _any_ response (including UNIMPLEMENTED) was received),
160 // or false if no response was received. This quickly tells us if we have
161 // a live connection to a remote GDB server...
162 if (QueryNoAckModeSupported())
163 {
164 return true;
165 }
166 else
167 {
168 if (error_ptr)
169 error_ptr->SetErrorString("failed to get reply to handshake packet");
170 }
171 }
172 else
173 {
174 if (error_ptr)
175 error_ptr->SetErrorString("failed to send the handshake ack");
176 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000177 return false;
178}
179
Greg Claytonfb909312013-11-23 01:58:15 +0000180bool
Greg Claytonb30c50c2015-05-29 00:01:55 +0000181GDBRemoteCommunicationClient::GetEchoSupported ()
182{
183 if (m_supports_qEcho == eLazyBoolCalculate)
184 {
185 GetRemoteQSupported();
186 }
187 return m_supports_qEcho == eLazyBoolYes;
188}
189
190
191bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000192GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
193{
194 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
195 {
196 GetRemoteQSupported();
197 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000198 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000199}
200
201bool
202GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
203{
204 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
205 {
206 GetRemoteQSupported();
207 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000208 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000209}
210
211bool
212GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
213{
214 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
215 {
216 GetRemoteQSupported();
217 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000218 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000219}
220
Steve Pucci03904ac2014-03-04 23:18:46 +0000221bool
222GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
223{
224 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
225 {
226 GetRemoteQSupported();
227 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000228 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000229}
230
Colin Rileyc3c95b22015-04-16 15:51:33 +0000231bool
232GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
233{
234 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
235 {
236 GetRemoteQSupported();
237 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000238 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000239}
240
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000241uint64_t
242GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
243{
244 if (m_max_packet_size == 0)
245 {
246 GetRemoteQSupported();
247 }
248 return m_max_packet_size;
249}
250
251bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000252GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000253{
254 if (m_supports_not_sending_acks == eLazyBoolCalculate)
255 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000256 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000257 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000258
Jason Molenda36a216e2014-07-24 01:36:24 +0000259 // This is the first real packet that we'll send in a debug session and it may take a little
260 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
261
262 const uint32_t minimum_timeout = 6;
263 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000264 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000265
Greg Clayton1cb64962011-03-24 04:28:38 +0000266 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000267 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000268 {
269 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000270 {
271 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000272 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000273 }
Greg Claytonfb909312013-11-23 01:58:15 +0000274 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000275 }
276 }
Greg Claytonfb909312013-11-23 01:58:15 +0000277 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000278}
279
280void
Greg Clayton44633992012-04-10 03:22:03 +0000281GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
282{
283 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
284 {
285 m_supports_threads_in_stop_reply = eLazyBoolNo;
286
287 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000288 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000289 {
290 if (response.IsOKResponse())
291 m_supports_threads_in_stop_reply = eLazyBoolYes;
292 }
293 }
294}
295
Jim Inghamcd16df92012-07-20 21:37:13 +0000296bool
297GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
298{
299 if (m_attach_or_wait_reply == eLazyBoolCalculate)
300 {
301 m_attach_or_wait_reply = eLazyBoolNo;
302
303 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000304 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000305 {
306 if (response.IsOKResponse())
307 m_attach_or_wait_reply = eLazyBoolYes;
308 }
309 }
310 if (m_attach_or_wait_reply == eLazyBoolYes)
311 return true;
312 else
313 return false;
314}
315
Jim Ingham279ceec2012-07-25 21:12:43 +0000316bool
317GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
318{
319 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
320 {
321 m_prepare_for_reg_writing_reply = eLazyBoolNo;
322
323 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000324 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000325 {
326 if (response.IsOKResponse())
327 m_prepare_for_reg_writing_reply = eLazyBoolYes;
328 }
329 }
330 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
331 return true;
332 else
333 return false;
334}
335
Greg Clayton44633992012-04-10 03:22:03 +0000336
337void
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000338GDBRemoteCommunicationClient::ResetDiscoverableSettings (bool did_exec)
Greg Clayton576d8832011-03-22 04:00:09 +0000339{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000340 if (did_exec == false)
341 {
342 // Hard reset everything, this is when we first connect to a GDB server
343 m_supports_not_sending_acks = eLazyBoolCalculate;
344 m_supports_thread_suffix = eLazyBoolCalculate;
345 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
346 m_supports_vCont_c = eLazyBoolCalculate;
347 m_supports_vCont_C = eLazyBoolCalculate;
348 m_supports_vCont_s = eLazyBoolCalculate;
349 m_supports_vCont_S = eLazyBoolCalculate;
350 m_supports_p = eLazyBoolCalculate;
351 m_supports_x = eLazyBoolCalculate;
352 m_supports_QSaveRegisterState = eLazyBoolCalculate;
353 m_qHostInfo_is_valid = eLazyBoolCalculate;
354 m_curr_pid_is_valid = eLazyBoolCalculate;
355 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
356 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
357 m_supports_memory_region_info = eLazyBoolCalculate;
358 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
359 m_attach_or_wait_reply = eLazyBoolCalculate;
360 m_avoid_g_packets = eLazyBoolCalculate;
361 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
362 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
363 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
364 m_supports_qXfer_features_read = eLazyBoolCalculate;
365 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
366 m_supports_qProcessInfoPID = true;
367 m_supports_qfProcessInfo = true;
368 m_supports_qUserName = true;
369 m_supports_qGroupName = true;
370 m_supports_qThreadStopInfo = true;
371 m_supports_z0 = true;
372 m_supports_z1 = true;
373 m_supports_z2 = true;
374 m_supports_z3 = true;
375 m_supports_z4 = true;
376 m_supports_QEnvironment = true;
377 m_supports_QEnvironmentHexEncoded = true;
378 m_supports_qSymbol = true;
379 m_host_arch.Clear();
380 m_os_version_major = UINT32_MAX;
381 m_os_version_minor = UINT32_MAX;
382 m_os_version_update = UINT32_MAX;
383 m_os_build.clear();
384 m_os_kernel.clear();
385 m_hostname.clear();
386 m_gdb_server_name.clear();
387 m_gdb_server_version = UINT32_MAX;
388 m_default_packet_timeout = 0;
389 m_max_packet_size = 0;
390 }
391
392 // These flags should be reset when we first connect to a GDB server
393 // and when our inferior process execs
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000394 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000395 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000396}
397
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000398void
399GDBRemoteCommunicationClient::GetRemoteQSupported ()
400{
401 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000402 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000403 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000404 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000405 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000406 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000407 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
408
Colin Rileyc3c95b22015-04-16 15:51:33 +0000409 // build the qSupported packet
410 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
411 StreamString packet;
412 packet.PutCString( "qSupported" );
413 for ( uint32_t i = 0; i < features.size( ); ++i )
414 {
415 packet.PutCString( i==0 ? ":" : ";");
416 packet.PutCString( features[i].c_str( ) );
417 }
418
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000419 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000420 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000421 response,
422 /*send_async=*/false) == PacketResult::Success)
423 {
424 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000425 if (::strstr (response_cstr, "qXfer:auxv:read+"))
426 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000427 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
428 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
429 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
430 {
431 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
432 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
433 }
434 if (::strstr (response_cstr, "qXfer:libraries:read+"))
435 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000436 if (::strstr (response_cstr, "qXfer:features:read+"))
437 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000438
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000439
440 // Look for a list of compressions in the features list e.g.
441 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
442 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
443 if (features_list)
444 {
445 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
446 if (compressions)
447 {
448 std::vector<std::string> supported_compressions;
449 compressions += sizeof ("SupportedCompressions=") - 1;
450 const char *end_of_compressions = strchr (compressions, ';');
451 if (end_of_compressions == NULL)
452 {
453 end_of_compressions = strchr (compressions, '\0');
454 }
455 const char *current_compression = compressions;
456 while (current_compression < end_of_compressions)
457 {
458 const char *next_compression_name = strchr (current_compression, ',');
459 const char *end_of_this_word = next_compression_name;
460 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
461 {
462 end_of_this_word = end_of_compressions;
463 }
464
465 if (end_of_this_word)
466 {
467 if (end_of_this_word == current_compression)
468 {
469 current_compression++;
470 }
471 else
472 {
473 std::string this_compression (current_compression, end_of_this_word - current_compression);
474 supported_compressions.push_back (this_compression);
475 current_compression = end_of_this_word + 1;
476 }
477 }
478 else
479 {
480 supported_compressions.push_back (current_compression);
481 current_compression = end_of_compressions;
482 }
483 }
484
485 if (supported_compressions.size() > 0)
486 {
487 MaybeEnableCompression (supported_compressions);
488 }
489 }
490 }
491
Greg Claytonb30c50c2015-05-29 00:01:55 +0000492 if (::strstr (response_cstr, "qEcho"))
493 m_supports_qEcho = eLazyBoolYes;
494 else
495 m_supports_qEcho = eLazyBoolNo;
496
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000497 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
498 if (packet_size_str)
499 {
500 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
501 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
502 if (m_max_packet_size == 0)
503 {
504 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
505 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
506 if (log)
507 log->Printf ("Garbled PacketSize spec in qSupported response");
508 }
509 }
510 }
511}
Greg Clayton576d8832011-03-22 04:00:09 +0000512
513bool
514GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
515{
516 if (m_supports_thread_suffix == eLazyBoolCalculate)
517 {
518 StringExtractorGDBRemote response;
519 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000520 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000521 {
522 if (response.IsOKResponse())
523 m_supports_thread_suffix = eLazyBoolYes;
524 }
525 }
526 return m_supports_thread_suffix;
527}
528bool
529GDBRemoteCommunicationClient::GetVContSupported (char flavor)
530{
531 if (m_supports_vCont_c == eLazyBoolCalculate)
532 {
533 StringExtractorGDBRemote response;
534 m_supports_vCont_any = eLazyBoolNo;
535 m_supports_vCont_all = eLazyBoolNo;
536 m_supports_vCont_c = eLazyBoolNo;
537 m_supports_vCont_C = eLazyBoolNo;
538 m_supports_vCont_s = eLazyBoolNo;
539 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000540 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000541 {
542 const char *response_cstr = response.GetStringRef().c_str();
543 if (::strstr (response_cstr, ";c"))
544 m_supports_vCont_c = eLazyBoolYes;
545
546 if (::strstr (response_cstr, ";C"))
547 m_supports_vCont_C = eLazyBoolYes;
548
549 if (::strstr (response_cstr, ";s"))
550 m_supports_vCont_s = eLazyBoolYes;
551
552 if (::strstr (response_cstr, ";S"))
553 m_supports_vCont_S = eLazyBoolYes;
554
555 if (m_supports_vCont_c == eLazyBoolYes &&
556 m_supports_vCont_C == eLazyBoolYes &&
557 m_supports_vCont_s == eLazyBoolYes &&
558 m_supports_vCont_S == eLazyBoolYes)
559 {
560 m_supports_vCont_all = eLazyBoolYes;
561 }
562
563 if (m_supports_vCont_c == eLazyBoolYes ||
564 m_supports_vCont_C == eLazyBoolYes ||
565 m_supports_vCont_s == eLazyBoolYes ||
566 m_supports_vCont_S == eLazyBoolYes)
567 {
568 m_supports_vCont_any = eLazyBoolYes;
569 }
570 }
571 }
572
573 switch (flavor)
574 {
575 case 'a': return m_supports_vCont_any;
576 case 'A': return m_supports_vCont_all;
577 case 'c': return m_supports_vCont_c;
578 case 'C': return m_supports_vCont_C;
579 case 's': return m_supports_vCont_s;
580 case 'S': return m_supports_vCont_S;
581 default: break;
582 }
583 return false;
584}
585
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000586// Check if the target supports 'p' packet. It sends out a 'p'
587// packet and checks the response. A normal packet will tell us
588// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000589//
590// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000591bool
Sean Callananb1de1142013-09-04 23:24:15 +0000592GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000593{
594 if (m_supports_p == eLazyBoolCalculate)
595 {
596 StringExtractorGDBRemote response;
597 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000598 char packet[256];
599 if (GetThreadSuffixSupported())
600 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
601 else
602 snprintf(packet, sizeof(packet), "p0");
603
Greg Clayton3dedae12013-12-06 21:45:27 +0000604 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000605 {
606 if (response.IsNormalResponse())
607 m_supports_p = eLazyBoolYes;
608 }
609 }
610 return m_supports_p;
611}
Greg Clayton576d8832011-03-22 04:00:09 +0000612
Greg Clayton358cf1e2015-06-25 21:46:34 +0000613StructuredData::ObjectSP
614GDBRemoteCommunicationClient::GetThreadsInfo()
615{
616 // Get information on all threads at one using the "jThreadsInfo" packet
617 StructuredData::ObjectSP object_sp;
618
619 if (m_supports_jThreadsInfo)
620 {
621 StringExtractorGDBRemote response;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000622 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
623 {
624 if (response.IsUnsupportedResponse())
625 {
626 m_supports_jThreadsInfo = false;
627 }
628 else if (!response.Empty())
629 {
630 object_sp = StructuredData::ParseJSON (response.GetStringRef());
631 }
632 }
633 }
634 return object_sp;
635}
636
637
Jason Molendabdc4f122014-05-06 02:59:39 +0000638bool
Jason Molenda705b1802014-06-13 02:37:02 +0000639GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
640{
641 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
642 {
643 StringExtractorGDBRemote response;
644 m_supports_jThreadExtendedInfo = eLazyBoolNo;
645 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
646 {
647 if (response.IsOKResponse())
648 {
649 m_supports_jThreadExtendedInfo = eLazyBoolYes;
650 }
651 }
652 }
653 return m_supports_jThreadExtendedInfo;
654}
655
656bool
Jason Molenda20ee21b2015-07-10 23:15:22 +0000657GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported ()
658{
659 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate)
660 {
661 StringExtractorGDBRemote response;
662 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
663 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", response, false) == PacketResult::Success)
664 {
665 if (response.IsOKResponse())
666 {
667 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
668 }
669 }
670 }
671 return m_supports_jLoadedDynamicLibrariesInfos;
672}
673
674bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000675GDBRemoteCommunicationClient::GetxPacketSupported ()
676{
677 if (m_supports_x == eLazyBoolCalculate)
678 {
679 StringExtractorGDBRemote response;
680 m_supports_x = eLazyBoolNo;
681 char packet[256];
682 snprintf (packet, sizeof (packet), "x0,0");
683 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
684 {
685 if (response.IsOKResponse())
686 m_supports_x = eLazyBoolYes;
687 }
688 }
689 return m_supports_x;
690}
691
Greg Clayton3dedae12013-12-06 21:45:27 +0000692GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000693GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
694(
695 const char *payload_prefix,
696 std::string &response_string
697)
698{
699 Mutex::Locker locker;
700 if (!GetSequenceMutex(locker,
701 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
702 {
703 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
704 if (log)
705 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
706 payload_prefix);
707 return PacketResult::ErrorNoSequenceLock;
708 }
709
710 response_string = "";
711 std::string payload_prefix_str(payload_prefix);
712 unsigned int response_size = 0x1000;
713 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
714 response_size = GetRemoteMaxPacketSize();
715 }
716
717 for (unsigned int offset = 0; true; offset += response_size)
718 {
719 StringExtractorGDBRemote this_response;
720 // Construct payload
721 char sizeDescriptor[128];
722 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
723 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
724 this_response,
725 /*send_async=*/false);
726 if (result != PacketResult::Success)
727 return result;
728
729 const std::string &this_string = this_response.GetStringRef();
730
731 // Check for m or l as first character; l seems to mean this is the last chunk
732 char first_char = *this_string.c_str();
733 if (first_char != 'm' && first_char != 'l')
734 {
735 return PacketResult::ErrorReplyInvalid;
736 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000737 // Concatenate the result so far (skipping 'm' or 'l')
738 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000739 if (first_char == 'l')
740 // We're done
741 return PacketResult::Success;
742 }
743}
744
745GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000746GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
747(
748 const char *payload,
749 StringExtractorGDBRemote &response,
750 bool send_async
751)
752{
753 return SendPacketAndWaitForResponse (payload,
754 ::strlen (payload),
755 response,
756 send_async);
757}
758
Greg Clayton3dedae12013-12-06 21:45:27 +0000759GDBRemoteCommunicationClient::PacketResult
760GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
761 size_t payload_length,
762 StringExtractorGDBRemote &response)
763{
764 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
765 if (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000766 packet_result = ReadPacket (response, GetPacketTimeoutInMicroSeconds (), true);
Greg Clayton3dedae12013-12-06 21:45:27 +0000767 return packet_result;
768}
769
770GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000771GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
772(
773 const char *payload,
774 size_t payload_length,
775 StringExtractorGDBRemote &response,
776 bool send_async
777)
778{
Greg Clayton3dedae12013-12-06 21:45:27 +0000779 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000780 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000781 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000782
783 // In order to stop async notifications from being processed in the middle of the
Bruce Mitchenere171da52015-07-22 00:16:02 +0000784 // send/receive sequence Hijack the broadcast. Then rebroadcast any events when we are done.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000785 static Listener hijack_listener("lldb.NotifyHijacker");
786 HijackBroadcaster(&hijack_listener, eBroadcastBitGdbReadThreadGotNotify);
787
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000788 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000789 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000790 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000791 }
792 else
793 {
794 if (send_async)
795 {
Greg Claytond3544052012-05-31 21:24:20 +0000796 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000797 {
Greg Claytond3544052012-05-31 21:24:20 +0000798 Mutex::Locker async_locker (m_async_mutex);
799 m_async_packet.assign(payload, payload_length);
800 m_async_packet_predicate.SetValue (true, eBroadcastNever);
801
802 if (log)
803 log->Printf ("async: async packet = %s", m_async_packet.c_str());
804
805 bool timed_out = false;
806 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000807 {
Greg Claytond3544052012-05-31 21:24:20 +0000808 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000809 {
Jim Inghambabfc382012-06-06 00:32:39 +0000810 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000811 TimeValue timeout_time;
812 timeout_time = TimeValue::Now();
813 timeout_time.OffsetWithSeconds (m_packet_timeout);
814
Greg Clayton576d8832011-03-22 04:00:09 +0000815 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000816 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000817
Greg Claytond3544052012-05-31 21:24:20 +0000818 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000819 {
Greg Claytond3544052012-05-31 21:24:20 +0000820 if (log)
821 log->Printf ("async: got response");
822
823 // Swap the response buffer to avoid malloc and string copy
824 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000825 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000826 }
827 else
828 {
829 if (log)
830 log->Printf ("async: timed out waiting for response");
831 }
832
833 // Make sure we wait until the continue packet has been sent again...
834 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
835 {
836 if (log)
837 {
838 if (timed_out)
839 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
840 else
841 log->Printf ("async: async packet sent");
842 }
843 }
844 else
845 {
846 if (log)
847 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000848 }
849 }
850 else
851 {
Greg Claytond3544052012-05-31 21:24:20 +0000852 // We had a racy condition where we went to send the interrupt
853 // yet we were able to get the lock, so the process must have
854 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000855 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000856 log->Printf ("async: got lock without sending interrupt");
857 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000858 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000859 }
860 }
861 else
862 {
Greg Clayton644247c2011-07-07 01:59:51 +0000863 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000864 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000865 }
866 }
867 else
868 {
869 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000870 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000871 }
872 }
873 else
874 {
875 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000876 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000877 }
878 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000879
Bruce Mitchenere171da52015-07-22 00:16:02 +0000880 // Remove our Hijacking listener from the broadcast.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000881 RestoreBroadcaster();
882
Bruce Mitchenere171da52015-07-22 00:16:02 +0000883 // If a notification event occurred, rebroadcast since it can now be processed safely.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000884 EventSP event_sp;
885 if (hijack_listener.GetNextEvent(event_sp))
886 BroadcastEvent(event_sp);
887
Greg Clayton3dedae12013-12-06 21:45:27 +0000888 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000889}
890
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000891static const char *end_delimiter = "--end--;";
892static const int end_delimiter_len = 8;
893
894std::string
895GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
896( ProcessGDBRemote *process,
897 StringExtractorGDBRemote& profileDataExtractor
898)
899{
900 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
901 std::stringstream final_output;
902 std::string name, value;
903
904 // Going to assuming thread_used_usec comes first, else bail out.
905 while (profileDataExtractor.GetNameColonValue(name, value))
906 {
907 if (name.compare("thread_used_id") == 0)
908 {
909 StringExtractor threadIDHexExtractor(value.c_str());
910 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
911
912 bool has_used_usec = false;
913 uint32_t curr_used_usec = 0;
914 std::string usec_name, usec_value;
915 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
916 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
917 {
918 if (usec_name.compare("thread_used_usec") == 0)
919 {
920 has_used_usec = true;
921 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
922 }
923 else
924 {
925 // We didn't find what we want, it is probably
926 // an older version. Bail out.
927 profileDataExtractor.SetFilePos(input_file_pos);
928 }
929 }
930
931 if (has_used_usec)
932 {
933 uint32_t prev_used_usec = 0;
934 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
935 if (iterator != m_thread_id_to_used_usec_map.end())
936 {
937 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
938 }
939
940 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
941 // A good first time record is one that runs for at least 0.25 sec
942 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
943 bool good_subsequent_time = (prev_used_usec > 0) &&
944 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
945
946 if (good_first_time || good_subsequent_time)
947 {
948 // We try to avoid doing too many index id reservation,
949 // resulting in fast increase of index ids.
950
951 final_output << name << ":";
952 int32_t index_id = process->AssignIndexIDToThread(thread_id);
953 final_output << index_id << ";";
954
955 final_output << usec_name << ":" << usec_value << ";";
956 }
957 else
958 {
959 // Skip past 'thread_used_name'.
960 std::string local_name, local_value;
961 profileDataExtractor.GetNameColonValue(local_name, local_value);
962 }
963
964 // Store current time as previous time so that they can be compared later.
965 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
966 }
967 else
968 {
969 // Bail out and use old string.
970 final_output << name << ":" << value << ";";
971 }
972 }
973 else
974 {
975 final_output << name << ":" << value << ";";
976 }
977 }
978 final_output << end_delimiter;
979 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
980
981 return final_output.str();
982}
983
Ewan Crawford76df2882015-06-23 12:32:06 +0000984bool
985GDBRemoteCommunicationClient::SendvContPacket
986(
987 ProcessGDBRemote *process,
988 const char *payload,
989 size_t packet_length,
990 StringExtractorGDBRemote &response
991)
992{
993
994 m_curr_tid = LLDB_INVALID_THREAD_ID;
995 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
996 if (log)
997 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
998
999 // we want to lock down packet sending while we continue
1000 Mutex::Locker locker(m_sequence_mutex);
1001
1002 // here we broadcast this before we even send the packet!!
1003 // this signals doContinue() to exit
1004 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1005
1006 // set the public state to running
1007 m_public_is_running.SetValue(true, eBroadcastNever);
1008
1009 // Set the starting continue packet into "continue_packet". This packet
1010 // may change if we are interrupted and we continue after an async packet...
1011 std::string continue_packet(payload, packet_length);
1012
1013 if (log)
1014 log->Printf("GDBRemoteCommunicationClient::%s () sending vCont packet: %s", __FUNCTION__, continue_packet.c_str());
1015
1016 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
1017 return false;
1018
1019 // set the private state to running and broadcast this
1020 m_private_is_running.SetValue(true, eBroadcastAlways);
1021
1022 if (log)
1023 log->Printf("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1024
1025 // wait for the response to the vCont
1026 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1027 {
1028 if (response.IsOKResponse())
1029 return true;
1030 }
1031
1032 return false;
1033}
1034
Greg Clayton576d8832011-03-22 04:00:09 +00001035StateType
1036GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
1037(
1038 ProcessGDBRemote *process,
1039 const char *payload,
1040 size_t packet_length,
1041 StringExtractorGDBRemote &response
1042)
1043{
Greg Clayton1f5181a2012-07-02 22:05:25 +00001044 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +00001045 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +00001046 if (log)
1047 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1048
1049 Mutex::Locker locker(m_sequence_mutex);
1050 StateType state = eStateRunning;
1051
1052 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1053 m_public_is_running.SetValue (true, eBroadcastNever);
1054 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +00001055 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +00001056 std::string continue_packet(payload, packet_length);
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001057
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001058 const auto sigstop_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
1059 const auto sigint_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGINT");
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001060
Greg Clayton3f875c52013-02-22 22:23:55 +00001061 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +00001062
Greg Clayton576d8832011-03-22 04:00:09 +00001063 while (state == eStateRunning)
1064 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001065 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +00001066 {
1067 if (log)
1068 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +00001069 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +00001070 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +00001071 else
1072 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001073
Greg Claytone889ad62011-10-27 22:04:16 +00001074 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +00001075 }
1076
Greg Clayton3f875c52013-02-22 22:23:55 +00001077 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001078
1079 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001080 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001081
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001082 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001083 {
1084 if (response.Empty())
1085 state = eStateInvalid;
1086 else
1087 {
1088 const char stop_type = response.GetChar();
1089 if (log)
1090 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
1091 switch (stop_type)
1092 {
1093 case 'T':
1094 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +00001095 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001096 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +00001097 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001098 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
1099 {
1100 lldb::pid_t pid = GetCurrentProcessID ();
1101 if (pid != LLDB_INVALID_PROCESS_ID)
1102 process->SetID (pid);
1103 }
1104 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +00001105 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001106
1107 // Privately notify any internal threads that we have stopped
1108 // in case we wanted to interrupt our process, yet we might
1109 // send a packet and continue without returning control to the
1110 // user.
1111 m_private_is_running.SetValue (false, eBroadcastAlways);
1112
1113 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1114
Jim Inghambabfc382012-06-06 00:32:39 +00001115 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1116 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +00001117 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001118 // We sent an interrupt packet to stop the inferior process
1119 // for an async signal or to send an async packet while running
1120 // but we might have been single stepping and received the
1121 // stop packet for the step instead of for the interrupt packet.
1122 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1123 // is used, so if we get anything else, we need to try and
1124 // get another stop reply packet that may have been sent
1125 // due to sending the interrupt when the target is stopped
1126 // which will just re-send a copy of the last stop reply
1127 // packet. If we don't do this, then the reply for our
1128 // async packet will be the repeat stop reply packet and cause
1129 // a lot of trouble for us!
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001130 if (signo != sigint_signo && signo != sigstop_signo)
Greg Clayton2687cd12012-03-29 01:55:41 +00001131 {
Greg Claytonfb72fde2012-05-15 02:50:49 +00001132 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001133
Bruce Mitchenera868c132015-07-02 18:48:40 +00001134 // We didn't get a SIGINT or SIGSTOP, so try for a
Jason Molendada9765b2015-08-26 04:07:30 +00001135 // very brief time (0.1s) to get another stop reply
Greg Clayton2687cd12012-03-29 01:55:41 +00001136 // packet to make sure it doesn't get in the way
1137 StringExtractorGDBRemote extra_stop_reply_packet;
Jason Molendada9765b2015-08-26 04:07:30 +00001138 uint32_t timeout_usec = 100000;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001139 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +00001140 {
1141 switch (extra_stop_reply_packet.GetChar())
1142 {
1143 case 'T':
1144 case 'S':
1145 // We did get an extra stop reply, which means
1146 // our interrupt didn't stop the target so we
1147 // shouldn't continue after the async signal
1148 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +00001149 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001150 break;
1151 }
1152 }
1153 }
1154 }
1155
1156 if (m_async_signal != -1)
1157 {
1158 if (log)
1159 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1160
1161 // Save off the async signal we are supposed to send
1162 const int async_signal = m_async_signal;
1163 // Clear the async signal member so we don't end up
1164 // sending the signal multiple times...
1165 m_async_signal = -1;
1166 // Check which signal we stopped with
1167 if (signo == async_signal)
1168 {
1169 if (log)
1170 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1171
1172 // We already stopped with a signal that we wanted
1173 // to stop with, so we are done
1174 }
1175 else
1176 {
1177 // We stopped with a different signal that the one
1178 // we wanted to stop with, so now we must resume
1179 // with the signal we want
1180 char signal_packet[32];
1181 int signal_packet_len = 0;
1182 signal_packet_len = ::snprintf (signal_packet,
1183 sizeof (signal_packet),
1184 "C%2.2x",
1185 async_signal);
1186
1187 if (log)
1188 log->Printf ("async: stopped with signal %s, resume with %s",
1189 Host::GetSignalAsCString (signo),
1190 Host::GetSignalAsCString (async_signal));
1191
1192 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001193 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001194 continue_packet.assign(signal_packet, signal_packet_len);
1195 continue;
1196 }
1197 }
1198 else if (m_async_packet_predicate.GetValue())
1199 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001200 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001201
1202 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001203 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001204 m_async_response.Clear();
1205 if (m_async_packet.empty())
1206 {
Jim Inghama6195b72013-12-18 01:24:33 +00001207 m_async_result = PacketResult::ErrorSendFailed;
1208 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001209 packet_log->Printf ("async: error: empty async packet");
1210
1211 }
1212 else
1213 {
1214 if (packet_log)
1215 packet_log->Printf ("async: sending packet");
1216
Jim Inghama6195b72013-12-18 01:24:33 +00001217 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1218 m_async_packet.size(),
1219 m_async_response,
1220 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001221 }
1222 // Let the other thread that was trying to send the async
1223 // packet know that the packet has been sent and response is
1224 // ready...
1225 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1226
1227 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001228 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001229
1230 // Set the continue packet to resume if our interrupt
1231 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001232 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001233 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001234 // Reverting this for now as it is causing deadlocks
1235 // in programs (<rdar://problem/11529853>). In the future
1236 // we should check our thread list and "do the right thing"
1237 // for new threads that show up while we stop and run async
1238 // packets. Setting the packet to 'c' to continue all threads
1239 // is the right thing to do 99.99% of the time because if a
1240 // thread was single stepping, and we sent an interrupt, we
1241 // will notice above that we didn't stop due to an interrupt
1242 // but stopped due to stepping and we would _not_ continue.
1243 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001244 continue;
1245 }
1246 }
1247 // Stop with signal and thread info
1248 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001249 }
Greg Clayton576d8832011-03-22 04:00:09 +00001250 break;
1251
1252 case 'W':
1253 case 'X':
1254 // process exited
1255 state = eStateExited;
1256 break;
1257
1258 case 'O':
1259 // STDOUT
1260 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001261 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001262 std::string inferior_stdout;
1263 inferior_stdout.reserve(response.GetBytesLeft () / 2);
Dawn Perchik554a8572015-09-17 17:55:32 +00001264
1265 uint8_t ch;
1266 while (response.GetHexU8Ex(ch))
1267 {
1268 if (ch != 0)
1269 inferior_stdout.append(1, (char)ch);
1270 }
Greg Clayton576d8832011-03-22 04:00:09 +00001271 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1272 }
1273 break;
1274
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001275 case 'A':
1276 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1277 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001278 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001279 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1280 if (m_partial_profile_data.length() > 0)
1281 {
1282 m_partial_profile_data.append(input);
1283 input = m_partial_profile_data;
1284 m_partial_profile_data.clear();
1285 }
1286
1287 size_t found, pos = 0, len = input.length();
1288 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1289 {
1290 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001291 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1292 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001293
1294 pos = found + end_delimiter_len;
1295 }
1296
1297 if (pos < len)
1298 {
1299 // Last incomplete chunk.
1300 m_partial_profile_data = input.substr(pos);
1301 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001302 }
1303 break;
1304
Greg Clayton576d8832011-03-22 04:00:09 +00001305 case 'E':
1306 // ERROR
1307 state = eStateInvalid;
1308 break;
1309
1310 default:
1311 if (log)
1312 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1313 state = eStateInvalid;
1314 break;
1315 }
1316 }
1317 }
1318 else
1319 {
1320 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001321 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
Greg Clayton576d8832011-03-22 04:00:09 +00001322 state = eStateInvalid;
1323 }
1324 }
1325 if (log)
1326 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1327 response.SetFilePos(0);
1328 m_private_is_running.SetValue (false, eBroadcastAlways);
1329 m_public_is_running.SetValue (false, eBroadcastAlways);
1330 return state;
1331}
1332
1333bool
1334GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1335{
Greg Clayton2687cd12012-03-29 01:55:41 +00001336 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001337 m_async_signal = signo;
1338 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001339 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001340 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001341 return true;
1342 m_async_signal = -1;
1343 return false;
1344}
1345
Greg Clayton37a0a242012-04-11 00:24:49 +00001346// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001347// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1348// (the expected result), then it will send the halt packet. If it does succeed
1349// then the caller that requested the interrupt will want to keep the sequence
1350// locked down so that no one else can send packets while the caller has control.
1351// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001352// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001353// else (like read/write memory), so we need to interrupt the running process
1354// (gdb remote protocol requires this), and do what we need to do, then resume.
1355
1356bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001357GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001358(
1359 Mutex::Locker& locker,
1360 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001361 bool &timed_out
1362)
1363{
Greg Clayton576d8832011-03-22 04:00:09 +00001364 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001365 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001366
1367 if (IsRunning())
1368 {
1369 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001370 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001371 {
1372 if (log)
1373 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1374 }
1375 else
Greg Clayton576d8832011-03-22 04:00:09 +00001376 {
1377 // Someone has the mutex locked waiting for a response or for the
1378 // inferior to stop, so send the interrupt on the down low...
1379 char ctrl_c = '\x03';
1380 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001381 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001382 if (log)
1383 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001384 if (bytes_written > 0)
1385 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001386 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001387 if (seconds_to_wait_for_stop)
1388 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001389 TimeValue timeout;
1390 if (seconds_to_wait_for_stop)
1391 {
1392 timeout = TimeValue::Now();
1393 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1394 }
Greg Clayton576d8832011-03-22 04:00:09 +00001395 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1396 {
1397 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001398 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001399 return true;
1400 }
1401 else
1402 {
1403 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001404 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001405 }
1406 }
1407 else
1408 {
1409 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001410 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001411 return true;
1412 }
1413 }
1414 else
1415 {
1416 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001417 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001418 }
1419 return false;
1420 }
Greg Clayton576d8832011-03-22 04:00:09 +00001421 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001422 else
1423 {
1424 if (log)
1425 log->Printf ("SendInterrupt () - not running");
1426 }
Greg Clayton576d8832011-03-22 04:00:09 +00001427 return true;
1428}
1429
1430lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001431GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001432{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001433 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001434 return m_curr_pid;
1435
1436 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001437 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001438 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001439 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001440 // We really got it.
1441 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001442 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001443 else
1444 {
Todd Fialae24614f2014-05-14 00:15:32 +00001445 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1446 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1447 // The gdb remote protocol documents $qC as returning the thread id, which newer
1448 // debugserver and lldb-gdbserver stubs return correctly.
1449 StringExtractorGDBRemote response;
1450 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001451 {
Todd Fialae24614f2014-05-14 00:15:32 +00001452 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001453 {
Todd Fialae24614f2014-05-14 00:15:32 +00001454 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001455 {
Todd Fialae24614f2014-05-14 00:15:32 +00001456 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1457 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001458 {
Todd Fialae24614f2014-05-14 00:15:32 +00001459 m_curr_pid_is_valid = eLazyBoolYes;
1460 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001461 }
1462 }
1463 }
1464 }
Jaydeep Patil1142f832015-08-13 03:46:36 +00001465
1466 // If we don't get a response for $qC, check if $qfThreadID gives us a result.
1467 if (m_curr_pid == LLDB_INVALID_PROCESS_ID)
1468 {
1469 std::vector<lldb::tid_t> thread_ids;
1470 bool sequence_mutex_unavailable;
1471 size_t size;
1472 size = GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1473 if (size && sequence_mutex_unavailable == false)
1474 {
1475 m_curr_pid = thread_ids.front();
1476 m_curr_pid_is_valid = eLazyBoolYes;
1477 return m_curr_pid;
1478 }
1479 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001480 }
1481
Greg Clayton576d8832011-03-22 04:00:09 +00001482 return LLDB_INVALID_PROCESS_ID;
1483}
1484
1485bool
1486GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1487{
1488 error_str.clear();
1489 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001490 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001491 {
1492 if (response.IsOKResponse())
1493 return true;
1494 if (response.GetChar() == 'E')
1495 {
1496 // A string the describes what failed when launching...
1497 error_str = response.GetStringRef().substr(1);
1498 }
1499 else
1500 {
1501 error_str.assign ("unknown error occurred launching process");
1502 }
1503 }
1504 else
1505 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001506 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001507 }
1508 return false;
1509}
1510
1511int
Greg Claytonfbb76342013-11-20 21:07:01 +00001512GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001513{
Greg Claytonfbb76342013-11-20 21:07:01 +00001514 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001515 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001516 std::vector<const char *> argv;
1517 FileSpec exe_file = launch_info.GetExecutableFile();
1518 std::string exe_path;
1519 const char *arg = NULL;
1520 const Args &launch_args = launch_info.GetArguments();
1521 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +00001522 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +00001523 else
1524 {
1525 arg = launch_args.GetArgumentAtIndex(0);
1526 if (arg)
1527 exe_path = arg;
1528 }
1529 if (!exe_path.empty())
1530 {
1531 argv.push_back(exe_path.c_str());
1532 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1533 {
1534 if (arg)
1535 argv.push_back(arg);
1536 }
1537 }
1538 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001539 {
1540 StreamString packet;
1541 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001542 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001543 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001544 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001545 const int arg_len = strlen(arg);
1546 if (i > 0)
1547 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001548 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001549 packet.PutBytesAsRawHex8 (arg, arg_len);
1550 }
1551
1552 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001553 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001554 {
1555 if (response.IsOKResponse())
1556 return 0;
1557 uint8_t error = response.GetError();
1558 if (error)
1559 return error;
1560 }
1561 }
1562 return -1;
1563}
1564
1565int
1566GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1567{
1568 if (name_equal_value && name_equal_value[0])
1569 {
1570 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001571 bool send_hex_encoding = false;
1572 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001573 {
Greg Clayton89600582013-10-10 17:53:50 +00001574 if (isprint(*p))
1575 {
1576 switch (*p)
1577 {
1578 case '$':
1579 case '#':
1580 send_hex_encoding = true;
1581 break;
1582 default:
1583 break;
1584 }
1585 }
1586 else
1587 {
1588 // We have non printable characters, lets hex encode this...
1589 send_hex_encoding = true;
1590 }
1591 }
1592
1593 StringExtractorGDBRemote response;
1594 if (send_hex_encoding)
1595 {
1596 if (m_supports_QEnvironmentHexEncoded)
1597 {
1598 packet.PutCString("QEnvironmentHexEncoded:");
1599 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001600 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001601 {
1602 if (response.IsOKResponse())
1603 return 0;
1604 uint8_t error = response.GetError();
1605 if (error)
1606 return error;
1607 if (response.IsUnsupportedResponse())
1608 m_supports_QEnvironmentHexEncoded = false;
1609 }
1610 }
1611
1612 }
1613 else if (m_supports_QEnvironment)
1614 {
1615 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001616 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001617 {
1618 if (response.IsOKResponse())
1619 return 0;
1620 uint8_t error = response.GetError();
1621 if (error)
1622 return error;
1623 if (response.IsUnsupportedResponse())
1624 m_supports_QEnvironment = false;
1625 }
Greg Clayton576d8832011-03-22 04:00:09 +00001626 }
1627 }
1628 return -1;
1629}
1630
Greg Claytonc4103b32011-05-08 04:53:50 +00001631int
1632GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1633{
1634 if (arch && arch[0])
1635 {
1636 StreamString packet;
1637 packet.Printf("QLaunchArch:%s", arch);
1638 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001639 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001640 {
1641 if (response.IsOKResponse())
1642 return 0;
1643 uint8_t error = response.GetError();
1644 if (error)
1645 return error;
1646 }
1647 }
1648 return -1;
1649}
1650
Jason Molendaa3329782014-03-29 18:54:20 +00001651int
1652GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1653{
1654 if (data && *data != '\0')
1655 {
1656 StreamString packet;
1657 packet.Printf("QSetProcessEvent:%s", data);
1658 StringExtractorGDBRemote response;
1659 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1660 {
1661 if (response.IsOKResponse())
1662 {
1663 if (was_supported)
1664 *was_supported = true;
1665 return 0;
1666 }
1667 else if (response.IsUnsupportedResponse())
1668 {
1669 if (was_supported)
1670 *was_supported = false;
1671 return -1;
1672 }
1673 else
1674 {
1675 uint8_t error = response.GetError();
1676 if (was_supported)
1677 *was_supported = true;
1678 if (error)
1679 return error;
1680 }
1681 }
1682 }
1683 return -1;
1684}
1685
Greg Clayton576d8832011-03-22 04:00:09 +00001686bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001687GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1688 uint32_t &minor,
1689 uint32_t &update)
1690{
1691 if (GetHostInfo ())
1692 {
1693 if (m_os_version_major != UINT32_MAX)
1694 {
1695 major = m_os_version_major;
1696 minor = m_os_version_minor;
1697 update = m_os_version_update;
1698 return true;
1699 }
1700 }
1701 return false;
1702}
1703
1704bool
1705GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1706{
1707 if (GetHostInfo ())
1708 {
1709 if (!m_os_build.empty())
1710 {
1711 s = m_os_build;
1712 return true;
1713 }
1714 }
1715 s.clear();
1716 return false;
1717}
1718
1719
1720bool
1721GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1722{
1723 if (GetHostInfo ())
1724 {
1725 if (!m_os_kernel.empty())
1726 {
1727 s = m_os_kernel;
1728 return true;
1729 }
1730 }
1731 s.clear();
1732 return false;
1733}
1734
1735bool
1736GDBRemoteCommunicationClient::GetHostname (std::string &s)
1737{
1738 if (GetHostInfo ())
1739 {
1740 if (!m_hostname.empty())
1741 {
1742 s = m_hostname;
1743 return true;
1744 }
1745 }
1746 s.clear();
1747 return false;
1748}
1749
1750ArchSpec
1751GDBRemoteCommunicationClient::GetSystemArchitecture ()
1752{
1753 if (GetHostInfo ())
1754 return m_host_arch;
1755 return ArchSpec();
1756}
1757
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001758const lldb_private::ArchSpec &
1759GDBRemoteCommunicationClient::GetProcessArchitecture ()
1760{
1761 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1762 GetCurrentProcessInfo ();
1763 return m_process_arch;
1764}
1765
Jason Molendaa3329782014-03-29 18:54:20 +00001766bool
1767GDBRemoteCommunicationClient::GetGDBServerVersion()
1768{
1769 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1770 {
1771 m_gdb_server_name.clear();
1772 m_gdb_server_version = 0;
1773 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1774
1775 StringExtractorGDBRemote response;
1776 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1777 {
1778 if (response.IsNormalResponse())
1779 {
1780 std::string name;
1781 std::string value;
1782 bool success = false;
1783 while (response.GetNameColonValue(name, value))
1784 {
1785 if (name.compare("name") == 0)
1786 {
1787 success = true;
1788 m_gdb_server_name.swap(value);
1789 }
1790 else if (name.compare("version") == 0)
1791 {
1792 size_t dot_pos = value.find('.');
1793 if (dot_pos != std::string::npos)
1794 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001795 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001796 if (version != UINT32_MAX)
1797 {
1798 success = true;
1799 m_gdb_server_version = version;
1800 }
1801 }
1802 }
1803 if (success)
1804 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1805 }
1806 }
1807 }
1808 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1809}
1810
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001811void
1812GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1813{
1814 CompressionType avail_type = CompressionType::None;
1815 std::string avail_name;
1816
1817#if defined (HAVE_LIBCOMPRESSION)
1818 // libcompression is weak linked so test if compression_decode_buffer() is available
1819 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1820 {
1821 for (auto compression : supported_compressions)
1822 {
1823 if (compression == "lzfse")
1824 {
1825 avail_type = CompressionType::LZFSE;
1826 avail_name = compression;
1827 break;
1828 }
1829 }
1830 }
1831#endif
1832
1833#if defined (HAVE_LIBCOMPRESSION)
1834 // libcompression is weak linked so test if compression_decode_buffer() is available
1835 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1836 {
1837 for (auto compression : supported_compressions)
1838 {
1839 if (compression == "zlib-deflate")
1840 {
1841 avail_type = CompressionType::ZlibDeflate;
1842 avail_name = compression;
1843 break;
1844 }
1845 }
1846 }
1847#endif
1848
1849#if defined (HAVE_LIBZ)
1850 if (avail_type == CompressionType::None)
1851 {
1852 for (auto compression : supported_compressions)
1853 {
1854 if (compression == "zlib-deflate")
1855 {
1856 avail_type = CompressionType::ZlibDeflate;
1857 avail_name = compression;
1858 break;
1859 }
1860 }
1861 }
1862#endif
1863
1864#if defined (HAVE_LIBCOMPRESSION)
1865 // libcompression is weak linked so test if compression_decode_buffer() is available
1866 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1867 {
1868 for (auto compression : supported_compressions)
1869 {
1870 if (compression == "lz4")
1871 {
1872 avail_type = CompressionType::LZ4;
1873 avail_name = compression;
1874 break;
1875 }
1876 }
1877 }
1878#endif
1879
1880#if defined (HAVE_LIBCOMPRESSION)
1881 // libcompression is weak linked so test if compression_decode_buffer() is available
1882 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1883 {
1884 for (auto compression : supported_compressions)
1885 {
1886 if (compression == "lzma")
1887 {
1888 avail_type = CompressionType::LZMA;
1889 avail_name = compression;
1890 break;
1891 }
1892 }
1893 }
1894#endif
1895
1896 if (avail_type != CompressionType::None)
1897 {
1898 StringExtractorGDBRemote response;
1899 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1900 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1901 return;
1902
1903 if (response.IsOKResponse())
1904 {
1905 m_compression_type = avail_type;
1906 }
1907 }
1908}
1909
Jason Molendaa3329782014-03-29 18:54:20 +00001910const char *
1911GDBRemoteCommunicationClient::GetGDBServerProgramName()
1912{
1913 if (GetGDBServerVersion())
1914 {
1915 if (!m_gdb_server_name.empty())
1916 return m_gdb_server_name.c_str();
1917 }
1918 return NULL;
1919}
1920
1921uint32_t
1922GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1923{
1924 if (GetGDBServerVersion())
1925 return m_gdb_server_version;
1926 return 0;
1927}
Greg Clayton1cb64962011-03-24 04:28:38 +00001928
1929bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001930GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1931{
1932 StringExtractorGDBRemote response;
1933 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1934 return false;
1935
1936 if (!response.IsNormalResponse())
1937 return false;
1938
1939 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1940 tid = response.GetHexMaxU32(true, -1);
1941
1942 return true;
1943}
1944
1945bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001946GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001947{
Todd Fialaaf245d12014-06-30 21:05:18 +00001948 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1949
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001950 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001951 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001952 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001953 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001954 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001955 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001956 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001957 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001958 std::string name;
1959 std::string value;
1960 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1961 uint32_t sub = 0;
1962 std::string arch_name;
1963 std::string os_name;
1964 std::string vendor_name;
1965 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001966 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001967 uint32_t pointer_byte_size = 0;
1968 StringExtractor extractor;
1969 ByteOrder byte_order = eByteOrderInvalid;
1970 uint32_t num_keys_decoded = 0;
1971 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001972 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001973 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001974 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001975 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001976 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001977 if (cpu != LLDB_INVALID_CPUTYPE)
1978 ++num_keys_decoded;
1979 }
1980 else if (name.compare("cpusubtype") == 0)
1981 {
1982 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001983 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001984 if (sub != 0)
1985 ++num_keys_decoded;
1986 }
1987 else if (name.compare("arch") == 0)
1988 {
1989 arch_name.swap (value);
1990 ++num_keys_decoded;
1991 }
1992 else if (name.compare("triple") == 0)
1993 {
Greg Clayton44272a42014-09-18 00:18:32 +00001994 extractor.GetStringRef ().swap (value);
1995 extractor.SetFilePos(0);
1996 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001997 ++num_keys_decoded;
1998 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001999 else if (name.compare ("distribution_id") == 0)
2000 {
2001 extractor.GetStringRef ().swap (value);
2002 extractor.SetFilePos (0);
2003 extractor.GetHexByteString (distribution_id);
2004 ++num_keys_decoded;
2005 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002006 else if (name.compare("os_build") == 0)
2007 {
2008 extractor.GetStringRef().swap(value);
2009 extractor.SetFilePos(0);
2010 extractor.GetHexByteString (m_os_build);
2011 ++num_keys_decoded;
2012 }
2013 else if (name.compare("hostname") == 0)
2014 {
2015 extractor.GetStringRef().swap(value);
2016 extractor.SetFilePos(0);
2017 extractor.GetHexByteString (m_hostname);
2018 ++num_keys_decoded;
2019 }
2020 else if (name.compare("os_kernel") == 0)
2021 {
2022 extractor.GetStringRef().swap(value);
2023 extractor.SetFilePos(0);
2024 extractor.GetHexByteString (m_os_kernel);
2025 ++num_keys_decoded;
2026 }
2027 else if (name.compare("ostype") == 0)
2028 {
2029 os_name.swap (value);
2030 ++num_keys_decoded;
2031 }
2032 else if (name.compare("vendor") == 0)
2033 {
2034 vendor_name.swap(value);
2035 ++num_keys_decoded;
2036 }
2037 else if (name.compare("endian") == 0)
2038 {
2039 ++num_keys_decoded;
2040 if (value.compare("little") == 0)
2041 byte_order = eByteOrderLittle;
2042 else if (value.compare("big") == 0)
2043 byte_order = eByteOrderBig;
2044 else if (value.compare("pdp") == 0)
2045 byte_order = eByteOrderPDP;
2046 else
2047 --num_keys_decoded;
2048 }
2049 else if (name.compare("ptrsize") == 0)
2050 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002051 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002052 if (pointer_byte_size != 0)
2053 ++num_keys_decoded;
2054 }
2055 else if (name.compare("os_version") == 0)
2056 {
2057 Args::StringToVersion (value.c_str(),
2058 m_os_version_major,
2059 m_os_version_minor,
2060 m_os_version_update);
2061 if (m_os_version_major != UINT32_MAX)
2062 ++num_keys_decoded;
2063 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002064 else if (name.compare("watchpoint_exceptions_received") == 0)
2065 {
2066 ++num_keys_decoded;
2067 if (strcmp(value.c_str(),"before") == 0)
2068 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2069 else if (strcmp(value.c_str(),"after") == 0)
2070 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
2071 else
2072 --num_keys_decoded;
2073 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002074 else if (name.compare("default_packet_timeout") == 0)
2075 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002076 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002077 if (m_default_packet_timeout > 0)
2078 {
2079 SetPacketTimeout(m_default_packet_timeout);
2080 ++num_keys_decoded;
2081 }
2082 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002083
Greg Clayton32e0a752011-03-30 18:16:51 +00002084 }
2085
2086 if (num_keys_decoded > 0)
2087 m_qHostInfo_is_valid = eLazyBoolYes;
2088
2089 if (triple.empty())
2090 {
2091 if (arch_name.empty())
2092 {
2093 if (cpu != LLDB_INVALID_CPUTYPE)
2094 {
2095 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2096 if (pointer_byte_size)
2097 {
2098 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2099 }
2100 if (byte_order != eByteOrderInvalid)
2101 {
2102 assert (byte_order == m_host_arch.GetByteOrder());
2103 }
Greg Clayton70512312012-05-08 01:45:38 +00002104
2105 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
2106 {
2107 switch (m_host_arch.GetMachine())
2108 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002109 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002110 case llvm::Triple::arm:
2111 case llvm::Triple::thumb:
2112 os_name = "ios";
2113 break;
2114 default:
2115 os_name = "macosx";
2116 break;
2117 }
2118 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002119 if (!vendor_name.empty())
2120 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2121 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00002122 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00002123
2124 }
2125 }
2126 else
2127 {
2128 std::string triple;
2129 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00002130 if (!vendor_name.empty() || !os_name.empty())
2131 {
2132 triple += '-';
2133 if (vendor_name.empty())
2134 triple += "unknown";
2135 else
2136 triple += vendor_name;
2137 triple += '-';
2138 if (os_name.empty())
2139 triple += "unknown";
2140 else
2141 triple += os_name;
2142 }
2143 m_host_arch.SetTriple (triple.c_str());
2144
2145 llvm::Triple &host_triple = m_host_arch.GetTriple();
2146 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2147 {
2148 switch (m_host_arch.GetMachine())
2149 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002150 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002151 case llvm::Triple::arm:
2152 case llvm::Triple::thumb:
2153 host_triple.setOS(llvm::Triple::IOS);
2154 break;
2155 default:
2156 host_triple.setOS(llvm::Triple::MacOSX);
2157 break;
2158 }
2159 }
Greg Clayton1cb64962011-03-24 04:28:38 +00002160 if (pointer_byte_size)
2161 {
2162 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2163 }
2164 if (byte_order != eByteOrderInvalid)
2165 {
2166 assert (byte_order == m_host_arch.GetByteOrder());
2167 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002168
Greg Clayton1cb64962011-03-24 04:28:38 +00002169 }
2170 }
2171 else
2172 {
Greg Clayton70512312012-05-08 01:45:38 +00002173 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00002174 if (pointer_byte_size)
2175 {
2176 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2177 }
2178 if (byte_order != eByteOrderInvalid)
2179 {
2180 assert (byte_order == m_host_arch.GetByteOrder());
2181 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002182
2183 if (log)
2184 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 +00002185 }
2186 if (!distribution_id.empty ())
2187 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00002188 }
Greg Clayton576d8832011-03-22 04:00:09 +00002189 }
2190 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002191 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00002192}
2193
2194int
2195GDBRemoteCommunicationClient::SendAttach
2196(
2197 lldb::pid_t pid,
2198 StringExtractorGDBRemote& response
2199)
2200{
2201 if (pid != LLDB_INVALID_PROCESS_ID)
2202 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002203 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002204 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002205 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002206 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002207 {
2208 if (response.IsErrorResponse())
2209 return response.GetError();
2210 return 0;
2211 }
2212 }
2213 return -1;
2214}
2215
Vince Harrone0be4252015-02-06 18:32:57 +00002216int
2217GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2218{
2219 StreamString packet;
2220 packet.PutCString("I");
2221 packet.PutBytesAsRawHex8(data, data_len);
2222 StringExtractorGDBRemote response;
2223 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2224 {
2225 return 0;
2226 }
2227 return response.GetError();
2228
2229}
2230
Greg Clayton576d8832011-03-22 04:00:09 +00002231const lldb_private::ArchSpec &
2232GDBRemoteCommunicationClient::GetHostArchitecture ()
2233{
Greg Clayton32e0a752011-03-30 18:16:51 +00002234 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00002235 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00002236 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00002237}
2238
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002239uint32_t
2240GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2241{
2242 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2243 GetHostInfo ();
2244 return m_default_packet_timeout;
2245}
2246
Greg Clayton576d8832011-03-22 04:00:09 +00002247addr_t
2248GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2249{
Greg Clayton70b57652011-05-15 01:25:55 +00002250 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002251 {
Greg Clayton70b57652011-05-15 01:25:55 +00002252 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002253 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002254 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00002255 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00002256 permissions & lldb::ePermissionsReadable ? "r" : "",
2257 permissions & lldb::ePermissionsWritable ? "w" : "",
2258 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00002259 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002260 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002261 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002262 {
Todd Fialaf105f582014-06-21 00:48:09 +00002263 if (response.IsUnsupportedResponse())
2264 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2265 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002266 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2267 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002268 else
2269 {
2270 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2271 }
Greg Clayton576d8832011-03-22 04:00:09 +00002272 }
2273 return LLDB_INVALID_ADDRESS;
2274}
2275
2276bool
2277GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2278{
Greg Clayton70b57652011-05-15 01:25:55 +00002279 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002280 {
Greg Clayton70b57652011-05-15 01:25:55 +00002281 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002282 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002283 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002284 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002285 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002286 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002287 {
Todd Fialaf105f582014-06-21 00:48:09 +00002288 if (response.IsUnsupportedResponse())
2289 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2290 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002291 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002292 }
2293 else
2294 {
2295 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00002296 }
Greg Clayton576d8832011-03-22 04:00:09 +00002297 }
2298 return false;
2299}
2300
Jim Inghamacff8952013-05-02 00:27:30 +00002301Error
2302GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00002303{
Jim Inghamacff8952013-05-02 00:27:30 +00002304 Error error;
2305
2306 if (keep_stopped)
2307 {
2308 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2309 {
2310 char packet[64];
2311 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002312 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002313 StringExtractorGDBRemote response;
Jim Ingham4920a4e2015-07-15 00:59:25 +00002314 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success
2315 && response.IsOKResponse())
Jim Inghamacff8952013-05-02 00:27:30 +00002316 {
2317 m_supports_detach_stay_stopped = eLazyBoolYes;
2318 }
2319 else
2320 {
2321 m_supports_detach_stay_stopped = eLazyBoolNo;
2322 }
2323 }
2324
2325 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2326 {
2327 error.SetErrorString("Stays stopped not supported by this target.");
2328 return error;
2329 }
2330 else
2331 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002332 StringExtractorGDBRemote response;
Jason Molenda2a667382015-07-15 00:16:09 +00002333 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002334 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002335 error.SetErrorString ("Sending extended disconnect packet failed.");
2336 }
2337 }
2338 else
2339 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002340 StringExtractorGDBRemote response;
2341 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002342 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002343 error.SetErrorString ("Sending disconnect packet failed.");
2344 }
2345 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002346}
2347
Greg Clayton46fb5582011-11-18 07:03:08 +00002348Error
2349GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2350 lldb_private::MemoryRegionInfo &region_info)
2351{
2352 Error error;
2353 region_info.Clear();
2354
2355 if (m_supports_memory_region_info != eLazyBoolNo)
2356 {
2357 m_supports_memory_region_info = eLazyBoolYes;
2358 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002359 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002360 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002361 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002362 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002363 {
2364 std::string name;
2365 std::string value;
2366 addr_t addr_value;
2367 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002368 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002369 while (success && response.GetNameColonValue(name, value))
2370 {
2371 if (name.compare ("start") == 0)
2372 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002373 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002374 if (success)
2375 region_info.GetRange().SetRangeBase(addr_value);
2376 }
2377 else if (name.compare ("size") == 0)
2378 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002379 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002380 if (success)
2381 region_info.GetRange().SetByteSize (addr_value);
2382 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002383 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002384 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002385 saw_permissions = true;
2386 if (region_info.GetRange().Contains (addr))
2387 {
2388 if (value.find('r') != std::string::npos)
2389 region_info.SetReadable (MemoryRegionInfo::eYes);
2390 else
2391 region_info.SetReadable (MemoryRegionInfo::eNo);
2392
2393 if (value.find('w') != std::string::npos)
2394 region_info.SetWritable (MemoryRegionInfo::eYes);
2395 else
2396 region_info.SetWritable (MemoryRegionInfo::eNo);
2397
2398 if (value.find('x') != std::string::npos)
2399 region_info.SetExecutable (MemoryRegionInfo::eYes);
2400 else
2401 region_info.SetExecutable (MemoryRegionInfo::eNo);
2402 }
2403 else
2404 {
2405 // The reported region does not contain this address -- we're looking at an unmapped page
2406 region_info.SetReadable (MemoryRegionInfo::eNo);
2407 region_info.SetWritable (MemoryRegionInfo::eNo);
2408 region_info.SetExecutable (MemoryRegionInfo::eNo);
2409 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002410 }
2411 else if (name.compare ("error") == 0)
2412 {
2413 StringExtractorGDBRemote name_extractor;
2414 // Swap "value" over into "name_extractor"
2415 name_extractor.GetStringRef().swap(value);
2416 // Now convert the HEX bytes into a string value
2417 name_extractor.GetHexByteString (value);
2418 error.SetErrorString(value.c_str());
2419 }
2420 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002421
2422 // We got a valid address range back but no permissions -- which means this is an unmapped page
2423 if (region_info.GetRange().IsValid() && saw_permissions == false)
2424 {
2425 region_info.SetReadable (MemoryRegionInfo::eNo);
2426 region_info.SetWritable (MemoryRegionInfo::eNo);
2427 region_info.SetExecutable (MemoryRegionInfo::eNo);
2428 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002429 }
2430 else
2431 {
2432 m_supports_memory_region_info = eLazyBoolNo;
2433 }
2434 }
2435
2436 if (m_supports_memory_region_info == eLazyBoolNo)
2437 {
2438 error.SetErrorString("qMemoryRegionInfo is not supported");
2439 }
2440 if (error.Fail())
2441 region_info.Clear();
2442 return error;
2443
2444}
2445
Johnny Chen64637202012-05-23 21:09:52 +00002446Error
2447GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2448{
2449 Error error;
2450
2451 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2452 {
2453 num = m_num_supported_hardware_watchpoints;
2454 return error;
2455 }
2456
2457 // Set num to 0 first.
2458 num = 0;
2459 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2460 {
2461 char packet[64];
2462 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002463 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002464 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002465 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002466 {
2467 m_supports_watchpoint_support_info = eLazyBoolYes;
2468 std::string name;
2469 std::string value;
2470 while (response.GetNameColonValue(name, value))
2471 {
2472 if (name.compare ("num") == 0)
2473 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002474 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002475 m_num_supported_hardware_watchpoints = num;
2476 }
2477 }
2478 }
2479 else
2480 {
2481 m_supports_watchpoint_support_info = eLazyBoolNo;
2482 }
2483 }
2484
2485 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2486 {
2487 error.SetErrorString("qWatchpointSupportInfo is not supported");
2488 }
2489 return error;
2490
2491}
Greg Clayton46fb5582011-11-18 07:03:08 +00002492
Enrico Granataf04a2192012-07-13 23:18:48 +00002493lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002494GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002495{
2496 Error error(GetWatchpointSupportInfo(num));
2497 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00002498 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00002499 return error;
2500}
2501
2502lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002503GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002504{
2505 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00002506 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00002507
2508 // we assume watchpoints will happen after running the relevant opcode
2509 // and we only want to override this behavior if we have explicitly
2510 // received a qHostInfo telling us otherwise
2511 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00002512 {
2513 // On targets like MIPS, watchpoint exceptions are always generated
2514 // before the instruction is executed. The connected target may not
2515 // support qHostInfo or qWatchpointSupportInfo packets.
2516 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2517 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
2518 after = false;
2519 else
2520 after = true;
2521 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002522 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00002523 {
2524 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
2525 // if it is not calculated before.
2526 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
2527 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2528 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
2529 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2530
Enrico Granataf04a2192012-07-13 23:18:48 +00002531 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00002532 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002533 return error;
2534}
2535
Greg Clayton576d8832011-03-22 04:00:09 +00002536int
Chaoren Lind3173f32015-05-29 19:52:29 +00002537GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002538{
Chaoren Lind3173f32015-05-29 19:52:29 +00002539 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002540 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002541 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002542 StreamString packet;
2543 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002544 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00002545
2546 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002547 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002548 {
2549 if (response.IsOKResponse())
2550 return 0;
2551 uint8_t error = response.GetError();
2552 if (error)
2553 return error;
2554 }
2555 }
2556 return -1;
2557}
2558
2559int
Chaoren Lind3173f32015-05-29 19:52:29 +00002560GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002561{
Chaoren Lind3173f32015-05-29 19:52:29 +00002562 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002563 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002564 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002565 StreamString packet;
2566 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002567 packet.PutCStringAsRawHex8(path.c_str());
2568
Greg Clayton576d8832011-03-22 04:00:09 +00002569 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002570 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002571 {
2572 if (response.IsOKResponse())
2573 return 0;
2574 uint8_t error = response.GetError();
2575 if (error)
2576 return error;
2577 }
2578 }
2579 return -1;
2580}
2581
2582int
Chaoren Lind3173f32015-05-29 19:52:29 +00002583GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002584{
Chaoren Lind3173f32015-05-29 19:52:29 +00002585 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002586 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002587 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002588 StreamString packet;
2589 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002590 packet.PutCStringAsRawHex8(path.c_str());
2591
Greg Clayton576d8832011-03-22 04:00:09 +00002592 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002593 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002594 {
2595 if (response.IsOKResponse())
2596 return 0;
2597 uint8_t error = response.GetError();
2598 if (error)
2599 return error;
2600 }
2601 }
2602 return -1;
2603}
2604
Greg Claytonfbb76342013-11-20 21:07:01 +00002605bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002606GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00002607{
2608 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002609 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002610 {
2611 if (response.IsUnsupportedResponse())
2612 return false;
2613 if (response.IsErrorResponse())
2614 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00002615 std::string cwd;
2616 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00002617 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00002618 return !cwd.empty();
2619 }
2620 return false;
2621}
2622
Greg Clayton576d8832011-03-22 04:00:09 +00002623int
Chaoren Lind3173f32015-05-29 19:52:29 +00002624GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002625{
Chaoren Lind3173f32015-05-29 19:52:29 +00002626 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002627 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002628 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002629 StreamString packet;
2630 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002631 packet.PutCStringAsRawHex8(path.c_str());
2632
Greg Clayton576d8832011-03-22 04:00:09 +00002633 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002634 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002635 {
2636 if (response.IsOKResponse())
2637 return 0;
2638 uint8_t error = response.GetError();
2639 if (error)
2640 return error;
2641 }
2642 }
2643 return -1;
2644}
2645
2646int
2647GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2648{
Greg Clayton32e0a752011-03-30 18:16:51 +00002649 char packet[32];
2650 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002651 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002652 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002653 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002654 {
2655 if (response.IsOKResponse())
2656 return 0;
2657 uint8_t error = response.GetError();
2658 if (error)
2659 return error;
2660 }
2661 return -1;
2662}
Greg Clayton32e0a752011-03-30 18:16:51 +00002663
Jim Ingham106d0282014-06-25 02:32:56 +00002664int
2665GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2666{
2667 char packet[32];
2668 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2669 assert (packet_len < (int)sizeof(packet));
2670 StringExtractorGDBRemote response;
2671 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2672 {
2673 if (response.IsOKResponse())
2674 return 0;
2675 uint8_t error = response.GetError();
2676 if (error)
2677 return error;
2678 }
2679 return -1;
2680}
2681
2682
Greg Clayton32e0a752011-03-30 18:16:51 +00002683bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002684GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002685{
2686 if (response.IsNormalResponse())
2687 {
2688 std::string name;
2689 std::string value;
2690 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002691
2692 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2693 uint32_t sub = 0;
2694 std::string vendor;
2695 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002696
2697 while (response.GetNameColonValue(name, value))
2698 {
2699 if (name.compare("pid") == 0)
2700 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002701 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002702 }
2703 else if (name.compare("ppid") == 0)
2704 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002705 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002706 }
2707 else if (name.compare("uid") == 0)
2708 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002709 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002710 }
2711 else if (name.compare("euid") == 0)
2712 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002713 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002714 }
2715 else if (name.compare("gid") == 0)
2716 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002717 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002718 }
2719 else if (name.compare("egid") == 0)
2720 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002721 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002722 }
2723 else if (name.compare("triple") == 0)
2724 {
Greg Clayton44272a42014-09-18 00:18:32 +00002725 StringExtractor extractor;
2726 extractor.GetStringRef().swap(value);
2727 extractor.SetFilePos(0);
2728 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002729 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002730 }
2731 else if (name.compare("name") == 0)
2732 {
2733 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002734 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002735 // control the characters in a process name
2736 extractor.GetStringRef().swap(value);
2737 extractor.SetFilePos(0);
2738 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002739 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002740 }
Jason Molenda89c37492014-01-27 22:23:20 +00002741 else if (name.compare("cputype") == 0)
2742 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002743 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002744 }
2745 else if (name.compare("cpusubtype") == 0)
2746 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002747 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002748 }
2749 else if (name.compare("vendor") == 0)
2750 {
2751 vendor = value;
2752 }
2753 else if (name.compare("ostype") == 0)
2754 {
2755 os_type = value;
2756 }
2757 }
2758
2759 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2760 {
2761 if (vendor == "apple")
2762 {
2763 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2764 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2765 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2766 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002767 }
2768
2769 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2770 return true;
2771 }
2772 return false;
2773}
2774
2775bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002776GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002777{
2778 process_info.Clear();
2779
2780 if (m_supports_qProcessInfoPID)
2781 {
2782 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002783 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002784 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002785 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002786 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002787 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002788 return DecodeProcessInfoResponse (response, process_info);
2789 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002790 else
2791 {
2792 m_supports_qProcessInfoPID = false;
2793 return false;
2794 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002795 }
2796 return false;
2797}
2798
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002799bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002800GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002801{
Todd Fiala3daa1762014-09-15 16:01:29 +00002802 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2803
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002804 if (allow_lazy)
2805 {
2806 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2807 return true;
2808 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2809 return false;
2810 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002811
2812 GetHostInfo ();
2813
2814 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002815 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002816 {
2817 if (response.IsNormalResponse())
2818 {
2819 std::string name;
2820 std::string value;
2821 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2822 uint32_t sub = 0;
2823 std::string arch_name;
2824 std::string os_name;
2825 std::string vendor_name;
2826 std::string triple;
2827 uint32_t pointer_byte_size = 0;
2828 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002829 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002830 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002831 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002832 while (response.GetNameColonValue(name, value))
2833 {
2834 if (name.compare("cputype") == 0)
2835 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002836 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002837 if (cpu != LLDB_INVALID_CPUTYPE)
2838 ++num_keys_decoded;
2839 }
2840 else if (name.compare("cpusubtype") == 0)
2841 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002842 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002843 if (sub != 0)
2844 ++num_keys_decoded;
2845 }
Todd Fialac540dd02014-08-26 18:21:02 +00002846 else if (name.compare("triple") == 0)
2847 {
Greg Clayton44272a42014-09-18 00:18:32 +00002848 StringExtractor extractor;
2849 extractor.GetStringRef().swap(value);
2850 extractor.SetFilePos(0);
2851 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002852 ++num_keys_decoded;
2853 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002854 else if (name.compare("ostype") == 0)
2855 {
2856 os_name.swap (value);
2857 ++num_keys_decoded;
2858 }
2859 else if (name.compare("vendor") == 0)
2860 {
2861 vendor_name.swap(value);
2862 ++num_keys_decoded;
2863 }
2864 else if (name.compare("endian") == 0)
2865 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002866 ++num_keys_decoded;
2867 if (value.compare("little") == 0)
2868 byte_order = eByteOrderLittle;
2869 else if (value.compare("big") == 0)
2870 byte_order = eByteOrderBig;
2871 else if (value.compare("pdp") == 0)
2872 byte_order = eByteOrderPDP;
2873 else
2874 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002875 }
2876 else if (name.compare("ptrsize") == 0)
2877 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002878 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002879 if (pointer_byte_size != 0)
2880 ++num_keys_decoded;
2881 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002882 else if (name.compare("pid") == 0)
2883 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002884 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002885 if (pid != LLDB_INVALID_PROCESS_ID)
2886 ++num_keys_decoded;
2887 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002888 }
2889 if (num_keys_decoded > 0)
2890 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002891 if (pid != LLDB_INVALID_PROCESS_ID)
2892 {
2893 m_curr_pid_is_valid = eLazyBoolYes;
2894 m_curr_pid = pid;
2895 }
Todd Fialac540dd02014-08-26 18:21:02 +00002896
2897 // Set the ArchSpec from the triple if we have it.
2898 if (!triple.empty ())
2899 {
2900 m_process_arch.SetTriple (triple.c_str ());
2901 if (pointer_byte_size)
2902 {
2903 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2904 }
2905 }
2906 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002907 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002908 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2909
2910 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2911 switch (triple.getObjectFormat()) {
2912 case llvm::Triple::MachO:
2913 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2914 break;
2915 case llvm::Triple::ELF:
2916 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2917 break;
2918 case llvm::Triple::COFF:
2919 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2920 break;
2921 case llvm::Triple::UnknownObjectFormat:
2922 if (log)
2923 log->Printf("error: failed to determine target architecture");
2924 return false;
2925 }
2926
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002927 if (pointer_byte_size)
2928 {
2929 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2930 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002931 if (byte_order != eByteOrderInvalid)
2932 {
2933 assert (byte_order == m_process_arch.GetByteOrder());
2934 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002935 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002936 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002937 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2938 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002939 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002940 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002941 }
2942 }
2943 else
2944 {
2945 m_qProcessInfo_is_valid = eLazyBoolNo;
2946 }
2947
2948 return false;
2949}
2950
2951
Greg Clayton32e0a752011-03-30 18:16:51 +00002952uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002953GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2954 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002955{
2956 process_infos.Clear();
2957
2958 if (m_supports_qfProcessInfo)
2959 {
2960 StreamString packet;
2961 packet.PutCString ("qfProcessInfo");
2962 if (!match_info.MatchAllProcesses())
2963 {
2964 packet.PutChar (':');
2965 const char *name = match_info.GetProcessInfo().GetName();
2966 bool has_name_match = false;
2967 if (name && name[0])
2968 {
2969 has_name_match = true;
2970 NameMatchType name_match_type = match_info.GetNameMatchType();
2971 switch (name_match_type)
2972 {
2973 case eNameMatchIgnore:
2974 has_name_match = false;
2975 break;
2976
2977 case eNameMatchEquals:
2978 packet.PutCString ("name_match:equals;");
2979 break;
2980
2981 case eNameMatchContains:
2982 packet.PutCString ("name_match:contains;");
2983 break;
2984
2985 case eNameMatchStartsWith:
2986 packet.PutCString ("name_match:starts_with;");
2987 break;
2988
2989 case eNameMatchEndsWith:
2990 packet.PutCString ("name_match:ends_with;");
2991 break;
2992
2993 case eNameMatchRegularExpression:
2994 packet.PutCString ("name_match:regex;");
2995 break;
2996 }
2997 if (has_name_match)
2998 {
2999 packet.PutCString ("name:");
3000 packet.PutBytesAsRawHex8(name, ::strlen(name));
3001 packet.PutChar (';');
3002 }
3003 }
3004
3005 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003006 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003007 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003008 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00003009 if (match_info.GetProcessInfo().UserIDIsValid())
3010 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
3011 if (match_info.GetProcessInfo().GroupIDIsValid())
3012 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003013 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
3014 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
3015 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3016 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
3017 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3018 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
3019 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
3020 {
3021 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
3022 const llvm::Triple &triple = match_arch.GetTriple();
3023 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00003024 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00003025 packet.PutChar (';');
3026 }
3027 }
3028 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00003029 // Increase timeout as the first qfProcessInfo packet takes a long time
3030 // on Android. The value of 1min was arrived at empirically.
3031 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00003032 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003033 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003034 do
3035 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003036 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00003037 if (!DecodeProcessInfoResponse (response, process_info))
3038 break;
3039 process_infos.Append(process_info);
3040 response.GetStringRef().clear();
3041 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00003042 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00003043 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003044 else
3045 {
3046 m_supports_qfProcessInfo = false;
3047 return 0;
3048 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003049 }
3050 return process_infos.GetSize();
3051
3052}
3053
3054bool
3055GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
3056{
3057 if (m_supports_qUserName)
3058 {
3059 char packet[32];
3060 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003061 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003062 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003063 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003064 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003065 if (response.IsNormalResponse())
3066 {
3067 // Make sure we parsed the right number of characters. The response is
3068 // the hex encoded user name and should make up the entire packet.
3069 // If there are any non-hex ASCII bytes, the length won't match below..
3070 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3071 return true;
3072 }
3073 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003074 else
3075 {
3076 m_supports_qUserName = false;
3077 return false;
3078 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003079 }
3080 return false;
3081
3082}
3083
3084bool
3085GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3086{
3087 if (m_supports_qGroupName)
3088 {
3089 char packet[32];
3090 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003091 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003092 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003093 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003094 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003095 if (response.IsNormalResponse())
3096 {
3097 // Make sure we parsed the right number of characters. The response is
3098 // the hex encoded group name and should make up the entire packet.
3099 // If there are any non-hex ASCII bytes, the length won't match below..
3100 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3101 return true;
3102 }
3103 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003104 else
3105 {
3106 m_supports_qGroupName = false;
3107 return false;
3108 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003109 }
3110 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003111}
Greg Clayton32e0a752011-03-30 18:16:51 +00003112
Ewan Crawford78baa192015-05-13 09:18:18 +00003113bool
3114GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3115{
3116 // Form non-stop packet request
3117 char packet[32];
3118 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3119 assert(packet_len < (int)sizeof(packet));
3120
3121 StringExtractorGDBRemote response;
3122 // Send to target
3123 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3124 if (response.IsOKResponse())
3125 return true;
3126
3127 // Failed or not supported
3128 return false;
3129
3130}
3131
Greg Claytone034a042015-05-21 20:52:06 +00003132static void
3133MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3134{
3135 packet.Clear();
3136 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3137 uint32_t bytes_left = send_size;
3138 while (bytes_left > 0)
3139 {
3140 if (bytes_left >= 26)
3141 {
3142 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3143 bytes_left -= 26;
3144 }
3145 else
3146 {
3147 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3148 bytes_left = 0;
3149 }
3150 }
3151}
3152
3153template<typename T>
3154T calculate_standard_deviation(const std::vector<T> &v)
3155{
3156 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3157 T mean = sum / (T)v.size();
3158 T accum = T(0);
3159 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3160 T delta = d - mean;
3161 accum += delta * delta;
3162 });
3163
3164 T stdev = sqrt(accum / (v.size()-1));
3165 return stdev;
3166}
3167
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003168void
Greg Claytone034a042015-05-21 20:52:06 +00003169GDBRemoteCommunicationClient::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 +00003170{
3171 uint32_t i;
3172 TimeValue start_time, end_time;
3173 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003174 if (SendSpeedTestPacket (0, 0))
3175 {
Greg Claytone034a042015-05-21 20:52:06 +00003176 StreamString packet;
3177 if (json)
3178 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3179 else
3180 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3181 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00003182
Greg Claytone034a042015-05-21 20:52:06 +00003183 uint32_t result_idx = 0;
3184 uint32_t send_size;
3185 std::vector<float> packet_times;
3186
3187 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3188 {
3189 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3190 {
3191 MakeSpeedTestPacket (packet, send_size, recv_size);
3192
3193 packet_times.clear();
3194 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00003195 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00003196 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00003197 {
Greg Claytone034a042015-05-21 20:52:06 +00003198 TimeValue packet_start_time = TimeValue::Now();
3199 StringExtractorGDBRemote response;
3200 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3201 TimeValue packet_end_time = TimeValue::Now();
3202 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3203 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003204 }
3205 end_time = TimeValue::Now();
3206 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00003207
3208 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3209 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3210 float average_ms_per_packet = total_ms / num_packets;
3211 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3212 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00003213 {
Greg Claytone034a042015-05-21 20:52:06 +00003214 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);
3215 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00003216 }
3217 else
3218 {
Greg Claytone034a042015-05-21 20:52:06 +00003219 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",
3220 send_size,
3221 recv_size,
3222 total_time_nsec / TimeValue::NanoSecPerSec,
3223 total_time_nsec % TimeValue::NanoSecPerSec,
3224 packets_per_second,
3225 average_ms_per_packet,
3226 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00003227 }
Greg Claytone034a042015-05-21 20:52:06 +00003228 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003229 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003230 }
Greg Claytone034a042015-05-21 20:52:06 +00003231
3232 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3233
3234 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3235 if (json)
3236 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3237 else
3238 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3239 strm.Flush();
3240 send_size = 0;
3241 result_idx = 0;
3242 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3243 {
3244 MakeSpeedTestPacket (packet, send_size, recv_size);
3245
3246 // If we have a receive size, test how long it takes to receive 4MB of data
3247 if (recv_size > 0)
3248 {
3249 start_time = TimeValue::Now();
3250 uint32_t bytes_read = 0;
3251 uint32_t packet_count = 0;
3252 while (bytes_read < k_recv_amount)
3253 {
3254 StringExtractorGDBRemote response;
3255 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3256 bytes_read += recv_size;
3257 ++packet_count;
3258 }
3259 end_time = TimeValue::Now();
3260 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3261 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3262 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3263 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3264 float average_ms_per_packet = total_ms / packet_count;
3265
3266 if (json)
3267 {
3268 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);
3269 ++result_idx;
3270 }
3271 else
3272 {
3273 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",
3274 send_size,
3275 recv_size,
3276 packet_count,
3277 k_recv_amount_mb,
3278 total_time_nsec / TimeValue::NanoSecPerSec,
3279 total_time_nsec % TimeValue::NanoSecPerSec,
3280 mb_second,
3281 packets_per_second,
3282 average_ms_per_packet);
3283 }
3284 strm.Flush();
3285 }
3286 }
3287 if (json)
3288 strm.Printf("\n ]\n }\n}\n");
3289 else
3290 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003291 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003292}
3293
3294bool
3295GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3296{
3297 StreamString packet;
3298 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3299 uint32_t bytes_left = send_size;
3300 while (bytes_left > 0)
3301 {
3302 if (bytes_left >= 26)
3303 {
3304 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3305 bytes_left -= 26;
3306 }
3307 else
3308 {
3309 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3310 bytes_left = 0;
3311 }
3312 }
3313
3314 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003315 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00003316}
Greg Clayton8b82f082011-04-12 05:54:46 +00003317
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003318bool
3319GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
3320 lldb::pid_t &pid,
3321 uint16_t &port,
3322 std::string &socket_name)
Greg Clayton8b82f082011-04-12 05:54:46 +00003323{
Daniel Maleae0f8f572013-08-26 23:57:52 +00003324 pid = LLDB_INVALID_PROCESS_ID;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003325 port = 0;
3326 socket_name.clear();
3327
Greg Clayton8b82f082011-04-12 05:54:46 +00003328 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003329 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00003330 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003331 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00003332 if (remote_accept_hostname && remote_accept_hostname[0])
3333 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003334 else
3335 {
Zachary Turner97a14e62014-08-19 17:18:29 +00003336 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00003337 {
3338 // Make the GDB server we launch only accept connections from this host
3339 stream.Printf("host:%s;", hostname.c_str());
3340 }
3341 else
3342 {
3343 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3344 stream.Printf("host:*;");
3345 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003346 }
3347 const char *packet = stream.GetData();
3348 int packet_len = stream.GetSize();
3349
Vince Harron1b5a74e2015-01-21 22:42:49 +00003350 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003351 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003352
Tamas Berghammer912800c2015-02-24 10:23:39 +00003353 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003354 {
3355 std::string name;
3356 std::string value;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003357 StringExtractor extractor;
Greg Clayton8b82f082011-04-12 05:54:46 +00003358 while (response.GetNameColonValue(name, value))
3359 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003360 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003361 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003362 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003363 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003364 else if (name.compare("socket_name") == 0)
3365 {
3366 extractor.GetStringRef().swap(value);
3367 extractor.SetFilePos(0);
3368 extractor.GetHexByteString(value);
3369
3370 socket_name = value;
3371 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003372 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003373 return true;
Greg Clayton8b82f082011-04-12 05:54:46 +00003374 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003375 return false;
Greg Clayton8b82f082011-04-12 05:54:46 +00003376}
3377
3378bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003379GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3380{
3381 StreamString stream;
3382 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3383 const char *packet = stream.GetData();
3384 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003385
Daniel Maleae0f8f572013-08-26 23:57:52 +00003386 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003387 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003388 {
3389 if (response.IsOKResponse())
3390 return true;
3391 }
3392 return false;
3393}
3394
3395bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003396GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003397{
3398 if (m_curr_tid == tid)
3399 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003400
Greg Clayton8b82f082011-04-12 05:54:46 +00003401 char packet[32];
3402 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003403 if (tid == UINT64_MAX)
3404 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003405 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003406 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003407 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003408 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003409 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003410 {
3411 if (response.IsOKResponse())
3412 {
3413 m_curr_tid = tid;
3414 return true;
3415 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003416
3417 /*
3418 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
3419 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3420 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3421 */
3422 if (response.IsUnsupportedResponse() && IsConnected())
3423 {
3424 m_curr_tid = 1;
3425 return true;
3426 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003427 }
3428 return false;
3429}
3430
3431bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003432GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003433{
3434 if (m_curr_tid_run == tid)
3435 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003436
Greg Clayton8b82f082011-04-12 05:54:46 +00003437 char packet[32];
3438 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003439 if (tid == UINT64_MAX)
3440 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003441 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003442 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3443
Andy Gibbsa297a972013-06-19 19:04:53 +00003444 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003445 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003446 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003447 {
3448 if (response.IsOKResponse())
3449 {
3450 m_curr_tid_run = tid;
3451 return true;
3452 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003453
3454 /*
3455 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
3456 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3457 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3458 */
3459 if (response.IsUnsupportedResponse() && IsConnected())
3460 {
3461 m_curr_tid_run = 1;
3462 return true;
3463 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003464 }
3465 return false;
3466}
3467
3468bool
3469GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3470{
Greg Clayton3dedae12013-12-06 21:45:27 +00003471 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003472 return response.IsNormalResponse();
3473 return false;
3474}
3475
3476bool
Greg Claytonf402f782012-10-13 02:11:55 +00003477GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003478{
3479 if (m_supports_qThreadStopInfo)
3480 {
3481 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003482 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003483 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003484 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003485 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003486 if (response.IsUnsupportedResponse())
3487 m_supports_qThreadStopInfo = false;
3488 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003489 return true;
3490 else
3491 return false;
3492 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003493 else
3494 {
3495 m_supports_qThreadStopInfo = false;
3496 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003497 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003498 return false;
3499}
3500
3501
3502uint8_t
3503GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3504{
Todd Fiala616b8272014-10-09 00:55:04 +00003505 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3506 if (log)
3507 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3508 __FUNCTION__, insert ? "add" : "remove", addr);
3509
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003510 // Check if the stub is known not to support this breakpoint type
3511 if (!SupportsGDBStoppointPacket(type))
3512 return UINT8_MAX;
3513 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003514 char packet[64];
3515 const int packet_len = ::snprintf (packet,
3516 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003517 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003518 insert ? 'Z' : 'z',
3519 type,
3520 addr,
3521 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003522 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003523 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003524 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003525 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003526 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003527 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003528 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003529 if (response.IsOKResponse())
3530 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003531
3532 // Error while setting breakpoint, send back specific error
3533 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003534 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003535
3536 // Empty packet informs us that breakpoint is not supported
3537 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003538 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003539 // Disable this breakpoint type since it is unsupported
3540 switch (type)
3541 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003542 case eBreakpointSoftware: m_supports_z0 = false; break;
3543 case eBreakpointHardware: m_supports_z1 = false; break;
3544 case eWatchpointWrite: m_supports_z2 = false; break;
3545 case eWatchpointRead: m_supports_z3 = false; break;
3546 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003547 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003548 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003549 }
3550 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003551 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003552 return UINT8_MAX;
3553}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003554
3555size_t
3556GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3557 bool &sequence_mutex_unavailable)
3558{
3559 Mutex::Locker locker;
3560 thread_ids.clear();
3561
Jim Ingham4ceb9282012-06-08 22:50:40 +00003562 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003563 {
3564 sequence_mutex_unavailable = false;
3565 StringExtractorGDBRemote response;
3566
Greg Clayton3dedae12013-12-06 21:45:27 +00003567 PacketResult packet_result;
3568 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3569 packet_result == PacketResult::Success && response.IsNormalResponse();
3570 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003571 {
3572 char ch = response.GetChar();
3573 if (ch == 'l')
3574 break;
3575 if (ch == 'm')
3576 {
3577 do
3578 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003579 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003580
3581 if (tid != LLDB_INVALID_THREAD_ID)
3582 {
3583 thread_ids.push_back (tid);
3584 }
3585 ch = response.GetChar(); // Skip the command separator
3586 } while (ch == ','); // Make sure we got a comma separator
3587 }
3588 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003589
3590 /*
3591 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3592 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
3593 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
3594 * Assume pid=tid=1 in such cases.
3595 */
3596 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
3597 {
3598 thread_ids.push_back (1);
3599 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00003600 }
3601 else
3602 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003603#if defined (LLDB_CONFIGURATION_DEBUG)
3604 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3605#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003606 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003607 if (log)
3608 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003609#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003610 sequence_mutex_unavailable = true;
3611 }
3612 return thread_ids.size();
3613}
Greg Clayton37a0a242012-04-11 00:24:49 +00003614
3615lldb::addr_t
3616GDBRemoteCommunicationClient::GetShlibInfoAddr()
3617{
3618 if (!IsRunning())
3619 {
3620 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003621 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003622 {
3623 if (response.IsNormalResponse())
3624 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3625 }
3626 }
3627 return LLDB_INVALID_ADDRESS;
3628}
3629
Daniel Maleae0f8f572013-08-26 23:57:52 +00003630lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003631GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3632 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3633 int *status_ptr, // Pass NULL if you don't want the process exit status
3634 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3635 std::string *command_output, // Pass NULL if you don't want the command output
3636 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003637{
3638 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003639 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003640 stream.PutBytesAsRawHex8(command, strlen(command));
3641 stream.PutChar(',');
3642 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003643 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003644 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003645 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003646 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003647 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003648 }
3649 const char *packet = stream.GetData();
3650 int packet_len = stream.GetSize();
3651 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003652 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003653 {
3654 if (response.GetChar() != 'F')
3655 return Error("malformed reply");
3656 if (response.GetChar() != ',')
3657 return Error("malformed reply");
3658 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3659 if (exitcode == UINT32_MAX)
3660 return Error("unable to run remote process");
3661 else if (status_ptr)
3662 *status_ptr = exitcode;
3663 if (response.GetChar() != ',')
3664 return Error("malformed reply");
3665 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3666 if (signo_ptr)
3667 *signo_ptr = signo;
3668 if (response.GetChar() != ',')
3669 return Error("malformed reply");
3670 std::string output;
3671 response.GetEscapedBinaryData(output);
3672 if (command_output)
3673 command_output->assign(output);
3674 return Error();
3675 }
3676 return Error("unable to send packet");
3677}
3678
Greg Claytonfbb76342013-11-20 21:07:01 +00003679Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003680GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3681 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003682{
Chaoren Lind3173f32015-05-29 19:52:29 +00003683 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003684 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003685 stream.PutCString("qPlatform_mkdir:");
3686 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003687 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003688 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003689 const char *packet = stream.GetData();
3690 int packet_len = stream.GetSize();
3691 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003692
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003693 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3694 return Error("failed to send '%s' packet", packet);
3695
3696 if (response.GetChar() != 'F')
3697 return Error("invalid response to '%s' packet", packet);
3698
3699 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003700}
3701
Greg Claytonfbb76342013-11-20 21:07:01 +00003702Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003703GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3704 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003705{
Chaoren Lind3173f32015-05-29 19:52:29 +00003706 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003707 lldb_private::StreamString stream;
3708 stream.PutCString("qPlatform_chmod:");
3709 stream.PutHex32(file_permissions);
3710 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003711 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003712 const char *packet = stream.GetData();
3713 int packet_len = stream.GetSize();
3714 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003715
3716 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3717 return Error("failed to send '%s' packet", packet);
3718
3719 if (response.GetChar() != 'F')
3720 return Error("invalid response to '%s' packet", packet);
3721
Chaoren Lince36c4c2015-05-05 18:43:19 +00003722 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003723}
3724
Daniel Maleae0f8f572013-08-26 23:57:52 +00003725static uint64_t
3726ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3727 uint64_t fail_result,
3728 Error &error)
3729{
3730 response.SetFilePos(0);
3731 if (response.GetChar() != 'F')
3732 return fail_result;
3733 int32_t result = response.GetS32 (-2);
3734 if (result == -2)
3735 return fail_result;
3736 if (response.GetChar() == ',')
3737 {
3738 int result_errno = response.GetS32 (-2);
3739 if (result_errno != -2)
3740 error.SetError(result_errno, eErrorTypePOSIX);
3741 else
3742 error.SetError(-1, eErrorTypeGeneric);
3743 }
3744 else
3745 error.Clear();
3746 return result;
3747}
3748lldb::user_id_t
3749GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3750 uint32_t flags,
3751 mode_t mode,
3752 Error &error)
3753{
Chaoren Lind3173f32015-05-29 19:52:29 +00003754 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003755 lldb_private::StreamString stream;
3756 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003757 if (path.empty())
3758 return UINT64_MAX;
3759 stream.PutCStringAsRawHex8(path.c_str());
3760 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003761 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003762 stream.PutChar(',');
3763 stream.PutHex32(mode);
3764 const char* packet = stream.GetData();
3765 int packet_len = stream.GetSize();
3766 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003767 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003768 {
3769 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3770 }
3771 return UINT64_MAX;
3772}
3773
3774bool
3775GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3776 Error &error)
3777{
3778 lldb_private::StreamString stream;
3779 stream.Printf("vFile:close:%i", (int)fd);
3780 const char* packet = stream.GetData();
3781 int packet_len = stream.GetSize();
3782 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003783 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003784 {
3785 return ParseHostIOPacketResponse (response, -1, error) == 0;
3786 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003787 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003788}
3789
3790// Extension of host I/O packets to get the file size.
3791lldb::user_id_t
3792GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3793{
Chaoren Lind3173f32015-05-29 19:52:29 +00003794 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003795 lldb_private::StreamString stream;
3796 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003797 stream.PutCStringAsRawHex8(path.c_str());
3798 const char* packet = stream.GetData();
3799 int packet_len = stream.GetSize();
3800 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003801 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003802 {
3803 if (response.GetChar() != 'F')
3804 return UINT64_MAX;
3805 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3806 return retcode;
3807 }
3808 return UINT64_MAX;
3809}
3810
Greg Claytonfbb76342013-11-20 21:07:01 +00003811Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003812GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3813 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003814{
Chaoren Lind3173f32015-05-29 19:52:29 +00003815 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003816 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003817 lldb_private::StreamString stream;
3818 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003819 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003820 const char* packet = stream.GetData();
3821 int packet_len = stream.GetSize();
3822 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003823 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003824 {
3825 if (response.GetChar() != 'F')
3826 {
3827 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003828 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003829 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003830 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003831 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003832 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003833 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003834 if (response.GetChar() == ',')
3835 {
3836 int response_errno = response.GetS32(-1);
3837 if (response_errno > 0)
3838 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3839 else
3840 error.SetErrorToGenericError();
3841 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003842 else
3843 error.SetErrorToGenericError();
3844 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003845 else
3846 {
3847 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3848 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003849 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003850 }
3851 else
3852 {
3853 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3854 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003855 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003856}
3857
3858uint64_t
3859GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3860 uint64_t offset,
3861 void *dst,
3862 uint64_t dst_len,
3863 Error &error)
3864{
3865 lldb_private::StreamString stream;
3866 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3867 const char* packet = stream.GetData();
3868 int packet_len = stream.GetSize();
3869 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003870 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003871 {
3872 if (response.GetChar() != 'F')
3873 return 0;
3874 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3875 if (retcode == UINT32_MAX)
3876 return retcode;
3877 const char next = (response.Peek() ? *response.Peek() : 0);
3878 if (next == ',')
3879 return 0;
3880 if (next == ';')
3881 {
3882 response.GetChar(); // skip the semicolon
3883 std::string buffer;
3884 if (response.GetEscapedBinaryData(buffer))
3885 {
3886 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3887 if (data_to_write > 0)
3888 memcpy(dst, &buffer[0], data_to_write);
3889 return data_to_write;
3890 }
3891 }
3892 }
3893 return 0;
3894}
3895
3896uint64_t
3897GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3898 uint64_t offset,
3899 const void* src,
3900 uint64_t src_len,
3901 Error &error)
3902{
3903 lldb_private::StreamGDBRemote stream;
3904 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3905 stream.PutEscapedBytes(src, src_len);
3906 const char* packet = stream.GetData();
3907 int packet_len = stream.GetSize();
3908 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003909 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003910 {
3911 if (response.GetChar() != 'F')
3912 {
3913 error.SetErrorStringWithFormat("write file failed");
3914 return 0;
3915 }
3916 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3917 if (bytes_written == UINT64_MAX)
3918 {
3919 error.SetErrorToGenericError();
3920 if (response.GetChar() == ',')
3921 {
3922 int response_errno = response.GetS32(-1);
3923 if (response_errno > 0)
3924 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3925 }
3926 return 0;
3927 }
3928 return bytes_written;
3929 }
3930 else
3931 {
3932 error.SetErrorString ("failed to send vFile:pwrite packet");
3933 }
3934 return 0;
3935}
3936
Greg Claytonfbb76342013-11-20 21:07:01 +00003937Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003938GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003939{
Chaoren Lind3173f32015-05-29 19:52:29 +00003940 std::string src_path{src.GetPath(false)},
3941 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003942 Error error;
3943 lldb_private::StreamGDBRemote stream;
3944 stream.PutCString("vFile:symlink:");
3945 // the unix symlink() command reverses its parameters where the dst if first,
3946 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003947 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003948 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003949 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003950 const char* packet = stream.GetData();
3951 int packet_len = stream.GetSize();
3952 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003953 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003954 {
3955 if (response.GetChar() == 'F')
3956 {
3957 uint32_t result = response.GetU32(UINT32_MAX);
3958 if (result != 0)
3959 {
3960 error.SetErrorToGenericError();
3961 if (response.GetChar() == ',')
3962 {
3963 int response_errno = response.GetS32(-1);
3964 if (response_errno > 0)
3965 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3966 }
3967 }
3968 }
3969 else
3970 {
3971 // Should have returned with 'F<result>[,<errno>]'
3972 error.SetErrorStringWithFormat("symlink failed");
3973 }
3974 }
3975 else
3976 {
3977 error.SetErrorString ("failed to send vFile:symlink packet");
3978 }
3979 return error;
3980}
3981
3982Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003983GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00003984{
Chaoren Lind3173f32015-05-29 19:52:29 +00003985 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003986 Error error;
3987 lldb_private::StreamGDBRemote stream;
3988 stream.PutCString("vFile:unlink:");
3989 // the unix symlink() command reverses its parameters where the dst if first,
3990 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003991 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003992 const char* packet = stream.GetData();
3993 int packet_len = stream.GetSize();
3994 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003995 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003996 {
3997 if (response.GetChar() == 'F')
3998 {
3999 uint32_t result = response.GetU32(UINT32_MAX);
4000 if (result != 0)
4001 {
4002 error.SetErrorToGenericError();
4003 if (response.GetChar() == ',')
4004 {
4005 int response_errno = response.GetS32(-1);
4006 if (response_errno > 0)
4007 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4008 }
4009 }
4010 }
4011 else
4012 {
4013 // Should have returned with 'F<result>[,<errno>]'
4014 error.SetErrorStringWithFormat("unlink failed");
4015 }
4016 }
4017 else
4018 {
4019 error.SetErrorString ("failed to send vFile:unlink packet");
4020 }
4021 return error;
4022}
4023
Daniel Maleae0f8f572013-08-26 23:57:52 +00004024// Extension of host I/O packets to get whether a file exists.
4025bool
4026GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
4027{
Chaoren Lind3173f32015-05-29 19:52:29 +00004028 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004029 lldb_private::StreamString stream;
4030 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004031 stream.PutCStringAsRawHex8(path.c_str());
4032 const char* packet = stream.GetData();
4033 int packet_len = stream.GetSize();
4034 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004035 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004036 {
4037 if (response.GetChar() != 'F')
4038 return false;
4039 if (response.GetChar() != ',')
4040 return false;
4041 bool retcode = (response.GetChar() != '0');
4042 return retcode;
4043 }
4044 return false;
4045}
4046
4047bool
4048GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
4049 uint64_t &high,
4050 uint64_t &low)
4051{
Chaoren Lind3173f32015-05-29 19:52:29 +00004052 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004053 lldb_private::StreamString stream;
4054 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004055 stream.PutCStringAsRawHex8(path.c_str());
4056 const char* packet = stream.GetData();
4057 int packet_len = stream.GetSize();
4058 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004059 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004060 {
4061 if (response.GetChar() != 'F')
4062 return false;
4063 if (response.GetChar() != ',')
4064 return false;
4065 if (response.Peek() && *response.Peek() == 'x')
4066 return false;
4067 low = response.GetHexMaxU64(false, UINT64_MAX);
4068 high = response.GetHexMaxU64(false, UINT64_MAX);
4069 return true;
4070 }
4071 return false;
4072}
Greg Claytonf74cf862013-11-13 23:28:31 +00004073
4074bool
Jason Molendaa3329782014-03-29 18:54:20 +00004075GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
4076{
4077 // Some targets have issues with g/G packets and we need to avoid using them
4078 if (m_avoid_g_packets == eLazyBoolCalculate)
4079 {
4080 if (process)
4081 {
4082 m_avoid_g_packets = eLazyBoolNo;
4083 const ArchSpec &arch = process->GetTarget().GetArchitecture();
4084 if (arch.IsValid()
4085 && arch.GetTriple().getVendor() == llvm::Triple::Apple
4086 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00004087 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00004088 {
4089 m_avoid_g_packets = eLazyBoolYes;
4090 uint32_t gdb_server_version = GetGDBServerProgramVersion();
4091 if (gdb_server_version != 0)
4092 {
4093 const char *gdb_server_name = GetGDBServerProgramName();
4094 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
4095 {
4096 if (gdb_server_version >= 310)
4097 m_avoid_g_packets = eLazyBoolNo;
4098 }
4099 }
4100 }
4101 }
4102 }
4103 return m_avoid_g_packets == eLazyBoolYes;
4104}
4105
4106bool
Greg Claytonf74cf862013-11-13 23:28:31 +00004107GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4108{
4109 Mutex::Locker locker;
4110 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4111 {
4112 const bool thread_suffix_supported = GetThreadSuffixSupported();
4113
4114 if (thread_suffix_supported || SetCurrentThread(tid))
4115 {
4116 char packet[64];
4117 int packet_len = 0;
4118 if (thread_suffix_supported)
4119 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4120 else
4121 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4122 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004123 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004124 }
4125 }
4126 return false;
4127
4128}
4129
4130
4131bool
4132GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4133{
4134 Mutex::Locker locker;
4135 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4136 {
4137 const bool thread_suffix_supported = GetThreadSuffixSupported();
4138
4139 if (thread_suffix_supported || SetCurrentThread(tid))
4140 {
4141 char packet[64];
4142 int packet_len = 0;
4143 // Get all registers in one packet
4144 if (thread_suffix_supported)
4145 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4146 else
4147 packet_len = ::snprintf (packet, sizeof(packet), "g");
4148 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004149 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004150 }
4151 }
4152 return false;
4153}
4154bool
4155GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4156{
4157 save_id = 0; // Set to invalid save ID
4158 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4159 return false;
4160
4161 m_supports_QSaveRegisterState = eLazyBoolYes;
4162 Mutex::Locker locker;
4163 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4164 {
4165 const bool thread_suffix_supported = GetThreadSuffixSupported();
4166 if (thread_suffix_supported || SetCurrentThread(tid))
4167 {
4168 char packet[256];
4169 if (thread_suffix_supported)
4170 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4171 else
Ilia K686b1fe2015-02-27 19:43:08 +00004172 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00004173
4174 StringExtractorGDBRemote response;
4175
Greg Clayton3dedae12013-12-06 21:45:27 +00004176 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004177 {
4178 if (response.IsUnsupportedResponse())
4179 {
4180 // This packet isn't supported, don't try calling it again
4181 m_supports_QSaveRegisterState = eLazyBoolNo;
4182 }
4183
4184 const uint32_t response_save_id = response.GetU32(0);
4185 if (response_save_id != 0)
4186 {
4187 save_id = response_save_id;
4188 return true;
4189 }
4190 }
4191 }
4192 }
4193 return false;
4194}
4195
4196bool
4197GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4198{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004199 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00004200 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4201 // order to be useful
4202 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4203 return false;
4204
4205 Mutex::Locker locker;
4206 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4207 {
4208 const bool thread_suffix_supported = GetThreadSuffixSupported();
4209 if (thread_suffix_supported || SetCurrentThread(tid))
4210 {
4211 char packet[256];
4212 if (thread_suffix_supported)
4213 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4214 else
4215 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4216
4217 StringExtractorGDBRemote response;
4218
Greg Clayton3dedae12013-12-06 21:45:27 +00004219 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004220 {
4221 if (response.IsOKResponse())
4222 {
4223 return true;
4224 }
4225 else if (response.IsUnsupportedResponse())
4226 {
4227 // This packet isn't supported, don't try calling this packet or
4228 // QSaveRegisterState again...
4229 m_supports_QSaveRegisterState = eLazyBoolNo;
4230 }
4231 }
4232 }
4233 }
4234 return false;
4235}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004236
4237bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004238GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004239 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004240 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004241{
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00004242 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004243 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004244 return false;
4245
4246 StreamString packet;
4247 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004248 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004249 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00004250 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00004251 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004252
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004253 StringExtractorGDBRemote response;
4254 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4255 return false;
4256
Aidan Doddsdf627e72015-05-05 08:31:55 +00004257 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004258 return false;
4259
4260 std::string name;
4261 std::string value;
4262 bool success;
4263 StringExtractor extractor;
4264
4265 module_spec.Clear ();
4266 module_spec.GetFileSpec () = module_file_spec;
4267
4268 while (response.GetNameColonValue (name, value))
4269 {
4270 if (name == "uuid" || name == "md5")
4271 {
4272 extractor.GetStringRef ().swap (value);
4273 extractor.SetFilePos (0);
4274 extractor.GetHexByteString (value);
4275 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4276 }
4277 else if (name == "triple")
4278 {
4279 extractor.GetStringRef ().swap (value);
4280 extractor.SetFilePos (0);
4281 extractor.GetHexByteString (value);
4282 module_spec.GetArchitecture().SetTriple (value.c_str ());
4283 }
4284 else if (name == "file_offset")
4285 {
4286 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4287 if (success)
4288 module_spec.SetObjectOffset (ival);
4289 }
4290 else if (name == "file_size")
4291 {
4292 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4293 if (success)
4294 module_spec.SetObjectSize (ival);
4295 }
4296 else if (name == "file_path")
4297 {
4298 extractor.GetStringRef ().swap (value);
4299 extractor.SetFilePos (0);
4300 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00004301 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004302 }
4303 }
4304
4305 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004306}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004307
4308// query the target remote for extended information using the qXfer packet
4309//
4310// example: object='features', annex='target.xml', out=<xml output>
4311// return: 'true' on success
4312// 'false' on failure (err set)
4313bool
4314GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4315 const lldb_private::ConstString annex,
4316 std::string & out,
4317 lldb_private::Error & err) {
4318
4319 std::stringstream output;
4320 StringExtractorGDBRemote chunk;
4321
Greg Claytond04f0ed2015-05-26 18:00:51 +00004322 uint64_t size = GetRemoteMaxPacketSize();
4323 if (size == 0)
4324 size = 0x1000;
4325 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4326 int offset = 0;
4327 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004328
4329 // loop until all data has been read
4330 while ( active ) {
4331
4332 // send query extended feature packet
4333 std::stringstream packet;
4334 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00004335 << object.AsCString("") << ":read:"
4336 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00004337 << std::hex << offset << ","
4338 << std::hex << size;
4339
4340 GDBRemoteCommunication::PacketResult res =
4341 SendPacketAndWaitForResponse( packet.str().c_str(),
4342 chunk,
4343 false );
4344
4345 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4346 err.SetErrorString( "Error sending $qXfer packet" );
4347 return false;
4348 }
4349
4350 const std::string & str = chunk.GetStringRef( );
4351 if ( str.length() == 0 ) {
4352 // should have some data in chunk
4353 err.SetErrorString( "Empty response from $qXfer packet" );
4354 return false;
4355 }
4356
4357 // check packet code
4358 switch ( str[0] ) {
4359 // last chunk
4360 case ( 'l' ):
4361 active = false;
Aidan Doddsed9f6122015-04-29 10:08:17 +00004362 // fall through intentional
Colin Rileyc3c95b22015-04-16 15:51:33 +00004363
4364 // more chunks
4365 case ( 'm' ) :
4366 if ( str.length() > 1 )
4367 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00004368 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004369 break;
4370
4371 // unknown chunk
4372 default:
4373 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4374 return false;
4375 }
4376 }
4377
4378 out = output.str( );
4379 err.Success( );
4380 return true;
4381}
Greg Clayton0b90be12015-06-23 21:27:50 +00004382
4383// Notify the target that gdb is prepared to serve symbol lookup requests.
4384// packet: "qSymbol::"
4385// reply:
4386// OK The target does not need to look up any (more) symbols.
4387// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
4388// LLDB may provide the value by sending another qSymbol packet
4389// in the form of"qSymbol:<sym_value>:<sym_name>".
4390
4391void
4392GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4393{
4394 if (m_supports_qSymbol)
4395 {
4396 Mutex::Locker locker;
4397 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4398 {
4399 StreamString packet;
4400 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00004401 StringExtractorGDBRemote response;
4402 while (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00004403 {
Greg Clayton42b01482015-08-11 22:07:46 +00004404 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00004405 {
Greg Clayton42b01482015-08-11 22:07:46 +00004406 // We are done serving symbols requests
4407 return;
4408 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004409
Greg Clayton42b01482015-08-11 22:07:46 +00004410 if (response.IsUnsupportedResponse())
4411 {
4412 // qSymbol is not supported by the current GDB server we are connected to
4413 m_supports_qSymbol = false;
4414 return;
4415 }
4416 else
4417 {
4418 llvm::StringRef response_str(response.GetStringRef());
4419 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00004420 {
Greg Clayton42b01482015-08-11 22:07:46 +00004421 response.SetFilePos(strlen("qSymbol:"));
4422 std::string symbol_name;
4423 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00004424 {
Greg Clayton42b01482015-08-11 22:07:46 +00004425 if (symbol_name.empty())
4426 return;
4427
4428 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4429 lldb_private::SymbolContextList sc_list;
4430 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00004431 {
Greg Clayton42b01482015-08-11 22:07:46 +00004432 const size_t num_scs = sc_list.GetSize();
4433 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 +00004434 {
Greg Clayton42b01482015-08-11 22:07:46 +00004435 SymbolContext sc;
4436 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00004437 {
Greg Clayton42b01482015-08-11 22:07:46 +00004438 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00004439 {
Greg Clayton42b01482015-08-11 22:07:46 +00004440 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00004441 {
Greg Clayton42b01482015-08-11 22:07:46 +00004442 case eSymbolTypeInvalid:
4443 case eSymbolTypeAbsolute:
4444 case eSymbolTypeUndefined:
4445 case eSymbolTypeSourceFile:
4446 case eSymbolTypeHeaderFile:
4447 case eSymbolTypeObjectFile:
4448 case eSymbolTypeCommonBlock:
4449 case eSymbolTypeBlock:
4450 case eSymbolTypeLocal:
4451 case eSymbolTypeParam:
4452 case eSymbolTypeVariable:
4453 case eSymbolTypeVariableType:
4454 case eSymbolTypeLineEntry:
4455 case eSymbolTypeLineHeader:
4456 case eSymbolTypeScopeBegin:
4457 case eSymbolTypeScopeEnd:
4458 case eSymbolTypeAdditional:
4459 case eSymbolTypeCompiler:
4460 case eSymbolTypeInstrumentation:
4461 case eSymbolTypeTrampoline:
4462 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004463
Greg Clayton42b01482015-08-11 22:07:46 +00004464 case eSymbolTypeCode:
4465 case eSymbolTypeResolver:
4466 case eSymbolTypeData:
4467 case eSymbolTypeRuntime:
4468 case eSymbolTypeException:
4469 case eSymbolTypeObjCClass:
4470 case eSymbolTypeObjCMetaClass:
4471 case eSymbolTypeObjCIVar:
4472 case eSymbolTypeReExported:
4473 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4474 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004475 }
4476 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004477 }
4478 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004479 }
Greg Clayton42b01482015-08-11 22:07:46 +00004480 // This is the normal path where our symbol lookup was successful and we want
4481 // to send a packet with the new symbol value and see if another lookup needs to be
4482 // done.
4483
4484 // Change "packet" to contain the requested symbol value and name
4485 packet.Clear();
4486 packet.PutCString("qSymbol:");
4487 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4488 packet.Printf("%" PRIx64, symbol_load_addr);
4489 packet.PutCString(":");
4490 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4491 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00004492 }
4493 }
4494 }
4495 }
4496 // If we make it here, the symbol request packet response wasn't valid or
4497 // our symbol lookup failed so we must abort
4498 return;
4499
4500 }
4501 }
4502}
4503