blob: cad49efcaf5874810300f944c4da130d7062ce05 [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;
622 m_supports_jThreadExtendedInfo = eLazyBoolNo;
623 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
624 {
625 if (response.IsUnsupportedResponse())
626 {
627 m_supports_jThreadsInfo = false;
628 }
629 else if (!response.Empty())
630 {
631 object_sp = StructuredData::ParseJSON (response.GetStringRef());
632 }
633 }
634 }
635 return object_sp;
636}
637
638
Jason Molendabdc4f122014-05-06 02:59:39 +0000639bool
Jason Molenda705b1802014-06-13 02:37:02 +0000640GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
641{
642 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
643 {
644 StringExtractorGDBRemote response;
645 m_supports_jThreadExtendedInfo = eLazyBoolNo;
646 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
647 {
648 if (response.IsOKResponse())
649 {
650 m_supports_jThreadExtendedInfo = eLazyBoolYes;
651 }
652 }
653 }
654 return m_supports_jThreadExtendedInfo;
655}
656
657bool
Jason Molenda20ee21b2015-07-10 23:15:22 +0000658GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported ()
659{
660 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate)
661 {
662 StringExtractorGDBRemote response;
663 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
664 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", response, false) == PacketResult::Success)
665 {
666 if (response.IsOKResponse())
667 {
668 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
669 }
670 }
671 }
672 return m_supports_jLoadedDynamicLibrariesInfos;
673}
674
675bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000676GDBRemoteCommunicationClient::GetxPacketSupported ()
677{
678 if (m_supports_x == eLazyBoolCalculate)
679 {
680 StringExtractorGDBRemote response;
681 m_supports_x = eLazyBoolNo;
682 char packet[256];
683 snprintf (packet, sizeof (packet), "x0,0");
684 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
685 {
686 if (response.IsOKResponse())
687 m_supports_x = eLazyBoolYes;
688 }
689 }
690 return m_supports_x;
691}
692
Greg Clayton3dedae12013-12-06 21:45:27 +0000693GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000694GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
695(
696 const char *payload_prefix,
697 std::string &response_string
698)
699{
700 Mutex::Locker locker;
701 if (!GetSequenceMutex(locker,
702 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
703 {
704 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
705 if (log)
706 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
707 payload_prefix);
708 return PacketResult::ErrorNoSequenceLock;
709 }
710
711 response_string = "";
712 std::string payload_prefix_str(payload_prefix);
713 unsigned int response_size = 0x1000;
714 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
715 response_size = GetRemoteMaxPacketSize();
716 }
717
718 for (unsigned int offset = 0; true; offset += response_size)
719 {
720 StringExtractorGDBRemote this_response;
721 // Construct payload
722 char sizeDescriptor[128];
723 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
724 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
725 this_response,
726 /*send_async=*/false);
727 if (result != PacketResult::Success)
728 return result;
729
730 const std::string &this_string = this_response.GetStringRef();
731
732 // Check for m or l as first character; l seems to mean this is the last chunk
733 char first_char = *this_string.c_str();
734 if (first_char != 'm' && first_char != 'l')
735 {
736 return PacketResult::ErrorReplyInvalid;
737 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000738 // Concatenate the result so far (skipping 'm' or 'l')
739 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000740 if (first_char == 'l')
741 // We're done
742 return PacketResult::Success;
743 }
744}
745
746GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000747GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
748(
749 const char *payload,
750 StringExtractorGDBRemote &response,
751 bool send_async
752)
753{
754 return SendPacketAndWaitForResponse (payload,
755 ::strlen (payload),
756 response,
757 send_async);
758}
759
Greg Clayton3dedae12013-12-06 21:45:27 +0000760GDBRemoteCommunicationClient::PacketResult
761GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
762 size_t payload_length,
763 StringExtractorGDBRemote &response)
764{
765 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
766 if (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000767 packet_result = ReadPacket (response, GetPacketTimeoutInMicroSeconds (), true);
Greg Clayton3dedae12013-12-06 21:45:27 +0000768 return packet_result;
769}
770
771GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000772GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
773(
774 const char *payload,
775 size_t payload_length,
776 StringExtractorGDBRemote &response,
777 bool send_async
778)
779{
Greg Clayton3dedae12013-12-06 21:45:27 +0000780 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000781 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000782 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000783
784 // In order to stop async notifications from being processed in the middle of the
Bruce Mitchenere171da52015-07-22 00:16:02 +0000785 // send/receive sequence Hijack the broadcast. Then rebroadcast any events when we are done.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000786 static Listener hijack_listener("lldb.NotifyHijacker");
787 HijackBroadcaster(&hijack_listener, eBroadcastBitGdbReadThreadGotNotify);
788
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000789 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000790 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000791 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000792 }
793 else
794 {
795 if (send_async)
796 {
Greg Claytond3544052012-05-31 21:24:20 +0000797 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000798 {
Greg Claytond3544052012-05-31 21:24:20 +0000799 Mutex::Locker async_locker (m_async_mutex);
800 m_async_packet.assign(payload, payload_length);
801 m_async_packet_predicate.SetValue (true, eBroadcastNever);
802
803 if (log)
804 log->Printf ("async: async packet = %s", m_async_packet.c_str());
805
806 bool timed_out = false;
807 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000808 {
Greg Claytond3544052012-05-31 21:24:20 +0000809 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000810 {
Jim Inghambabfc382012-06-06 00:32:39 +0000811 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000812 TimeValue timeout_time;
813 timeout_time = TimeValue::Now();
814 timeout_time.OffsetWithSeconds (m_packet_timeout);
815
Greg Clayton576d8832011-03-22 04:00:09 +0000816 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000817 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000818
Greg Claytond3544052012-05-31 21:24:20 +0000819 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000820 {
Greg Claytond3544052012-05-31 21:24:20 +0000821 if (log)
822 log->Printf ("async: got response");
823
824 // Swap the response buffer to avoid malloc and string copy
825 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000826 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000827 }
828 else
829 {
830 if (log)
831 log->Printf ("async: timed out waiting for response");
832 }
833
834 // Make sure we wait until the continue packet has been sent again...
835 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
836 {
837 if (log)
838 {
839 if (timed_out)
840 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
841 else
842 log->Printf ("async: async packet sent");
843 }
844 }
845 else
846 {
847 if (log)
848 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000849 }
850 }
851 else
852 {
Greg Claytond3544052012-05-31 21:24:20 +0000853 // We had a racy condition where we went to send the interrupt
854 // yet we were able to get the lock, so the process must have
855 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000856 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000857 log->Printf ("async: got lock without sending interrupt");
858 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000859 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000860 }
861 }
862 else
863 {
Greg Clayton644247c2011-07-07 01:59:51 +0000864 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000865 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000866 }
867 }
868 else
869 {
870 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000871 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000872 }
873 }
874 else
875 {
876 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000877 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000878 }
879 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000880
Bruce Mitchenere171da52015-07-22 00:16:02 +0000881 // Remove our Hijacking listener from the broadcast.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000882 RestoreBroadcaster();
883
Bruce Mitchenere171da52015-07-22 00:16:02 +0000884 // If a notification event occurred, rebroadcast since it can now be processed safely.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000885 EventSP event_sp;
886 if (hijack_listener.GetNextEvent(event_sp))
887 BroadcastEvent(event_sp);
888
Greg Clayton3dedae12013-12-06 21:45:27 +0000889 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000890}
891
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000892static const char *end_delimiter = "--end--;";
893static const int end_delimiter_len = 8;
894
895std::string
896GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
897( ProcessGDBRemote *process,
898 StringExtractorGDBRemote& profileDataExtractor
899)
900{
901 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
902 std::stringstream final_output;
903 std::string name, value;
904
905 // Going to assuming thread_used_usec comes first, else bail out.
906 while (profileDataExtractor.GetNameColonValue(name, value))
907 {
908 if (name.compare("thread_used_id") == 0)
909 {
910 StringExtractor threadIDHexExtractor(value.c_str());
911 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
912
913 bool has_used_usec = false;
914 uint32_t curr_used_usec = 0;
915 std::string usec_name, usec_value;
916 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
917 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
918 {
919 if (usec_name.compare("thread_used_usec") == 0)
920 {
921 has_used_usec = true;
922 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
923 }
924 else
925 {
926 // We didn't find what we want, it is probably
927 // an older version. Bail out.
928 profileDataExtractor.SetFilePos(input_file_pos);
929 }
930 }
931
932 if (has_used_usec)
933 {
934 uint32_t prev_used_usec = 0;
935 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
936 if (iterator != m_thread_id_to_used_usec_map.end())
937 {
938 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
939 }
940
941 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
942 // A good first time record is one that runs for at least 0.25 sec
943 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
944 bool good_subsequent_time = (prev_used_usec > 0) &&
945 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
946
947 if (good_first_time || good_subsequent_time)
948 {
949 // We try to avoid doing too many index id reservation,
950 // resulting in fast increase of index ids.
951
952 final_output << name << ":";
953 int32_t index_id = process->AssignIndexIDToThread(thread_id);
954 final_output << index_id << ";";
955
956 final_output << usec_name << ":" << usec_value << ";";
957 }
958 else
959 {
960 // Skip past 'thread_used_name'.
961 std::string local_name, local_value;
962 profileDataExtractor.GetNameColonValue(local_name, local_value);
963 }
964
965 // Store current time as previous time so that they can be compared later.
966 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
967 }
968 else
969 {
970 // Bail out and use old string.
971 final_output << name << ":" << value << ";";
972 }
973 }
974 else
975 {
976 final_output << name << ":" << value << ";";
977 }
978 }
979 final_output << end_delimiter;
980 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
981
982 return final_output.str();
983}
984
Ewan Crawford76df2882015-06-23 12:32:06 +0000985bool
986GDBRemoteCommunicationClient::SendvContPacket
987(
988 ProcessGDBRemote *process,
989 const char *payload,
990 size_t packet_length,
991 StringExtractorGDBRemote &response
992)
993{
994
995 m_curr_tid = LLDB_INVALID_THREAD_ID;
996 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
997 if (log)
998 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
999
1000 // we want to lock down packet sending while we continue
1001 Mutex::Locker locker(m_sequence_mutex);
1002
1003 // here we broadcast this before we even send the packet!!
1004 // this signals doContinue() to exit
1005 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1006
1007 // set the public state to running
1008 m_public_is_running.SetValue(true, eBroadcastNever);
1009
1010 // Set the starting continue packet into "continue_packet". This packet
1011 // may change if we are interrupted and we continue after an async packet...
1012 std::string continue_packet(payload, packet_length);
1013
1014 if (log)
1015 log->Printf("GDBRemoteCommunicationClient::%s () sending vCont packet: %s", __FUNCTION__, continue_packet.c_str());
1016
1017 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
1018 return false;
1019
1020 // set the private state to running and broadcast this
1021 m_private_is_running.SetValue(true, eBroadcastAlways);
1022
1023 if (log)
1024 log->Printf("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1025
1026 // wait for the response to the vCont
1027 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1028 {
1029 if (response.IsOKResponse())
1030 return true;
1031 }
1032
1033 return false;
1034}
1035
Greg Clayton576d8832011-03-22 04:00:09 +00001036StateType
1037GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
1038(
1039 ProcessGDBRemote *process,
1040 const char *payload,
1041 size_t packet_length,
1042 StringExtractorGDBRemote &response
1043)
1044{
Greg Clayton1f5181a2012-07-02 22:05:25 +00001045 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +00001046 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +00001047 if (log)
1048 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1049
1050 Mutex::Locker locker(m_sequence_mutex);
1051 StateType state = eStateRunning;
1052
1053 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1054 m_public_is_running.SetValue (true, eBroadcastNever);
1055 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +00001056 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +00001057 std::string continue_packet(payload, packet_length);
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001058
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001059 const auto sigstop_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
1060 const auto sigint_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGINT");
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001061
Greg Clayton3f875c52013-02-22 22:23:55 +00001062 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +00001063
Greg Clayton576d8832011-03-22 04:00:09 +00001064 while (state == eStateRunning)
1065 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001066 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +00001067 {
1068 if (log)
1069 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +00001070 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +00001071 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +00001072 else
1073 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001074
Greg Claytone889ad62011-10-27 22:04:16 +00001075 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +00001076 }
1077
Greg Clayton3f875c52013-02-22 22:23:55 +00001078 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001079
1080 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001081 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001082
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001083 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001084 {
1085 if (response.Empty())
1086 state = eStateInvalid;
1087 else
1088 {
1089 const char stop_type = response.GetChar();
1090 if (log)
1091 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
1092 switch (stop_type)
1093 {
1094 case 'T':
1095 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +00001096 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001097 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +00001098 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001099 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
1100 {
1101 lldb::pid_t pid = GetCurrentProcessID ();
1102 if (pid != LLDB_INVALID_PROCESS_ID)
1103 process->SetID (pid);
1104 }
1105 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +00001106 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001107
1108 // Privately notify any internal threads that we have stopped
1109 // in case we wanted to interrupt our process, yet we might
1110 // send a packet and continue without returning control to the
1111 // user.
1112 m_private_is_running.SetValue (false, eBroadcastAlways);
1113
1114 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1115
Jim Inghambabfc382012-06-06 00:32:39 +00001116 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1117 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +00001118 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001119 // We sent an interrupt packet to stop the inferior process
1120 // for an async signal or to send an async packet while running
1121 // but we might have been single stepping and received the
1122 // stop packet for the step instead of for the interrupt packet.
1123 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1124 // is used, so if we get anything else, we need to try and
1125 // get another stop reply packet that may have been sent
1126 // due to sending the interrupt when the target is stopped
1127 // which will just re-send a copy of the last stop reply
1128 // packet. If we don't do this, then the reply for our
1129 // async packet will be the repeat stop reply packet and cause
1130 // a lot of trouble for us!
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001131 if (signo != sigint_signo && signo != sigstop_signo)
Greg Clayton2687cd12012-03-29 01:55:41 +00001132 {
Greg Claytonfb72fde2012-05-15 02:50:49 +00001133 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001134
Bruce Mitchenera868c132015-07-02 18:48:40 +00001135 // We didn't get a SIGINT or SIGSTOP, so try for a
Jason Molendada9765b2015-08-26 04:07:30 +00001136 // very brief time (0.1s) to get another stop reply
Greg Clayton2687cd12012-03-29 01:55:41 +00001137 // packet to make sure it doesn't get in the way
1138 StringExtractorGDBRemote extra_stop_reply_packet;
Jason Molendada9765b2015-08-26 04:07:30 +00001139 uint32_t timeout_usec = 100000;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001140 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +00001141 {
1142 switch (extra_stop_reply_packet.GetChar())
1143 {
1144 case 'T':
1145 case 'S':
1146 // We did get an extra stop reply, which means
1147 // our interrupt didn't stop the target so we
1148 // shouldn't continue after the async signal
1149 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +00001150 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001151 break;
1152 }
1153 }
1154 }
1155 }
1156
1157 if (m_async_signal != -1)
1158 {
1159 if (log)
1160 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1161
1162 // Save off the async signal we are supposed to send
1163 const int async_signal = m_async_signal;
1164 // Clear the async signal member so we don't end up
1165 // sending the signal multiple times...
1166 m_async_signal = -1;
1167 // Check which signal we stopped with
1168 if (signo == async_signal)
1169 {
1170 if (log)
1171 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1172
1173 // We already stopped with a signal that we wanted
1174 // to stop with, so we are done
1175 }
1176 else
1177 {
1178 // We stopped with a different signal that the one
1179 // we wanted to stop with, so now we must resume
1180 // with the signal we want
1181 char signal_packet[32];
1182 int signal_packet_len = 0;
1183 signal_packet_len = ::snprintf (signal_packet,
1184 sizeof (signal_packet),
1185 "C%2.2x",
1186 async_signal);
1187
1188 if (log)
1189 log->Printf ("async: stopped with signal %s, resume with %s",
1190 Host::GetSignalAsCString (signo),
1191 Host::GetSignalAsCString (async_signal));
1192
1193 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001194 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001195 continue_packet.assign(signal_packet, signal_packet_len);
1196 continue;
1197 }
1198 }
1199 else if (m_async_packet_predicate.GetValue())
1200 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001201 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001202
1203 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001204 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001205 m_async_response.Clear();
1206 if (m_async_packet.empty())
1207 {
Jim Inghama6195b72013-12-18 01:24:33 +00001208 m_async_result = PacketResult::ErrorSendFailed;
1209 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001210 packet_log->Printf ("async: error: empty async packet");
1211
1212 }
1213 else
1214 {
1215 if (packet_log)
1216 packet_log->Printf ("async: sending packet");
1217
Jim Inghama6195b72013-12-18 01:24:33 +00001218 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1219 m_async_packet.size(),
1220 m_async_response,
1221 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001222 }
1223 // Let the other thread that was trying to send the async
1224 // packet know that the packet has been sent and response is
1225 // ready...
1226 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1227
1228 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001229 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001230
1231 // Set the continue packet to resume if our interrupt
1232 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001233 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001234 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001235 // Reverting this for now as it is causing deadlocks
1236 // in programs (<rdar://problem/11529853>). In the future
1237 // we should check our thread list and "do the right thing"
1238 // for new threads that show up while we stop and run async
1239 // packets. Setting the packet to 'c' to continue all threads
1240 // is the right thing to do 99.99% of the time because if a
1241 // thread was single stepping, and we sent an interrupt, we
1242 // will notice above that we didn't stop due to an interrupt
1243 // but stopped due to stepping and we would _not_ continue.
1244 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001245 continue;
1246 }
1247 }
1248 // Stop with signal and thread info
1249 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001250 }
Greg Clayton576d8832011-03-22 04:00:09 +00001251 break;
1252
1253 case 'W':
1254 case 'X':
1255 // process exited
1256 state = eStateExited;
1257 break;
1258
1259 case 'O':
1260 // STDOUT
1261 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001262 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001263 std::string inferior_stdout;
1264 inferior_stdout.reserve(response.GetBytesLeft () / 2);
Dawn Perchik554a8572015-09-17 17:55:32 +00001265
1266 uint8_t ch;
1267 while (response.GetHexU8Ex(ch))
1268 {
1269 if (ch != 0)
1270 inferior_stdout.append(1, (char)ch);
1271 }
Greg Clayton576d8832011-03-22 04:00:09 +00001272 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1273 }
1274 break;
1275
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001276 case 'A':
1277 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1278 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001279 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001280 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1281 if (m_partial_profile_data.length() > 0)
1282 {
1283 m_partial_profile_data.append(input);
1284 input = m_partial_profile_data;
1285 m_partial_profile_data.clear();
1286 }
1287
1288 size_t found, pos = 0, len = input.length();
1289 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1290 {
1291 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001292 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1293 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001294
1295 pos = found + end_delimiter_len;
1296 }
1297
1298 if (pos < len)
1299 {
1300 // Last incomplete chunk.
1301 m_partial_profile_data = input.substr(pos);
1302 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001303 }
1304 break;
1305
Greg Clayton576d8832011-03-22 04:00:09 +00001306 case 'E':
1307 // ERROR
1308 state = eStateInvalid;
1309 break;
1310
1311 default:
1312 if (log)
1313 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1314 state = eStateInvalid;
1315 break;
1316 }
1317 }
1318 }
1319 else
1320 {
1321 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001322 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
Greg Clayton576d8832011-03-22 04:00:09 +00001323 state = eStateInvalid;
1324 }
1325 }
1326 if (log)
1327 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1328 response.SetFilePos(0);
1329 m_private_is_running.SetValue (false, eBroadcastAlways);
1330 m_public_is_running.SetValue (false, eBroadcastAlways);
1331 return state;
1332}
1333
1334bool
1335GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1336{
Greg Clayton2687cd12012-03-29 01:55:41 +00001337 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001338 m_async_signal = signo;
1339 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001340 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001341 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001342 return true;
1343 m_async_signal = -1;
1344 return false;
1345}
1346
Greg Clayton37a0a242012-04-11 00:24:49 +00001347// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001348// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1349// (the expected result), then it will send the halt packet. If it does succeed
1350// then the caller that requested the interrupt will want to keep the sequence
1351// locked down so that no one else can send packets while the caller has control.
1352// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001353// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001354// else (like read/write memory), so we need to interrupt the running process
1355// (gdb remote protocol requires this), and do what we need to do, then resume.
1356
1357bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001358GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001359(
1360 Mutex::Locker& locker,
1361 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001362 bool &timed_out
1363)
1364{
Greg Clayton576d8832011-03-22 04:00:09 +00001365 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001366 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001367
1368 if (IsRunning())
1369 {
1370 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001371 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001372 {
1373 if (log)
1374 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1375 }
1376 else
Greg Clayton576d8832011-03-22 04:00:09 +00001377 {
1378 // Someone has the mutex locked waiting for a response or for the
1379 // inferior to stop, so send the interrupt on the down low...
1380 char ctrl_c = '\x03';
1381 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001382 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001383 if (log)
1384 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001385 if (bytes_written > 0)
1386 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001387 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001388 if (seconds_to_wait_for_stop)
1389 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001390 TimeValue timeout;
1391 if (seconds_to_wait_for_stop)
1392 {
1393 timeout = TimeValue::Now();
1394 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1395 }
Greg Clayton576d8832011-03-22 04:00:09 +00001396 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1397 {
1398 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001399 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001400 return true;
1401 }
1402 else
1403 {
1404 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001405 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001406 }
1407 }
1408 else
1409 {
1410 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001411 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001412 return true;
1413 }
1414 }
1415 else
1416 {
1417 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001418 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001419 }
1420 return false;
1421 }
Greg Clayton576d8832011-03-22 04:00:09 +00001422 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001423 else
1424 {
1425 if (log)
1426 log->Printf ("SendInterrupt () - not running");
1427 }
Greg Clayton576d8832011-03-22 04:00:09 +00001428 return true;
1429}
1430
1431lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001432GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001433{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001434 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001435 return m_curr_pid;
1436
1437 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001438 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001439 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001440 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001441 // We really got it.
1442 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001443 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001444 else
1445 {
Todd Fialae24614f2014-05-14 00:15:32 +00001446 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1447 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1448 // The gdb remote protocol documents $qC as returning the thread id, which newer
1449 // debugserver and lldb-gdbserver stubs return correctly.
1450 StringExtractorGDBRemote response;
1451 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001452 {
Todd Fialae24614f2014-05-14 00:15:32 +00001453 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001454 {
Todd Fialae24614f2014-05-14 00:15:32 +00001455 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001456 {
Todd Fialae24614f2014-05-14 00:15:32 +00001457 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1458 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001459 {
Todd Fialae24614f2014-05-14 00:15:32 +00001460 m_curr_pid_is_valid = eLazyBoolYes;
1461 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001462 }
1463 }
1464 }
1465 }
Jaydeep Patil1142f832015-08-13 03:46:36 +00001466
1467 // If we don't get a response for $qC, check if $qfThreadID gives us a result.
1468 if (m_curr_pid == LLDB_INVALID_PROCESS_ID)
1469 {
1470 std::vector<lldb::tid_t> thread_ids;
1471 bool sequence_mutex_unavailable;
1472 size_t size;
1473 size = GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1474 if (size && sequence_mutex_unavailable == false)
1475 {
1476 m_curr_pid = thread_ids.front();
1477 m_curr_pid_is_valid = eLazyBoolYes;
1478 return m_curr_pid;
1479 }
1480 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001481 }
1482
Greg Clayton576d8832011-03-22 04:00:09 +00001483 return LLDB_INVALID_PROCESS_ID;
1484}
1485
1486bool
1487GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1488{
1489 error_str.clear();
1490 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001491 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001492 {
1493 if (response.IsOKResponse())
1494 return true;
1495 if (response.GetChar() == 'E')
1496 {
1497 // A string the describes what failed when launching...
1498 error_str = response.GetStringRef().substr(1);
1499 }
1500 else
1501 {
1502 error_str.assign ("unknown error occurred launching process");
1503 }
1504 }
1505 else
1506 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001507 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001508 }
1509 return false;
1510}
1511
1512int
Greg Claytonfbb76342013-11-20 21:07:01 +00001513GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001514{
Greg Claytonfbb76342013-11-20 21:07:01 +00001515 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001516 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001517 std::vector<const char *> argv;
1518 FileSpec exe_file = launch_info.GetExecutableFile();
1519 std::string exe_path;
1520 const char *arg = NULL;
1521 const Args &launch_args = launch_info.GetArguments();
1522 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +00001523 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +00001524 else
1525 {
1526 arg = launch_args.GetArgumentAtIndex(0);
1527 if (arg)
1528 exe_path = arg;
1529 }
1530 if (!exe_path.empty())
1531 {
1532 argv.push_back(exe_path.c_str());
1533 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1534 {
1535 if (arg)
1536 argv.push_back(arg);
1537 }
1538 }
1539 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001540 {
1541 StreamString packet;
1542 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001543 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001544 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001545 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001546 const int arg_len = strlen(arg);
1547 if (i > 0)
1548 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001549 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001550 packet.PutBytesAsRawHex8 (arg, arg_len);
1551 }
1552
1553 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001554 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001555 {
1556 if (response.IsOKResponse())
1557 return 0;
1558 uint8_t error = response.GetError();
1559 if (error)
1560 return error;
1561 }
1562 }
1563 return -1;
1564}
1565
1566int
1567GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1568{
1569 if (name_equal_value && name_equal_value[0])
1570 {
1571 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001572 bool send_hex_encoding = false;
1573 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001574 {
Greg Clayton89600582013-10-10 17:53:50 +00001575 if (isprint(*p))
1576 {
1577 switch (*p)
1578 {
1579 case '$':
1580 case '#':
1581 send_hex_encoding = true;
1582 break;
1583 default:
1584 break;
1585 }
1586 }
1587 else
1588 {
1589 // We have non printable characters, lets hex encode this...
1590 send_hex_encoding = true;
1591 }
1592 }
1593
1594 StringExtractorGDBRemote response;
1595 if (send_hex_encoding)
1596 {
1597 if (m_supports_QEnvironmentHexEncoded)
1598 {
1599 packet.PutCString("QEnvironmentHexEncoded:");
1600 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001601 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001602 {
1603 if (response.IsOKResponse())
1604 return 0;
1605 uint8_t error = response.GetError();
1606 if (error)
1607 return error;
1608 if (response.IsUnsupportedResponse())
1609 m_supports_QEnvironmentHexEncoded = false;
1610 }
1611 }
1612
1613 }
1614 else if (m_supports_QEnvironment)
1615 {
1616 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001617 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001618 {
1619 if (response.IsOKResponse())
1620 return 0;
1621 uint8_t error = response.GetError();
1622 if (error)
1623 return error;
1624 if (response.IsUnsupportedResponse())
1625 m_supports_QEnvironment = false;
1626 }
Greg Clayton576d8832011-03-22 04:00:09 +00001627 }
1628 }
1629 return -1;
1630}
1631
Greg Claytonc4103b32011-05-08 04:53:50 +00001632int
1633GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1634{
1635 if (arch && arch[0])
1636 {
1637 StreamString packet;
1638 packet.Printf("QLaunchArch:%s", arch);
1639 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001640 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001641 {
1642 if (response.IsOKResponse())
1643 return 0;
1644 uint8_t error = response.GetError();
1645 if (error)
1646 return error;
1647 }
1648 }
1649 return -1;
1650}
1651
Jason Molendaa3329782014-03-29 18:54:20 +00001652int
1653GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1654{
1655 if (data && *data != '\0')
1656 {
1657 StreamString packet;
1658 packet.Printf("QSetProcessEvent:%s", data);
1659 StringExtractorGDBRemote response;
1660 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1661 {
1662 if (response.IsOKResponse())
1663 {
1664 if (was_supported)
1665 *was_supported = true;
1666 return 0;
1667 }
1668 else if (response.IsUnsupportedResponse())
1669 {
1670 if (was_supported)
1671 *was_supported = false;
1672 return -1;
1673 }
1674 else
1675 {
1676 uint8_t error = response.GetError();
1677 if (was_supported)
1678 *was_supported = true;
1679 if (error)
1680 return error;
1681 }
1682 }
1683 }
1684 return -1;
1685}
1686
Greg Clayton576d8832011-03-22 04:00:09 +00001687bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001688GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1689 uint32_t &minor,
1690 uint32_t &update)
1691{
1692 if (GetHostInfo ())
1693 {
1694 if (m_os_version_major != UINT32_MAX)
1695 {
1696 major = m_os_version_major;
1697 minor = m_os_version_minor;
1698 update = m_os_version_update;
1699 return true;
1700 }
1701 }
1702 return false;
1703}
1704
1705bool
1706GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1707{
1708 if (GetHostInfo ())
1709 {
1710 if (!m_os_build.empty())
1711 {
1712 s = m_os_build;
1713 return true;
1714 }
1715 }
1716 s.clear();
1717 return false;
1718}
1719
1720
1721bool
1722GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1723{
1724 if (GetHostInfo ())
1725 {
1726 if (!m_os_kernel.empty())
1727 {
1728 s = m_os_kernel;
1729 return true;
1730 }
1731 }
1732 s.clear();
1733 return false;
1734}
1735
1736bool
1737GDBRemoteCommunicationClient::GetHostname (std::string &s)
1738{
1739 if (GetHostInfo ())
1740 {
1741 if (!m_hostname.empty())
1742 {
1743 s = m_hostname;
1744 return true;
1745 }
1746 }
1747 s.clear();
1748 return false;
1749}
1750
1751ArchSpec
1752GDBRemoteCommunicationClient::GetSystemArchitecture ()
1753{
1754 if (GetHostInfo ())
1755 return m_host_arch;
1756 return ArchSpec();
1757}
1758
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001759const lldb_private::ArchSpec &
1760GDBRemoteCommunicationClient::GetProcessArchitecture ()
1761{
1762 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1763 GetCurrentProcessInfo ();
1764 return m_process_arch;
1765}
1766
Jason Molendaa3329782014-03-29 18:54:20 +00001767bool
1768GDBRemoteCommunicationClient::GetGDBServerVersion()
1769{
1770 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1771 {
1772 m_gdb_server_name.clear();
1773 m_gdb_server_version = 0;
1774 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1775
1776 StringExtractorGDBRemote response;
1777 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1778 {
1779 if (response.IsNormalResponse())
1780 {
1781 std::string name;
1782 std::string value;
1783 bool success = false;
1784 while (response.GetNameColonValue(name, value))
1785 {
1786 if (name.compare("name") == 0)
1787 {
1788 success = true;
1789 m_gdb_server_name.swap(value);
1790 }
1791 else if (name.compare("version") == 0)
1792 {
1793 size_t dot_pos = value.find('.');
1794 if (dot_pos != std::string::npos)
1795 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001796 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001797 if (version != UINT32_MAX)
1798 {
1799 success = true;
1800 m_gdb_server_version = version;
1801 }
1802 }
1803 }
1804 if (success)
1805 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1806 }
1807 }
1808 }
1809 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1810}
1811
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001812void
1813GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1814{
1815 CompressionType avail_type = CompressionType::None;
1816 std::string avail_name;
1817
1818#if defined (HAVE_LIBCOMPRESSION)
1819 // libcompression is weak linked so test if compression_decode_buffer() is available
1820 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1821 {
1822 for (auto compression : supported_compressions)
1823 {
1824 if (compression == "lzfse")
1825 {
1826 avail_type = CompressionType::LZFSE;
1827 avail_name = compression;
1828 break;
1829 }
1830 }
1831 }
1832#endif
1833
1834#if defined (HAVE_LIBCOMPRESSION)
1835 // libcompression is weak linked so test if compression_decode_buffer() is available
1836 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1837 {
1838 for (auto compression : supported_compressions)
1839 {
1840 if (compression == "zlib-deflate")
1841 {
1842 avail_type = CompressionType::ZlibDeflate;
1843 avail_name = compression;
1844 break;
1845 }
1846 }
1847 }
1848#endif
1849
1850#if defined (HAVE_LIBZ)
1851 if (avail_type == CompressionType::None)
1852 {
1853 for (auto compression : supported_compressions)
1854 {
1855 if (compression == "zlib-deflate")
1856 {
1857 avail_type = CompressionType::ZlibDeflate;
1858 avail_name = compression;
1859 break;
1860 }
1861 }
1862 }
1863#endif
1864
1865#if defined (HAVE_LIBCOMPRESSION)
1866 // libcompression is weak linked so test if compression_decode_buffer() is available
1867 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1868 {
1869 for (auto compression : supported_compressions)
1870 {
1871 if (compression == "lz4")
1872 {
1873 avail_type = CompressionType::LZ4;
1874 avail_name = compression;
1875 break;
1876 }
1877 }
1878 }
1879#endif
1880
1881#if defined (HAVE_LIBCOMPRESSION)
1882 // libcompression is weak linked so test if compression_decode_buffer() is available
1883 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1884 {
1885 for (auto compression : supported_compressions)
1886 {
1887 if (compression == "lzma")
1888 {
1889 avail_type = CompressionType::LZMA;
1890 avail_name = compression;
1891 break;
1892 }
1893 }
1894 }
1895#endif
1896
1897 if (avail_type != CompressionType::None)
1898 {
1899 StringExtractorGDBRemote response;
1900 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1901 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1902 return;
1903
1904 if (response.IsOKResponse())
1905 {
1906 m_compression_type = avail_type;
1907 }
1908 }
1909}
1910
Jason Molendaa3329782014-03-29 18:54:20 +00001911const char *
1912GDBRemoteCommunicationClient::GetGDBServerProgramName()
1913{
1914 if (GetGDBServerVersion())
1915 {
1916 if (!m_gdb_server_name.empty())
1917 return m_gdb_server_name.c_str();
1918 }
1919 return NULL;
1920}
1921
1922uint32_t
1923GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1924{
1925 if (GetGDBServerVersion())
1926 return m_gdb_server_version;
1927 return 0;
1928}
Greg Clayton1cb64962011-03-24 04:28:38 +00001929
1930bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001931GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1932{
1933 StringExtractorGDBRemote response;
1934 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1935 return false;
1936
1937 if (!response.IsNormalResponse())
1938 return false;
1939
1940 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1941 tid = response.GetHexMaxU32(true, -1);
1942
1943 return true;
1944}
1945
1946bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001947GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001948{
Todd Fialaaf245d12014-06-30 21:05:18 +00001949 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1950
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001951 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001952 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001953 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001954 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001955 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001956 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001957 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001958 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001959 std::string name;
1960 std::string value;
1961 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1962 uint32_t sub = 0;
1963 std::string arch_name;
1964 std::string os_name;
1965 std::string vendor_name;
1966 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001967 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001968 uint32_t pointer_byte_size = 0;
1969 StringExtractor extractor;
1970 ByteOrder byte_order = eByteOrderInvalid;
1971 uint32_t num_keys_decoded = 0;
1972 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001973 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001974 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001975 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001976 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001977 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001978 if (cpu != LLDB_INVALID_CPUTYPE)
1979 ++num_keys_decoded;
1980 }
1981 else if (name.compare("cpusubtype") == 0)
1982 {
1983 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001984 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001985 if (sub != 0)
1986 ++num_keys_decoded;
1987 }
1988 else if (name.compare("arch") == 0)
1989 {
1990 arch_name.swap (value);
1991 ++num_keys_decoded;
1992 }
1993 else if (name.compare("triple") == 0)
1994 {
Greg Clayton44272a42014-09-18 00:18:32 +00001995 extractor.GetStringRef ().swap (value);
1996 extractor.SetFilePos(0);
1997 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001998 ++num_keys_decoded;
1999 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00002000 else if (name.compare ("distribution_id") == 0)
2001 {
2002 extractor.GetStringRef ().swap (value);
2003 extractor.SetFilePos (0);
2004 extractor.GetHexByteString (distribution_id);
2005 ++num_keys_decoded;
2006 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002007 else if (name.compare("os_build") == 0)
2008 {
2009 extractor.GetStringRef().swap(value);
2010 extractor.SetFilePos(0);
2011 extractor.GetHexByteString (m_os_build);
2012 ++num_keys_decoded;
2013 }
2014 else if (name.compare("hostname") == 0)
2015 {
2016 extractor.GetStringRef().swap(value);
2017 extractor.SetFilePos(0);
2018 extractor.GetHexByteString (m_hostname);
2019 ++num_keys_decoded;
2020 }
2021 else if (name.compare("os_kernel") == 0)
2022 {
2023 extractor.GetStringRef().swap(value);
2024 extractor.SetFilePos(0);
2025 extractor.GetHexByteString (m_os_kernel);
2026 ++num_keys_decoded;
2027 }
2028 else if (name.compare("ostype") == 0)
2029 {
2030 os_name.swap (value);
2031 ++num_keys_decoded;
2032 }
2033 else if (name.compare("vendor") == 0)
2034 {
2035 vendor_name.swap(value);
2036 ++num_keys_decoded;
2037 }
2038 else if (name.compare("endian") == 0)
2039 {
2040 ++num_keys_decoded;
2041 if (value.compare("little") == 0)
2042 byte_order = eByteOrderLittle;
2043 else if (value.compare("big") == 0)
2044 byte_order = eByteOrderBig;
2045 else if (value.compare("pdp") == 0)
2046 byte_order = eByteOrderPDP;
2047 else
2048 --num_keys_decoded;
2049 }
2050 else if (name.compare("ptrsize") == 0)
2051 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002052 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002053 if (pointer_byte_size != 0)
2054 ++num_keys_decoded;
2055 }
2056 else if (name.compare("os_version") == 0)
2057 {
2058 Args::StringToVersion (value.c_str(),
2059 m_os_version_major,
2060 m_os_version_minor,
2061 m_os_version_update);
2062 if (m_os_version_major != UINT32_MAX)
2063 ++num_keys_decoded;
2064 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002065 else if (name.compare("watchpoint_exceptions_received") == 0)
2066 {
2067 ++num_keys_decoded;
2068 if (strcmp(value.c_str(),"before") == 0)
2069 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2070 else if (strcmp(value.c_str(),"after") == 0)
2071 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
2072 else
2073 --num_keys_decoded;
2074 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002075 else if (name.compare("default_packet_timeout") == 0)
2076 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002077 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002078 if (m_default_packet_timeout > 0)
2079 {
2080 SetPacketTimeout(m_default_packet_timeout);
2081 ++num_keys_decoded;
2082 }
2083 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002084
Greg Clayton32e0a752011-03-30 18:16:51 +00002085 }
2086
2087 if (num_keys_decoded > 0)
2088 m_qHostInfo_is_valid = eLazyBoolYes;
2089
2090 if (triple.empty())
2091 {
2092 if (arch_name.empty())
2093 {
2094 if (cpu != LLDB_INVALID_CPUTYPE)
2095 {
2096 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2097 if (pointer_byte_size)
2098 {
2099 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2100 }
2101 if (byte_order != eByteOrderInvalid)
2102 {
2103 assert (byte_order == m_host_arch.GetByteOrder());
2104 }
Greg Clayton70512312012-05-08 01:45:38 +00002105
2106 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
2107 {
2108 switch (m_host_arch.GetMachine())
2109 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002110 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002111 case llvm::Triple::arm:
2112 case llvm::Triple::thumb:
2113 os_name = "ios";
2114 break;
2115 default:
2116 os_name = "macosx";
2117 break;
2118 }
2119 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002120 if (!vendor_name.empty())
2121 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2122 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00002123 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00002124
2125 }
2126 }
2127 else
2128 {
2129 std::string triple;
2130 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00002131 if (!vendor_name.empty() || !os_name.empty())
2132 {
2133 triple += '-';
2134 if (vendor_name.empty())
2135 triple += "unknown";
2136 else
2137 triple += vendor_name;
2138 triple += '-';
2139 if (os_name.empty())
2140 triple += "unknown";
2141 else
2142 triple += os_name;
2143 }
2144 m_host_arch.SetTriple (triple.c_str());
2145
2146 llvm::Triple &host_triple = m_host_arch.GetTriple();
2147 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2148 {
2149 switch (m_host_arch.GetMachine())
2150 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002151 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002152 case llvm::Triple::arm:
2153 case llvm::Triple::thumb:
2154 host_triple.setOS(llvm::Triple::IOS);
2155 break;
2156 default:
2157 host_triple.setOS(llvm::Triple::MacOSX);
2158 break;
2159 }
2160 }
Greg Clayton1cb64962011-03-24 04:28:38 +00002161 if (pointer_byte_size)
2162 {
2163 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2164 }
2165 if (byte_order != eByteOrderInvalid)
2166 {
2167 assert (byte_order == m_host_arch.GetByteOrder());
2168 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002169
Greg Clayton1cb64962011-03-24 04:28:38 +00002170 }
2171 }
2172 else
2173 {
Greg Clayton70512312012-05-08 01:45:38 +00002174 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00002175 if (pointer_byte_size)
2176 {
2177 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2178 }
2179 if (byte_order != eByteOrderInvalid)
2180 {
2181 assert (byte_order == m_host_arch.GetByteOrder());
2182 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002183
2184 if (log)
2185 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 +00002186 }
2187 if (!distribution_id.empty ())
2188 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00002189 }
Greg Clayton576d8832011-03-22 04:00:09 +00002190 }
2191 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002192 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00002193}
2194
2195int
2196GDBRemoteCommunicationClient::SendAttach
2197(
2198 lldb::pid_t pid,
2199 StringExtractorGDBRemote& response
2200)
2201{
2202 if (pid != LLDB_INVALID_PROCESS_ID)
2203 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002204 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002205 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002206 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002207 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002208 {
2209 if (response.IsErrorResponse())
2210 return response.GetError();
2211 return 0;
2212 }
2213 }
2214 return -1;
2215}
2216
Vince Harrone0be4252015-02-06 18:32:57 +00002217int
2218GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2219{
2220 StreamString packet;
2221 packet.PutCString("I");
2222 packet.PutBytesAsRawHex8(data, data_len);
2223 StringExtractorGDBRemote response;
2224 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2225 {
2226 return 0;
2227 }
2228 return response.GetError();
2229
2230}
2231
Greg Clayton576d8832011-03-22 04:00:09 +00002232const lldb_private::ArchSpec &
2233GDBRemoteCommunicationClient::GetHostArchitecture ()
2234{
Greg Clayton32e0a752011-03-30 18:16:51 +00002235 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00002236 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00002237 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00002238}
2239
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002240uint32_t
2241GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2242{
2243 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2244 GetHostInfo ();
2245 return m_default_packet_timeout;
2246}
2247
Greg Clayton576d8832011-03-22 04:00:09 +00002248addr_t
2249GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2250{
Greg Clayton70b57652011-05-15 01:25:55 +00002251 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002252 {
Greg Clayton70b57652011-05-15 01:25:55 +00002253 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002254 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002255 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00002256 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00002257 permissions & lldb::ePermissionsReadable ? "r" : "",
2258 permissions & lldb::ePermissionsWritable ? "w" : "",
2259 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00002260 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002261 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002262 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002263 {
Todd Fialaf105f582014-06-21 00:48:09 +00002264 if (response.IsUnsupportedResponse())
2265 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2266 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002267 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2268 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002269 else
2270 {
2271 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2272 }
Greg Clayton576d8832011-03-22 04:00:09 +00002273 }
2274 return LLDB_INVALID_ADDRESS;
2275}
2276
2277bool
2278GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2279{
Greg Clayton70b57652011-05-15 01:25:55 +00002280 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002281 {
Greg Clayton70b57652011-05-15 01:25:55 +00002282 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002283 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002284 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002285 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002286 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002287 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002288 {
Todd Fialaf105f582014-06-21 00:48:09 +00002289 if (response.IsUnsupportedResponse())
2290 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2291 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002292 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002293 }
2294 else
2295 {
2296 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00002297 }
Greg Clayton576d8832011-03-22 04:00:09 +00002298 }
2299 return false;
2300}
2301
Jim Inghamacff8952013-05-02 00:27:30 +00002302Error
2303GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00002304{
Jim Inghamacff8952013-05-02 00:27:30 +00002305 Error error;
2306
2307 if (keep_stopped)
2308 {
2309 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2310 {
2311 char packet[64];
2312 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002313 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002314 StringExtractorGDBRemote response;
Jim Ingham4920a4e2015-07-15 00:59:25 +00002315 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success
2316 && response.IsOKResponse())
Jim Inghamacff8952013-05-02 00:27:30 +00002317 {
2318 m_supports_detach_stay_stopped = eLazyBoolYes;
2319 }
2320 else
2321 {
2322 m_supports_detach_stay_stopped = eLazyBoolNo;
2323 }
2324 }
2325
2326 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2327 {
2328 error.SetErrorString("Stays stopped not supported by this target.");
2329 return error;
2330 }
2331 else
2332 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002333 StringExtractorGDBRemote response;
Jason Molenda2a667382015-07-15 00:16:09 +00002334 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002335 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002336 error.SetErrorString ("Sending extended disconnect packet failed.");
2337 }
2338 }
2339 else
2340 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002341 StringExtractorGDBRemote response;
2342 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002343 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002344 error.SetErrorString ("Sending disconnect packet failed.");
2345 }
2346 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002347}
2348
Greg Clayton46fb5582011-11-18 07:03:08 +00002349Error
2350GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2351 lldb_private::MemoryRegionInfo &region_info)
2352{
2353 Error error;
2354 region_info.Clear();
2355
2356 if (m_supports_memory_region_info != eLazyBoolNo)
2357 {
2358 m_supports_memory_region_info = eLazyBoolYes;
2359 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002360 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002361 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002362 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002363 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002364 {
2365 std::string name;
2366 std::string value;
2367 addr_t addr_value;
2368 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002369 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002370 while (success && response.GetNameColonValue(name, value))
2371 {
2372 if (name.compare ("start") == 0)
2373 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002374 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002375 if (success)
2376 region_info.GetRange().SetRangeBase(addr_value);
2377 }
2378 else if (name.compare ("size") == 0)
2379 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002380 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002381 if (success)
2382 region_info.GetRange().SetByteSize (addr_value);
2383 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002384 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002385 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002386 saw_permissions = true;
2387 if (region_info.GetRange().Contains (addr))
2388 {
2389 if (value.find('r') != std::string::npos)
2390 region_info.SetReadable (MemoryRegionInfo::eYes);
2391 else
2392 region_info.SetReadable (MemoryRegionInfo::eNo);
2393
2394 if (value.find('w') != std::string::npos)
2395 region_info.SetWritable (MemoryRegionInfo::eYes);
2396 else
2397 region_info.SetWritable (MemoryRegionInfo::eNo);
2398
2399 if (value.find('x') != std::string::npos)
2400 region_info.SetExecutable (MemoryRegionInfo::eYes);
2401 else
2402 region_info.SetExecutable (MemoryRegionInfo::eNo);
2403 }
2404 else
2405 {
2406 // The reported region does not contain this address -- we're looking at an unmapped page
2407 region_info.SetReadable (MemoryRegionInfo::eNo);
2408 region_info.SetWritable (MemoryRegionInfo::eNo);
2409 region_info.SetExecutable (MemoryRegionInfo::eNo);
2410 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002411 }
2412 else if (name.compare ("error") == 0)
2413 {
2414 StringExtractorGDBRemote name_extractor;
2415 // Swap "value" over into "name_extractor"
2416 name_extractor.GetStringRef().swap(value);
2417 // Now convert the HEX bytes into a string value
2418 name_extractor.GetHexByteString (value);
2419 error.SetErrorString(value.c_str());
2420 }
2421 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002422
2423 // We got a valid address range back but no permissions -- which means this is an unmapped page
2424 if (region_info.GetRange().IsValid() && saw_permissions == false)
2425 {
2426 region_info.SetReadable (MemoryRegionInfo::eNo);
2427 region_info.SetWritable (MemoryRegionInfo::eNo);
2428 region_info.SetExecutable (MemoryRegionInfo::eNo);
2429 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002430 }
2431 else
2432 {
2433 m_supports_memory_region_info = eLazyBoolNo;
2434 }
2435 }
2436
2437 if (m_supports_memory_region_info == eLazyBoolNo)
2438 {
2439 error.SetErrorString("qMemoryRegionInfo is not supported");
2440 }
2441 if (error.Fail())
2442 region_info.Clear();
2443 return error;
2444
2445}
2446
Johnny Chen64637202012-05-23 21:09:52 +00002447Error
2448GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2449{
2450 Error error;
2451
2452 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2453 {
2454 num = m_num_supported_hardware_watchpoints;
2455 return error;
2456 }
2457
2458 // Set num to 0 first.
2459 num = 0;
2460 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2461 {
2462 char packet[64];
2463 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002464 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002465 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002466 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002467 {
2468 m_supports_watchpoint_support_info = eLazyBoolYes;
2469 std::string name;
2470 std::string value;
2471 while (response.GetNameColonValue(name, value))
2472 {
2473 if (name.compare ("num") == 0)
2474 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002475 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002476 m_num_supported_hardware_watchpoints = num;
2477 }
2478 }
2479 }
2480 else
2481 {
2482 m_supports_watchpoint_support_info = eLazyBoolNo;
2483 }
2484 }
2485
2486 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2487 {
2488 error.SetErrorString("qWatchpointSupportInfo is not supported");
2489 }
2490 return error;
2491
2492}
Greg Clayton46fb5582011-11-18 07:03:08 +00002493
Enrico Granataf04a2192012-07-13 23:18:48 +00002494lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002495GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002496{
2497 Error error(GetWatchpointSupportInfo(num));
2498 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00002499 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00002500 return error;
2501}
2502
2503lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002504GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002505{
2506 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00002507 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00002508
2509 // we assume watchpoints will happen after running the relevant opcode
2510 // and we only want to override this behavior if we have explicitly
2511 // received a qHostInfo telling us otherwise
2512 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00002513 {
2514 // On targets like MIPS, watchpoint exceptions are always generated
2515 // before the instruction is executed. The connected target may not
2516 // support qHostInfo or qWatchpointSupportInfo packets.
2517 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2518 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
2519 after = false;
2520 else
2521 after = true;
2522 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002523 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00002524 {
2525 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
2526 // if it is not calculated before.
2527 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
2528 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2529 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
2530 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2531
Enrico Granataf04a2192012-07-13 23:18:48 +00002532 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00002533 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002534 return error;
2535}
2536
Greg Clayton576d8832011-03-22 04:00:09 +00002537int
Chaoren Lind3173f32015-05-29 19:52:29 +00002538GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002539{
Chaoren Lind3173f32015-05-29 19:52:29 +00002540 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002541 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002542 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002543 StreamString packet;
2544 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002545 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00002546
2547 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002548 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002549 {
2550 if (response.IsOKResponse())
2551 return 0;
2552 uint8_t error = response.GetError();
2553 if (error)
2554 return error;
2555 }
2556 }
2557 return -1;
2558}
2559
2560int
Chaoren Lind3173f32015-05-29 19:52:29 +00002561GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002562{
Chaoren Lind3173f32015-05-29 19:52:29 +00002563 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002564 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002565 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002566 StreamString packet;
2567 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002568 packet.PutCStringAsRawHex8(path.c_str());
2569
Greg Clayton576d8832011-03-22 04:00:09 +00002570 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002571 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002572 {
2573 if (response.IsOKResponse())
2574 return 0;
2575 uint8_t error = response.GetError();
2576 if (error)
2577 return error;
2578 }
2579 }
2580 return -1;
2581}
2582
2583int
Chaoren Lind3173f32015-05-29 19:52:29 +00002584GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002585{
Chaoren Lind3173f32015-05-29 19:52:29 +00002586 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002587 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002588 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002589 StreamString packet;
2590 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002591 packet.PutCStringAsRawHex8(path.c_str());
2592
Greg Clayton576d8832011-03-22 04:00:09 +00002593 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002594 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002595 {
2596 if (response.IsOKResponse())
2597 return 0;
2598 uint8_t error = response.GetError();
2599 if (error)
2600 return error;
2601 }
2602 }
2603 return -1;
2604}
2605
Greg Claytonfbb76342013-11-20 21:07:01 +00002606bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002607GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00002608{
2609 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002610 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002611 {
2612 if (response.IsUnsupportedResponse())
2613 return false;
2614 if (response.IsErrorResponse())
2615 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00002616 std::string cwd;
2617 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00002618 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00002619 return !cwd.empty();
2620 }
2621 return false;
2622}
2623
Greg Clayton576d8832011-03-22 04:00:09 +00002624int
Chaoren Lind3173f32015-05-29 19:52:29 +00002625GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002626{
Chaoren Lind3173f32015-05-29 19:52:29 +00002627 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002628 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002629 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002630 StreamString packet;
2631 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002632 packet.PutCStringAsRawHex8(path.c_str());
2633
Greg Clayton576d8832011-03-22 04:00:09 +00002634 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002635 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002636 {
2637 if (response.IsOKResponse())
2638 return 0;
2639 uint8_t error = response.GetError();
2640 if (error)
2641 return error;
2642 }
2643 }
2644 return -1;
2645}
2646
2647int
2648GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2649{
Greg Clayton32e0a752011-03-30 18:16:51 +00002650 char packet[32];
2651 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002652 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002653 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002654 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002655 {
2656 if (response.IsOKResponse())
2657 return 0;
2658 uint8_t error = response.GetError();
2659 if (error)
2660 return error;
2661 }
2662 return -1;
2663}
Greg Clayton32e0a752011-03-30 18:16:51 +00002664
Jim Ingham106d0282014-06-25 02:32:56 +00002665int
2666GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2667{
2668 char packet[32];
2669 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2670 assert (packet_len < (int)sizeof(packet));
2671 StringExtractorGDBRemote response;
2672 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2673 {
2674 if (response.IsOKResponse())
2675 return 0;
2676 uint8_t error = response.GetError();
2677 if (error)
2678 return error;
2679 }
2680 return -1;
2681}
2682
2683
Greg Clayton32e0a752011-03-30 18:16:51 +00002684bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002685GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002686{
2687 if (response.IsNormalResponse())
2688 {
2689 std::string name;
2690 std::string value;
2691 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002692
2693 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2694 uint32_t sub = 0;
2695 std::string vendor;
2696 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002697
2698 while (response.GetNameColonValue(name, value))
2699 {
2700 if (name.compare("pid") == 0)
2701 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002702 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002703 }
2704 else if (name.compare("ppid") == 0)
2705 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002706 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002707 }
2708 else if (name.compare("uid") == 0)
2709 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002710 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002711 }
2712 else if (name.compare("euid") == 0)
2713 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002714 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002715 }
2716 else if (name.compare("gid") == 0)
2717 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002718 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002719 }
2720 else if (name.compare("egid") == 0)
2721 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002722 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002723 }
2724 else if (name.compare("triple") == 0)
2725 {
Greg Clayton44272a42014-09-18 00:18:32 +00002726 StringExtractor extractor;
2727 extractor.GetStringRef().swap(value);
2728 extractor.SetFilePos(0);
2729 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002730 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002731 }
2732 else if (name.compare("name") == 0)
2733 {
2734 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002735 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002736 // control the characters in a process name
2737 extractor.GetStringRef().swap(value);
2738 extractor.SetFilePos(0);
2739 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002740 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002741 }
Jason Molenda89c37492014-01-27 22:23:20 +00002742 else if (name.compare("cputype") == 0)
2743 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002744 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002745 }
2746 else if (name.compare("cpusubtype") == 0)
2747 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002748 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002749 }
2750 else if (name.compare("vendor") == 0)
2751 {
2752 vendor = value;
2753 }
2754 else if (name.compare("ostype") == 0)
2755 {
2756 os_type = value;
2757 }
2758 }
2759
2760 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2761 {
2762 if (vendor == "apple")
2763 {
2764 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2765 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2766 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2767 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002768 }
2769
2770 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2771 return true;
2772 }
2773 return false;
2774}
2775
2776bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002777GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002778{
2779 process_info.Clear();
2780
2781 if (m_supports_qProcessInfoPID)
2782 {
2783 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002784 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002785 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002786 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002787 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002788 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002789 return DecodeProcessInfoResponse (response, process_info);
2790 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002791 else
2792 {
2793 m_supports_qProcessInfoPID = false;
2794 return false;
2795 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002796 }
2797 return false;
2798}
2799
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002800bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002801GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002802{
Todd Fiala3daa1762014-09-15 16:01:29 +00002803 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2804
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002805 if (allow_lazy)
2806 {
2807 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2808 return true;
2809 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2810 return false;
2811 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002812
2813 GetHostInfo ();
2814
2815 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002816 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002817 {
2818 if (response.IsNormalResponse())
2819 {
2820 std::string name;
2821 std::string value;
2822 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2823 uint32_t sub = 0;
2824 std::string arch_name;
2825 std::string os_name;
2826 std::string vendor_name;
2827 std::string triple;
2828 uint32_t pointer_byte_size = 0;
2829 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002830 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002831 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002832 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002833 while (response.GetNameColonValue(name, value))
2834 {
2835 if (name.compare("cputype") == 0)
2836 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002837 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002838 if (cpu != LLDB_INVALID_CPUTYPE)
2839 ++num_keys_decoded;
2840 }
2841 else if (name.compare("cpusubtype") == 0)
2842 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002843 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002844 if (sub != 0)
2845 ++num_keys_decoded;
2846 }
Todd Fialac540dd02014-08-26 18:21:02 +00002847 else if (name.compare("triple") == 0)
2848 {
Greg Clayton44272a42014-09-18 00:18:32 +00002849 StringExtractor extractor;
2850 extractor.GetStringRef().swap(value);
2851 extractor.SetFilePos(0);
2852 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002853 ++num_keys_decoded;
2854 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002855 else if (name.compare("ostype") == 0)
2856 {
2857 os_name.swap (value);
2858 ++num_keys_decoded;
2859 }
2860 else if (name.compare("vendor") == 0)
2861 {
2862 vendor_name.swap(value);
2863 ++num_keys_decoded;
2864 }
2865 else if (name.compare("endian") == 0)
2866 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002867 ++num_keys_decoded;
2868 if (value.compare("little") == 0)
2869 byte_order = eByteOrderLittle;
2870 else if (value.compare("big") == 0)
2871 byte_order = eByteOrderBig;
2872 else if (value.compare("pdp") == 0)
2873 byte_order = eByteOrderPDP;
2874 else
2875 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002876 }
2877 else if (name.compare("ptrsize") == 0)
2878 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002879 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002880 if (pointer_byte_size != 0)
2881 ++num_keys_decoded;
2882 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002883 else if (name.compare("pid") == 0)
2884 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002885 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002886 if (pid != LLDB_INVALID_PROCESS_ID)
2887 ++num_keys_decoded;
2888 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002889 }
2890 if (num_keys_decoded > 0)
2891 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002892 if (pid != LLDB_INVALID_PROCESS_ID)
2893 {
2894 m_curr_pid_is_valid = eLazyBoolYes;
2895 m_curr_pid = pid;
2896 }
Todd Fialac540dd02014-08-26 18:21:02 +00002897
2898 // Set the ArchSpec from the triple if we have it.
2899 if (!triple.empty ())
2900 {
2901 m_process_arch.SetTriple (triple.c_str ());
2902 if (pointer_byte_size)
2903 {
2904 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2905 }
2906 }
2907 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002908 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002909 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2910
2911 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2912 switch (triple.getObjectFormat()) {
2913 case llvm::Triple::MachO:
2914 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2915 break;
2916 case llvm::Triple::ELF:
2917 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2918 break;
2919 case llvm::Triple::COFF:
2920 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2921 break;
2922 case llvm::Triple::UnknownObjectFormat:
2923 if (log)
2924 log->Printf("error: failed to determine target architecture");
2925 return false;
2926 }
2927
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002928 if (pointer_byte_size)
2929 {
2930 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2931 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002932 if (byte_order != eByteOrderInvalid)
2933 {
2934 assert (byte_order == m_process_arch.GetByteOrder());
2935 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002936 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002937 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002938 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2939 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002940 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002941 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002942 }
2943 }
2944 else
2945 {
2946 m_qProcessInfo_is_valid = eLazyBoolNo;
2947 }
2948
2949 return false;
2950}
2951
2952
Greg Clayton32e0a752011-03-30 18:16:51 +00002953uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002954GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2955 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002956{
2957 process_infos.Clear();
2958
2959 if (m_supports_qfProcessInfo)
2960 {
2961 StreamString packet;
2962 packet.PutCString ("qfProcessInfo");
2963 if (!match_info.MatchAllProcesses())
2964 {
2965 packet.PutChar (':');
2966 const char *name = match_info.GetProcessInfo().GetName();
2967 bool has_name_match = false;
2968 if (name && name[0])
2969 {
2970 has_name_match = true;
2971 NameMatchType name_match_type = match_info.GetNameMatchType();
2972 switch (name_match_type)
2973 {
2974 case eNameMatchIgnore:
2975 has_name_match = false;
2976 break;
2977
2978 case eNameMatchEquals:
2979 packet.PutCString ("name_match:equals;");
2980 break;
2981
2982 case eNameMatchContains:
2983 packet.PutCString ("name_match:contains;");
2984 break;
2985
2986 case eNameMatchStartsWith:
2987 packet.PutCString ("name_match:starts_with;");
2988 break;
2989
2990 case eNameMatchEndsWith:
2991 packet.PutCString ("name_match:ends_with;");
2992 break;
2993
2994 case eNameMatchRegularExpression:
2995 packet.PutCString ("name_match:regex;");
2996 break;
2997 }
2998 if (has_name_match)
2999 {
3000 packet.PutCString ("name:");
3001 packet.PutBytesAsRawHex8(name, ::strlen(name));
3002 packet.PutChar (';');
3003 }
3004 }
3005
3006 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003007 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003008 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003009 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00003010 if (match_info.GetProcessInfo().UserIDIsValid())
3011 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
3012 if (match_info.GetProcessInfo().GroupIDIsValid())
3013 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003014 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
3015 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
3016 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3017 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
3018 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3019 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
3020 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
3021 {
3022 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
3023 const llvm::Triple &triple = match_arch.GetTriple();
3024 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00003025 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00003026 packet.PutChar (';');
3027 }
3028 }
3029 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00003030 // Increase timeout as the first qfProcessInfo packet takes a long time
3031 // on Android. The value of 1min was arrived at empirically.
3032 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00003033 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003034 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003035 do
3036 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003037 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00003038 if (!DecodeProcessInfoResponse (response, process_info))
3039 break;
3040 process_infos.Append(process_info);
3041 response.GetStringRef().clear();
3042 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00003043 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00003044 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003045 else
3046 {
3047 m_supports_qfProcessInfo = false;
3048 return 0;
3049 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003050 }
3051 return process_infos.GetSize();
3052
3053}
3054
3055bool
3056GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
3057{
3058 if (m_supports_qUserName)
3059 {
3060 char packet[32];
3061 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003062 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003063 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003064 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003065 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003066 if (response.IsNormalResponse())
3067 {
3068 // Make sure we parsed the right number of characters. The response is
3069 // the hex encoded user name and should make up the entire packet.
3070 // If there are any non-hex ASCII bytes, the length won't match below..
3071 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3072 return true;
3073 }
3074 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003075 else
3076 {
3077 m_supports_qUserName = false;
3078 return false;
3079 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003080 }
3081 return false;
3082
3083}
3084
3085bool
3086GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3087{
3088 if (m_supports_qGroupName)
3089 {
3090 char packet[32];
3091 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003092 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003093 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003094 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003095 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003096 if (response.IsNormalResponse())
3097 {
3098 // Make sure we parsed the right number of characters. The response is
3099 // the hex encoded group name and should make up the entire packet.
3100 // If there are any non-hex ASCII bytes, the length won't match below..
3101 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3102 return true;
3103 }
3104 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003105 else
3106 {
3107 m_supports_qGroupName = false;
3108 return false;
3109 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003110 }
3111 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003112}
Greg Clayton32e0a752011-03-30 18:16:51 +00003113
Ewan Crawford78baa192015-05-13 09:18:18 +00003114bool
3115GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3116{
3117 // Form non-stop packet request
3118 char packet[32];
3119 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3120 assert(packet_len < (int)sizeof(packet));
3121
3122 StringExtractorGDBRemote response;
3123 // Send to target
3124 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3125 if (response.IsOKResponse())
3126 return true;
3127
3128 // Failed or not supported
3129 return false;
3130
3131}
3132
Greg Claytone034a042015-05-21 20:52:06 +00003133static void
3134MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3135{
3136 packet.Clear();
3137 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3138 uint32_t bytes_left = send_size;
3139 while (bytes_left > 0)
3140 {
3141 if (bytes_left >= 26)
3142 {
3143 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3144 bytes_left -= 26;
3145 }
3146 else
3147 {
3148 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3149 bytes_left = 0;
3150 }
3151 }
3152}
3153
3154template<typename T>
3155T calculate_standard_deviation(const std::vector<T> &v)
3156{
3157 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3158 T mean = sum / (T)v.size();
3159 T accum = T(0);
3160 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3161 T delta = d - mean;
3162 accum += delta * delta;
3163 });
3164
3165 T stdev = sqrt(accum / (v.size()-1));
3166 return stdev;
3167}
3168
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003169void
Greg Claytone034a042015-05-21 20:52:06 +00003170GDBRemoteCommunicationClient::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 +00003171{
3172 uint32_t i;
3173 TimeValue start_time, end_time;
3174 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003175 if (SendSpeedTestPacket (0, 0))
3176 {
Greg Claytone034a042015-05-21 20:52:06 +00003177 StreamString packet;
3178 if (json)
3179 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3180 else
3181 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3182 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00003183
Greg Claytone034a042015-05-21 20:52:06 +00003184 uint32_t result_idx = 0;
3185 uint32_t send_size;
3186 std::vector<float> packet_times;
3187
3188 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3189 {
3190 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3191 {
3192 MakeSpeedTestPacket (packet, send_size, recv_size);
3193
3194 packet_times.clear();
3195 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00003196 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00003197 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00003198 {
Greg Claytone034a042015-05-21 20:52:06 +00003199 TimeValue packet_start_time = TimeValue::Now();
3200 StringExtractorGDBRemote response;
3201 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3202 TimeValue packet_end_time = TimeValue::Now();
3203 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3204 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003205 }
3206 end_time = TimeValue::Now();
3207 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00003208
3209 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3210 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3211 float average_ms_per_packet = total_ms / num_packets;
3212 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3213 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00003214 {
Greg Claytone034a042015-05-21 20:52:06 +00003215 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);
3216 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00003217 }
3218 else
3219 {
Greg Claytone034a042015-05-21 20:52:06 +00003220 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",
3221 send_size,
3222 recv_size,
3223 total_time_nsec / TimeValue::NanoSecPerSec,
3224 total_time_nsec % TimeValue::NanoSecPerSec,
3225 packets_per_second,
3226 average_ms_per_packet,
3227 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00003228 }
Greg Claytone034a042015-05-21 20:52:06 +00003229 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003230 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003231 }
Greg Claytone034a042015-05-21 20:52:06 +00003232
3233 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3234
3235 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3236 if (json)
3237 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3238 else
3239 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3240 strm.Flush();
3241 send_size = 0;
3242 result_idx = 0;
3243 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3244 {
3245 MakeSpeedTestPacket (packet, send_size, recv_size);
3246
3247 // If we have a receive size, test how long it takes to receive 4MB of data
3248 if (recv_size > 0)
3249 {
3250 start_time = TimeValue::Now();
3251 uint32_t bytes_read = 0;
3252 uint32_t packet_count = 0;
3253 while (bytes_read < k_recv_amount)
3254 {
3255 StringExtractorGDBRemote response;
3256 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3257 bytes_read += recv_size;
3258 ++packet_count;
3259 }
3260 end_time = TimeValue::Now();
3261 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3262 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3263 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3264 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3265 float average_ms_per_packet = total_ms / packet_count;
3266
3267 if (json)
3268 {
3269 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);
3270 ++result_idx;
3271 }
3272 else
3273 {
3274 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",
3275 send_size,
3276 recv_size,
3277 packet_count,
3278 k_recv_amount_mb,
3279 total_time_nsec / TimeValue::NanoSecPerSec,
3280 total_time_nsec % TimeValue::NanoSecPerSec,
3281 mb_second,
3282 packets_per_second,
3283 average_ms_per_packet);
3284 }
3285 strm.Flush();
3286 }
3287 }
3288 if (json)
3289 strm.Printf("\n ]\n }\n}\n");
3290 else
3291 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003292 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003293}
3294
3295bool
3296GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3297{
3298 StreamString packet;
3299 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3300 uint32_t bytes_left = send_size;
3301 while (bytes_left > 0)
3302 {
3303 if (bytes_left >= 26)
3304 {
3305 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3306 bytes_left -= 26;
3307 }
3308 else
3309 {
3310 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3311 bytes_left = 0;
3312 }
3313 }
3314
3315 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003316 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00003317}
Greg Clayton8b82f082011-04-12 05:54:46 +00003318
3319uint16_t
Greg Claytondbf04572013-12-04 19:40:33 +00003320GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
Greg Clayton8b82f082011-04-12 05:54:46 +00003321{
Daniel Maleae0f8f572013-08-26 23:57:52 +00003322 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00003323 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003324 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00003325 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003326 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00003327 if (remote_accept_hostname && remote_accept_hostname[0])
3328 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003329 else
3330 {
Zachary Turner97a14e62014-08-19 17:18:29 +00003331 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00003332 {
3333 // Make the GDB server we launch only accept connections from this host
3334 stream.Printf("host:%s;", hostname.c_str());
3335 }
3336 else
3337 {
3338 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3339 stream.Printf("host:*;");
3340 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003341 }
3342 const char *packet = stream.GetData();
3343 int packet_len = stream.GetSize();
3344
Vince Harron1b5a74e2015-01-21 22:42:49 +00003345 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003346 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
3347
3348 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003349 {
3350 std::string name;
3351 std::string value;
3352 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00003353 while (response.GetNameColonValue(name, value))
3354 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003355 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003356 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003357 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003358 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00003359 }
3360 return port;
3361 }
3362 return 0;
3363}
3364
3365bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003366GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3367{
3368 StreamString stream;
3369 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3370 const char *packet = stream.GetData();
3371 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003372
Daniel Maleae0f8f572013-08-26 23:57:52 +00003373 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003374 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003375 {
3376 if (response.IsOKResponse())
3377 return true;
3378 }
3379 return false;
3380}
3381
3382bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003383GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003384{
3385 if (m_curr_tid == tid)
3386 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003387
Greg Clayton8b82f082011-04-12 05:54:46 +00003388 char packet[32];
3389 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003390 if (tid == UINT64_MAX)
3391 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003392 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003393 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003394 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003395 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003396 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003397 {
3398 if (response.IsOKResponse())
3399 {
3400 m_curr_tid = tid;
3401 return true;
3402 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003403
3404 /*
3405 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
3406 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3407 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3408 */
3409 if (response.IsUnsupportedResponse() && IsConnected())
3410 {
3411 m_curr_tid = 1;
3412 return true;
3413 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003414 }
3415 return false;
3416}
3417
3418bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003419GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003420{
3421 if (m_curr_tid_run == tid)
3422 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003423
Greg Clayton8b82f082011-04-12 05:54:46 +00003424 char packet[32];
3425 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003426 if (tid == UINT64_MAX)
3427 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003428 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003429 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3430
Andy Gibbsa297a972013-06-19 19:04:53 +00003431 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003432 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003433 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003434 {
3435 if (response.IsOKResponse())
3436 {
3437 m_curr_tid_run = tid;
3438 return true;
3439 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003440
3441 /*
3442 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
3443 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3444 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3445 */
3446 if (response.IsUnsupportedResponse() && IsConnected())
3447 {
3448 m_curr_tid_run = 1;
3449 return true;
3450 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003451 }
3452 return false;
3453}
3454
3455bool
3456GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3457{
Greg Clayton3dedae12013-12-06 21:45:27 +00003458 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003459 return response.IsNormalResponse();
3460 return false;
3461}
3462
3463bool
Greg Claytonf402f782012-10-13 02:11:55 +00003464GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003465{
3466 if (m_supports_qThreadStopInfo)
3467 {
3468 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003469 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003470 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003471 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003472 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003473 if (response.IsUnsupportedResponse())
3474 m_supports_qThreadStopInfo = false;
3475 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003476 return true;
3477 else
3478 return false;
3479 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003480 else
3481 {
3482 m_supports_qThreadStopInfo = false;
3483 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003484 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003485 return false;
3486}
3487
3488
3489uint8_t
3490GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3491{
Todd Fiala616b8272014-10-09 00:55:04 +00003492 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3493 if (log)
3494 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3495 __FUNCTION__, insert ? "add" : "remove", addr);
3496
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003497 // Check if the stub is known not to support this breakpoint type
3498 if (!SupportsGDBStoppointPacket(type))
3499 return UINT8_MAX;
3500 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003501 char packet[64];
3502 const int packet_len = ::snprintf (packet,
3503 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003504 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003505 insert ? 'Z' : 'z',
3506 type,
3507 addr,
3508 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003509 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003510 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003511 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003512 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003513 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003514 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003515 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003516 if (response.IsOKResponse())
3517 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003518
3519 // Error while setting breakpoint, send back specific error
3520 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003521 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003522
3523 // Empty packet informs us that breakpoint is not supported
3524 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003525 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003526 // Disable this breakpoint type since it is unsupported
3527 switch (type)
3528 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003529 case eBreakpointSoftware: m_supports_z0 = false; break;
3530 case eBreakpointHardware: m_supports_z1 = false; break;
3531 case eWatchpointWrite: m_supports_z2 = false; break;
3532 case eWatchpointRead: m_supports_z3 = false; break;
3533 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003534 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003535 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003536 }
3537 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003538 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003539 return UINT8_MAX;
3540}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003541
3542size_t
3543GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3544 bool &sequence_mutex_unavailable)
3545{
3546 Mutex::Locker locker;
3547 thread_ids.clear();
3548
Jim Ingham4ceb9282012-06-08 22:50:40 +00003549 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003550 {
3551 sequence_mutex_unavailable = false;
3552 StringExtractorGDBRemote response;
3553
Greg Clayton3dedae12013-12-06 21:45:27 +00003554 PacketResult packet_result;
3555 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3556 packet_result == PacketResult::Success && response.IsNormalResponse();
3557 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003558 {
3559 char ch = response.GetChar();
3560 if (ch == 'l')
3561 break;
3562 if (ch == 'm')
3563 {
3564 do
3565 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003566 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003567
3568 if (tid != LLDB_INVALID_THREAD_ID)
3569 {
3570 thread_ids.push_back (tid);
3571 }
3572 ch = response.GetChar(); // Skip the command separator
3573 } while (ch == ','); // Make sure we got a comma separator
3574 }
3575 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003576
3577 /*
3578 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3579 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
3580 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
3581 * Assume pid=tid=1 in such cases.
3582 */
3583 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
3584 {
3585 thread_ids.push_back (1);
3586 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00003587 }
3588 else
3589 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003590#if defined (LLDB_CONFIGURATION_DEBUG)
3591 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3592#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003593 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003594 if (log)
3595 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003596#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003597 sequence_mutex_unavailable = true;
3598 }
3599 return thread_ids.size();
3600}
Greg Clayton37a0a242012-04-11 00:24:49 +00003601
3602lldb::addr_t
3603GDBRemoteCommunicationClient::GetShlibInfoAddr()
3604{
3605 if (!IsRunning())
3606 {
3607 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003608 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003609 {
3610 if (response.IsNormalResponse())
3611 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3612 }
3613 }
3614 return LLDB_INVALID_ADDRESS;
3615}
3616
Daniel Maleae0f8f572013-08-26 23:57:52 +00003617lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003618GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3619 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3620 int *status_ptr, // Pass NULL if you don't want the process exit status
3621 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3622 std::string *command_output, // Pass NULL if you don't want the command output
3623 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003624{
3625 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003626 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003627 stream.PutBytesAsRawHex8(command, strlen(command));
3628 stream.PutChar(',');
3629 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003630 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003631 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003632 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003633 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003634 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003635 }
3636 const char *packet = stream.GetData();
3637 int packet_len = stream.GetSize();
3638 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003639 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003640 {
3641 if (response.GetChar() != 'F')
3642 return Error("malformed reply");
3643 if (response.GetChar() != ',')
3644 return Error("malformed reply");
3645 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3646 if (exitcode == UINT32_MAX)
3647 return Error("unable to run remote process");
3648 else if (status_ptr)
3649 *status_ptr = exitcode;
3650 if (response.GetChar() != ',')
3651 return Error("malformed reply");
3652 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3653 if (signo_ptr)
3654 *signo_ptr = signo;
3655 if (response.GetChar() != ',')
3656 return Error("malformed reply");
3657 std::string output;
3658 response.GetEscapedBinaryData(output);
3659 if (command_output)
3660 command_output->assign(output);
3661 return Error();
3662 }
3663 return Error("unable to send packet");
3664}
3665
Greg Claytonfbb76342013-11-20 21:07:01 +00003666Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003667GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3668 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003669{
Chaoren Lind3173f32015-05-29 19:52:29 +00003670 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003671 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003672 stream.PutCString("qPlatform_mkdir:");
3673 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003674 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003675 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003676 const char *packet = stream.GetData();
3677 int packet_len = stream.GetSize();
3678 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003679
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003680 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3681 return Error("failed to send '%s' packet", packet);
3682
3683 if (response.GetChar() != 'F')
3684 return Error("invalid response to '%s' packet", packet);
3685
3686 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003687}
3688
Greg Claytonfbb76342013-11-20 21:07:01 +00003689Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003690GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3691 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003692{
Chaoren Lind3173f32015-05-29 19:52:29 +00003693 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003694 lldb_private::StreamString stream;
3695 stream.PutCString("qPlatform_chmod:");
3696 stream.PutHex32(file_permissions);
3697 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003698 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003699 const char *packet = stream.GetData();
3700 int packet_len = stream.GetSize();
3701 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003702
3703 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3704 return Error("failed to send '%s' packet", packet);
3705
3706 if (response.GetChar() != 'F')
3707 return Error("invalid response to '%s' packet", packet);
3708
Chaoren Lince36c4c2015-05-05 18:43:19 +00003709 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003710}
3711
Daniel Maleae0f8f572013-08-26 23:57:52 +00003712static uint64_t
3713ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3714 uint64_t fail_result,
3715 Error &error)
3716{
3717 response.SetFilePos(0);
3718 if (response.GetChar() != 'F')
3719 return fail_result;
3720 int32_t result = response.GetS32 (-2);
3721 if (result == -2)
3722 return fail_result;
3723 if (response.GetChar() == ',')
3724 {
3725 int result_errno = response.GetS32 (-2);
3726 if (result_errno != -2)
3727 error.SetError(result_errno, eErrorTypePOSIX);
3728 else
3729 error.SetError(-1, eErrorTypeGeneric);
3730 }
3731 else
3732 error.Clear();
3733 return result;
3734}
3735lldb::user_id_t
3736GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3737 uint32_t flags,
3738 mode_t mode,
3739 Error &error)
3740{
Chaoren Lind3173f32015-05-29 19:52:29 +00003741 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003742 lldb_private::StreamString stream;
3743 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003744 if (path.empty())
3745 return UINT64_MAX;
3746 stream.PutCStringAsRawHex8(path.c_str());
3747 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003748 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003749 stream.PutChar(',');
3750 stream.PutHex32(mode);
3751 const char* packet = stream.GetData();
3752 int packet_len = stream.GetSize();
3753 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003754 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003755 {
3756 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3757 }
3758 return UINT64_MAX;
3759}
3760
3761bool
3762GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3763 Error &error)
3764{
3765 lldb_private::StreamString stream;
3766 stream.Printf("vFile:close:%i", (int)fd);
3767 const char* packet = stream.GetData();
3768 int packet_len = stream.GetSize();
3769 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003770 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003771 {
3772 return ParseHostIOPacketResponse (response, -1, error) == 0;
3773 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003774 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003775}
3776
3777// Extension of host I/O packets to get the file size.
3778lldb::user_id_t
3779GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3780{
Chaoren Lind3173f32015-05-29 19:52:29 +00003781 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003782 lldb_private::StreamString stream;
3783 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003784 stream.PutCStringAsRawHex8(path.c_str());
3785 const char* packet = stream.GetData();
3786 int packet_len = stream.GetSize();
3787 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003788 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003789 {
3790 if (response.GetChar() != 'F')
3791 return UINT64_MAX;
3792 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3793 return retcode;
3794 }
3795 return UINT64_MAX;
3796}
3797
Greg Claytonfbb76342013-11-20 21:07:01 +00003798Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003799GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3800 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003801{
Chaoren Lind3173f32015-05-29 19:52:29 +00003802 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003803 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003804 lldb_private::StreamString stream;
3805 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003806 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003807 const char* packet = stream.GetData();
3808 int packet_len = stream.GetSize();
3809 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003810 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003811 {
3812 if (response.GetChar() != 'F')
3813 {
3814 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003815 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003816 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003817 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003818 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003819 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003820 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003821 if (response.GetChar() == ',')
3822 {
3823 int response_errno = response.GetS32(-1);
3824 if (response_errno > 0)
3825 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3826 else
3827 error.SetErrorToGenericError();
3828 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003829 else
3830 error.SetErrorToGenericError();
3831 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003832 else
3833 {
3834 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3835 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003836 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003837 }
3838 else
3839 {
3840 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3841 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003842 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003843}
3844
3845uint64_t
3846GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3847 uint64_t offset,
3848 void *dst,
3849 uint64_t dst_len,
3850 Error &error)
3851{
3852 lldb_private::StreamString stream;
3853 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3854 const char* packet = stream.GetData();
3855 int packet_len = stream.GetSize();
3856 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003857 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003858 {
3859 if (response.GetChar() != 'F')
3860 return 0;
3861 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3862 if (retcode == UINT32_MAX)
3863 return retcode;
3864 const char next = (response.Peek() ? *response.Peek() : 0);
3865 if (next == ',')
3866 return 0;
3867 if (next == ';')
3868 {
3869 response.GetChar(); // skip the semicolon
3870 std::string buffer;
3871 if (response.GetEscapedBinaryData(buffer))
3872 {
3873 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3874 if (data_to_write > 0)
3875 memcpy(dst, &buffer[0], data_to_write);
3876 return data_to_write;
3877 }
3878 }
3879 }
3880 return 0;
3881}
3882
3883uint64_t
3884GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3885 uint64_t offset,
3886 const void* src,
3887 uint64_t src_len,
3888 Error &error)
3889{
3890 lldb_private::StreamGDBRemote stream;
3891 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3892 stream.PutEscapedBytes(src, src_len);
3893 const char* packet = stream.GetData();
3894 int packet_len = stream.GetSize();
3895 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003896 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003897 {
3898 if (response.GetChar() != 'F')
3899 {
3900 error.SetErrorStringWithFormat("write file failed");
3901 return 0;
3902 }
3903 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3904 if (bytes_written == UINT64_MAX)
3905 {
3906 error.SetErrorToGenericError();
3907 if (response.GetChar() == ',')
3908 {
3909 int response_errno = response.GetS32(-1);
3910 if (response_errno > 0)
3911 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3912 }
3913 return 0;
3914 }
3915 return bytes_written;
3916 }
3917 else
3918 {
3919 error.SetErrorString ("failed to send vFile:pwrite packet");
3920 }
3921 return 0;
3922}
3923
Greg Claytonfbb76342013-11-20 21:07:01 +00003924Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003925GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003926{
Chaoren Lind3173f32015-05-29 19:52:29 +00003927 std::string src_path{src.GetPath(false)},
3928 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003929 Error error;
3930 lldb_private::StreamGDBRemote stream;
3931 stream.PutCString("vFile:symlink:");
3932 // the unix symlink() command reverses its parameters where the dst if first,
3933 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003934 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003935 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003936 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003937 const char* packet = stream.GetData();
3938 int packet_len = stream.GetSize();
3939 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003940 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003941 {
3942 if (response.GetChar() == 'F')
3943 {
3944 uint32_t result = response.GetU32(UINT32_MAX);
3945 if (result != 0)
3946 {
3947 error.SetErrorToGenericError();
3948 if (response.GetChar() == ',')
3949 {
3950 int response_errno = response.GetS32(-1);
3951 if (response_errno > 0)
3952 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3953 }
3954 }
3955 }
3956 else
3957 {
3958 // Should have returned with 'F<result>[,<errno>]'
3959 error.SetErrorStringWithFormat("symlink failed");
3960 }
3961 }
3962 else
3963 {
3964 error.SetErrorString ("failed to send vFile:symlink packet");
3965 }
3966 return error;
3967}
3968
3969Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003970GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00003971{
Chaoren Lind3173f32015-05-29 19:52:29 +00003972 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003973 Error error;
3974 lldb_private::StreamGDBRemote stream;
3975 stream.PutCString("vFile:unlink:");
3976 // the unix symlink() command reverses its parameters where the dst if first,
3977 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003978 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003979 const char* packet = stream.GetData();
3980 int packet_len = stream.GetSize();
3981 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003982 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003983 {
3984 if (response.GetChar() == 'F')
3985 {
3986 uint32_t result = response.GetU32(UINT32_MAX);
3987 if (result != 0)
3988 {
3989 error.SetErrorToGenericError();
3990 if (response.GetChar() == ',')
3991 {
3992 int response_errno = response.GetS32(-1);
3993 if (response_errno > 0)
3994 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3995 }
3996 }
3997 }
3998 else
3999 {
4000 // Should have returned with 'F<result>[,<errno>]'
4001 error.SetErrorStringWithFormat("unlink failed");
4002 }
4003 }
4004 else
4005 {
4006 error.SetErrorString ("failed to send vFile:unlink packet");
4007 }
4008 return error;
4009}
4010
Daniel Maleae0f8f572013-08-26 23:57:52 +00004011// Extension of host I/O packets to get whether a file exists.
4012bool
4013GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
4014{
Chaoren Lind3173f32015-05-29 19:52:29 +00004015 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004016 lldb_private::StreamString stream;
4017 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004018 stream.PutCStringAsRawHex8(path.c_str());
4019 const char* packet = stream.GetData();
4020 int packet_len = stream.GetSize();
4021 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004022 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004023 {
4024 if (response.GetChar() != 'F')
4025 return false;
4026 if (response.GetChar() != ',')
4027 return false;
4028 bool retcode = (response.GetChar() != '0');
4029 return retcode;
4030 }
4031 return false;
4032}
4033
4034bool
4035GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
4036 uint64_t &high,
4037 uint64_t &low)
4038{
Chaoren Lind3173f32015-05-29 19:52:29 +00004039 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004040 lldb_private::StreamString stream;
4041 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004042 stream.PutCStringAsRawHex8(path.c_str());
4043 const char* packet = stream.GetData();
4044 int packet_len = stream.GetSize();
4045 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004046 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004047 {
4048 if (response.GetChar() != 'F')
4049 return false;
4050 if (response.GetChar() != ',')
4051 return false;
4052 if (response.Peek() && *response.Peek() == 'x')
4053 return false;
4054 low = response.GetHexMaxU64(false, UINT64_MAX);
4055 high = response.GetHexMaxU64(false, UINT64_MAX);
4056 return true;
4057 }
4058 return false;
4059}
Greg Claytonf74cf862013-11-13 23:28:31 +00004060
4061bool
Jason Molendaa3329782014-03-29 18:54:20 +00004062GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
4063{
4064 // Some targets have issues with g/G packets and we need to avoid using them
4065 if (m_avoid_g_packets == eLazyBoolCalculate)
4066 {
4067 if (process)
4068 {
4069 m_avoid_g_packets = eLazyBoolNo;
4070 const ArchSpec &arch = process->GetTarget().GetArchitecture();
4071 if (arch.IsValid()
4072 && arch.GetTriple().getVendor() == llvm::Triple::Apple
4073 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00004074 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00004075 {
4076 m_avoid_g_packets = eLazyBoolYes;
4077 uint32_t gdb_server_version = GetGDBServerProgramVersion();
4078 if (gdb_server_version != 0)
4079 {
4080 const char *gdb_server_name = GetGDBServerProgramName();
4081 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
4082 {
4083 if (gdb_server_version >= 310)
4084 m_avoid_g_packets = eLazyBoolNo;
4085 }
4086 }
4087 }
4088 }
4089 }
4090 return m_avoid_g_packets == eLazyBoolYes;
4091}
4092
4093bool
Greg Claytonf74cf862013-11-13 23:28:31 +00004094GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4095{
4096 Mutex::Locker locker;
4097 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4098 {
4099 const bool thread_suffix_supported = GetThreadSuffixSupported();
4100
4101 if (thread_suffix_supported || SetCurrentThread(tid))
4102 {
4103 char packet[64];
4104 int packet_len = 0;
4105 if (thread_suffix_supported)
4106 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4107 else
4108 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4109 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004110 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004111 }
4112 }
4113 return false;
4114
4115}
4116
4117
4118bool
4119GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4120{
4121 Mutex::Locker locker;
4122 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4123 {
4124 const bool thread_suffix_supported = GetThreadSuffixSupported();
4125
4126 if (thread_suffix_supported || SetCurrentThread(tid))
4127 {
4128 char packet[64];
4129 int packet_len = 0;
4130 // Get all registers in one packet
4131 if (thread_suffix_supported)
4132 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4133 else
4134 packet_len = ::snprintf (packet, sizeof(packet), "g");
4135 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004136 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004137 }
4138 }
4139 return false;
4140}
4141bool
4142GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4143{
4144 save_id = 0; // Set to invalid save ID
4145 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4146 return false;
4147
4148 m_supports_QSaveRegisterState = eLazyBoolYes;
4149 Mutex::Locker locker;
4150 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4151 {
4152 const bool thread_suffix_supported = GetThreadSuffixSupported();
4153 if (thread_suffix_supported || SetCurrentThread(tid))
4154 {
4155 char packet[256];
4156 if (thread_suffix_supported)
4157 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4158 else
Ilia K686b1fe2015-02-27 19:43:08 +00004159 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00004160
4161 StringExtractorGDBRemote response;
4162
Greg Clayton3dedae12013-12-06 21:45:27 +00004163 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004164 {
4165 if (response.IsUnsupportedResponse())
4166 {
4167 // This packet isn't supported, don't try calling it again
4168 m_supports_QSaveRegisterState = eLazyBoolNo;
4169 }
4170
4171 const uint32_t response_save_id = response.GetU32(0);
4172 if (response_save_id != 0)
4173 {
4174 save_id = response_save_id;
4175 return true;
4176 }
4177 }
4178 }
4179 }
4180 return false;
4181}
4182
4183bool
4184GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4185{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004186 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00004187 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4188 // order to be useful
4189 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4190 return false;
4191
4192 Mutex::Locker locker;
4193 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4194 {
4195 const bool thread_suffix_supported = GetThreadSuffixSupported();
4196 if (thread_suffix_supported || SetCurrentThread(tid))
4197 {
4198 char packet[256];
4199 if (thread_suffix_supported)
4200 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4201 else
4202 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4203
4204 StringExtractorGDBRemote response;
4205
Greg Clayton3dedae12013-12-06 21:45:27 +00004206 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004207 {
4208 if (response.IsOKResponse())
4209 {
4210 return true;
4211 }
4212 else if (response.IsUnsupportedResponse())
4213 {
4214 // This packet isn't supported, don't try calling this packet or
4215 // QSaveRegisterState again...
4216 m_supports_QSaveRegisterState = eLazyBoolNo;
4217 }
4218 }
4219 }
4220 }
4221 return false;
4222}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004223
4224bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004225GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004226 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004227 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004228{
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00004229 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004230 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004231 return false;
4232
4233 StreamString packet;
4234 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004235 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004236 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00004237 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00004238 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004239
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004240 StringExtractorGDBRemote response;
4241 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4242 return false;
4243
Aidan Doddsdf627e72015-05-05 08:31:55 +00004244 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004245 return false;
4246
4247 std::string name;
4248 std::string value;
4249 bool success;
4250 StringExtractor extractor;
4251
4252 module_spec.Clear ();
4253 module_spec.GetFileSpec () = module_file_spec;
4254
4255 while (response.GetNameColonValue (name, value))
4256 {
4257 if (name == "uuid" || name == "md5")
4258 {
4259 extractor.GetStringRef ().swap (value);
4260 extractor.SetFilePos (0);
4261 extractor.GetHexByteString (value);
4262 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4263 }
4264 else if (name == "triple")
4265 {
4266 extractor.GetStringRef ().swap (value);
4267 extractor.SetFilePos (0);
4268 extractor.GetHexByteString (value);
4269 module_spec.GetArchitecture().SetTriple (value.c_str ());
4270 }
4271 else if (name == "file_offset")
4272 {
4273 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4274 if (success)
4275 module_spec.SetObjectOffset (ival);
4276 }
4277 else if (name == "file_size")
4278 {
4279 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4280 if (success)
4281 module_spec.SetObjectSize (ival);
4282 }
4283 else if (name == "file_path")
4284 {
4285 extractor.GetStringRef ().swap (value);
4286 extractor.SetFilePos (0);
4287 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00004288 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004289 }
4290 }
4291
4292 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004293}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004294
4295// query the target remote for extended information using the qXfer packet
4296//
4297// example: object='features', annex='target.xml', out=<xml output>
4298// return: 'true' on success
4299// 'false' on failure (err set)
4300bool
4301GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4302 const lldb_private::ConstString annex,
4303 std::string & out,
4304 lldb_private::Error & err) {
4305
4306 std::stringstream output;
4307 StringExtractorGDBRemote chunk;
4308
Greg Claytond04f0ed2015-05-26 18:00:51 +00004309 uint64_t size = GetRemoteMaxPacketSize();
4310 if (size == 0)
4311 size = 0x1000;
4312 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4313 int offset = 0;
4314 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004315
4316 // loop until all data has been read
4317 while ( active ) {
4318
4319 // send query extended feature packet
4320 std::stringstream packet;
4321 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00004322 << object.AsCString("") << ":read:"
4323 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00004324 << std::hex << offset << ","
4325 << std::hex << size;
4326
4327 GDBRemoteCommunication::PacketResult res =
4328 SendPacketAndWaitForResponse( packet.str().c_str(),
4329 chunk,
4330 false );
4331
4332 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4333 err.SetErrorString( "Error sending $qXfer packet" );
4334 return false;
4335 }
4336
4337 const std::string & str = chunk.GetStringRef( );
4338 if ( str.length() == 0 ) {
4339 // should have some data in chunk
4340 err.SetErrorString( "Empty response from $qXfer packet" );
4341 return false;
4342 }
4343
4344 // check packet code
4345 switch ( str[0] ) {
4346 // last chunk
4347 case ( 'l' ):
4348 active = false;
Aidan Doddsed9f6122015-04-29 10:08:17 +00004349 // fall through intentional
Colin Rileyc3c95b22015-04-16 15:51:33 +00004350
4351 // more chunks
4352 case ( 'm' ) :
4353 if ( str.length() > 1 )
4354 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00004355 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004356 break;
4357
4358 // unknown chunk
4359 default:
4360 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4361 return false;
4362 }
4363 }
4364
4365 out = output.str( );
4366 err.Success( );
4367 return true;
4368}
Greg Clayton0b90be12015-06-23 21:27:50 +00004369
4370// Notify the target that gdb is prepared to serve symbol lookup requests.
4371// packet: "qSymbol::"
4372// reply:
4373// OK The target does not need to look up any (more) symbols.
4374// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
4375// LLDB may provide the value by sending another qSymbol packet
4376// in the form of"qSymbol:<sym_value>:<sym_name>".
4377
4378void
4379GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4380{
4381 if (m_supports_qSymbol)
4382 {
4383 Mutex::Locker locker;
4384 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4385 {
4386 StreamString packet;
4387 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00004388 StringExtractorGDBRemote response;
4389 while (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00004390 {
Greg Clayton42b01482015-08-11 22:07:46 +00004391 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00004392 {
Greg Clayton42b01482015-08-11 22:07:46 +00004393 // We are done serving symbols requests
4394 return;
4395 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004396
Greg Clayton42b01482015-08-11 22:07:46 +00004397 if (response.IsUnsupportedResponse())
4398 {
4399 // qSymbol is not supported by the current GDB server we are connected to
4400 m_supports_qSymbol = false;
4401 return;
4402 }
4403 else
4404 {
4405 llvm::StringRef response_str(response.GetStringRef());
4406 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00004407 {
Greg Clayton42b01482015-08-11 22:07:46 +00004408 response.SetFilePos(strlen("qSymbol:"));
4409 std::string symbol_name;
4410 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00004411 {
Greg Clayton42b01482015-08-11 22:07:46 +00004412 if (symbol_name.empty())
4413 return;
4414
4415 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4416 lldb_private::SymbolContextList sc_list;
4417 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00004418 {
Greg Clayton42b01482015-08-11 22:07:46 +00004419 const size_t num_scs = sc_list.GetSize();
4420 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 +00004421 {
Greg Clayton42b01482015-08-11 22:07:46 +00004422 SymbolContext sc;
4423 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00004424 {
Greg Clayton42b01482015-08-11 22:07:46 +00004425 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00004426 {
Greg Clayton42b01482015-08-11 22:07:46 +00004427 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00004428 {
Greg Clayton42b01482015-08-11 22:07:46 +00004429 case eSymbolTypeInvalid:
4430 case eSymbolTypeAbsolute:
4431 case eSymbolTypeUndefined:
4432 case eSymbolTypeSourceFile:
4433 case eSymbolTypeHeaderFile:
4434 case eSymbolTypeObjectFile:
4435 case eSymbolTypeCommonBlock:
4436 case eSymbolTypeBlock:
4437 case eSymbolTypeLocal:
4438 case eSymbolTypeParam:
4439 case eSymbolTypeVariable:
4440 case eSymbolTypeVariableType:
4441 case eSymbolTypeLineEntry:
4442 case eSymbolTypeLineHeader:
4443 case eSymbolTypeScopeBegin:
4444 case eSymbolTypeScopeEnd:
4445 case eSymbolTypeAdditional:
4446 case eSymbolTypeCompiler:
4447 case eSymbolTypeInstrumentation:
4448 case eSymbolTypeTrampoline:
4449 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004450
Greg Clayton42b01482015-08-11 22:07:46 +00004451 case eSymbolTypeCode:
4452 case eSymbolTypeResolver:
4453 case eSymbolTypeData:
4454 case eSymbolTypeRuntime:
4455 case eSymbolTypeException:
4456 case eSymbolTypeObjCClass:
4457 case eSymbolTypeObjCMetaClass:
4458 case eSymbolTypeObjCIVar:
4459 case eSymbolTypeReExported:
4460 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4461 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004462 }
4463 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004464 }
4465 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004466 }
Greg Clayton42b01482015-08-11 22:07:46 +00004467 // This is the normal path where our symbol lookup was successful and we want
4468 // to send a packet with the new symbol value and see if another lookup needs to be
4469 // done.
4470
4471 // Change "packet" to contain the requested symbol value and name
4472 packet.Clear();
4473 packet.PutCString("qSymbol:");
4474 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4475 packet.Printf("%" PRIx64, symbol_load_addr);
4476 packet.PutCString(":");
4477 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4478 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00004479 }
4480 }
4481 }
4482 }
4483 // If we make it here, the symbol request packet response wasn't valid or
4484 // our symbol lookup failed so we must abort
4485 return;
4486
4487 }
4488 }
4489}
4490