blob: 5c7f6caca511f1e9ce47a41fd058a190f9b31ff7 [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
Greg Clayton576d8832011-03-22 04:00:09 +00001052 m_public_is_running.SetValue (true, eBroadcastNever);
1053 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +00001054 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +00001055 std::string continue_packet(payload, packet_length);
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001056
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001057 const auto sigstop_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
1058 const auto sigint_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGINT");
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001059
Greg Clayton3f875c52013-02-22 22:23:55 +00001060 bool got_async_packet = false;
Pavel Labath9e131f72015-10-27 09:23:55 +00001061 bool broadcast_sent = 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
Pavel Labath9e131f72015-10-27 09:23:55 +00001074 if (! broadcast_sent)
1075 {
1076 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1077 broadcast_sent = true;
1078 }
1079
Greg Claytone889ad62011-10-27 22:04:16 +00001080 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +00001081 }
1082
Greg Clayton3f875c52013-02-22 22:23:55 +00001083 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001084
1085 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001086 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001087
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001088 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001089 {
1090 if (response.Empty())
1091 state = eStateInvalid;
1092 else
1093 {
1094 const char stop_type = response.GetChar();
1095 if (log)
1096 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
1097 switch (stop_type)
1098 {
1099 case 'T':
1100 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +00001101 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001102 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +00001103 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001104 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
1105 {
1106 lldb::pid_t pid = GetCurrentProcessID ();
1107 if (pid != LLDB_INVALID_PROCESS_ID)
1108 process->SetID (pid);
1109 }
1110 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +00001111 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001112
1113 // Privately notify any internal threads that we have stopped
1114 // in case we wanted to interrupt our process, yet we might
1115 // send a packet and continue without returning control to the
1116 // user.
1117 m_private_is_running.SetValue (false, eBroadcastAlways);
1118
1119 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1120
Jim Inghambabfc382012-06-06 00:32:39 +00001121 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1122 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +00001123 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001124 // We sent an interrupt packet to stop the inferior process
1125 // for an async signal or to send an async packet while running
1126 // but we might have been single stepping and received the
1127 // stop packet for the step instead of for the interrupt packet.
1128 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1129 // is used, so if we get anything else, we need to try and
1130 // get another stop reply packet that may have been sent
1131 // due to sending the interrupt when the target is stopped
1132 // which will just re-send a copy of the last stop reply
1133 // packet. If we don't do this, then the reply for our
1134 // async packet will be the repeat stop reply packet and cause
1135 // a lot of trouble for us!
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001136 if (signo != sigint_signo && signo != sigstop_signo)
Greg Clayton2687cd12012-03-29 01:55:41 +00001137 {
Greg Claytonfb72fde2012-05-15 02:50:49 +00001138 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001139
Bruce Mitchenera868c132015-07-02 18:48:40 +00001140 // We didn't get a SIGINT or SIGSTOP, so try for a
Jason Molendada9765b2015-08-26 04:07:30 +00001141 // very brief time (0.1s) to get another stop reply
Greg Clayton2687cd12012-03-29 01:55:41 +00001142 // packet to make sure it doesn't get in the way
1143 StringExtractorGDBRemote extra_stop_reply_packet;
Jason Molendada9765b2015-08-26 04:07:30 +00001144 uint32_t timeout_usec = 100000;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001145 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +00001146 {
1147 switch (extra_stop_reply_packet.GetChar())
1148 {
1149 case 'T':
1150 case 'S':
1151 // We did get an extra stop reply, which means
1152 // our interrupt didn't stop the target so we
1153 // shouldn't continue after the async signal
1154 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +00001155 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001156 break;
1157 }
1158 }
1159 }
1160 }
1161
1162 if (m_async_signal != -1)
1163 {
1164 if (log)
1165 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1166
1167 // Save off the async signal we are supposed to send
1168 const int async_signal = m_async_signal;
1169 // Clear the async signal member so we don't end up
1170 // sending the signal multiple times...
1171 m_async_signal = -1;
1172 // Check which signal we stopped with
1173 if (signo == async_signal)
1174 {
1175 if (log)
1176 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1177
1178 // We already stopped with a signal that we wanted
1179 // to stop with, so we are done
1180 }
1181 else
1182 {
1183 // We stopped with a different signal that the one
1184 // we wanted to stop with, so now we must resume
1185 // with the signal we want
1186 char signal_packet[32];
1187 int signal_packet_len = 0;
1188 signal_packet_len = ::snprintf (signal_packet,
1189 sizeof (signal_packet),
1190 "C%2.2x",
1191 async_signal);
1192
1193 if (log)
1194 log->Printf ("async: stopped with signal %s, resume with %s",
1195 Host::GetSignalAsCString (signo),
1196 Host::GetSignalAsCString (async_signal));
1197
1198 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001199 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001200 continue_packet.assign(signal_packet, signal_packet_len);
1201 continue;
1202 }
1203 }
1204 else if (m_async_packet_predicate.GetValue())
1205 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001206 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001207
1208 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001209 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001210 m_async_response.Clear();
1211 if (m_async_packet.empty())
1212 {
Jim Inghama6195b72013-12-18 01:24:33 +00001213 m_async_result = PacketResult::ErrorSendFailed;
1214 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001215 packet_log->Printf ("async: error: empty async packet");
1216
1217 }
1218 else
1219 {
1220 if (packet_log)
1221 packet_log->Printf ("async: sending packet");
1222
Jim Inghama6195b72013-12-18 01:24:33 +00001223 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1224 m_async_packet.size(),
1225 m_async_response,
1226 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001227 }
1228 // Let the other thread that was trying to send the async
1229 // packet know that the packet has been sent and response is
1230 // ready...
1231 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1232
1233 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001234 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001235
1236 // Set the continue packet to resume if our interrupt
1237 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001238 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001239 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001240 // Reverting this for now as it is causing deadlocks
1241 // in programs (<rdar://problem/11529853>). In the future
1242 // we should check our thread list and "do the right thing"
1243 // for new threads that show up while we stop and run async
1244 // packets. Setting the packet to 'c' to continue all threads
1245 // is the right thing to do 99.99% of the time because if a
1246 // thread was single stepping, and we sent an interrupt, we
1247 // will notice above that we didn't stop due to an interrupt
1248 // but stopped due to stepping and we would _not_ continue.
1249 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001250 continue;
1251 }
1252 }
1253 // Stop with signal and thread info
1254 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001255 }
Greg Clayton576d8832011-03-22 04:00:09 +00001256 break;
1257
1258 case 'W':
1259 case 'X':
1260 // process exited
1261 state = eStateExited;
1262 break;
1263
1264 case 'O':
1265 // STDOUT
1266 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001267 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001268 std::string inferior_stdout;
1269 inferior_stdout.reserve(response.GetBytesLeft () / 2);
Dawn Perchik554a8572015-09-17 17:55:32 +00001270
1271 uint8_t ch;
1272 while (response.GetHexU8Ex(ch))
1273 {
1274 if (ch != 0)
1275 inferior_stdout.append(1, (char)ch);
1276 }
Greg Clayton576d8832011-03-22 04:00:09 +00001277 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1278 }
1279 break;
1280
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001281 case 'A':
1282 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1283 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001284 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001285 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1286 if (m_partial_profile_data.length() > 0)
1287 {
1288 m_partial_profile_data.append(input);
1289 input = m_partial_profile_data;
1290 m_partial_profile_data.clear();
1291 }
1292
1293 size_t found, pos = 0, len = input.length();
1294 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1295 {
1296 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001297 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1298 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001299
1300 pos = found + end_delimiter_len;
1301 }
1302
1303 if (pos < len)
1304 {
1305 // Last incomplete chunk.
1306 m_partial_profile_data = input.substr(pos);
1307 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001308 }
1309 break;
1310
Greg Clayton576d8832011-03-22 04:00:09 +00001311 case 'E':
1312 // ERROR
1313 state = eStateInvalid;
1314 break;
1315
1316 default:
1317 if (log)
1318 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1319 state = eStateInvalid;
1320 break;
1321 }
1322 }
1323 }
1324 else
1325 {
1326 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001327 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
Greg Clayton576d8832011-03-22 04:00:09 +00001328 state = eStateInvalid;
1329 }
1330 }
1331 if (log)
1332 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1333 response.SetFilePos(0);
1334 m_private_is_running.SetValue (false, eBroadcastAlways);
1335 m_public_is_running.SetValue (false, eBroadcastAlways);
1336 return state;
1337}
1338
1339bool
1340GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1341{
Greg Clayton2687cd12012-03-29 01:55:41 +00001342 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001343 m_async_signal = signo;
1344 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001345 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001346 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001347 return true;
1348 m_async_signal = -1;
1349 return false;
1350}
1351
Greg Clayton37a0a242012-04-11 00:24:49 +00001352// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001353// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1354// (the expected result), then it will send the halt packet. If it does succeed
1355// then the caller that requested the interrupt will want to keep the sequence
1356// locked down so that no one else can send packets while the caller has control.
1357// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001358// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001359// else (like read/write memory), so we need to interrupt the running process
1360// (gdb remote protocol requires this), and do what we need to do, then resume.
1361
1362bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001363GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001364(
1365 Mutex::Locker& locker,
1366 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001367 bool &timed_out
1368)
1369{
Greg Clayton576d8832011-03-22 04:00:09 +00001370 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001371 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001372
1373 if (IsRunning())
1374 {
1375 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001376 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001377 {
1378 if (log)
1379 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1380 }
1381 else
Greg Clayton576d8832011-03-22 04:00:09 +00001382 {
1383 // Someone has the mutex locked waiting for a response or for the
1384 // inferior to stop, so send the interrupt on the down low...
1385 char ctrl_c = '\x03';
1386 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001387 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001388 if (log)
1389 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001390 if (bytes_written > 0)
1391 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001392 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001393 if (seconds_to_wait_for_stop)
1394 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001395 TimeValue timeout;
1396 if (seconds_to_wait_for_stop)
1397 {
1398 timeout = TimeValue::Now();
1399 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1400 }
Greg Clayton576d8832011-03-22 04:00:09 +00001401 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1402 {
1403 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001404 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001405 return true;
1406 }
1407 else
1408 {
1409 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001410 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001411 }
1412 }
1413 else
1414 {
1415 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001416 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001417 return true;
1418 }
1419 }
1420 else
1421 {
1422 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001423 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001424 }
1425 return false;
1426 }
Greg Clayton576d8832011-03-22 04:00:09 +00001427 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001428 else
1429 {
1430 if (log)
1431 log->Printf ("SendInterrupt () - not running");
1432 }
Greg Clayton576d8832011-03-22 04:00:09 +00001433 return true;
1434}
1435
1436lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001437GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001438{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001439 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001440 return m_curr_pid;
1441
1442 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001443 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001444 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001445 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001446 // We really got it.
1447 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001448 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001449 else
1450 {
Todd Fialae24614f2014-05-14 00:15:32 +00001451 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1452 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1453 // The gdb remote protocol documents $qC as returning the thread id, which newer
1454 // debugserver and lldb-gdbserver stubs return correctly.
1455 StringExtractorGDBRemote response;
1456 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001457 {
Todd Fialae24614f2014-05-14 00:15:32 +00001458 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001459 {
Todd Fialae24614f2014-05-14 00:15:32 +00001460 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001461 {
Todd Fialae24614f2014-05-14 00:15:32 +00001462 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1463 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001464 {
Todd Fialae24614f2014-05-14 00:15:32 +00001465 m_curr_pid_is_valid = eLazyBoolYes;
1466 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001467 }
1468 }
1469 }
1470 }
Jaydeep Patil1142f832015-08-13 03:46:36 +00001471
1472 // If we don't get a response for $qC, check if $qfThreadID gives us a result.
1473 if (m_curr_pid == LLDB_INVALID_PROCESS_ID)
1474 {
1475 std::vector<lldb::tid_t> thread_ids;
1476 bool sequence_mutex_unavailable;
1477 size_t size;
1478 size = GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1479 if (size && sequence_mutex_unavailable == false)
1480 {
1481 m_curr_pid = thread_ids.front();
1482 m_curr_pid_is_valid = eLazyBoolYes;
1483 return m_curr_pid;
1484 }
1485 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001486 }
1487
Greg Clayton576d8832011-03-22 04:00:09 +00001488 return LLDB_INVALID_PROCESS_ID;
1489}
1490
1491bool
1492GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1493{
1494 error_str.clear();
1495 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001496 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001497 {
1498 if (response.IsOKResponse())
1499 return true;
1500 if (response.GetChar() == 'E')
1501 {
1502 // A string the describes what failed when launching...
1503 error_str = response.GetStringRef().substr(1);
1504 }
1505 else
1506 {
1507 error_str.assign ("unknown error occurred launching process");
1508 }
1509 }
1510 else
1511 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001512 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001513 }
1514 return false;
1515}
1516
1517int
Greg Claytonfbb76342013-11-20 21:07:01 +00001518GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001519{
Greg Claytonfbb76342013-11-20 21:07:01 +00001520 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001521 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001522 std::vector<const char *> argv;
1523 FileSpec exe_file = launch_info.GetExecutableFile();
1524 std::string exe_path;
1525 const char *arg = NULL;
1526 const Args &launch_args = launch_info.GetArguments();
1527 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +00001528 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +00001529 else
1530 {
1531 arg = launch_args.GetArgumentAtIndex(0);
1532 if (arg)
1533 exe_path = arg;
1534 }
1535 if (!exe_path.empty())
1536 {
1537 argv.push_back(exe_path.c_str());
1538 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1539 {
1540 if (arg)
1541 argv.push_back(arg);
1542 }
1543 }
1544 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001545 {
1546 StreamString packet;
1547 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001548 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001549 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001550 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001551 const int arg_len = strlen(arg);
1552 if (i > 0)
1553 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001554 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001555 packet.PutBytesAsRawHex8 (arg, arg_len);
1556 }
1557
1558 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001559 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001560 {
1561 if (response.IsOKResponse())
1562 return 0;
1563 uint8_t error = response.GetError();
1564 if (error)
1565 return error;
1566 }
1567 }
1568 return -1;
1569}
1570
1571int
1572GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1573{
1574 if (name_equal_value && name_equal_value[0])
1575 {
1576 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001577 bool send_hex_encoding = false;
1578 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001579 {
Greg Clayton89600582013-10-10 17:53:50 +00001580 if (isprint(*p))
1581 {
1582 switch (*p)
1583 {
1584 case '$':
1585 case '#':
Jason Molenda60bdafb2015-11-05 23:51:05 +00001586 case '*':
Tim Northover974ff612015-11-09 22:05:05 +00001587 case '}':
Greg Clayton89600582013-10-10 17:53:50 +00001588 send_hex_encoding = true;
1589 break;
1590 default:
1591 break;
1592 }
1593 }
1594 else
1595 {
1596 // We have non printable characters, lets hex encode this...
1597 send_hex_encoding = true;
1598 }
1599 }
1600
1601 StringExtractorGDBRemote response;
1602 if (send_hex_encoding)
1603 {
1604 if (m_supports_QEnvironmentHexEncoded)
1605 {
1606 packet.PutCString("QEnvironmentHexEncoded:");
1607 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001608 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001609 {
1610 if (response.IsOKResponse())
1611 return 0;
1612 uint8_t error = response.GetError();
1613 if (error)
1614 return error;
1615 if (response.IsUnsupportedResponse())
1616 m_supports_QEnvironmentHexEncoded = false;
1617 }
1618 }
1619
1620 }
1621 else if (m_supports_QEnvironment)
1622 {
1623 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001624 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001625 {
1626 if (response.IsOKResponse())
1627 return 0;
1628 uint8_t error = response.GetError();
1629 if (error)
1630 return error;
1631 if (response.IsUnsupportedResponse())
1632 m_supports_QEnvironment = false;
1633 }
Greg Clayton576d8832011-03-22 04:00:09 +00001634 }
1635 }
1636 return -1;
1637}
1638
Greg Claytonc4103b32011-05-08 04:53:50 +00001639int
1640GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1641{
1642 if (arch && arch[0])
1643 {
1644 StreamString packet;
1645 packet.Printf("QLaunchArch:%s", arch);
1646 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001647 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001648 {
1649 if (response.IsOKResponse())
1650 return 0;
1651 uint8_t error = response.GetError();
1652 if (error)
1653 return error;
1654 }
1655 }
1656 return -1;
1657}
1658
Jason Molendaa3329782014-03-29 18:54:20 +00001659int
1660GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1661{
1662 if (data && *data != '\0')
1663 {
1664 StreamString packet;
1665 packet.Printf("QSetProcessEvent:%s", data);
1666 StringExtractorGDBRemote response;
1667 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1668 {
1669 if (response.IsOKResponse())
1670 {
1671 if (was_supported)
1672 *was_supported = true;
1673 return 0;
1674 }
1675 else if (response.IsUnsupportedResponse())
1676 {
1677 if (was_supported)
1678 *was_supported = false;
1679 return -1;
1680 }
1681 else
1682 {
1683 uint8_t error = response.GetError();
1684 if (was_supported)
1685 *was_supported = true;
1686 if (error)
1687 return error;
1688 }
1689 }
1690 }
1691 return -1;
1692}
1693
Greg Clayton576d8832011-03-22 04:00:09 +00001694bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001695GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1696 uint32_t &minor,
1697 uint32_t &update)
1698{
1699 if (GetHostInfo ())
1700 {
1701 if (m_os_version_major != UINT32_MAX)
1702 {
1703 major = m_os_version_major;
1704 minor = m_os_version_minor;
1705 update = m_os_version_update;
1706 return true;
1707 }
1708 }
1709 return false;
1710}
1711
1712bool
1713GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1714{
1715 if (GetHostInfo ())
1716 {
1717 if (!m_os_build.empty())
1718 {
1719 s = m_os_build;
1720 return true;
1721 }
1722 }
1723 s.clear();
1724 return false;
1725}
1726
1727
1728bool
1729GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1730{
1731 if (GetHostInfo ())
1732 {
1733 if (!m_os_kernel.empty())
1734 {
1735 s = m_os_kernel;
1736 return true;
1737 }
1738 }
1739 s.clear();
1740 return false;
1741}
1742
1743bool
1744GDBRemoteCommunicationClient::GetHostname (std::string &s)
1745{
1746 if (GetHostInfo ())
1747 {
1748 if (!m_hostname.empty())
1749 {
1750 s = m_hostname;
1751 return true;
1752 }
1753 }
1754 s.clear();
1755 return false;
1756}
1757
1758ArchSpec
1759GDBRemoteCommunicationClient::GetSystemArchitecture ()
1760{
1761 if (GetHostInfo ())
1762 return m_host_arch;
1763 return ArchSpec();
1764}
1765
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001766const lldb_private::ArchSpec &
1767GDBRemoteCommunicationClient::GetProcessArchitecture ()
1768{
1769 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1770 GetCurrentProcessInfo ();
1771 return m_process_arch;
1772}
1773
Jason Molendaa3329782014-03-29 18:54:20 +00001774bool
1775GDBRemoteCommunicationClient::GetGDBServerVersion()
1776{
1777 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1778 {
1779 m_gdb_server_name.clear();
1780 m_gdb_server_version = 0;
1781 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1782
1783 StringExtractorGDBRemote response;
1784 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1785 {
1786 if (response.IsNormalResponse())
1787 {
1788 std::string name;
1789 std::string value;
1790 bool success = false;
1791 while (response.GetNameColonValue(name, value))
1792 {
1793 if (name.compare("name") == 0)
1794 {
1795 success = true;
1796 m_gdb_server_name.swap(value);
1797 }
1798 else if (name.compare("version") == 0)
1799 {
1800 size_t dot_pos = value.find('.');
1801 if (dot_pos != std::string::npos)
1802 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001803 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001804 if (version != UINT32_MAX)
1805 {
1806 success = true;
1807 m_gdb_server_version = version;
1808 }
1809 }
1810 }
1811 if (success)
1812 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1813 }
1814 }
1815 }
1816 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1817}
1818
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001819void
1820GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1821{
1822 CompressionType avail_type = CompressionType::None;
1823 std::string avail_name;
1824
1825#if defined (HAVE_LIBCOMPRESSION)
1826 // libcompression is weak linked so test if compression_decode_buffer() is available
1827 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1828 {
1829 for (auto compression : supported_compressions)
1830 {
1831 if (compression == "lzfse")
1832 {
1833 avail_type = CompressionType::LZFSE;
1834 avail_name = compression;
1835 break;
1836 }
1837 }
1838 }
1839#endif
1840
1841#if defined (HAVE_LIBCOMPRESSION)
1842 // libcompression is weak linked so test if compression_decode_buffer() is available
1843 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1844 {
1845 for (auto compression : supported_compressions)
1846 {
1847 if (compression == "zlib-deflate")
1848 {
1849 avail_type = CompressionType::ZlibDeflate;
1850 avail_name = compression;
1851 break;
1852 }
1853 }
1854 }
1855#endif
1856
1857#if defined (HAVE_LIBZ)
1858 if (avail_type == CompressionType::None)
1859 {
1860 for (auto compression : supported_compressions)
1861 {
1862 if (compression == "zlib-deflate")
1863 {
1864 avail_type = CompressionType::ZlibDeflate;
1865 avail_name = compression;
1866 break;
1867 }
1868 }
1869 }
1870#endif
1871
1872#if defined (HAVE_LIBCOMPRESSION)
1873 // libcompression is weak linked so test if compression_decode_buffer() is available
1874 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1875 {
1876 for (auto compression : supported_compressions)
1877 {
1878 if (compression == "lz4")
1879 {
1880 avail_type = CompressionType::LZ4;
1881 avail_name = compression;
1882 break;
1883 }
1884 }
1885 }
1886#endif
1887
1888#if defined (HAVE_LIBCOMPRESSION)
1889 // libcompression is weak linked so test if compression_decode_buffer() is available
1890 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1891 {
1892 for (auto compression : supported_compressions)
1893 {
1894 if (compression == "lzma")
1895 {
1896 avail_type = CompressionType::LZMA;
1897 avail_name = compression;
1898 break;
1899 }
1900 }
1901 }
1902#endif
1903
1904 if (avail_type != CompressionType::None)
1905 {
1906 StringExtractorGDBRemote response;
1907 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1908 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1909 return;
1910
1911 if (response.IsOKResponse())
1912 {
1913 m_compression_type = avail_type;
1914 }
1915 }
1916}
1917
Jason Molendaa3329782014-03-29 18:54:20 +00001918const char *
1919GDBRemoteCommunicationClient::GetGDBServerProgramName()
1920{
1921 if (GetGDBServerVersion())
1922 {
1923 if (!m_gdb_server_name.empty())
1924 return m_gdb_server_name.c_str();
1925 }
1926 return NULL;
1927}
1928
1929uint32_t
1930GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1931{
1932 if (GetGDBServerVersion())
1933 return m_gdb_server_version;
1934 return 0;
1935}
Greg Clayton1cb64962011-03-24 04:28:38 +00001936
1937bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001938GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1939{
1940 StringExtractorGDBRemote response;
1941 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1942 return false;
1943
1944 if (!response.IsNormalResponse())
1945 return false;
1946
1947 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1948 tid = response.GetHexMaxU32(true, -1);
1949
1950 return true;
1951}
1952
1953bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001954GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001955{
Todd Fialaaf245d12014-06-30 21:05:18 +00001956 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1957
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001958 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001959 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001960 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001961 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001962 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001963 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001964 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001965 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001966 std::string name;
1967 std::string value;
1968 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1969 uint32_t sub = 0;
1970 std::string arch_name;
1971 std::string os_name;
1972 std::string vendor_name;
1973 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001974 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001975 uint32_t pointer_byte_size = 0;
1976 StringExtractor extractor;
1977 ByteOrder byte_order = eByteOrderInvalid;
1978 uint32_t num_keys_decoded = 0;
1979 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001980 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001981 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001982 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001983 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001984 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001985 if (cpu != LLDB_INVALID_CPUTYPE)
1986 ++num_keys_decoded;
1987 }
1988 else if (name.compare("cpusubtype") == 0)
1989 {
1990 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001991 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001992 if (sub != 0)
1993 ++num_keys_decoded;
1994 }
1995 else if (name.compare("arch") == 0)
1996 {
1997 arch_name.swap (value);
1998 ++num_keys_decoded;
1999 }
2000 else if (name.compare("triple") == 0)
2001 {
Greg Clayton44272a42014-09-18 00:18:32 +00002002 extractor.GetStringRef ().swap (value);
2003 extractor.SetFilePos(0);
2004 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00002005 ++num_keys_decoded;
2006 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00002007 else if (name.compare ("distribution_id") == 0)
2008 {
2009 extractor.GetStringRef ().swap (value);
2010 extractor.SetFilePos (0);
2011 extractor.GetHexByteString (distribution_id);
2012 ++num_keys_decoded;
2013 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002014 else if (name.compare("os_build") == 0)
2015 {
2016 extractor.GetStringRef().swap(value);
2017 extractor.SetFilePos(0);
2018 extractor.GetHexByteString (m_os_build);
2019 ++num_keys_decoded;
2020 }
2021 else if (name.compare("hostname") == 0)
2022 {
2023 extractor.GetStringRef().swap(value);
2024 extractor.SetFilePos(0);
2025 extractor.GetHexByteString (m_hostname);
2026 ++num_keys_decoded;
2027 }
2028 else if (name.compare("os_kernel") == 0)
2029 {
2030 extractor.GetStringRef().swap(value);
2031 extractor.SetFilePos(0);
2032 extractor.GetHexByteString (m_os_kernel);
2033 ++num_keys_decoded;
2034 }
2035 else if (name.compare("ostype") == 0)
2036 {
2037 os_name.swap (value);
2038 ++num_keys_decoded;
2039 }
2040 else if (name.compare("vendor") == 0)
2041 {
2042 vendor_name.swap(value);
2043 ++num_keys_decoded;
2044 }
2045 else if (name.compare("endian") == 0)
2046 {
2047 ++num_keys_decoded;
2048 if (value.compare("little") == 0)
2049 byte_order = eByteOrderLittle;
2050 else if (value.compare("big") == 0)
2051 byte_order = eByteOrderBig;
2052 else if (value.compare("pdp") == 0)
2053 byte_order = eByteOrderPDP;
2054 else
2055 --num_keys_decoded;
2056 }
2057 else if (name.compare("ptrsize") == 0)
2058 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002059 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002060 if (pointer_byte_size != 0)
2061 ++num_keys_decoded;
2062 }
2063 else if (name.compare("os_version") == 0)
2064 {
2065 Args::StringToVersion (value.c_str(),
2066 m_os_version_major,
2067 m_os_version_minor,
2068 m_os_version_update);
2069 if (m_os_version_major != UINT32_MAX)
2070 ++num_keys_decoded;
2071 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002072 else if (name.compare("watchpoint_exceptions_received") == 0)
2073 {
2074 ++num_keys_decoded;
2075 if (strcmp(value.c_str(),"before") == 0)
2076 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2077 else if (strcmp(value.c_str(),"after") == 0)
2078 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
2079 else
2080 --num_keys_decoded;
2081 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002082 else if (name.compare("default_packet_timeout") == 0)
2083 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002084 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002085 if (m_default_packet_timeout > 0)
2086 {
2087 SetPacketTimeout(m_default_packet_timeout);
2088 ++num_keys_decoded;
2089 }
2090 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002091
Greg Clayton32e0a752011-03-30 18:16:51 +00002092 }
2093
2094 if (num_keys_decoded > 0)
2095 m_qHostInfo_is_valid = eLazyBoolYes;
2096
2097 if (triple.empty())
2098 {
2099 if (arch_name.empty())
2100 {
2101 if (cpu != LLDB_INVALID_CPUTYPE)
2102 {
2103 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2104 if (pointer_byte_size)
2105 {
2106 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2107 }
2108 if (byte_order != eByteOrderInvalid)
2109 {
2110 assert (byte_order == m_host_arch.GetByteOrder());
2111 }
Greg Clayton70512312012-05-08 01:45:38 +00002112
2113 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
2114 {
2115 switch (m_host_arch.GetMachine())
2116 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002117 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002118 case llvm::Triple::arm:
2119 case llvm::Triple::thumb:
2120 os_name = "ios";
2121 break;
2122 default:
2123 os_name = "macosx";
2124 break;
2125 }
2126 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002127 if (!vendor_name.empty())
2128 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2129 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00002130 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00002131
2132 }
2133 }
2134 else
2135 {
2136 std::string triple;
2137 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00002138 if (!vendor_name.empty() || !os_name.empty())
2139 {
2140 triple += '-';
2141 if (vendor_name.empty())
2142 triple += "unknown";
2143 else
2144 triple += vendor_name;
2145 triple += '-';
2146 if (os_name.empty())
2147 triple += "unknown";
2148 else
2149 triple += os_name;
2150 }
2151 m_host_arch.SetTriple (triple.c_str());
2152
2153 llvm::Triple &host_triple = m_host_arch.GetTriple();
2154 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2155 {
2156 switch (m_host_arch.GetMachine())
2157 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002158 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002159 case llvm::Triple::arm:
2160 case llvm::Triple::thumb:
2161 host_triple.setOS(llvm::Triple::IOS);
2162 break;
2163 default:
2164 host_triple.setOS(llvm::Triple::MacOSX);
2165 break;
2166 }
2167 }
Greg Clayton1cb64962011-03-24 04:28:38 +00002168 if (pointer_byte_size)
2169 {
2170 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2171 }
2172 if (byte_order != eByteOrderInvalid)
2173 {
2174 assert (byte_order == m_host_arch.GetByteOrder());
2175 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002176
Greg Clayton1cb64962011-03-24 04:28:38 +00002177 }
2178 }
2179 else
2180 {
Greg Clayton70512312012-05-08 01:45:38 +00002181 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00002182 if (pointer_byte_size)
2183 {
2184 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2185 }
2186 if (byte_order != eByteOrderInvalid)
2187 {
2188 assert (byte_order == m_host_arch.GetByteOrder());
2189 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002190
2191 if (log)
2192 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 +00002193 }
2194 if (!distribution_id.empty ())
2195 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00002196 }
Greg Clayton576d8832011-03-22 04:00:09 +00002197 }
2198 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002199 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00002200}
2201
2202int
2203GDBRemoteCommunicationClient::SendAttach
2204(
2205 lldb::pid_t pid,
2206 StringExtractorGDBRemote& response
2207)
2208{
2209 if (pid != LLDB_INVALID_PROCESS_ID)
2210 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002211 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002212 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002213 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002214 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002215 {
2216 if (response.IsErrorResponse())
2217 return response.GetError();
2218 return 0;
2219 }
2220 }
2221 return -1;
2222}
2223
Vince Harrone0be4252015-02-06 18:32:57 +00002224int
2225GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2226{
2227 StreamString packet;
2228 packet.PutCString("I");
2229 packet.PutBytesAsRawHex8(data, data_len);
2230 StringExtractorGDBRemote response;
2231 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2232 {
2233 return 0;
2234 }
2235 return response.GetError();
2236
2237}
2238
Greg Clayton576d8832011-03-22 04:00:09 +00002239const lldb_private::ArchSpec &
2240GDBRemoteCommunicationClient::GetHostArchitecture ()
2241{
Greg Clayton32e0a752011-03-30 18:16:51 +00002242 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00002243 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00002244 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00002245}
2246
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002247uint32_t
2248GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2249{
2250 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2251 GetHostInfo ();
2252 return m_default_packet_timeout;
2253}
2254
Greg Clayton576d8832011-03-22 04:00:09 +00002255addr_t
2256GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2257{
Greg Clayton70b57652011-05-15 01:25:55 +00002258 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002259 {
Greg Clayton70b57652011-05-15 01:25:55 +00002260 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002261 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002262 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00002263 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00002264 permissions & lldb::ePermissionsReadable ? "r" : "",
2265 permissions & lldb::ePermissionsWritable ? "w" : "",
2266 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00002267 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002268 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002269 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002270 {
Todd Fialaf105f582014-06-21 00:48:09 +00002271 if (response.IsUnsupportedResponse())
2272 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2273 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002274 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2275 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002276 else
2277 {
2278 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2279 }
Greg Clayton576d8832011-03-22 04:00:09 +00002280 }
2281 return LLDB_INVALID_ADDRESS;
2282}
2283
2284bool
2285GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2286{
Greg Clayton70b57652011-05-15 01:25:55 +00002287 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002288 {
Greg Clayton70b57652011-05-15 01:25:55 +00002289 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002290 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002291 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002292 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002293 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002294 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002295 {
Todd Fialaf105f582014-06-21 00:48:09 +00002296 if (response.IsUnsupportedResponse())
2297 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2298 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002299 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002300 }
2301 else
2302 {
2303 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00002304 }
Greg Clayton576d8832011-03-22 04:00:09 +00002305 }
2306 return false;
2307}
2308
Jim Inghamacff8952013-05-02 00:27:30 +00002309Error
2310GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00002311{
Jim Inghamacff8952013-05-02 00:27:30 +00002312 Error error;
2313
2314 if (keep_stopped)
2315 {
2316 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2317 {
2318 char packet[64];
2319 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002320 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002321 StringExtractorGDBRemote response;
Jim Ingham4920a4e2015-07-15 00:59:25 +00002322 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success
2323 && response.IsOKResponse())
Jim Inghamacff8952013-05-02 00:27:30 +00002324 {
2325 m_supports_detach_stay_stopped = eLazyBoolYes;
2326 }
2327 else
2328 {
2329 m_supports_detach_stay_stopped = eLazyBoolNo;
2330 }
2331 }
2332
2333 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2334 {
2335 error.SetErrorString("Stays stopped not supported by this target.");
2336 return error;
2337 }
2338 else
2339 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002340 StringExtractorGDBRemote response;
Jason Molenda2a667382015-07-15 00:16:09 +00002341 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, 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 extended disconnect packet failed.");
2344 }
2345 }
2346 else
2347 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002348 StringExtractorGDBRemote response;
2349 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002350 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002351 error.SetErrorString ("Sending disconnect packet failed.");
2352 }
2353 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002354}
2355
Greg Clayton46fb5582011-11-18 07:03:08 +00002356Error
2357GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2358 lldb_private::MemoryRegionInfo &region_info)
2359{
2360 Error error;
2361 region_info.Clear();
2362
2363 if (m_supports_memory_region_info != eLazyBoolNo)
2364 {
2365 m_supports_memory_region_info = eLazyBoolYes;
2366 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002367 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002368 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002369 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002370 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002371 {
2372 std::string name;
2373 std::string value;
2374 addr_t addr_value;
2375 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002376 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002377 while (success && response.GetNameColonValue(name, value))
2378 {
2379 if (name.compare ("start") == 0)
2380 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002381 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002382 if (success)
2383 region_info.GetRange().SetRangeBase(addr_value);
2384 }
2385 else if (name.compare ("size") == 0)
2386 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002387 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002388 if (success)
2389 region_info.GetRange().SetByteSize (addr_value);
2390 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002391 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002392 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002393 saw_permissions = true;
2394 if (region_info.GetRange().Contains (addr))
2395 {
2396 if (value.find('r') != std::string::npos)
2397 region_info.SetReadable (MemoryRegionInfo::eYes);
2398 else
2399 region_info.SetReadable (MemoryRegionInfo::eNo);
2400
2401 if (value.find('w') != std::string::npos)
2402 region_info.SetWritable (MemoryRegionInfo::eYes);
2403 else
2404 region_info.SetWritable (MemoryRegionInfo::eNo);
2405
2406 if (value.find('x') != std::string::npos)
2407 region_info.SetExecutable (MemoryRegionInfo::eYes);
2408 else
2409 region_info.SetExecutable (MemoryRegionInfo::eNo);
2410 }
2411 else
2412 {
2413 // The reported region does not contain this address -- we're looking at an unmapped page
2414 region_info.SetReadable (MemoryRegionInfo::eNo);
2415 region_info.SetWritable (MemoryRegionInfo::eNo);
2416 region_info.SetExecutable (MemoryRegionInfo::eNo);
2417 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002418 }
2419 else if (name.compare ("error") == 0)
2420 {
2421 StringExtractorGDBRemote name_extractor;
2422 // Swap "value" over into "name_extractor"
2423 name_extractor.GetStringRef().swap(value);
2424 // Now convert the HEX bytes into a string value
2425 name_extractor.GetHexByteString (value);
2426 error.SetErrorString(value.c_str());
2427 }
2428 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002429
2430 // We got a valid address range back but no permissions -- which means this is an unmapped page
2431 if (region_info.GetRange().IsValid() && saw_permissions == false)
2432 {
2433 region_info.SetReadable (MemoryRegionInfo::eNo);
2434 region_info.SetWritable (MemoryRegionInfo::eNo);
2435 region_info.SetExecutable (MemoryRegionInfo::eNo);
2436 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002437 }
2438 else
2439 {
2440 m_supports_memory_region_info = eLazyBoolNo;
2441 }
2442 }
2443
2444 if (m_supports_memory_region_info == eLazyBoolNo)
2445 {
2446 error.SetErrorString("qMemoryRegionInfo is not supported");
2447 }
2448 if (error.Fail())
2449 region_info.Clear();
2450 return error;
2451
2452}
2453
Johnny Chen64637202012-05-23 21:09:52 +00002454Error
2455GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2456{
2457 Error error;
2458
2459 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2460 {
2461 num = m_num_supported_hardware_watchpoints;
2462 return error;
2463 }
2464
2465 // Set num to 0 first.
2466 num = 0;
2467 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2468 {
2469 char packet[64];
2470 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002471 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002472 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002473 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002474 {
2475 m_supports_watchpoint_support_info = eLazyBoolYes;
2476 std::string name;
2477 std::string value;
2478 while (response.GetNameColonValue(name, value))
2479 {
2480 if (name.compare ("num") == 0)
2481 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002482 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002483 m_num_supported_hardware_watchpoints = num;
2484 }
2485 }
2486 }
2487 else
2488 {
2489 m_supports_watchpoint_support_info = eLazyBoolNo;
2490 }
2491 }
2492
2493 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2494 {
2495 error.SetErrorString("qWatchpointSupportInfo is not supported");
2496 }
2497 return error;
2498
2499}
Greg Clayton46fb5582011-11-18 07:03:08 +00002500
Enrico Granataf04a2192012-07-13 23:18:48 +00002501lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002502GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002503{
2504 Error error(GetWatchpointSupportInfo(num));
2505 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00002506 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00002507 return error;
2508}
2509
2510lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002511GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002512{
2513 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00002514 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00002515
2516 // we assume watchpoints will happen after running the relevant opcode
2517 // and we only want to override this behavior if we have explicitly
2518 // received a qHostInfo telling us otherwise
2519 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00002520 {
2521 // On targets like MIPS, watchpoint exceptions are always generated
2522 // before the instruction is executed. The connected target may not
2523 // support qHostInfo or qWatchpointSupportInfo packets.
2524 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2525 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
2526 after = false;
2527 else
2528 after = true;
2529 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002530 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00002531 {
2532 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
2533 // if it is not calculated before.
2534 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
2535 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2536 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
2537 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2538
Enrico Granataf04a2192012-07-13 23:18:48 +00002539 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00002540 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002541 return error;
2542}
2543
Greg Clayton576d8832011-03-22 04:00:09 +00002544int
Chaoren Lind3173f32015-05-29 19:52:29 +00002545GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002546{
Chaoren Lind3173f32015-05-29 19:52:29 +00002547 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002548 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002549 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002550 StreamString packet;
2551 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002552 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00002553
2554 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002555 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002556 {
2557 if (response.IsOKResponse())
2558 return 0;
2559 uint8_t error = response.GetError();
2560 if (error)
2561 return error;
2562 }
2563 }
2564 return -1;
2565}
2566
2567int
Chaoren Lind3173f32015-05-29 19:52:29 +00002568GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002569{
Chaoren Lind3173f32015-05-29 19:52:29 +00002570 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002571 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002572 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002573 StreamString packet;
2574 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002575 packet.PutCStringAsRawHex8(path.c_str());
2576
Greg Clayton576d8832011-03-22 04:00:09 +00002577 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002578 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002579 {
2580 if (response.IsOKResponse())
2581 return 0;
2582 uint8_t error = response.GetError();
2583 if (error)
2584 return error;
2585 }
2586 }
2587 return -1;
2588}
2589
2590int
Chaoren Lind3173f32015-05-29 19:52:29 +00002591GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002592{
Chaoren Lind3173f32015-05-29 19:52:29 +00002593 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002594 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002595 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002596 StreamString packet;
2597 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002598 packet.PutCStringAsRawHex8(path.c_str());
2599
Greg Clayton576d8832011-03-22 04:00:09 +00002600 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002601 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002602 {
2603 if (response.IsOKResponse())
2604 return 0;
2605 uint8_t error = response.GetError();
2606 if (error)
2607 return error;
2608 }
2609 }
2610 return -1;
2611}
2612
Greg Claytonfbb76342013-11-20 21:07:01 +00002613bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002614GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00002615{
2616 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002617 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002618 {
2619 if (response.IsUnsupportedResponse())
2620 return false;
2621 if (response.IsErrorResponse())
2622 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00002623 std::string cwd;
2624 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00002625 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00002626 return !cwd.empty();
2627 }
2628 return false;
2629}
2630
Greg Clayton576d8832011-03-22 04:00:09 +00002631int
Chaoren Lind3173f32015-05-29 19:52:29 +00002632GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002633{
Chaoren Lind3173f32015-05-29 19:52:29 +00002634 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002635 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002636 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002637 StreamString packet;
2638 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002639 packet.PutCStringAsRawHex8(path.c_str());
2640
Greg Clayton576d8832011-03-22 04:00:09 +00002641 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002642 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002643 {
2644 if (response.IsOKResponse())
2645 return 0;
2646 uint8_t error = response.GetError();
2647 if (error)
2648 return error;
2649 }
2650 }
2651 return -1;
2652}
2653
2654int
2655GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2656{
Greg Clayton32e0a752011-03-30 18:16:51 +00002657 char packet[32];
2658 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002659 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002660 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002661 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002662 {
2663 if (response.IsOKResponse())
2664 return 0;
2665 uint8_t error = response.GetError();
2666 if (error)
2667 return error;
2668 }
2669 return -1;
2670}
Greg Clayton32e0a752011-03-30 18:16:51 +00002671
Jim Ingham106d0282014-06-25 02:32:56 +00002672int
2673GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2674{
2675 char packet[32];
2676 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2677 assert (packet_len < (int)sizeof(packet));
2678 StringExtractorGDBRemote response;
2679 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2680 {
2681 if (response.IsOKResponse())
2682 return 0;
2683 uint8_t error = response.GetError();
2684 if (error)
2685 return error;
2686 }
2687 return -1;
2688}
2689
2690
Greg Clayton32e0a752011-03-30 18:16:51 +00002691bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002692GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002693{
2694 if (response.IsNormalResponse())
2695 {
2696 std::string name;
2697 std::string value;
2698 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002699
2700 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2701 uint32_t sub = 0;
2702 std::string vendor;
2703 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002704
2705 while (response.GetNameColonValue(name, value))
2706 {
2707 if (name.compare("pid") == 0)
2708 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002709 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002710 }
2711 else if (name.compare("ppid") == 0)
2712 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002713 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002714 }
2715 else if (name.compare("uid") == 0)
2716 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002717 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002718 }
2719 else if (name.compare("euid") == 0)
2720 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002721 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002722 }
2723 else if (name.compare("gid") == 0)
2724 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002725 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002726 }
2727 else if (name.compare("egid") == 0)
2728 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002729 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002730 }
2731 else if (name.compare("triple") == 0)
2732 {
Greg Clayton44272a42014-09-18 00:18:32 +00002733 StringExtractor extractor;
2734 extractor.GetStringRef().swap(value);
2735 extractor.SetFilePos(0);
2736 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002737 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002738 }
2739 else if (name.compare("name") == 0)
2740 {
2741 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002742 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002743 // control the characters in a process name
2744 extractor.GetStringRef().swap(value);
2745 extractor.SetFilePos(0);
2746 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002747 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002748 }
Jason Molenda89c37492014-01-27 22:23:20 +00002749 else if (name.compare("cputype") == 0)
2750 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002751 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002752 }
2753 else if (name.compare("cpusubtype") == 0)
2754 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002755 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002756 }
2757 else if (name.compare("vendor") == 0)
2758 {
2759 vendor = value;
2760 }
2761 else if (name.compare("ostype") == 0)
2762 {
2763 os_type = value;
2764 }
2765 }
2766
2767 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2768 {
2769 if (vendor == "apple")
2770 {
2771 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2772 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2773 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2774 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002775 }
2776
2777 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2778 return true;
2779 }
2780 return false;
2781}
2782
2783bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002784GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002785{
2786 process_info.Clear();
2787
2788 if (m_supports_qProcessInfoPID)
2789 {
2790 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002791 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002792 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002793 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002794 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002795 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002796 return DecodeProcessInfoResponse (response, process_info);
2797 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002798 else
2799 {
2800 m_supports_qProcessInfoPID = false;
2801 return false;
2802 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002803 }
2804 return false;
2805}
2806
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002807bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002808GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002809{
Todd Fiala3daa1762014-09-15 16:01:29 +00002810 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2811
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002812 if (allow_lazy)
2813 {
2814 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2815 return true;
2816 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2817 return false;
2818 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002819
2820 GetHostInfo ();
2821
2822 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002823 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002824 {
2825 if (response.IsNormalResponse())
2826 {
2827 std::string name;
2828 std::string value;
2829 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2830 uint32_t sub = 0;
2831 std::string arch_name;
2832 std::string os_name;
2833 std::string vendor_name;
2834 std::string triple;
2835 uint32_t pointer_byte_size = 0;
2836 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002837 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002838 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002839 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002840 while (response.GetNameColonValue(name, value))
2841 {
2842 if (name.compare("cputype") == 0)
2843 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002844 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002845 if (cpu != LLDB_INVALID_CPUTYPE)
2846 ++num_keys_decoded;
2847 }
2848 else if (name.compare("cpusubtype") == 0)
2849 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002850 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002851 if (sub != 0)
2852 ++num_keys_decoded;
2853 }
Todd Fialac540dd02014-08-26 18:21:02 +00002854 else if (name.compare("triple") == 0)
2855 {
Greg Clayton44272a42014-09-18 00:18:32 +00002856 StringExtractor extractor;
2857 extractor.GetStringRef().swap(value);
2858 extractor.SetFilePos(0);
2859 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002860 ++num_keys_decoded;
2861 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002862 else if (name.compare("ostype") == 0)
2863 {
2864 os_name.swap (value);
2865 ++num_keys_decoded;
2866 }
2867 else if (name.compare("vendor") == 0)
2868 {
2869 vendor_name.swap(value);
2870 ++num_keys_decoded;
2871 }
2872 else if (name.compare("endian") == 0)
2873 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002874 ++num_keys_decoded;
2875 if (value.compare("little") == 0)
2876 byte_order = eByteOrderLittle;
2877 else if (value.compare("big") == 0)
2878 byte_order = eByteOrderBig;
2879 else if (value.compare("pdp") == 0)
2880 byte_order = eByteOrderPDP;
2881 else
2882 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002883 }
2884 else if (name.compare("ptrsize") == 0)
2885 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002886 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002887 if (pointer_byte_size != 0)
2888 ++num_keys_decoded;
2889 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002890 else if (name.compare("pid") == 0)
2891 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002892 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002893 if (pid != LLDB_INVALID_PROCESS_ID)
2894 ++num_keys_decoded;
2895 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002896 }
2897 if (num_keys_decoded > 0)
2898 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002899 if (pid != LLDB_INVALID_PROCESS_ID)
2900 {
2901 m_curr_pid_is_valid = eLazyBoolYes;
2902 m_curr_pid = pid;
2903 }
Todd Fialac540dd02014-08-26 18:21:02 +00002904
2905 // Set the ArchSpec from the triple if we have it.
2906 if (!triple.empty ())
2907 {
2908 m_process_arch.SetTriple (triple.c_str ());
2909 if (pointer_byte_size)
2910 {
2911 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2912 }
2913 }
2914 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002915 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002916 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2917
2918 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2919 switch (triple.getObjectFormat()) {
2920 case llvm::Triple::MachO:
2921 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2922 break;
2923 case llvm::Triple::ELF:
2924 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2925 break;
2926 case llvm::Triple::COFF:
2927 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2928 break;
2929 case llvm::Triple::UnknownObjectFormat:
2930 if (log)
2931 log->Printf("error: failed to determine target architecture");
2932 return false;
2933 }
2934
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002935 if (pointer_byte_size)
2936 {
2937 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2938 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002939 if (byte_order != eByteOrderInvalid)
2940 {
2941 assert (byte_order == m_process_arch.GetByteOrder());
2942 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002943 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002944 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002945 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2946 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002947 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002948 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002949 }
2950 }
2951 else
2952 {
2953 m_qProcessInfo_is_valid = eLazyBoolNo;
2954 }
2955
2956 return false;
2957}
2958
2959
Greg Clayton32e0a752011-03-30 18:16:51 +00002960uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002961GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2962 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002963{
2964 process_infos.Clear();
2965
2966 if (m_supports_qfProcessInfo)
2967 {
2968 StreamString packet;
2969 packet.PutCString ("qfProcessInfo");
2970 if (!match_info.MatchAllProcesses())
2971 {
2972 packet.PutChar (':');
2973 const char *name = match_info.GetProcessInfo().GetName();
2974 bool has_name_match = false;
2975 if (name && name[0])
2976 {
2977 has_name_match = true;
2978 NameMatchType name_match_type = match_info.GetNameMatchType();
2979 switch (name_match_type)
2980 {
2981 case eNameMatchIgnore:
2982 has_name_match = false;
2983 break;
2984
2985 case eNameMatchEquals:
2986 packet.PutCString ("name_match:equals;");
2987 break;
2988
2989 case eNameMatchContains:
2990 packet.PutCString ("name_match:contains;");
2991 break;
2992
2993 case eNameMatchStartsWith:
2994 packet.PutCString ("name_match:starts_with;");
2995 break;
2996
2997 case eNameMatchEndsWith:
2998 packet.PutCString ("name_match:ends_with;");
2999 break;
3000
3001 case eNameMatchRegularExpression:
3002 packet.PutCString ("name_match:regex;");
3003 break;
3004 }
3005 if (has_name_match)
3006 {
3007 packet.PutCString ("name:");
3008 packet.PutBytesAsRawHex8(name, ::strlen(name));
3009 packet.PutChar (';');
3010 }
3011 }
3012
3013 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003014 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003015 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003016 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00003017 if (match_info.GetProcessInfo().UserIDIsValid())
3018 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
3019 if (match_info.GetProcessInfo().GroupIDIsValid())
3020 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003021 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
3022 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
3023 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3024 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
3025 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3026 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
3027 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
3028 {
3029 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
3030 const llvm::Triple &triple = match_arch.GetTriple();
3031 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00003032 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00003033 packet.PutChar (';');
3034 }
3035 }
3036 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00003037 // Increase timeout as the first qfProcessInfo packet takes a long time
3038 // on Android. The value of 1min was arrived at empirically.
3039 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00003040 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003041 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003042 do
3043 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003044 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00003045 if (!DecodeProcessInfoResponse (response, process_info))
3046 break;
3047 process_infos.Append(process_info);
3048 response.GetStringRef().clear();
3049 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00003050 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00003051 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003052 else
3053 {
3054 m_supports_qfProcessInfo = false;
3055 return 0;
3056 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003057 }
3058 return process_infos.GetSize();
3059
3060}
3061
3062bool
3063GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
3064{
3065 if (m_supports_qUserName)
3066 {
3067 char packet[32];
3068 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003069 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003070 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003071 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003072 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003073 if (response.IsNormalResponse())
3074 {
3075 // Make sure we parsed the right number of characters. The response is
3076 // the hex encoded user name and should make up the entire packet.
3077 // If there are any non-hex ASCII bytes, the length won't match below..
3078 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3079 return true;
3080 }
3081 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003082 else
3083 {
3084 m_supports_qUserName = false;
3085 return false;
3086 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003087 }
3088 return false;
3089
3090}
3091
3092bool
3093GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3094{
3095 if (m_supports_qGroupName)
3096 {
3097 char packet[32];
3098 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003099 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003100 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003101 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003102 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003103 if (response.IsNormalResponse())
3104 {
3105 // Make sure we parsed the right number of characters. The response is
3106 // the hex encoded group name and should make up the entire packet.
3107 // If there are any non-hex ASCII bytes, the length won't match below..
3108 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3109 return true;
3110 }
3111 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003112 else
3113 {
3114 m_supports_qGroupName = false;
3115 return false;
3116 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003117 }
3118 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003119}
Greg Clayton32e0a752011-03-30 18:16:51 +00003120
Ewan Crawford78baa192015-05-13 09:18:18 +00003121bool
3122GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3123{
3124 // Form non-stop packet request
3125 char packet[32];
3126 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3127 assert(packet_len < (int)sizeof(packet));
3128
3129 StringExtractorGDBRemote response;
3130 // Send to target
3131 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3132 if (response.IsOKResponse())
3133 return true;
3134
3135 // Failed or not supported
3136 return false;
3137
3138}
3139
Greg Claytone034a042015-05-21 20:52:06 +00003140static void
3141MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3142{
3143 packet.Clear();
3144 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3145 uint32_t bytes_left = send_size;
3146 while (bytes_left > 0)
3147 {
3148 if (bytes_left >= 26)
3149 {
3150 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3151 bytes_left -= 26;
3152 }
3153 else
3154 {
3155 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3156 bytes_left = 0;
3157 }
3158 }
3159}
3160
3161template<typename T>
3162T calculate_standard_deviation(const std::vector<T> &v)
3163{
3164 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3165 T mean = sum / (T)v.size();
3166 T accum = T(0);
3167 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3168 T delta = d - mean;
3169 accum += delta * delta;
3170 });
3171
3172 T stdev = sqrt(accum / (v.size()-1));
3173 return stdev;
3174}
3175
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003176void
Greg Claytone034a042015-05-21 20:52:06 +00003177GDBRemoteCommunicationClient::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 +00003178{
3179 uint32_t i;
3180 TimeValue start_time, end_time;
3181 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003182 if (SendSpeedTestPacket (0, 0))
3183 {
Greg Claytone034a042015-05-21 20:52:06 +00003184 StreamString packet;
3185 if (json)
3186 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3187 else
3188 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3189 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00003190
Greg Claytone034a042015-05-21 20:52:06 +00003191 uint32_t result_idx = 0;
3192 uint32_t send_size;
3193 std::vector<float> packet_times;
3194
3195 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3196 {
3197 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3198 {
3199 MakeSpeedTestPacket (packet, send_size, recv_size);
3200
3201 packet_times.clear();
3202 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00003203 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00003204 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00003205 {
Greg Claytone034a042015-05-21 20:52:06 +00003206 TimeValue packet_start_time = TimeValue::Now();
3207 StringExtractorGDBRemote response;
3208 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3209 TimeValue packet_end_time = TimeValue::Now();
3210 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3211 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003212 }
3213 end_time = TimeValue::Now();
3214 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00003215
3216 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3217 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3218 float average_ms_per_packet = total_ms / num_packets;
3219 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3220 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00003221 {
Greg Claytone034a042015-05-21 20:52:06 +00003222 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);
3223 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00003224 }
3225 else
3226 {
Greg Claytone034a042015-05-21 20:52:06 +00003227 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",
3228 send_size,
3229 recv_size,
3230 total_time_nsec / TimeValue::NanoSecPerSec,
3231 total_time_nsec % TimeValue::NanoSecPerSec,
3232 packets_per_second,
3233 average_ms_per_packet,
3234 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00003235 }
Greg Claytone034a042015-05-21 20:52:06 +00003236 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003237 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003238 }
Greg Claytone034a042015-05-21 20:52:06 +00003239
3240 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3241
3242 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3243 if (json)
3244 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3245 else
3246 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3247 strm.Flush();
3248 send_size = 0;
3249 result_idx = 0;
3250 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3251 {
3252 MakeSpeedTestPacket (packet, send_size, recv_size);
3253
3254 // If we have a receive size, test how long it takes to receive 4MB of data
3255 if (recv_size > 0)
3256 {
3257 start_time = TimeValue::Now();
3258 uint32_t bytes_read = 0;
3259 uint32_t packet_count = 0;
3260 while (bytes_read < k_recv_amount)
3261 {
3262 StringExtractorGDBRemote response;
3263 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3264 bytes_read += recv_size;
3265 ++packet_count;
3266 }
3267 end_time = TimeValue::Now();
3268 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3269 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3270 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3271 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3272 float average_ms_per_packet = total_ms / packet_count;
3273
3274 if (json)
3275 {
3276 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);
3277 ++result_idx;
3278 }
3279 else
3280 {
3281 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",
3282 send_size,
3283 recv_size,
3284 packet_count,
3285 k_recv_amount_mb,
3286 total_time_nsec / TimeValue::NanoSecPerSec,
3287 total_time_nsec % TimeValue::NanoSecPerSec,
3288 mb_second,
3289 packets_per_second,
3290 average_ms_per_packet);
3291 }
3292 strm.Flush();
3293 }
3294 }
3295 if (json)
3296 strm.Printf("\n ]\n }\n}\n");
3297 else
3298 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003299 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003300}
3301
3302bool
3303GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3304{
3305 StreamString packet;
3306 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3307 uint32_t bytes_left = send_size;
3308 while (bytes_left > 0)
3309 {
3310 if (bytes_left >= 26)
3311 {
3312 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3313 bytes_left -= 26;
3314 }
3315 else
3316 {
3317 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3318 bytes_left = 0;
3319 }
3320 }
3321
3322 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003323 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00003324}
Greg Clayton8b82f082011-04-12 05:54:46 +00003325
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003326bool
3327GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
3328 lldb::pid_t &pid,
3329 uint16_t &port,
3330 std::string &socket_name)
Greg Clayton8b82f082011-04-12 05:54:46 +00003331{
Daniel Maleae0f8f572013-08-26 23:57:52 +00003332 pid = LLDB_INVALID_PROCESS_ID;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003333 port = 0;
3334 socket_name.clear();
3335
Greg Clayton8b82f082011-04-12 05:54:46 +00003336 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003337 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00003338 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003339 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00003340 if (remote_accept_hostname && remote_accept_hostname[0])
3341 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003342 else
3343 {
Zachary Turner97a14e62014-08-19 17:18:29 +00003344 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00003345 {
3346 // Make the GDB server we launch only accept connections from this host
3347 stream.Printf("host:%s;", hostname.c_str());
3348 }
3349 else
3350 {
3351 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3352 stream.Printf("host:*;");
3353 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003354 }
3355 const char *packet = stream.GetData();
3356 int packet_len = stream.GetSize();
3357
Vince Harron1b5a74e2015-01-21 22:42:49 +00003358 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003359 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003360
Tamas Berghammer912800c2015-02-24 10:23:39 +00003361 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003362 {
3363 std::string name;
3364 std::string value;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003365 StringExtractor extractor;
Greg Clayton8b82f082011-04-12 05:54:46 +00003366 while (response.GetNameColonValue(name, value))
3367 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003368 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003369 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003370 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003371 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003372 else if (name.compare("socket_name") == 0)
3373 {
3374 extractor.GetStringRef().swap(value);
3375 extractor.SetFilePos(0);
3376 extractor.GetHexByteString(value);
3377
3378 socket_name = value;
3379 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003380 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003381 return true;
Greg Clayton8b82f082011-04-12 05:54:46 +00003382 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003383 return false;
Greg Clayton8b82f082011-04-12 05:54:46 +00003384}
3385
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00003386size_t
3387GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls)
3388{
3389 connection_urls.clear();
3390
3391 StringExtractorGDBRemote response;
3392 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success)
3393 return 0;
3394
3395 StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef());
3396 if (!data)
3397 return 0;
3398
3399 StructuredData::Array* array = data->GetAsArray();
3400 if (!array)
3401 return 0;
3402
3403 for (size_t i = 0, count = array->GetSize(); i < count; ++i)
3404 {
3405 StructuredData::Dictionary* element = nullptr;
3406 if (!array->GetItemAtIndexAsDictionary(i, element))
3407 continue;
3408
3409 uint16_t port = 0;
3410 if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port")))
3411 port = port_osp->GetIntegerValue(0);
3412
3413 std::string socket_name;
3414 if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name")))
3415 socket_name = socket_name_osp->GetStringValue();
3416
3417 if (port != 0 || !socket_name.empty())
3418 connection_urls.emplace_back(port, socket_name);
3419 }
3420 return connection_urls.size();
3421}
3422
Greg Clayton8b82f082011-04-12 05:54:46 +00003423bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003424GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3425{
3426 StreamString stream;
3427 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3428 const char *packet = stream.GetData();
3429 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003430
Daniel Maleae0f8f572013-08-26 23:57:52 +00003431 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003432 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003433 {
3434 if (response.IsOKResponse())
3435 return true;
3436 }
3437 return false;
3438}
3439
3440bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003441GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003442{
3443 if (m_curr_tid == tid)
3444 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003445
Greg Clayton8b82f082011-04-12 05:54:46 +00003446 char packet[32];
3447 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003448 if (tid == UINT64_MAX)
3449 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003450 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003451 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003452 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003453 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003454 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003455 {
3456 if (response.IsOKResponse())
3457 {
3458 m_curr_tid = tid;
3459 return true;
3460 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003461
3462 /*
3463 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
3464 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3465 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3466 */
3467 if (response.IsUnsupportedResponse() && IsConnected())
3468 {
3469 m_curr_tid = 1;
3470 return true;
3471 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003472 }
3473 return false;
3474}
3475
3476bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003477GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003478{
3479 if (m_curr_tid_run == tid)
3480 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003481
Greg Clayton8b82f082011-04-12 05:54:46 +00003482 char packet[32];
3483 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003484 if (tid == UINT64_MAX)
3485 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003486 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003487 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3488
Andy Gibbsa297a972013-06-19 19:04:53 +00003489 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003490 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003491 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003492 {
3493 if (response.IsOKResponse())
3494 {
3495 m_curr_tid_run = tid;
3496 return true;
3497 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003498
3499 /*
3500 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
3501 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3502 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3503 */
3504 if (response.IsUnsupportedResponse() && IsConnected())
3505 {
3506 m_curr_tid_run = 1;
3507 return true;
3508 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003509 }
3510 return false;
3511}
3512
3513bool
3514GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3515{
Greg Clayton3dedae12013-12-06 21:45:27 +00003516 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003517 return response.IsNormalResponse();
3518 return false;
3519}
3520
3521bool
Greg Claytonf402f782012-10-13 02:11:55 +00003522GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003523{
3524 if (m_supports_qThreadStopInfo)
3525 {
3526 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003527 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003528 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003529 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003530 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003531 if (response.IsUnsupportedResponse())
3532 m_supports_qThreadStopInfo = false;
3533 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003534 return true;
3535 else
3536 return false;
3537 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003538 else
3539 {
3540 m_supports_qThreadStopInfo = false;
3541 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003542 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003543 return false;
3544}
3545
3546
3547uint8_t
3548GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3549{
Todd Fiala616b8272014-10-09 00:55:04 +00003550 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3551 if (log)
3552 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3553 __FUNCTION__, insert ? "add" : "remove", addr);
3554
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003555 // Check if the stub is known not to support this breakpoint type
3556 if (!SupportsGDBStoppointPacket(type))
3557 return UINT8_MAX;
3558 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003559 char packet[64];
3560 const int packet_len = ::snprintf (packet,
3561 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003562 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003563 insert ? 'Z' : 'z',
3564 type,
3565 addr,
3566 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003567 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003568 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003569 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003570 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003571 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003572 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003573 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003574 if (response.IsOKResponse())
3575 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003576
3577 // Error while setting breakpoint, send back specific error
3578 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003579 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003580
3581 // Empty packet informs us that breakpoint is not supported
3582 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003583 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003584 // Disable this breakpoint type since it is unsupported
3585 switch (type)
3586 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003587 case eBreakpointSoftware: m_supports_z0 = false; break;
3588 case eBreakpointHardware: m_supports_z1 = false; break;
3589 case eWatchpointWrite: m_supports_z2 = false; break;
3590 case eWatchpointRead: m_supports_z3 = false; break;
3591 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003592 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003593 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003594 }
3595 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003596 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003597 return UINT8_MAX;
3598}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003599
3600size_t
3601GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3602 bool &sequence_mutex_unavailable)
3603{
3604 Mutex::Locker locker;
3605 thread_ids.clear();
3606
Jim Ingham4ceb9282012-06-08 22:50:40 +00003607 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003608 {
3609 sequence_mutex_unavailable = false;
3610 StringExtractorGDBRemote response;
3611
Greg Clayton3dedae12013-12-06 21:45:27 +00003612 PacketResult packet_result;
3613 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3614 packet_result == PacketResult::Success && response.IsNormalResponse();
3615 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003616 {
3617 char ch = response.GetChar();
3618 if (ch == 'l')
3619 break;
3620 if (ch == 'm')
3621 {
3622 do
3623 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003624 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003625
3626 if (tid != LLDB_INVALID_THREAD_ID)
3627 {
3628 thread_ids.push_back (tid);
3629 }
3630 ch = response.GetChar(); // Skip the command separator
3631 } while (ch == ','); // Make sure we got a comma separator
3632 }
3633 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003634
3635 /*
3636 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3637 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
3638 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
3639 * Assume pid=tid=1 in such cases.
3640 */
3641 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
3642 {
3643 thread_ids.push_back (1);
3644 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00003645 }
3646 else
3647 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003648#if defined (LLDB_CONFIGURATION_DEBUG)
3649 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3650#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003651 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003652 if (log)
3653 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003654#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003655 sequence_mutex_unavailable = true;
3656 }
3657 return thread_ids.size();
3658}
Greg Clayton37a0a242012-04-11 00:24:49 +00003659
3660lldb::addr_t
3661GDBRemoteCommunicationClient::GetShlibInfoAddr()
3662{
3663 if (!IsRunning())
3664 {
3665 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003666 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003667 {
3668 if (response.IsNormalResponse())
3669 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3670 }
3671 }
3672 return LLDB_INVALID_ADDRESS;
3673}
3674
Daniel Maleae0f8f572013-08-26 23:57:52 +00003675lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003676GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3677 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3678 int *status_ptr, // Pass NULL if you don't want the process exit status
3679 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3680 std::string *command_output, // Pass NULL if you don't want the command output
3681 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003682{
3683 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003684 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003685 stream.PutBytesAsRawHex8(command, strlen(command));
3686 stream.PutChar(',');
3687 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003688 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003689 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003690 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003691 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003692 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003693 }
3694 const char *packet = stream.GetData();
3695 int packet_len = stream.GetSize();
3696 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003697 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003698 {
3699 if (response.GetChar() != 'F')
3700 return Error("malformed reply");
3701 if (response.GetChar() != ',')
3702 return Error("malformed reply");
3703 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3704 if (exitcode == UINT32_MAX)
3705 return Error("unable to run remote process");
3706 else if (status_ptr)
3707 *status_ptr = exitcode;
3708 if (response.GetChar() != ',')
3709 return Error("malformed reply");
3710 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3711 if (signo_ptr)
3712 *signo_ptr = signo;
3713 if (response.GetChar() != ',')
3714 return Error("malformed reply");
3715 std::string output;
3716 response.GetEscapedBinaryData(output);
3717 if (command_output)
3718 command_output->assign(output);
3719 return Error();
3720 }
3721 return Error("unable to send packet");
3722}
3723
Greg Claytonfbb76342013-11-20 21:07:01 +00003724Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003725GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3726 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003727{
Chaoren Lind3173f32015-05-29 19:52:29 +00003728 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003729 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003730 stream.PutCString("qPlatform_mkdir:");
3731 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003732 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003733 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003734 const char *packet = stream.GetData();
3735 int packet_len = stream.GetSize();
3736 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003737
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003738 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3739 return Error("failed to send '%s' packet", packet);
3740
3741 if (response.GetChar() != 'F')
3742 return Error("invalid response to '%s' packet", packet);
3743
3744 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003745}
3746
Greg Claytonfbb76342013-11-20 21:07:01 +00003747Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003748GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3749 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003750{
Chaoren Lind3173f32015-05-29 19:52:29 +00003751 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003752 lldb_private::StreamString stream;
3753 stream.PutCString("qPlatform_chmod:");
3754 stream.PutHex32(file_permissions);
3755 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003756 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003757 const char *packet = stream.GetData();
3758 int packet_len = stream.GetSize();
3759 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003760
3761 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3762 return Error("failed to send '%s' packet", packet);
3763
3764 if (response.GetChar() != 'F')
3765 return Error("invalid response to '%s' packet", packet);
3766
Chaoren Lince36c4c2015-05-05 18:43:19 +00003767 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003768}
3769
Daniel Maleae0f8f572013-08-26 23:57:52 +00003770static uint64_t
3771ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3772 uint64_t fail_result,
3773 Error &error)
3774{
3775 response.SetFilePos(0);
3776 if (response.GetChar() != 'F')
3777 return fail_result;
3778 int32_t result = response.GetS32 (-2);
3779 if (result == -2)
3780 return fail_result;
3781 if (response.GetChar() == ',')
3782 {
3783 int result_errno = response.GetS32 (-2);
3784 if (result_errno != -2)
3785 error.SetError(result_errno, eErrorTypePOSIX);
3786 else
3787 error.SetError(-1, eErrorTypeGeneric);
3788 }
3789 else
3790 error.Clear();
3791 return result;
3792}
3793lldb::user_id_t
3794GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3795 uint32_t flags,
3796 mode_t mode,
3797 Error &error)
3798{
Chaoren Lind3173f32015-05-29 19:52:29 +00003799 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003800 lldb_private::StreamString stream;
3801 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003802 if (path.empty())
3803 return UINT64_MAX;
3804 stream.PutCStringAsRawHex8(path.c_str());
3805 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003806 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003807 stream.PutChar(',');
3808 stream.PutHex32(mode);
3809 const char* packet = stream.GetData();
3810 int packet_len = stream.GetSize();
3811 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003812 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003813 {
3814 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3815 }
3816 return UINT64_MAX;
3817}
3818
3819bool
3820GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3821 Error &error)
3822{
3823 lldb_private::StreamString stream;
3824 stream.Printf("vFile:close:%i", (int)fd);
3825 const char* packet = stream.GetData();
3826 int packet_len = stream.GetSize();
3827 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003828 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003829 {
3830 return ParseHostIOPacketResponse (response, -1, error) == 0;
3831 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003832 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003833}
3834
3835// Extension of host I/O packets to get the file size.
3836lldb::user_id_t
3837GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3838{
Chaoren Lind3173f32015-05-29 19:52:29 +00003839 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003840 lldb_private::StreamString stream;
3841 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003842 stream.PutCStringAsRawHex8(path.c_str());
3843 const char* packet = stream.GetData();
3844 int packet_len = stream.GetSize();
3845 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003846 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003847 {
3848 if (response.GetChar() != 'F')
3849 return UINT64_MAX;
3850 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3851 return retcode;
3852 }
3853 return UINT64_MAX;
3854}
3855
Greg Claytonfbb76342013-11-20 21:07:01 +00003856Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003857GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3858 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003859{
Chaoren Lind3173f32015-05-29 19:52:29 +00003860 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003861 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003862 lldb_private::StreamString stream;
3863 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003864 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003865 const char* packet = stream.GetData();
3866 int packet_len = stream.GetSize();
3867 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003868 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003869 {
3870 if (response.GetChar() != 'F')
3871 {
3872 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003873 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003874 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003875 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003876 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003877 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003878 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003879 if (response.GetChar() == ',')
3880 {
3881 int response_errno = response.GetS32(-1);
3882 if (response_errno > 0)
3883 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3884 else
3885 error.SetErrorToGenericError();
3886 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003887 else
3888 error.SetErrorToGenericError();
3889 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003890 else
3891 {
3892 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3893 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003894 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003895 }
3896 else
3897 {
3898 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3899 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003900 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003901}
3902
3903uint64_t
3904GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3905 uint64_t offset,
3906 void *dst,
3907 uint64_t dst_len,
3908 Error &error)
3909{
3910 lldb_private::StreamString stream;
3911 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3912 const char* packet = stream.GetData();
3913 int packet_len = stream.GetSize();
3914 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003915 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003916 {
3917 if (response.GetChar() != 'F')
3918 return 0;
3919 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3920 if (retcode == UINT32_MAX)
3921 return retcode;
3922 const char next = (response.Peek() ? *response.Peek() : 0);
3923 if (next == ',')
3924 return 0;
3925 if (next == ';')
3926 {
3927 response.GetChar(); // skip the semicolon
3928 std::string buffer;
3929 if (response.GetEscapedBinaryData(buffer))
3930 {
3931 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3932 if (data_to_write > 0)
3933 memcpy(dst, &buffer[0], data_to_write);
3934 return data_to_write;
3935 }
3936 }
3937 }
3938 return 0;
3939}
3940
3941uint64_t
3942GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3943 uint64_t offset,
3944 const void* src,
3945 uint64_t src_len,
3946 Error &error)
3947{
3948 lldb_private::StreamGDBRemote stream;
3949 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3950 stream.PutEscapedBytes(src, src_len);
3951 const char* packet = stream.GetData();
3952 int packet_len = stream.GetSize();
3953 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003954 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003955 {
3956 if (response.GetChar() != 'F')
3957 {
3958 error.SetErrorStringWithFormat("write file failed");
3959 return 0;
3960 }
3961 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3962 if (bytes_written == UINT64_MAX)
3963 {
3964 error.SetErrorToGenericError();
3965 if (response.GetChar() == ',')
3966 {
3967 int response_errno = response.GetS32(-1);
3968 if (response_errno > 0)
3969 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3970 }
3971 return 0;
3972 }
3973 return bytes_written;
3974 }
3975 else
3976 {
3977 error.SetErrorString ("failed to send vFile:pwrite packet");
3978 }
3979 return 0;
3980}
3981
Greg Claytonfbb76342013-11-20 21:07:01 +00003982Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003983GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003984{
Chaoren Lind3173f32015-05-29 19:52:29 +00003985 std::string src_path{src.GetPath(false)},
3986 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003987 Error error;
3988 lldb_private::StreamGDBRemote stream;
3989 stream.PutCString("vFile:symlink:");
3990 // the unix symlink() command reverses its parameters where the dst if first,
3991 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003992 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003993 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003994 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003995 const char* packet = stream.GetData();
3996 int packet_len = stream.GetSize();
3997 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003998 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003999 {
4000 if (response.GetChar() == 'F')
4001 {
4002 uint32_t result = response.GetU32(UINT32_MAX);
4003 if (result != 0)
4004 {
4005 error.SetErrorToGenericError();
4006 if (response.GetChar() == ',')
4007 {
4008 int response_errno = response.GetS32(-1);
4009 if (response_errno > 0)
4010 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4011 }
4012 }
4013 }
4014 else
4015 {
4016 // Should have returned with 'F<result>[,<errno>]'
4017 error.SetErrorStringWithFormat("symlink failed");
4018 }
4019 }
4020 else
4021 {
4022 error.SetErrorString ("failed to send vFile:symlink packet");
4023 }
4024 return error;
4025}
4026
4027Error
Chaoren Lind3173f32015-05-29 19:52:29 +00004028GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00004029{
Chaoren Lind3173f32015-05-29 19:52:29 +00004030 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00004031 Error error;
4032 lldb_private::StreamGDBRemote stream;
4033 stream.PutCString("vFile:unlink:");
4034 // the unix symlink() command reverses its parameters where the dst if first,
4035 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00004036 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00004037 const char* packet = stream.GetData();
4038 int packet_len = stream.GetSize();
4039 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004040 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00004041 {
4042 if (response.GetChar() == 'F')
4043 {
4044 uint32_t result = response.GetU32(UINT32_MAX);
4045 if (result != 0)
4046 {
4047 error.SetErrorToGenericError();
4048 if (response.GetChar() == ',')
4049 {
4050 int response_errno = response.GetS32(-1);
4051 if (response_errno > 0)
4052 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4053 }
4054 }
4055 }
4056 else
4057 {
4058 // Should have returned with 'F<result>[,<errno>]'
4059 error.SetErrorStringWithFormat("unlink failed");
4060 }
4061 }
4062 else
4063 {
4064 error.SetErrorString ("failed to send vFile:unlink packet");
4065 }
4066 return error;
4067}
4068
Daniel Maleae0f8f572013-08-26 23:57:52 +00004069// Extension of host I/O packets to get whether a file exists.
4070bool
4071GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
4072{
Chaoren Lind3173f32015-05-29 19:52:29 +00004073 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004074 lldb_private::StreamString stream;
4075 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004076 stream.PutCStringAsRawHex8(path.c_str());
4077 const char* packet = stream.GetData();
4078 int packet_len = stream.GetSize();
4079 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004080 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004081 {
4082 if (response.GetChar() != 'F')
4083 return false;
4084 if (response.GetChar() != ',')
4085 return false;
4086 bool retcode = (response.GetChar() != '0');
4087 return retcode;
4088 }
4089 return false;
4090}
4091
4092bool
4093GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
4094 uint64_t &high,
4095 uint64_t &low)
4096{
Chaoren Lind3173f32015-05-29 19:52:29 +00004097 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004098 lldb_private::StreamString stream;
4099 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004100 stream.PutCStringAsRawHex8(path.c_str());
4101 const char* packet = stream.GetData();
4102 int packet_len = stream.GetSize();
4103 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004104 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004105 {
4106 if (response.GetChar() != 'F')
4107 return false;
4108 if (response.GetChar() != ',')
4109 return false;
4110 if (response.Peek() && *response.Peek() == 'x')
4111 return false;
4112 low = response.GetHexMaxU64(false, UINT64_MAX);
4113 high = response.GetHexMaxU64(false, UINT64_MAX);
4114 return true;
4115 }
4116 return false;
4117}
Greg Claytonf74cf862013-11-13 23:28:31 +00004118
4119bool
Jason Molendaa3329782014-03-29 18:54:20 +00004120GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
4121{
4122 // Some targets have issues with g/G packets and we need to avoid using them
4123 if (m_avoid_g_packets == eLazyBoolCalculate)
4124 {
4125 if (process)
4126 {
4127 m_avoid_g_packets = eLazyBoolNo;
4128 const ArchSpec &arch = process->GetTarget().GetArchitecture();
4129 if (arch.IsValid()
4130 && arch.GetTriple().getVendor() == llvm::Triple::Apple
4131 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00004132 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00004133 {
4134 m_avoid_g_packets = eLazyBoolYes;
4135 uint32_t gdb_server_version = GetGDBServerProgramVersion();
4136 if (gdb_server_version != 0)
4137 {
4138 const char *gdb_server_name = GetGDBServerProgramName();
4139 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
4140 {
4141 if (gdb_server_version >= 310)
4142 m_avoid_g_packets = eLazyBoolNo;
4143 }
4144 }
4145 }
4146 }
4147 }
4148 return m_avoid_g_packets == eLazyBoolYes;
4149}
4150
4151bool
Greg Claytonf74cf862013-11-13 23:28:31 +00004152GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4153{
4154 Mutex::Locker locker;
4155 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4156 {
4157 const bool thread_suffix_supported = GetThreadSuffixSupported();
4158
4159 if (thread_suffix_supported || SetCurrentThread(tid))
4160 {
4161 char packet[64];
4162 int packet_len = 0;
4163 if (thread_suffix_supported)
4164 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4165 else
4166 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4167 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004168 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004169 }
4170 }
4171 return false;
4172
4173}
4174
4175
4176bool
4177GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4178{
4179 Mutex::Locker locker;
4180 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4181 {
4182 const bool thread_suffix_supported = GetThreadSuffixSupported();
4183
4184 if (thread_suffix_supported || SetCurrentThread(tid))
4185 {
4186 char packet[64];
4187 int packet_len = 0;
4188 // Get all registers in one packet
4189 if (thread_suffix_supported)
4190 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4191 else
4192 packet_len = ::snprintf (packet, sizeof(packet), "g");
4193 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004194 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004195 }
4196 }
4197 return false;
4198}
4199bool
4200GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4201{
4202 save_id = 0; // Set to invalid save ID
4203 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4204 return false;
4205
4206 m_supports_QSaveRegisterState = eLazyBoolYes;
4207 Mutex::Locker locker;
4208 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4209 {
4210 const bool thread_suffix_supported = GetThreadSuffixSupported();
4211 if (thread_suffix_supported || SetCurrentThread(tid))
4212 {
4213 char packet[256];
4214 if (thread_suffix_supported)
4215 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4216 else
Ilia K686b1fe2015-02-27 19:43:08 +00004217 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00004218
4219 StringExtractorGDBRemote response;
4220
Greg Clayton3dedae12013-12-06 21:45:27 +00004221 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004222 {
4223 if (response.IsUnsupportedResponse())
4224 {
4225 // This packet isn't supported, don't try calling it again
4226 m_supports_QSaveRegisterState = eLazyBoolNo;
4227 }
4228
4229 const uint32_t response_save_id = response.GetU32(0);
4230 if (response_save_id != 0)
4231 {
4232 save_id = response_save_id;
4233 return true;
4234 }
4235 }
4236 }
4237 }
4238 return false;
4239}
4240
4241bool
4242GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4243{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004244 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00004245 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4246 // order to be useful
4247 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4248 return false;
4249
4250 Mutex::Locker locker;
4251 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4252 {
4253 const bool thread_suffix_supported = GetThreadSuffixSupported();
4254 if (thread_suffix_supported || SetCurrentThread(tid))
4255 {
4256 char packet[256];
4257 if (thread_suffix_supported)
4258 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4259 else
4260 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4261
4262 StringExtractorGDBRemote response;
4263
Greg Clayton3dedae12013-12-06 21:45:27 +00004264 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004265 {
4266 if (response.IsOKResponse())
4267 {
4268 return true;
4269 }
4270 else if (response.IsUnsupportedResponse())
4271 {
4272 // This packet isn't supported, don't try calling this packet or
4273 // QSaveRegisterState again...
4274 m_supports_QSaveRegisterState = eLazyBoolNo;
4275 }
4276 }
4277 }
4278 }
4279 return false;
4280}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004281
4282bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004283GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004284 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004285 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004286{
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00004287 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004288 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004289 return false;
4290
4291 StreamString packet;
4292 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004293 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004294 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00004295 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00004296 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004297
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004298 StringExtractorGDBRemote response;
4299 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4300 return false;
4301
Aidan Doddsdf627e72015-05-05 08:31:55 +00004302 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004303 return false;
4304
4305 std::string name;
4306 std::string value;
4307 bool success;
4308 StringExtractor extractor;
4309
4310 module_spec.Clear ();
4311 module_spec.GetFileSpec () = module_file_spec;
4312
4313 while (response.GetNameColonValue (name, value))
4314 {
4315 if (name == "uuid" || name == "md5")
4316 {
4317 extractor.GetStringRef ().swap (value);
4318 extractor.SetFilePos (0);
4319 extractor.GetHexByteString (value);
4320 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4321 }
4322 else if (name == "triple")
4323 {
4324 extractor.GetStringRef ().swap (value);
4325 extractor.SetFilePos (0);
4326 extractor.GetHexByteString (value);
4327 module_spec.GetArchitecture().SetTriple (value.c_str ());
4328 }
4329 else if (name == "file_offset")
4330 {
4331 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4332 if (success)
4333 module_spec.SetObjectOffset (ival);
4334 }
4335 else if (name == "file_size")
4336 {
4337 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4338 if (success)
4339 module_spec.SetObjectSize (ival);
4340 }
4341 else if (name == "file_path")
4342 {
4343 extractor.GetStringRef ().swap (value);
4344 extractor.SetFilePos (0);
4345 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00004346 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004347 }
4348 }
4349
4350 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004351}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004352
4353// query the target remote for extended information using the qXfer packet
4354//
4355// example: object='features', annex='target.xml', out=<xml output>
4356// return: 'true' on success
4357// 'false' on failure (err set)
4358bool
4359GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4360 const lldb_private::ConstString annex,
4361 std::string & out,
4362 lldb_private::Error & err) {
4363
4364 std::stringstream output;
4365 StringExtractorGDBRemote chunk;
4366
Greg Claytond04f0ed2015-05-26 18:00:51 +00004367 uint64_t size = GetRemoteMaxPacketSize();
4368 if (size == 0)
4369 size = 0x1000;
4370 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4371 int offset = 0;
4372 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004373
4374 // loop until all data has been read
4375 while ( active ) {
4376
4377 // send query extended feature packet
4378 std::stringstream packet;
4379 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00004380 << object.AsCString("") << ":read:"
4381 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00004382 << std::hex << offset << ","
4383 << std::hex << size;
4384
4385 GDBRemoteCommunication::PacketResult res =
4386 SendPacketAndWaitForResponse( packet.str().c_str(),
4387 chunk,
4388 false );
4389
4390 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4391 err.SetErrorString( "Error sending $qXfer packet" );
4392 return false;
4393 }
4394
4395 const std::string & str = chunk.GetStringRef( );
4396 if ( str.length() == 0 ) {
4397 // should have some data in chunk
4398 err.SetErrorString( "Empty response from $qXfer packet" );
4399 return false;
4400 }
4401
4402 // check packet code
4403 switch ( str[0] ) {
4404 // last chunk
4405 case ( 'l' ):
4406 active = false;
Aidan Doddsed9f6122015-04-29 10:08:17 +00004407 // fall through intentional
Colin Rileyc3c95b22015-04-16 15:51:33 +00004408
4409 // more chunks
4410 case ( 'm' ) :
4411 if ( str.length() > 1 )
4412 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00004413 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004414 break;
4415
4416 // unknown chunk
4417 default:
4418 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4419 return false;
4420 }
4421 }
4422
4423 out = output.str( );
4424 err.Success( );
4425 return true;
4426}
Greg Clayton0b90be12015-06-23 21:27:50 +00004427
4428// Notify the target that gdb is prepared to serve symbol lookup requests.
4429// packet: "qSymbol::"
4430// reply:
4431// OK The target does not need to look up any (more) symbols.
4432// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
4433// LLDB may provide the value by sending another qSymbol packet
4434// in the form of"qSymbol:<sym_value>:<sym_name>".
4435
4436void
4437GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4438{
4439 if (m_supports_qSymbol)
4440 {
4441 Mutex::Locker locker;
4442 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4443 {
4444 StreamString packet;
4445 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00004446 StringExtractorGDBRemote response;
4447 while (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00004448 {
Greg Clayton42b01482015-08-11 22:07:46 +00004449 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00004450 {
Greg Clayton42b01482015-08-11 22:07:46 +00004451 // We are done serving symbols requests
4452 return;
4453 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004454
Greg Clayton42b01482015-08-11 22:07:46 +00004455 if (response.IsUnsupportedResponse())
4456 {
4457 // qSymbol is not supported by the current GDB server we are connected to
4458 m_supports_qSymbol = false;
4459 return;
4460 }
4461 else
4462 {
4463 llvm::StringRef response_str(response.GetStringRef());
4464 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00004465 {
Greg Clayton42b01482015-08-11 22:07:46 +00004466 response.SetFilePos(strlen("qSymbol:"));
4467 std::string symbol_name;
4468 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00004469 {
Greg Clayton42b01482015-08-11 22:07:46 +00004470 if (symbol_name.empty())
4471 return;
4472
4473 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4474 lldb_private::SymbolContextList sc_list;
4475 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00004476 {
Greg Clayton42b01482015-08-11 22:07:46 +00004477 const size_t num_scs = sc_list.GetSize();
4478 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 +00004479 {
Greg Clayton42b01482015-08-11 22:07:46 +00004480 SymbolContext sc;
4481 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00004482 {
Greg Clayton42b01482015-08-11 22:07:46 +00004483 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00004484 {
Greg Clayton42b01482015-08-11 22:07:46 +00004485 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00004486 {
Greg Clayton42b01482015-08-11 22:07:46 +00004487 case eSymbolTypeInvalid:
4488 case eSymbolTypeAbsolute:
4489 case eSymbolTypeUndefined:
4490 case eSymbolTypeSourceFile:
4491 case eSymbolTypeHeaderFile:
4492 case eSymbolTypeObjectFile:
4493 case eSymbolTypeCommonBlock:
4494 case eSymbolTypeBlock:
4495 case eSymbolTypeLocal:
4496 case eSymbolTypeParam:
4497 case eSymbolTypeVariable:
4498 case eSymbolTypeVariableType:
4499 case eSymbolTypeLineEntry:
4500 case eSymbolTypeLineHeader:
4501 case eSymbolTypeScopeBegin:
4502 case eSymbolTypeScopeEnd:
4503 case eSymbolTypeAdditional:
4504 case eSymbolTypeCompiler:
4505 case eSymbolTypeInstrumentation:
4506 case eSymbolTypeTrampoline:
4507 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004508
Greg Clayton42b01482015-08-11 22:07:46 +00004509 case eSymbolTypeCode:
4510 case eSymbolTypeResolver:
4511 case eSymbolTypeData:
4512 case eSymbolTypeRuntime:
4513 case eSymbolTypeException:
4514 case eSymbolTypeObjCClass:
4515 case eSymbolTypeObjCMetaClass:
4516 case eSymbolTypeObjCIVar:
4517 case eSymbolTypeReExported:
4518 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4519 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004520 }
4521 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004522 }
4523 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004524 }
Greg Clayton42b01482015-08-11 22:07:46 +00004525 // This is the normal path where our symbol lookup was successful and we want
4526 // to send a packet with the new symbol value and see if another lookup needs to be
4527 // done.
4528
4529 // Change "packet" to contain the requested symbol value and name
4530 packet.Clear();
4531 packet.PutCString("qSymbol:");
4532 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4533 packet.Printf("%" PRIx64, symbol_load_addr);
4534 packet.PutCString(":");
4535 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4536 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00004537 }
4538 }
4539 }
4540 }
4541 // If we make it here, the symbol request packet response wasn't valid or
4542 // our symbol lookup failed so we must abort
4543 return;
4544
4545 }
4546 }
4547}
4548