blob: 63c1946dace90a708536ebb1b3c3dc3829eb2f52 [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),
Greg Clayton32e0a752011-03-30 18:16:51 +000090 m_supports_qProcessInfoPID (true),
91 m_supports_qfProcessInfo (true),
92 m_supports_qUserName (true),
93 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000094 m_supports_qThreadStopInfo (true),
95 m_supports_z0 (true),
96 m_supports_z1 (true),
97 m_supports_z2 (true),
98 m_supports_z3 (true),
99 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +0000100 m_supports_QEnvironment (true),
101 m_supports_QEnvironmentHexEncoded (true),
Greg Clayton0b90be12015-06-23 21:27:50 +0000102 m_supports_qSymbol (true),
Greg Clayton358cf1e2015-06-25 21:46:34 +0000103 m_supports_jThreadsInfo (true),
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000104 m_curr_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton8b82f082011-04-12 05:54:46 +0000105 m_curr_tid (LLDB_INVALID_THREAD_ID),
106 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +0000107 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +0000108 m_async_mutex (Mutex::eMutexTypeRecursive),
109 m_async_packet_predicate (false),
110 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +0000111 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +0000112 m_async_response (),
113 m_async_signal (-1),
Jim Inghamb8cd5752014-04-16 02:24:17 +0000114 m_interrupt_sent (false),
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000115 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +0000116 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000117 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +0000118 m_os_version_major (UINT32_MAX),
119 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000120 m_os_version_update (UINT32_MAX),
121 m_os_build (),
122 m_os_kernel (),
123 m_hostname (),
Jason Molendaa3329782014-03-29 18:54:20 +0000124 m_gdb_server_name(),
125 m_gdb_server_version(UINT32_MAX),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000126 m_default_packet_timeout (0),
127 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000128{
Greg Clayton576d8832011-03-22 04:00:09 +0000129}
130
131//----------------------------------------------------------------------
132// Destructor
133//----------------------------------------------------------------------
134GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
135{
Greg Clayton576d8832011-03-22 04:00:09 +0000136 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000137 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000138}
139
140bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000141GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
142{
Greg Claytonfb909312013-11-23 01:58:15 +0000143 ResetDiscoverableSettings();
144
Greg Clayton1cb64962011-03-24 04:28:38 +0000145 // Start the read thread after we send the handshake ack since if we
146 // fail to send the handshake ack, there is no reason to continue...
147 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000148 {
Ed Maste48f986f2013-12-18 15:31:45 +0000149 // Wait for any responses that might have been queued up in the remote
150 // GDB server and flush them all
151 StringExtractorGDBRemote response;
152 PacketResult packet_result = PacketResult::Success;
153 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
154 while (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000155 packet_result = ReadPacket (response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000156
Greg Claytonfb909312013-11-23 01:58:15 +0000157 // The return value from QueryNoAckModeSupported() is true if the packet
158 // was sent and _any_ response (including UNIMPLEMENTED) was received),
159 // or false if no response was received. This quickly tells us if we have
160 // a live connection to a remote GDB server...
161 if (QueryNoAckModeSupported())
162 {
163 return true;
164 }
165 else
166 {
167 if (error_ptr)
168 error_ptr->SetErrorString("failed to get reply to handshake packet");
169 }
170 }
171 else
172 {
173 if (error_ptr)
174 error_ptr->SetErrorString("failed to send the handshake ack");
175 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000176 return false;
177}
178
Greg Claytonfb909312013-11-23 01:58:15 +0000179bool
Greg Claytonb30c50c2015-05-29 00:01:55 +0000180GDBRemoteCommunicationClient::GetEchoSupported ()
181{
182 if (m_supports_qEcho == eLazyBoolCalculate)
183 {
184 GetRemoteQSupported();
185 }
186 return m_supports_qEcho == eLazyBoolYes;
187}
188
189
190bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000191GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
192{
193 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
194 {
195 GetRemoteQSupported();
196 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000197 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000198}
199
200bool
201GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
202{
203 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
204 {
205 GetRemoteQSupported();
206 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000207 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000208}
209
210bool
211GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
212{
213 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
214 {
215 GetRemoteQSupported();
216 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000217 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000218}
219
Steve Pucci03904ac2014-03-04 23:18:46 +0000220bool
221GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
222{
223 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
224 {
225 GetRemoteQSupported();
226 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000227 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000228}
229
Colin Rileyc3c95b22015-04-16 15:51:33 +0000230bool
231GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
232{
233 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
234 {
235 GetRemoteQSupported();
236 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000237 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000238}
239
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000240uint64_t
241GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
242{
243 if (m_max_packet_size == 0)
244 {
245 GetRemoteQSupported();
246 }
247 return m_max_packet_size;
248}
249
250bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000251GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000252{
253 if (m_supports_not_sending_acks == eLazyBoolCalculate)
254 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000255 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000256 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000257
Jason Molenda36a216e2014-07-24 01:36:24 +0000258 // This is the first real packet that we'll send in a debug session and it may take a little
259 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
260
261 const uint32_t minimum_timeout = 6;
262 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000263 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000264
Greg Clayton1cb64962011-03-24 04:28:38 +0000265 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000266 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000267 {
268 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000269 {
270 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000271 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000272 }
Greg Claytonfb909312013-11-23 01:58:15 +0000273 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000274 }
275 }
Greg Claytonfb909312013-11-23 01:58:15 +0000276 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000277}
278
279void
Greg Clayton44633992012-04-10 03:22:03 +0000280GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
281{
282 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
283 {
284 m_supports_threads_in_stop_reply = eLazyBoolNo;
285
286 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000287 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000288 {
289 if (response.IsOKResponse())
290 m_supports_threads_in_stop_reply = eLazyBoolYes;
291 }
292 }
293}
294
Jim Inghamcd16df92012-07-20 21:37:13 +0000295bool
296GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
297{
298 if (m_attach_or_wait_reply == eLazyBoolCalculate)
299 {
300 m_attach_or_wait_reply = eLazyBoolNo;
301
302 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000303 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000304 {
305 if (response.IsOKResponse())
306 m_attach_or_wait_reply = eLazyBoolYes;
307 }
308 }
309 if (m_attach_or_wait_reply == eLazyBoolYes)
310 return true;
311 else
312 return false;
313}
314
Jim Ingham279ceec2012-07-25 21:12:43 +0000315bool
316GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
317{
318 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
319 {
320 m_prepare_for_reg_writing_reply = eLazyBoolNo;
321
322 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000323 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000324 {
325 if (response.IsOKResponse())
326 m_prepare_for_reg_writing_reply = eLazyBoolYes;
327 }
328 }
329 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
330 return true;
331 else
332 return false;
333}
334
Greg Clayton44633992012-04-10 03:22:03 +0000335
336void
Greg Clayton576d8832011-03-22 04:00:09 +0000337GDBRemoteCommunicationClient::ResetDiscoverableSettings()
338{
339 m_supports_not_sending_acks = eLazyBoolCalculate;
340 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000341 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000342 m_supports_vCont_c = eLazyBoolCalculate;
343 m_supports_vCont_C = eLazyBoolCalculate;
344 m_supports_vCont_s = eLazyBoolCalculate;
345 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000346 m_supports_p = eLazyBoolCalculate;
Jason Molendabdc4f122014-05-06 02:59:39 +0000347 m_supports_x = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000348 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000349 m_qHostInfo_is_valid = eLazyBoolCalculate;
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000350 m_curr_pid_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000351 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000352 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000353 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000354 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000355 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
356 m_attach_or_wait_reply = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000357 m_avoid_g_packets = eLazyBoolCalculate;
Steve Pucci03904ac2014-03-04 23:18:46 +0000358 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000359 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
360 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000361 m_supports_qXfer_features_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000362 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000363
Greg Clayton32e0a752011-03-30 18:16:51 +0000364 m_supports_qProcessInfoPID = true;
365 m_supports_qfProcessInfo = true;
366 m_supports_qUserName = true;
367 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000368 m_supports_qThreadStopInfo = true;
369 m_supports_z0 = true;
370 m_supports_z1 = true;
371 m_supports_z2 = true;
372 m_supports_z3 = true;
373 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000374 m_supports_QEnvironment = true;
375 m_supports_QEnvironmentHexEncoded = true;
Greg Clayton0b90be12015-06-23 21:27:50 +0000376 m_supports_qSymbol = true;
Jason Molendaa3329782014-03-29 18:54:20 +0000377
Greg Claytond314e812011-03-23 00:09:55 +0000378 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000379 m_process_arch.Clear();
Jason Molendaa3329782014-03-29 18:54:20 +0000380 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;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000389
390 m_max_packet_size = 0;
Greg Clayton576d8832011-03-22 04:00:09 +0000391}
392
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000393void
394GDBRemoteCommunicationClient::GetRemoteQSupported ()
395{
396 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000397 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000398 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000399 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000400 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000401 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000402 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
403
Colin Rileyc3c95b22015-04-16 15:51:33 +0000404 // build the qSupported packet
405 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
406 StreamString packet;
407 packet.PutCString( "qSupported" );
408 for ( uint32_t i = 0; i < features.size( ); ++i )
409 {
410 packet.PutCString( i==0 ? ":" : ";");
411 packet.PutCString( features[i].c_str( ) );
412 }
413
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000414 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000415 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000416 response,
417 /*send_async=*/false) == PacketResult::Success)
418 {
419 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000420 if (::strstr (response_cstr, "qXfer:auxv:read+"))
421 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000422 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
423 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
424 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
425 {
426 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
427 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
428 }
429 if (::strstr (response_cstr, "qXfer:libraries:read+"))
430 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000431 if (::strstr (response_cstr, "qXfer:features:read+"))
432 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000433
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000434
435 // Look for a list of compressions in the features list e.g.
436 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
437 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
438 if (features_list)
439 {
440 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
441 if (compressions)
442 {
443 std::vector<std::string> supported_compressions;
444 compressions += sizeof ("SupportedCompressions=") - 1;
445 const char *end_of_compressions = strchr (compressions, ';');
446 if (end_of_compressions == NULL)
447 {
448 end_of_compressions = strchr (compressions, '\0');
449 }
450 const char *current_compression = compressions;
451 while (current_compression < end_of_compressions)
452 {
453 const char *next_compression_name = strchr (current_compression, ',');
454 const char *end_of_this_word = next_compression_name;
455 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
456 {
457 end_of_this_word = end_of_compressions;
458 }
459
460 if (end_of_this_word)
461 {
462 if (end_of_this_word == current_compression)
463 {
464 current_compression++;
465 }
466 else
467 {
468 std::string this_compression (current_compression, end_of_this_word - current_compression);
469 supported_compressions.push_back (this_compression);
470 current_compression = end_of_this_word + 1;
471 }
472 }
473 else
474 {
475 supported_compressions.push_back (current_compression);
476 current_compression = end_of_compressions;
477 }
478 }
479
480 if (supported_compressions.size() > 0)
481 {
482 MaybeEnableCompression (supported_compressions);
483 }
484 }
485 }
486
Greg Claytonb30c50c2015-05-29 00:01:55 +0000487 if (::strstr (response_cstr, "qEcho"))
488 m_supports_qEcho = eLazyBoolYes;
489 else
490 m_supports_qEcho = eLazyBoolNo;
491
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000492 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
493 if (packet_size_str)
494 {
495 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
496 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
497 if (m_max_packet_size == 0)
498 {
499 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
500 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
501 if (log)
502 log->Printf ("Garbled PacketSize spec in qSupported response");
503 }
504 }
505 }
506}
Greg Clayton576d8832011-03-22 04:00:09 +0000507
508bool
509GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
510{
511 if (m_supports_thread_suffix == eLazyBoolCalculate)
512 {
513 StringExtractorGDBRemote response;
514 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000515 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000516 {
517 if (response.IsOKResponse())
518 m_supports_thread_suffix = eLazyBoolYes;
519 }
520 }
521 return m_supports_thread_suffix;
522}
523bool
524GDBRemoteCommunicationClient::GetVContSupported (char flavor)
525{
526 if (m_supports_vCont_c == eLazyBoolCalculate)
527 {
528 StringExtractorGDBRemote response;
529 m_supports_vCont_any = eLazyBoolNo;
530 m_supports_vCont_all = eLazyBoolNo;
531 m_supports_vCont_c = eLazyBoolNo;
532 m_supports_vCont_C = eLazyBoolNo;
533 m_supports_vCont_s = eLazyBoolNo;
534 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000535 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000536 {
537 const char *response_cstr = response.GetStringRef().c_str();
538 if (::strstr (response_cstr, ";c"))
539 m_supports_vCont_c = eLazyBoolYes;
540
541 if (::strstr (response_cstr, ";C"))
542 m_supports_vCont_C = eLazyBoolYes;
543
544 if (::strstr (response_cstr, ";s"))
545 m_supports_vCont_s = eLazyBoolYes;
546
547 if (::strstr (response_cstr, ";S"))
548 m_supports_vCont_S = eLazyBoolYes;
549
550 if (m_supports_vCont_c == eLazyBoolYes &&
551 m_supports_vCont_C == eLazyBoolYes &&
552 m_supports_vCont_s == eLazyBoolYes &&
553 m_supports_vCont_S == eLazyBoolYes)
554 {
555 m_supports_vCont_all = eLazyBoolYes;
556 }
557
558 if (m_supports_vCont_c == eLazyBoolYes ||
559 m_supports_vCont_C == eLazyBoolYes ||
560 m_supports_vCont_s == eLazyBoolYes ||
561 m_supports_vCont_S == eLazyBoolYes)
562 {
563 m_supports_vCont_any = eLazyBoolYes;
564 }
565 }
566 }
567
568 switch (flavor)
569 {
570 case 'a': return m_supports_vCont_any;
571 case 'A': return m_supports_vCont_all;
572 case 'c': return m_supports_vCont_c;
573 case 'C': return m_supports_vCont_C;
574 case 's': return m_supports_vCont_s;
575 case 'S': return m_supports_vCont_S;
576 default: break;
577 }
578 return false;
579}
580
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000581// Check if the target supports 'p' packet. It sends out a 'p'
582// packet and checks the response. A normal packet will tell us
583// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000584//
585// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000586bool
Sean Callananb1de1142013-09-04 23:24:15 +0000587GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000588{
589 if (m_supports_p == eLazyBoolCalculate)
590 {
591 StringExtractorGDBRemote response;
592 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000593 char packet[256];
594 if (GetThreadSuffixSupported())
595 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
596 else
597 snprintf(packet, sizeof(packet), "p0");
598
Greg Clayton3dedae12013-12-06 21:45:27 +0000599 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000600 {
601 if (response.IsNormalResponse())
602 m_supports_p = eLazyBoolYes;
603 }
604 }
605 return m_supports_p;
606}
Greg Clayton576d8832011-03-22 04:00:09 +0000607
Greg Clayton358cf1e2015-06-25 21:46:34 +0000608StructuredData::ObjectSP
609GDBRemoteCommunicationClient::GetThreadsInfo()
610{
611 // Get information on all threads at one using the "jThreadsInfo" packet
612 StructuredData::ObjectSP object_sp;
613
614 if (m_supports_jThreadsInfo)
615 {
616 StringExtractorGDBRemote response;
617 m_supports_jThreadExtendedInfo = eLazyBoolNo;
618 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
619 {
620 if (response.IsUnsupportedResponse())
621 {
622 m_supports_jThreadsInfo = false;
623 }
624 else if (!response.Empty())
625 {
626 object_sp = StructuredData::ParseJSON (response.GetStringRef());
627 }
628 }
629 }
630 return object_sp;
631}
632
633
Jason Molendabdc4f122014-05-06 02:59:39 +0000634bool
Jason Molenda705b1802014-06-13 02:37:02 +0000635GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
636{
637 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
638 {
639 StringExtractorGDBRemote response;
640 m_supports_jThreadExtendedInfo = eLazyBoolNo;
641 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
642 {
643 if (response.IsOKResponse())
644 {
645 m_supports_jThreadExtendedInfo = eLazyBoolYes;
646 }
647 }
648 }
649 return m_supports_jThreadExtendedInfo;
650}
651
652bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000653GDBRemoteCommunicationClient::GetxPacketSupported ()
654{
655 if (m_supports_x == eLazyBoolCalculate)
656 {
657 StringExtractorGDBRemote response;
658 m_supports_x = eLazyBoolNo;
659 char packet[256];
660 snprintf (packet, sizeof (packet), "x0,0");
661 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
662 {
663 if (response.IsOKResponse())
664 m_supports_x = eLazyBoolYes;
665 }
666 }
667 return m_supports_x;
668}
669
Greg Clayton3dedae12013-12-06 21:45:27 +0000670GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000671GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
672(
673 const char *payload_prefix,
674 std::string &response_string
675)
676{
677 Mutex::Locker locker;
678 if (!GetSequenceMutex(locker,
679 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
680 {
681 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
682 if (log)
683 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
684 payload_prefix);
685 return PacketResult::ErrorNoSequenceLock;
686 }
687
688 response_string = "";
689 std::string payload_prefix_str(payload_prefix);
690 unsigned int response_size = 0x1000;
691 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
692 response_size = GetRemoteMaxPacketSize();
693 }
694
695 for (unsigned int offset = 0; true; offset += response_size)
696 {
697 StringExtractorGDBRemote this_response;
698 // Construct payload
699 char sizeDescriptor[128];
700 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
701 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
702 this_response,
703 /*send_async=*/false);
704 if (result != PacketResult::Success)
705 return result;
706
707 const std::string &this_string = this_response.GetStringRef();
708
709 // Check for m or l as first character; l seems to mean this is the last chunk
710 char first_char = *this_string.c_str();
711 if (first_char != 'm' && first_char != 'l')
712 {
713 return PacketResult::ErrorReplyInvalid;
714 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000715 // Concatenate the result so far (skipping 'm' or 'l')
716 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000717 if (first_char == 'l')
718 // We're done
719 return PacketResult::Success;
720 }
721}
722
723GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000724GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
725(
726 const char *payload,
727 StringExtractorGDBRemote &response,
728 bool send_async
729)
730{
731 return SendPacketAndWaitForResponse (payload,
732 ::strlen (payload),
733 response,
734 send_async);
735}
736
Greg Clayton3dedae12013-12-06 21:45:27 +0000737GDBRemoteCommunicationClient::PacketResult
738GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
739 size_t payload_length,
740 StringExtractorGDBRemote &response)
741{
742 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
743 if (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000744 packet_result = ReadPacket (response, GetPacketTimeoutInMicroSeconds (), true);
Greg Clayton3dedae12013-12-06 21:45:27 +0000745 return packet_result;
746}
747
748GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000749GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
750(
751 const char *payload,
752 size_t payload_length,
753 StringExtractorGDBRemote &response,
754 bool send_async
755)
756{
Greg Clayton3dedae12013-12-06 21:45:27 +0000757 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000758 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000759 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000760
761 // In order to stop async notifications from being processed in the middle of the
762 // send/recieve sequence Hijack the broadcast. Then rebroadcast any events when we are done.
763 static Listener hijack_listener("lldb.NotifyHijacker");
764 HijackBroadcaster(&hijack_listener, eBroadcastBitGdbReadThreadGotNotify);
765
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000766 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000767 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000768 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000769 }
770 else
771 {
772 if (send_async)
773 {
Greg Claytond3544052012-05-31 21:24:20 +0000774 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000775 {
Greg Claytond3544052012-05-31 21:24:20 +0000776 Mutex::Locker async_locker (m_async_mutex);
777 m_async_packet.assign(payload, payload_length);
778 m_async_packet_predicate.SetValue (true, eBroadcastNever);
779
780 if (log)
781 log->Printf ("async: async packet = %s", m_async_packet.c_str());
782
783 bool timed_out = false;
784 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000785 {
Greg Claytond3544052012-05-31 21:24:20 +0000786 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000787 {
Jim Inghambabfc382012-06-06 00:32:39 +0000788 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000789 TimeValue timeout_time;
790 timeout_time = TimeValue::Now();
791 timeout_time.OffsetWithSeconds (m_packet_timeout);
792
Greg Clayton576d8832011-03-22 04:00:09 +0000793 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000794 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000795
Greg Claytond3544052012-05-31 21:24:20 +0000796 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000797 {
Greg Claytond3544052012-05-31 21:24:20 +0000798 if (log)
799 log->Printf ("async: got response");
800
801 // Swap the response buffer to avoid malloc and string copy
802 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000803 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000804 }
805 else
806 {
807 if (log)
808 log->Printf ("async: timed out waiting for response");
809 }
810
811 // Make sure we wait until the continue packet has been sent again...
812 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
813 {
814 if (log)
815 {
816 if (timed_out)
817 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
818 else
819 log->Printf ("async: async packet sent");
820 }
821 }
822 else
823 {
824 if (log)
825 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000826 }
827 }
828 else
829 {
Greg Claytond3544052012-05-31 21:24:20 +0000830 // We had a racy condition where we went to send the interrupt
831 // yet we were able to get the lock, so the process must have
832 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000833 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000834 log->Printf ("async: got lock without sending interrupt");
835 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000836 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000837 }
838 }
839 else
840 {
Greg Clayton644247c2011-07-07 01:59:51 +0000841 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000842 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000843 }
844 }
845 else
846 {
847 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000848 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000849 }
850 }
851 else
852 {
853 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000854 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000855 }
856 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000857
858 // Remove our Hijacking listner from the broadcast.
859 RestoreBroadcaster();
860
861 // If a notification event occured, rebroadcast since it can now be processed safely.
862 EventSP event_sp;
863 if (hijack_listener.GetNextEvent(event_sp))
864 BroadcastEvent(event_sp);
865
Greg Clayton3dedae12013-12-06 21:45:27 +0000866 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000867}
868
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000869static const char *end_delimiter = "--end--;";
870static const int end_delimiter_len = 8;
871
872std::string
873GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
874( ProcessGDBRemote *process,
875 StringExtractorGDBRemote& profileDataExtractor
876)
877{
878 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
879 std::stringstream final_output;
880 std::string name, value;
881
882 // Going to assuming thread_used_usec comes first, else bail out.
883 while (profileDataExtractor.GetNameColonValue(name, value))
884 {
885 if (name.compare("thread_used_id") == 0)
886 {
887 StringExtractor threadIDHexExtractor(value.c_str());
888 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
889
890 bool has_used_usec = false;
891 uint32_t curr_used_usec = 0;
892 std::string usec_name, usec_value;
893 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
894 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
895 {
896 if (usec_name.compare("thread_used_usec") == 0)
897 {
898 has_used_usec = true;
899 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
900 }
901 else
902 {
903 // We didn't find what we want, it is probably
904 // an older version. Bail out.
905 profileDataExtractor.SetFilePos(input_file_pos);
906 }
907 }
908
909 if (has_used_usec)
910 {
911 uint32_t prev_used_usec = 0;
912 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
913 if (iterator != m_thread_id_to_used_usec_map.end())
914 {
915 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
916 }
917
918 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
919 // A good first time record is one that runs for at least 0.25 sec
920 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
921 bool good_subsequent_time = (prev_used_usec > 0) &&
922 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
923
924 if (good_first_time || good_subsequent_time)
925 {
926 // We try to avoid doing too many index id reservation,
927 // resulting in fast increase of index ids.
928
929 final_output << name << ":";
930 int32_t index_id = process->AssignIndexIDToThread(thread_id);
931 final_output << index_id << ";";
932
933 final_output << usec_name << ":" << usec_value << ";";
934 }
935 else
936 {
937 // Skip past 'thread_used_name'.
938 std::string local_name, local_value;
939 profileDataExtractor.GetNameColonValue(local_name, local_value);
940 }
941
942 // Store current time as previous time so that they can be compared later.
943 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
944 }
945 else
946 {
947 // Bail out and use old string.
948 final_output << name << ":" << value << ";";
949 }
950 }
951 else
952 {
953 final_output << name << ":" << value << ";";
954 }
955 }
956 final_output << end_delimiter;
957 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
958
959 return final_output.str();
960}
961
Ewan Crawford76df2882015-06-23 12:32:06 +0000962bool
963GDBRemoteCommunicationClient::SendvContPacket
964(
965 ProcessGDBRemote *process,
966 const char *payload,
967 size_t packet_length,
968 StringExtractorGDBRemote &response
969)
970{
971
972 m_curr_tid = LLDB_INVALID_THREAD_ID;
973 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
974 if (log)
975 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
976
977 // we want to lock down packet sending while we continue
978 Mutex::Locker locker(m_sequence_mutex);
979
980 // here we broadcast this before we even send the packet!!
981 // this signals doContinue() to exit
982 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
983
984 // set the public state to running
985 m_public_is_running.SetValue(true, eBroadcastNever);
986
987 // Set the starting continue packet into "continue_packet". This packet
988 // may change if we are interrupted and we continue after an async packet...
989 std::string continue_packet(payload, packet_length);
990
991 if (log)
992 log->Printf("GDBRemoteCommunicationClient::%s () sending vCont packet: %s", __FUNCTION__, continue_packet.c_str());
993
994 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
995 return false;
996
997 // set the private state to running and broadcast this
998 m_private_is_running.SetValue(true, eBroadcastAlways);
999
1000 if (log)
1001 log->Printf("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1002
1003 // wait for the response to the vCont
1004 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1005 {
1006 if (response.IsOKResponse())
1007 return true;
1008 }
1009
1010 return false;
1011}
1012
Greg Clayton576d8832011-03-22 04:00:09 +00001013StateType
1014GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
1015(
1016 ProcessGDBRemote *process,
1017 const char *payload,
1018 size_t packet_length,
1019 StringExtractorGDBRemote &response
1020)
1021{
Greg Clayton1f5181a2012-07-02 22:05:25 +00001022 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +00001023 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +00001024 if (log)
1025 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1026
1027 Mutex::Locker locker(m_sequence_mutex);
1028 StateType state = eStateRunning;
1029
1030 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1031 m_public_is_running.SetValue (true, eBroadcastNever);
1032 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +00001033 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +00001034 std::string continue_packet(payload, packet_length);
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001035
1036 const auto sigstop_signo = process->GetUnixSignals().GetSignalNumberFromName("SIGSTOP");
1037 const auto sigint_signo = process->GetUnixSignals().GetSignalNumberFromName("SIGINT");
1038
Greg Clayton3f875c52013-02-22 22:23:55 +00001039 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +00001040
Greg Clayton576d8832011-03-22 04:00:09 +00001041 while (state == eStateRunning)
1042 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001043 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +00001044 {
1045 if (log)
1046 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +00001047 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +00001048 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +00001049 else
1050 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001051
Greg Claytone889ad62011-10-27 22:04:16 +00001052 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +00001053 }
1054
Greg Clayton3f875c52013-02-22 22:23:55 +00001055 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001056
1057 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001058 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001059
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001060 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001061 {
1062 if (response.Empty())
1063 state = eStateInvalid;
1064 else
1065 {
1066 const char stop_type = response.GetChar();
1067 if (log)
1068 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
1069 switch (stop_type)
1070 {
1071 case 'T':
1072 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +00001073 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001074 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +00001075 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001076 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
1077 {
1078 lldb::pid_t pid = GetCurrentProcessID ();
1079 if (pid != LLDB_INVALID_PROCESS_ID)
1080 process->SetID (pid);
1081 }
1082 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +00001083 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001084
1085 // Privately notify any internal threads that we have stopped
1086 // in case we wanted to interrupt our process, yet we might
1087 // send a packet and continue without returning control to the
1088 // user.
1089 m_private_is_running.SetValue (false, eBroadcastAlways);
1090
1091 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1092
Jim Inghambabfc382012-06-06 00:32:39 +00001093 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1094 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +00001095 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001096 // We sent an interrupt packet to stop the inferior process
1097 // for an async signal or to send an async packet while running
1098 // but we might have been single stepping and received the
1099 // stop packet for the step instead of for the interrupt packet.
1100 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1101 // is used, so if we get anything else, we need to try and
1102 // get another stop reply packet that may have been sent
1103 // due to sending the interrupt when the target is stopped
1104 // which will just re-send a copy of the last stop reply
1105 // packet. If we don't do this, then the reply for our
1106 // async packet will be the repeat stop reply packet and cause
1107 // a lot of trouble for us!
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001108 if (signo != sigint_signo && signo != sigstop_signo)
Greg Clayton2687cd12012-03-29 01:55:41 +00001109 {
Greg Claytonfb72fde2012-05-15 02:50:49 +00001110 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001111
1112 // We didn't get a a SIGINT or SIGSTOP, so try for a
1113 // very brief time (1 ms) to get another stop reply
1114 // packet to make sure it doesn't get in the way
1115 StringExtractorGDBRemote extra_stop_reply_packet;
1116 uint32_t timeout_usec = 1000;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001117 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +00001118 {
1119 switch (extra_stop_reply_packet.GetChar())
1120 {
1121 case 'T':
1122 case 'S':
1123 // We did get an extra stop reply, which means
1124 // our interrupt didn't stop the target so we
1125 // shouldn't continue after the async signal
1126 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +00001127 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001128 break;
1129 }
1130 }
1131 }
1132 }
1133
1134 if (m_async_signal != -1)
1135 {
1136 if (log)
1137 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1138
1139 // Save off the async signal we are supposed to send
1140 const int async_signal = m_async_signal;
1141 // Clear the async signal member so we don't end up
1142 // sending the signal multiple times...
1143 m_async_signal = -1;
1144 // Check which signal we stopped with
1145 if (signo == async_signal)
1146 {
1147 if (log)
1148 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1149
1150 // We already stopped with a signal that we wanted
1151 // to stop with, so we are done
1152 }
1153 else
1154 {
1155 // We stopped with a different signal that the one
1156 // we wanted to stop with, so now we must resume
1157 // with the signal we want
1158 char signal_packet[32];
1159 int signal_packet_len = 0;
1160 signal_packet_len = ::snprintf (signal_packet,
1161 sizeof (signal_packet),
1162 "C%2.2x",
1163 async_signal);
1164
1165 if (log)
1166 log->Printf ("async: stopped with signal %s, resume with %s",
1167 Host::GetSignalAsCString (signo),
1168 Host::GetSignalAsCString (async_signal));
1169
1170 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001171 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001172 continue_packet.assign(signal_packet, signal_packet_len);
1173 continue;
1174 }
1175 }
1176 else if (m_async_packet_predicate.GetValue())
1177 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001178 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001179
1180 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001181 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001182 m_async_response.Clear();
1183 if (m_async_packet.empty())
1184 {
Jim Inghama6195b72013-12-18 01:24:33 +00001185 m_async_result = PacketResult::ErrorSendFailed;
1186 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001187 packet_log->Printf ("async: error: empty async packet");
1188
1189 }
1190 else
1191 {
1192 if (packet_log)
1193 packet_log->Printf ("async: sending packet");
1194
Jim Inghama6195b72013-12-18 01:24:33 +00001195 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1196 m_async_packet.size(),
1197 m_async_response,
1198 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001199 }
1200 // Let the other thread that was trying to send the async
1201 // packet know that the packet has been sent and response is
1202 // ready...
1203 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1204
1205 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001206 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001207
1208 // Set the continue packet to resume if our interrupt
1209 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001210 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001211 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001212 // Reverting this for now as it is causing deadlocks
1213 // in programs (<rdar://problem/11529853>). In the future
1214 // we should check our thread list and "do the right thing"
1215 // for new threads that show up while we stop and run async
1216 // packets. Setting the packet to 'c' to continue all threads
1217 // is the right thing to do 99.99% of the time because if a
1218 // thread was single stepping, and we sent an interrupt, we
1219 // will notice above that we didn't stop due to an interrupt
1220 // but stopped due to stepping and we would _not_ continue.
1221 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001222 continue;
1223 }
1224 }
1225 // Stop with signal and thread info
1226 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001227 }
Greg Clayton576d8832011-03-22 04:00:09 +00001228 break;
1229
1230 case 'W':
1231 case 'X':
1232 // process exited
1233 state = eStateExited;
1234 break;
1235
1236 case 'O':
1237 // STDOUT
1238 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001239 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001240 std::string inferior_stdout;
1241 inferior_stdout.reserve(response.GetBytesLeft () / 2);
1242 char ch;
1243 while ((ch = response.GetHexU8()) != '\0')
1244 inferior_stdout.append(1, ch);
1245 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1246 }
1247 break;
1248
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001249 case 'A':
1250 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1251 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001252 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001253 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1254 if (m_partial_profile_data.length() > 0)
1255 {
1256 m_partial_profile_data.append(input);
1257 input = m_partial_profile_data;
1258 m_partial_profile_data.clear();
1259 }
1260
1261 size_t found, pos = 0, len = input.length();
1262 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1263 {
1264 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001265 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1266 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001267
1268 pos = found + end_delimiter_len;
1269 }
1270
1271 if (pos < len)
1272 {
1273 // Last incomplete chunk.
1274 m_partial_profile_data = input.substr(pos);
1275 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001276 }
1277 break;
1278
Greg Clayton576d8832011-03-22 04:00:09 +00001279 case 'E':
1280 // ERROR
1281 state = eStateInvalid;
1282 break;
1283
1284 default:
1285 if (log)
1286 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1287 state = eStateInvalid;
1288 break;
1289 }
1290 }
1291 }
1292 else
1293 {
1294 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001295 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
Greg Clayton576d8832011-03-22 04:00:09 +00001296 state = eStateInvalid;
1297 }
1298 }
1299 if (log)
1300 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1301 response.SetFilePos(0);
1302 m_private_is_running.SetValue (false, eBroadcastAlways);
1303 m_public_is_running.SetValue (false, eBroadcastAlways);
1304 return state;
1305}
1306
1307bool
1308GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1309{
Greg Clayton2687cd12012-03-29 01:55:41 +00001310 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001311 m_async_signal = signo;
1312 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001313 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001314 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001315 return true;
1316 m_async_signal = -1;
1317 return false;
1318}
1319
Greg Clayton37a0a242012-04-11 00:24:49 +00001320// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001321// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1322// (the expected result), then it will send the halt packet. If it does succeed
1323// then the caller that requested the interrupt will want to keep the sequence
1324// locked down so that no one else can send packets while the caller has control.
1325// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001326// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001327// else (like read/write memory), so we need to interrupt the running process
1328// (gdb remote protocol requires this), and do what we need to do, then resume.
1329
1330bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001331GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001332(
1333 Mutex::Locker& locker,
1334 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001335 bool &timed_out
1336)
1337{
Greg Clayton576d8832011-03-22 04:00:09 +00001338 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001339 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001340
1341 if (IsRunning())
1342 {
1343 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001344 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001345 {
1346 if (log)
1347 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1348 }
1349 else
Greg Clayton576d8832011-03-22 04:00:09 +00001350 {
1351 // Someone has the mutex locked waiting for a response or for the
1352 // inferior to stop, so send the interrupt on the down low...
1353 char ctrl_c = '\x03';
1354 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001355 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001356 if (log)
1357 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001358 if (bytes_written > 0)
1359 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001360 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001361 if (seconds_to_wait_for_stop)
1362 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001363 TimeValue timeout;
1364 if (seconds_to_wait_for_stop)
1365 {
1366 timeout = TimeValue::Now();
1367 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1368 }
Greg Clayton576d8832011-03-22 04:00:09 +00001369 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1370 {
1371 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001372 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001373 return true;
1374 }
1375 else
1376 {
1377 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001378 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001379 }
1380 }
1381 else
1382 {
1383 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001384 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001385 return true;
1386 }
1387 }
1388 else
1389 {
1390 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001391 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001392 }
1393 return false;
1394 }
Greg Clayton576d8832011-03-22 04:00:09 +00001395 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001396 else
1397 {
1398 if (log)
1399 log->Printf ("SendInterrupt () - not running");
1400 }
Greg Clayton576d8832011-03-22 04:00:09 +00001401 return true;
1402}
1403
1404lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001405GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001406{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001407 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001408 return m_curr_pid;
1409
1410 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001411 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001412 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001413 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001414 // We really got it.
1415 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001416 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001417 else
1418 {
Todd Fialae24614f2014-05-14 00:15:32 +00001419 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1420 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1421 // The gdb remote protocol documents $qC as returning the thread id, which newer
1422 // debugserver and lldb-gdbserver stubs return correctly.
1423 StringExtractorGDBRemote response;
1424 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001425 {
Todd Fialae24614f2014-05-14 00:15:32 +00001426 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001427 {
Todd Fialae24614f2014-05-14 00:15:32 +00001428 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001429 {
Todd Fialae24614f2014-05-14 00:15:32 +00001430 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1431 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001432 {
Todd Fialae24614f2014-05-14 00:15:32 +00001433 m_curr_pid_is_valid = eLazyBoolYes;
1434 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001435 }
1436 }
1437 }
1438 }
1439 }
1440
Greg Clayton576d8832011-03-22 04:00:09 +00001441 return LLDB_INVALID_PROCESS_ID;
1442}
1443
1444bool
1445GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1446{
1447 error_str.clear();
1448 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001449 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001450 {
1451 if (response.IsOKResponse())
1452 return true;
1453 if (response.GetChar() == 'E')
1454 {
1455 // A string the describes what failed when launching...
1456 error_str = response.GetStringRef().substr(1);
1457 }
1458 else
1459 {
1460 error_str.assign ("unknown error occurred launching process");
1461 }
1462 }
1463 else
1464 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001465 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001466 }
1467 return false;
1468}
1469
1470int
Greg Claytonfbb76342013-11-20 21:07:01 +00001471GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001472{
Greg Claytonfbb76342013-11-20 21:07:01 +00001473 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001474 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001475 std::vector<const char *> argv;
1476 FileSpec exe_file = launch_info.GetExecutableFile();
1477 std::string exe_path;
1478 const char *arg = NULL;
1479 const Args &launch_args = launch_info.GetArguments();
1480 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +00001481 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +00001482 else
1483 {
1484 arg = launch_args.GetArgumentAtIndex(0);
1485 if (arg)
1486 exe_path = arg;
1487 }
1488 if (!exe_path.empty())
1489 {
1490 argv.push_back(exe_path.c_str());
1491 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1492 {
1493 if (arg)
1494 argv.push_back(arg);
1495 }
1496 }
1497 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001498 {
1499 StreamString packet;
1500 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001501 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001502 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001503 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001504 const int arg_len = strlen(arg);
1505 if (i > 0)
1506 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001507 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001508 packet.PutBytesAsRawHex8 (arg, arg_len);
1509 }
1510
1511 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001512 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001513 {
1514 if (response.IsOKResponse())
1515 return 0;
1516 uint8_t error = response.GetError();
1517 if (error)
1518 return error;
1519 }
1520 }
1521 return -1;
1522}
1523
1524int
1525GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1526{
1527 if (name_equal_value && name_equal_value[0])
1528 {
1529 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001530 bool send_hex_encoding = false;
1531 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001532 {
Greg Clayton89600582013-10-10 17:53:50 +00001533 if (isprint(*p))
1534 {
1535 switch (*p)
1536 {
1537 case '$':
1538 case '#':
1539 send_hex_encoding = true;
1540 break;
1541 default:
1542 break;
1543 }
1544 }
1545 else
1546 {
1547 // We have non printable characters, lets hex encode this...
1548 send_hex_encoding = true;
1549 }
1550 }
1551
1552 StringExtractorGDBRemote response;
1553 if (send_hex_encoding)
1554 {
1555 if (m_supports_QEnvironmentHexEncoded)
1556 {
1557 packet.PutCString("QEnvironmentHexEncoded:");
1558 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001559 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001560 {
1561 if (response.IsOKResponse())
1562 return 0;
1563 uint8_t error = response.GetError();
1564 if (error)
1565 return error;
1566 if (response.IsUnsupportedResponse())
1567 m_supports_QEnvironmentHexEncoded = false;
1568 }
1569 }
1570
1571 }
1572 else if (m_supports_QEnvironment)
1573 {
1574 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001575 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001576 {
1577 if (response.IsOKResponse())
1578 return 0;
1579 uint8_t error = response.GetError();
1580 if (error)
1581 return error;
1582 if (response.IsUnsupportedResponse())
1583 m_supports_QEnvironment = false;
1584 }
Greg Clayton576d8832011-03-22 04:00:09 +00001585 }
1586 }
1587 return -1;
1588}
1589
Greg Claytonc4103b32011-05-08 04:53:50 +00001590int
1591GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1592{
1593 if (arch && arch[0])
1594 {
1595 StreamString packet;
1596 packet.Printf("QLaunchArch:%s", arch);
1597 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001598 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001599 {
1600 if (response.IsOKResponse())
1601 return 0;
1602 uint8_t error = response.GetError();
1603 if (error)
1604 return error;
1605 }
1606 }
1607 return -1;
1608}
1609
Jason Molendaa3329782014-03-29 18:54:20 +00001610int
1611GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1612{
1613 if (data && *data != '\0')
1614 {
1615 StreamString packet;
1616 packet.Printf("QSetProcessEvent:%s", data);
1617 StringExtractorGDBRemote response;
1618 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1619 {
1620 if (response.IsOKResponse())
1621 {
1622 if (was_supported)
1623 *was_supported = true;
1624 return 0;
1625 }
1626 else if (response.IsUnsupportedResponse())
1627 {
1628 if (was_supported)
1629 *was_supported = false;
1630 return -1;
1631 }
1632 else
1633 {
1634 uint8_t error = response.GetError();
1635 if (was_supported)
1636 *was_supported = true;
1637 if (error)
1638 return error;
1639 }
1640 }
1641 }
1642 return -1;
1643}
1644
Greg Clayton576d8832011-03-22 04:00:09 +00001645bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001646GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1647 uint32_t &minor,
1648 uint32_t &update)
1649{
1650 if (GetHostInfo ())
1651 {
1652 if (m_os_version_major != UINT32_MAX)
1653 {
1654 major = m_os_version_major;
1655 minor = m_os_version_minor;
1656 update = m_os_version_update;
1657 return true;
1658 }
1659 }
1660 return false;
1661}
1662
1663bool
1664GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1665{
1666 if (GetHostInfo ())
1667 {
1668 if (!m_os_build.empty())
1669 {
1670 s = m_os_build;
1671 return true;
1672 }
1673 }
1674 s.clear();
1675 return false;
1676}
1677
1678
1679bool
1680GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1681{
1682 if (GetHostInfo ())
1683 {
1684 if (!m_os_kernel.empty())
1685 {
1686 s = m_os_kernel;
1687 return true;
1688 }
1689 }
1690 s.clear();
1691 return false;
1692}
1693
1694bool
1695GDBRemoteCommunicationClient::GetHostname (std::string &s)
1696{
1697 if (GetHostInfo ())
1698 {
1699 if (!m_hostname.empty())
1700 {
1701 s = m_hostname;
1702 return true;
1703 }
1704 }
1705 s.clear();
1706 return false;
1707}
1708
1709ArchSpec
1710GDBRemoteCommunicationClient::GetSystemArchitecture ()
1711{
1712 if (GetHostInfo ())
1713 return m_host_arch;
1714 return ArchSpec();
1715}
1716
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001717const lldb_private::ArchSpec &
1718GDBRemoteCommunicationClient::GetProcessArchitecture ()
1719{
1720 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1721 GetCurrentProcessInfo ();
1722 return m_process_arch;
1723}
1724
Jason Molendaa3329782014-03-29 18:54:20 +00001725bool
1726GDBRemoteCommunicationClient::GetGDBServerVersion()
1727{
1728 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1729 {
1730 m_gdb_server_name.clear();
1731 m_gdb_server_version = 0;
1732 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1733
1734 StringExtractorGDBRemote response;
1735 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1736 {
1737 if (response.IsNormalResponse())
1738 {
1739 std::string name;
1740 std::string value;
1741 bool success = false;
1742 while (response.GetNameColonValue(name, value))
1743 {
1744 if (name.compare("name") == 0)
1745 {
1746 success = true;
1747 m_gdb_server_name.swap(value);
1748 }
1749 else if (name.compare("version") == 0)
1750 {
1751 size_t dot_pos = value.find('.');
1752 if (dot_pos != std::string::npos)
1753 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001754 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001755 if (version != UINT32_MAX)
1756 {
1757 success = true;
1758 m_gdb_server_version = version;
1759 }
1760 }
1761 }
1762 if (success)
1763 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1764 }
1765 }
1766 }
1767 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1768}
1769
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001770void
1771GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1772{
1773 CompressionType avail_type = CompressionType::None;
1774 std::string avail_name;
1775
1776#if defined (HAVE_LIBCOMPRESSION)
1777 // libcompression is weak linked so test if compression_decode_buffer() is available
1778 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1779 {
1780 for (auto compression : supported_compressions)
1781 {
1782 if (compression == "lzfse")
1783 {
1784 avail_type = CompressionType::LZFSE;
1785 avail_name = compression;
1786 break;
1787 }
1788 }
1789 }
1790#endif
1791
1792#if defined (HAVE_LIBCOMPRESSION)
1793 // libcompression is weak linked so test if compression_decode_buffer() is available
1794 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1795 {
1796 for (auto compression : supported_compressions)
1797 {
1798 if (compression == "zlib-deflate")
1799 {
1800 avail_type = CompressionType::ZlibDeflate;
1801 avail_name = compression;
1802 break;
1803 }
1804 }
1805 }
1806#endif
1807
1808#if defined (HAVE_LIBZ)
1809 if (avail_type == CompressionType::None)
1810 {
1811 for (auto compression : supported_compressions)
1812 {
1813 if (compression == "zlib-deflate")
1814 {
1815 avail_type = CompressionType::ZlibDeflate;
1816 avail_name = compression;
1817 break;
1818 }
1819 }
1820 }
1821#endif
1822
1823#if defined (HAVE_LIBCOMPRESSION)
1824 // libcompression is weak linked so test if compression_decode_buffer() is available
1825 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1826 {
1827 for (auto compression : supported_compressions)
1828 {
1829 if (compression == "lz4")
1830 {
1831 avail_type = CompressionType::LZ4;
1832 avail_name = compression;
1833 break;
1834 }
1835 }
1836 }
1837#endif
1838
1839#if defined (HAVE_LIBCOMPRESSION)
1840 // libcompression is weak linked so test if compression_decode_buffer() is available
1841 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1842 {
1843 for (auto compression : supported_compressions)
1844 {
1845 if (compression == "lzma")
1846 {
1847 avail_type = CompressionType::LZMA;
1848 avail_name = compression;
1849 break;
1850 }
1851 }
1852 }
1853#endif
1854
1855 if (avail_type != CompressionType::None)
1856 {
1857 StringExtractorGDBRemote response;
1858 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1859 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1860 return;
1861
1862 if (response.IsOKResponse())
1863 {
1864 m_compression_type = avail_type;
1865 }
1866 }
1867}
1868
Jason Molendaa3329782014-03-29 18:54:20 +00001869const char *
1870GDBRemoteCommunicationClient::GetGDBServerProgramName()
1871{
1872 if (GetGDBServerVersion())
1873 {
1874 if (!m_gdb_server_name.empty())
1875 return m_gdb_server_name.c_str();
1876 }
1877 return NULL;
1878}
1879
1880uint32_t
1881GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1882{
1883 if (GetGDBServerVersion())
1884 return m_gdb_server_version;
1885 return 0;
1886}
Greg Clayton1cb64962011-03-24 04:28:38 +00001887
1888bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001889GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1890{
1891 StringExtractorGDBRemote response;
1892 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1893 return false;
1894
1895 if (!response.IsNormalResponse())
1896 return false;
1897
1898 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1899 tid = response.GetHexMaxU32(true, -1);
1900
1901 return true;
1902}
1903
1904bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001905GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001906{
Todd Fialaaf245d12014-06-30 21:05:18 +00001907 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1908
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001909 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001910 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001911 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001912 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001913 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001914 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001915 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001916 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001917 std::string name;
1918 std::string value;
1919 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1920 uint32_t sub = 0;
1921 std::string arch_name;
1922 std::string os_name;
1923 std::string vendor_name;
1924 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001925 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001926 uint32_t pointer_byte_size = 0;
1927 StringExtractor extractor;
1928 ByteOrder byte_order = eByteOrderInvalid;
1929 uint32_t num_keys_decoded = 0;
1930 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001931 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001932 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001933 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001934 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001935 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001936 if (cpu != LLDB_INVALID_CPUTYPE)
1937 ++num_keys_decoded;
1938 }
1939 else if (name.compare("cpusubtype") == 0)
1940 {
1941 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001942 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001943 if (sub != 0)
1944 ++num_keys_decoded;
1945 }
1946 else if (name.compare("arch") == 0)
1947 {
1948 arch_name.swap (value);
1949 ++num_keys_decoded;
1950 }
1951 else if (name.compare("triple") == 0)
1952 {
Greg Clayton44272a42014-09-18 00:18:32 +00001953 extractor.GetStringRef ().swap (value);
1954 extractor.SetFilePos(0);
1955 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001956 ++num_keys_decoded;
1957 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001958 else if (name.compare ("distribution_id") == 0)
1959 {
1960 extractor.GetStringRef ().swap (value);
1961 extractor.SetFilePos (0);
1962 extractor.GetHexByteString (distribution_id);
1963 ++num_keys_decoded;
1964 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001965 else if (name.compare("os_build") == 0)
1966 {
1967 extractor.GetStringRef().swap(value);
1968 extractor.SetFilePos(0);
1969 extractor.GetHexByteString (m_os_build);
1970 ++num_keys_decoded;
1971 }
1972 else if (name.compare("hostname") == 0)
1973 {
1974 extractor.GetStringRef().swap(value);
1975 extractor.SetFilePos(0);
1976 extractor.GetHexByteString (m_hostname);
1977 ++num_keys_decoded;
1978 }
1979 else if (name.compare("os_kernel") == 0)
1980 {
1981 extractor.GetStringRef().swap(value);
1982 extractor.SetFilePos(0);
1983 extractor.GetHexByteString (m_os_kernel);
1984 ++num_keys_decoded;
1985 }
1986 else if (name.compare("ostype") == 0)
1987 {
1988 os_name.swap (value);
1989 ++num_keys_decoded;
1990 }
1991 else if (name.compare("vendor") == 0)
1992 {
1993 vendor_name.swap(value);
1994 ++num_keys_decoded;
1995 }
1996 else if (name.compare("endian") == 0)
1997 {
1998 ++num_keys_decoded;
1999 if (value.compare("little") == 0)
2000 byte_order = eByteOrderLittle;
2001 else if (value.compare("big") == 0)
2002 byte_order = eByteOrderBig;
2003 else if (value.compare("pdp") == 0)
2004 byte_order = eByteOrderPDP;
2005 else
2006 --num_keys_decoded;
2007 }
2008 else if (name.compare("ptrsize") == 0)
2009 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002010 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002011 if (pointer_byte_size != 0)
2012 ++num_keys_decoded;
2013 }
2014 else if (name.compare("os_version") == 0)
2015 {
2016 Args::StringToVersion (value.c_str(),
2017 m_os_version_major,
2018 m_os_version_minor,
2019 m_os_version_update);
2020 if (m_os_version_major != UINT32_MAX)
2021 ++num_keys_decoded;
2022 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002023 else if (name.compare("watchpoint_exceptions_received") == 0)
2024 {
2025 ++num_keys_decoded;
2026 if (strcmp(value.c_str(),"before") == 0)
2027 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2028 else if (strcmp(value.c_str(),"after") == 0)
2029 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
2030 else
2031 --num_keys_decoded;
2032 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002033 else if (name.compare("default_packet_timeout") == 0)
2034 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002035 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002036 if (m_default_packet_timeout > 0)
2037 {
2038 SetPacketTimeout(m_default_packet_timeout);
2039 ++num_keys_decoded;
2040 }
2041 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002042
Greg Clayton32e0a752011-03-30 18:16:51 +00002043 }
2044
2045 if (num_keys_decoded > 0)
2046 m_qHostInfo_is_valid = eLazyBoolYes;
2047
2048 if (triple.empty())
2049 {
2050 if (arch_name.empty())
2051 {
2052 if (cpu != LLDB_INVALID_CPUTYPE)
2053 {
2054 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2055 if (pointer_byte_size)
2056 {
2057 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2058 }
2059 if (byte_order != eByteOrderInvalid)
2060 {
2061 assert (byte_order == m_host_arch.GetByteOrder());
2062 }
Greg Clayton70512312012-05-08 01:45:38 +00002063
2064 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
2065 {
2066 switch (m_host_arch.GetMachine())
2067 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002068 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002069 case llvm::Triple::arm:
2070 case llvm::Triple::thumb:
2071 os_name = "ios";
2072 break;
2073 default:
2074 os_name = "macosx";
2075 break;
2076 }
2077 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002078 if (!vendor_name.empty())
2079 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2080 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00002081 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00002082
2083 }
2084 }
2085 else
2086 {
2087 std::string triple;
2088 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00002089 if (!vendor_name.empty() || !os_name.empty())
2090 {
2091 triple += '-';
2092 if (vendor_name.empty())
2093 triple += "unknown";
2094 else
2095 triple += vendor_name;
2096 triple += '-';
2097 if (os_name.empty())
2098 triple += "unknown";
2099 else
2100 triple += os_name;
2101 }
2102 m_host_arch.SetTriple (triple.c_str());
2103
2104 llvm::Triple &host_triple = m_host_arch.GetTriple();
2105 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2106 {
2107 switch (m_host_arch.GetMachine())
2108 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002109 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002110 case llvm::Triple::arm:
2111 case llvm::Triple::thumb:
2112 host_triple.setOS(llvm::Triple::IOS);
2113 break;
2114 default:
2115 host_triple.setOS(llvm::Triple::MacOSX);
2116 break;
2117 }
2118 }
Greg Clayton1cb64962011-03-24 04:28:38 +00002119 if (pointer_byte_size)
2120 {
2121 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2122 }
2123 if (byte_order != eByteOrderInvalid)
2124 {
2125 assert (byte_order == m_host_arch.GetByteOrder());
2126 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002127
Greg Clayton1cb64962011-03-24 04:28:38 +00002128 }
2129 }
2130 else
2131 {
Greg Clayton70512312012-05-08 01:45:38 +00002132 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00002133 if (pointer_byte_size)
2134 {
2135 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2136 }
2137 if (byte_order != eByteOrderInvalid)
2138 {
2139 assert (byte_order == m_host_arch.GetByteOrder());
2140 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002141
2142 if (log)
2143 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 +00002144 }
2145 if (!distribution_id.empty ())
2146 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00002147 }
Greg Clayton576d8832011-03-22 04:00:09 +00002148 }
2149 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002150 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00002151}
2152
2153int
2154GDBRemoteCommunicationClient::SendAttach
2155(
2156 lldb::pid_t pid,
2157 StringExtractorGDBRemote& response
2158)
2159{
2160 if (pid != LLDB_INVALID_PROCESS_ID)
2161 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002162 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002163 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002164 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002165 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002166 {
2167 if (response.IsErrorResponse())
2168 return response.GetError();
2169 return 0;
2170 }
2171 }
2172 return -1;
2173}
2174
Vince Harrone0be4252015-02-06 18:32:57 +00002175int
2176GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2177{
2178 StreamString packet;
2179 packet.PutCString("I");
2180 packet.PutBytesAsRawHex8(data, data_len);
2181 StringExtractorGDBRemote response;
2182 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2183 {
2184 return 0;
2185 }
2186 return response.GetError();
2187
2188}
2189
Greg Clayton576d8832011-03-22 04:00:09 +00002190const lldb_private::ArchSpec &
2191GDBRemoteCommunicationClient::GetHostArchitecture ()
2192{
Greg Clayton32e0a752011-03-30 18:16:51 +00002193 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00002194 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00002195 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00002196}
2197
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002198uint32_t
2199GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2200{
2201 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2202 GetHostInfo ();
2203 return m_default_packet_timeout;
2204}
2205
Greg Clayton576d8832011-03-22 04:00:09 +00002206addr_t
2207GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2208{
Greg Clayton70b57652011-05-15 01:25:55 +00002209 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002210 {
Greg Clayton70b57652011-05-15 01:25:55 +00002211 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002212 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002213 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00002214 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00002215 permissions & lldb::ePermissionsReadable ? "r" : "",
2216 permissions & lldb::ePermissionsWritable ? "w" : "",
2217 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00002218 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002219 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002220 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002221 {
Todd Fialaf105f582014-06-21 00:48:09 +00002222 if (response.IsUnsupportedResponse())
2223 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2224 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002225 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2226 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002227 else
2228 {
2229 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2230 }
Greg Clayton576d8832011-03-22 04:00:09 +00002231 }
2232 return LLDB_INVALID_ADDRESS;
2233}
2234
2235bool
2236GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2237{
Greg Clayton70b57652011-05-15 01:25:55 +00002238 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002239 {
Greg Clayton70b57652011-05-15 01:25:55 +00002240 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002241 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002242 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002243 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002244 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002245 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002246 {
Todd Fialaf105f582014-06-21 00:48:09 +00002247 if (response.IsUnsupportedResponse())
2248 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2249 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002250 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002251 }
2252 else
2253 {
2254 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00002255 }
Greg Clayton576d8832011-03-22 04:00:09 +00002256 }
2257 return false;
2258}
2259
Jim Inghamacff8952013-05-02 00:27:30 +00002260Error
2261GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00002262{
Jim Inghamacff8952013-05-02 00:27:30 +00002263 Error error;
2264
2265 if (keep_stopped)
2266 {
2267 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2268 {
2269 char packet[64];
2270 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002271 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002272 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002273 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002274 {
2275 m_supports_detach_stay_stopped = eLazyBoolYes;
2276 }
2277 else
2278 {
2279 m_supports_detach_stay_stopped = eLazyBoolNo;
2280 }
2281 }
2282
2283 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2284 {
2285 error.SetErrorString("Stays stopped not supported by this target.");
2286 return error;
2287 }
2288 else
2289 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002290 StringExtractorGDBRemote response;
2291 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002292 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002293 error.SetErrorString ("Sending extended disconnect packet failed.");
2294 }
2295 }
2296 else
2297 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002298 StringExtractorGDBRemote response;
2299 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002300 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002301 error.SetErrorString ("Sending disconnect packet failed.");
2302 }
2303 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002304}
2305
Greg Clayton46fb5582011-11-18 07:03:08 +00002306Error
2307GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2308 lldb_private::MemoryRegionInfo &region_info)
2309{
2310 Error error;
2311 region_info.Clear();
2312
2313 if (m_supports_memory_region_info != eLazyBoolNo)
2314 {
2315 m_supports_memory_region_info = eLazyBoolYes;
2316 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002317 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002318 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002319 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002320 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002321 {
2322 std::string name;
2323 std::string value;
2324 addr_t addr_value;
2325 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002326 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002327 while (success && response.GetNameColonValue(name, value))
2328 {
2329 if (name.compare ("start") == 0)
2330 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002331 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002332 if (success)
2333 region_info.GetRange().SetRangeBase(addr_value);
2334 }
2335 else if (name.compare ("size") == 0)
2336 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002337 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002338 if (success)
2339 region_info.GetRange().SetByteSize (addr_value);
2340 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002341 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002342 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002343 saw_permissions = true;
2344 if (region_info.GetRange().Contains (addr))
2345 {
2346 if (value.find('r') != std::string::npos)
2347 region_info.SetReadable (MemoryRegionInfo::eYes);
2348 else
2349 region_info.SetReadable (MemoryRegionInfo::eNo);
2350
2351 if (value.find('w') != std::string::npos)
2352 region_info.SetWritable (MemoryRegionInfo::eYes);
2353 else
2354 region_info.SetWritable (MemoryRegionInfo::eNo);
2355
2356 if (value.find('x') != std::string::npos)
2357 region_info.SetExecutable (MemoryRegionInfo::eYes);
2358 else
2359 region_info.SetExecutable (MemoryRegionInfo::eNo);
2360 }
2361 else
2362 {
2363 // The reported region does not contain this address -- we're looking at an unmapped page
2364 region_info.SetReadable (MemoryRegionInfo::eNo);
2365 region_info.SetWritable (MemoryRegionInfo::eNo);
2366 region_info.SetExecutable (MemoryRegionInfo::eNo);
2367 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002368 }
2369 else if (name.compare ("error") == 0)
2370 {
2371 StringExtractorGDBRemote name_extractor;
2372 // Swap "value" over into "name_extractor"
2373 name_extractor.GetStringRef().swap(value);
2374 // Now convert the HEX bytes into a string value
2375 name_extractor.GetHexByteString (value);
2376 error.SetErrorString(value.c_str());
2377 }
2378 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002379
2380 // We got a valid address range back but no permissions -- which means this is an unmapped page
2381 if (region_info.GetRange().IsValid() && saw_permissions == false)
2382 {
2383 region_info.SetReadable (MemoryRegionInfo::eNo);
2384 region_info.SetWritable (MemoryRegionInfo::eNo);
2385 region_info.SetExecutable (MemoryRegionInfo::eNo);
2386 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002387 }
2388 else
2389 {
2390 m_supports_memory_region_info = eLazyBoolNo;
2391 }
2392 }
2393
2394 if (m_supports_memory_region_info == eLazyBoolNo)
2395 {
2396 error.SetErrorString("qMemoryRegionInfo is not supported");
2397 }
2398 if (error.Fail())
2399 region_info.Clear();
2400 return error;
2401
2402}
2403
Johnny Chen64637202012-05-23 21:09:52 +00002404Error
2405GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2406{
2407 Error error;
2408
2409 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2410 {
2411 num = m_num_supported_hardware_watchpoints;
2412 return error;
2413 }
2414
2415 // Set num to 0 first.
2416 num = 0;
2417 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2418 {
2419 char packet[64];
2420 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002421 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002422 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002423 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002424 {
2425 m_supports_watchpoint_support_info = eLazyBoolYes;
2426 std::string name;
2427 std::string value;
2428 while (response.GetNameColonValue(name, value))
2429 {
2430 if (name.compare ("num") == 0)
2431 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002432 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002433 m_num_supported_hardware_watchpoints = num;
2434 }
2435 }
2436 }
2437 else
2438 {
2439 m_supports_watchpoint_support_info = eLazyBoolNo;
2440 }
2441 }
2442
2443 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2444 {
2445 error.SetErrorString("qWatchpointSupportInfo is not supported");
2446 }
2447 return error;
2448
2449}
Greg Clayton46fb5582011-11-18 07:03:08 +00002450
Enrico Granataf04a2192012-07-13 23:18:48 +00002451lldb_private::Error
2452GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2453{
2454 Error error(GetWatchpointSupportInfo(num));
2455 if (error.Success())
2456 error = GetWatchpointsTriggerAfterInstruction(after);
2457 return error;
2458}
2459
2460lldb_private::Error
2461GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2462{
2463 Error error;
2464
2465 // we assume watchpoints will happen after running the relevant opcode
2466 // and we only want to override this behavior if we have explicitly
2467 // received a qHostInfo telling us otherwise
2468 if (m_qHostInfo_is_valid != eLazyBoolYes)
2469 after = true;
2470 else
2471 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2472 return error;
2473}
2474
Greg Clayton576d8832011-03-22 04:00:09 +00002475int
Chaoren Lind3173f32015-05-29 19:52:29 +00002476GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002477{
Chaoren Lind3173f32015-05-29 19:52:29 +00002478 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002479 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002480 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002481 StreamString packet;
2482 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002483 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00002484
2485 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002486 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002487 {
2488 if (response.IsOKResponse())
2489 return 0;
2490 uint8_t error = response.GetError();
2491 if (error)
2492 return error;
2493 }
2494 }
2495 return -1;
2496}
2497
2498int
Chaoren Lind3173f32015-05-29 19:52:29 +00002499GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002500{
Chaoren Lind3173f32015-05-29 19:52:29 +00002501 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002502 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002503 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002504 StreamString packet;
2505 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002506 packet.PutCStringAsRawHex8(path.c_str());
2507
Greg Clayton576d8832011-03-22 04:00:09 +00002508 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002509 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002510 {
2511 if (response.IsOKResponse())
2512 return 0;
2513 uint8_t error = response.GetError();
2514 if (error)
2515 return error;
2516 }
2517 }
2518 return -1;
2519}
2520
2521int
Chaoren Lind3173f32015-05-29 19:52:29 +00002522GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002523{
Chaoren Lind3173f32015-05-29 19:52:29 +00002524 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002525 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002526 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002527 StreamString packet;
2528 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002529 packet.PutCStringAsRawHex8(path.c_str());
2530
Greg Clayton576d8832011-03-22 04:00:09 +00002531 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002532 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002533 {
2534 if (response.IsOKResponse())
2535 return 0;
2536 uint8_t error = response.GetError();
2537 if (error)
2538 return error;
2539 }
2540 }
2541 return -1;
2542}
2543
Greg Claytonfbb76342013-11-20 21:07:01 +00002544bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002545GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00002546{
2547 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002548 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002549 {
2550 if (response.IsUnsupportedResponse())
2551 return false;
2552 if (response.IsErrorResponse())
2553 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00002554 std::string cwd;
2555 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00002556 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00002557 return !cwd.empty();
2558 }
2559 return false;
2560}
2561
Greg Clayton576d8832011-03-22 04:00:09 +00002562int
Chaoren Lind3173f32015-05-29 19:52:29 +00002563GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002564{
Chaoren Lind3173f32015-05-29 19:52:29 +00002565 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002566 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002567 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002568 StreamString packet;
2569 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002570 packet.PutCStringAsRawHex8(path.c_str());
2571
Greg Clayton576d8832011-03-22 04:00:09 +00002572 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002573 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002574 {
2575 if (response.IsOKResponse())
2576 return 0;
2577 uint8_t error = response.GetError();
2578 if (error)
2579 return error;
2580 }
2581 }
2582 return -1;
2583}
2584
2585int
2586GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2587{
Greg Clayton32e0a752011-03-30 18:16:51 +00002588 char packet[32];
2589 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002590 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002591 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002592 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002593 {
2594 if (response.IsOKResponse())
2595 return 0;
2596 uint8_t error = response.GetError();
2597 if (error)
2598 return error;
2599 }
2600 return -1;
2601}
Greg Clayton32e0a752011-03-30 18:16:51 +00002602
Jim Ingham106d0282014-06-25 02:32:56 +00002603int
2604GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2605{
2606 char packet[32];
2607 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2608 assert (packet_len < (int)sizeof(packet));
2609 StringExtractorGDBRemote response;
2610 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2611 {
2612 if (response.IsOKResponse())
2613 return 0;
2614 uint8_t error = response.GetError();
2615 if (error)
2616 return error;
2617 }
2618 return -1;
2619}
2620
2621
Greg Clayton32e0a752011-03-30 18:16:51 +00002622bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002623GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002624{
2625 if (response.IsNormalResponse())
2626 {
2627 std::string name;
2628 std::string value;
2629 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002630
2631 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2632 uint32_t sub = 0;
2633 std::string vendor;
2634 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002635
2636 while (response.GetNameColonValue(name, value))
2637 {
2638 if (name.compare("pid") == 0)
2639 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002640 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002641 }
2642 else if (name.compare("ppid") == 0)
2643 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002644 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002645 }
2646 else if (name.compare("uid") == 0)
2647 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002648 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002649 }
2650 else if (name.compare("euid") == 0)
2651 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002652 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002653 }
2654 else if (name.compare("gid") == 0)
2655 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002656 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002657 }
2658 else if (name.compare("egid") == 0)
2659 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002660 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002661 }
2662 else if (name.compare("triple") == 0)
2663 {
Greg Clayton44272a42014-09-18 00:18:32 +00002664 StringExtractor extractor;
2665 extractor.GetStringRef().swap(value);
2666 extractor.SetFilePos(0);
2667 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002668 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002669 }
2670 else if (name.compare("name") == 0)
2671 {
2672 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002673 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002674 // control the characters in a process name
2675 extractor.GetStringRef().swap(value);
2676 extractor.SetFilePos(0);
2677 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002678 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002679 }
Jason Molenda89c37492014-01-27 22:23:20 +00002680 else if (name.compare("cputype") == 0)
2681 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002682 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002683 }
2684 else if (name.compare("cpusubtype") == 0)
2685 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002686 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002687 }
2688 else if (name.compare("vendor") == 0)
2689 {
2690 vendor = value;
2691 }
2692 else if (name.compare("ostype") == 0)
2693 {
2694 os_type = value;
2695 }
2696 }
2697
2698 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2699 {
2700 if (vendor == "apple")
2701 {
2702 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2703 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2704 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2705 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002706 }
2707
2708 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2709 return true;
2710 }
2711 return false;
2712}
2713
2714bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002715GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002716{
2717 process_info.Clear();
2718
2719 if (m_supports_qProcessInfoPID)
2720 {
2721 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002722 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002723 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002724 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002725 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002726 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002727 return DecodeProcessInfoResponse (response, process_info);
2728 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002729 else
2730 {
2731 m_supports_qProcessInfoPID = false;
2732 return false;
2733 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002734 }
2735 return false;
2736}
2737
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002738bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002739GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002740{
Todd Fiala3daa1762014-09-15 16:01:29 +00002741 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2742
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002743 if (allow_lazy)
2744 {
2745 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2746 return true;
2747 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2748 return false;
2749 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002750
2751 GetHostInfo ();
2752
2753 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002754 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002755 {
2756 if (response.IsNormalResponse())
2757 {
2758 std::string name;
2759 std::string value;
2760 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2761 uint32_t sub = 0;
2762 std::string arch_name;
2763 std::string os_name;
2764 std::string vendor_name;
2765 std::string triple;
2766 uint32_t pointer_byte_size = 0;
2767 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002768 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002769 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002770 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002771 while (response.GetNameColonValue(name, value))
2772 {
2773 if (name.compare("cputype") == 0)
2774 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002775 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002776 if (cpu != LLDB_INVALID_CPUTYPE)
2777 ++num_keys_decoded;
2778 }
2779 else if (name.compare("cpusubtype") == 0)
2780 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002781 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002782 if (sub != 0)
2783 ++num_keys_decoded;
2784 }
Todd Fialac540dd02014-08-26 18:21:02 +00002785 else if (name.compare("triple") == 0)
2786 {
Greg Clayton44272a42014-09-18 00:18:32 +00002787 StringExtractor extractor;
2788 extractor.GetStringRef().swap(value);
2789 extractor.SetFilePos(0);
2790 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002791 ++num_keys_decoded;
2792 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002793 else if (name.compare("ostype") == 0)
2794 {
2795 os_name.swap (value);
2796 ++num_keys_decoded;
2797 }
2798 else if (name.compare("vendor") == 0)
2799 {
2800 vendor_name.swap(value);
2801 ++num_keys_decoded;
2802 }
2803 else if (name.compare("endian") == 0)
2804 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002805 ++num_keys_decoded;
2806 if (value.compare("little") == 0)
2807 byte_order = eByteOrderLittle;
2808 else if (value.compare("big") == 0)
2809 byte_order = eByteOrderBig;
2810 else if (value.compare("pdp") == 0)
2811 byte_order = eByteOrderPDP;
2812 else
2813 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002814 }
2815 else if (name.compare("ptrsize") == 0)
2816 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002817 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002818 if (pointer_byte_size != 0)
2819 ++num_keys_decoded;
2820 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002821 else if (name.compare("pid") == 0)
2822 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002823 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002824 if (pid != LLDB_INVALID_PROCESS_ID)
2825 ++num_keys_decoded;
2826 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002827 }
2828 if (num_keys_decoded > 0)
2829 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002830 if (pid != LLDB_INVALID_PROCESS_ID)
2831 {
2832 m_curr_pid_is_valid = eLazyBoolYes;
2833 m_curr_pid = pid;
2834 }
Todd Fialac540dd02014-08-26 18:21:02 +00002835
2836 // Set the ArchSpec from the triple if we have it.
2837 if (!triple.empty ())
2838 {
2839 m_process_arch.SetTriple (triple.c_str ());
2840 if (pointer_byte_size)
2841 {
2842 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2843 }
2844 }
2845 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002846 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002847 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2848
2849 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2850 switch (triple.getObjectFormat()) {
2851 case llvm::Triple::MachO:
2852 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2853 break;
2854 case llvm::Triple::ELF:
2855 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2856 break;
2857 case llvm::Triple::COFF:
2858 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2859 break;
2860 case llvm::Triple::UnknownObjectFormat:
2861 if (log)
2862 log->Printf("error: failed to determine target architecture");
2863 return false;
2864 }
2865
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002866 if (pointer_byte_size)
2867 {
2868 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2869 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002870 if (byte_order != eByteOrderInvalid)
2871 {
2872 assert (byte_order == m_process_arch.GetByteOrder());
2873 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002874 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002875 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002876 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2877 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002878 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002879 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002880 }
2881 }
2882 else
2883 {
2884 m_qProcessInfo_is_valid = eLazyBoolNo;
2885 }
2886
2887 return false;
2888}
2889
2890
Greg Clayton32e0a752011-03-30 18:16:51 +00002891uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002892GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2893 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002894{
2895 process_infos.Clear();
2896
2897 if (m_supports_qfProcessInfo)
2898 {
2899 StreamString packet;
2900 packet.PutCString ("qfProcessInfo");
2901 if (!match_info.MatchAllProcesses())
2902 {
2903 packet.PutChar (':');
2904 const char *name = match_info.GetProcessInfo().GetName();
2905 bool has_name_match = false;
2906 if (name && name[0])
2907 {
2908 has_name_match = true;
2909 NameMatchType name_match_type = match_info.GetNameMatchType();
2910 switch (name_match_type)
2911 {
2912 case eNameMatchIgnore:
2913 has_name_match = false;
2914 break;
2915
2916 case eNameMatchEquals:
2917 packet.PutCString ("name_match:equals;");
2918 break;
2919
2920 case eNameMatchContains:
2921 packet.PutCString ("name_match:contains;");
2922 break;
2923
2924 case eNameMatchStartsWith:
2925 packet.PutCString ("name_match:starts_with;");
2926 break;
2927
2928 case eNameMatchEndsWith:
2929 packet.PutCString ("name_match:ends_with;");
2930 break;
2931
2932 case eNameMatchRegularExpression:
2933 packet.PutCString ("name_match:regex;");
2934 break;
2935 }
2936 if (has_name_match)
2937 {
2938 packet.PutCString ("name:");
2939 packet.PutBytesAsRawHex8(name, ::strlen(name));
2940 packet.PutChar (';');
2941 }
2942 }
2943
2944 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002945 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002946 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002947 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002948 if (match_info.GetProcessInfo().UserIDIsValid())
2949 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2950 if (match_info.GetProcessInfo().GroupIDIsValid())
2951 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002952 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2953 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2954 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2955 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2956 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2957 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2958 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2959 {
2960 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2961 const llvm::Triple &triple = match_arch.GetTriple();
2962 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00002963 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002964 packet.PutChar (';');
2965 }
2966 }
2967 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00002968 // Increase timeout as the first qfProcessInfo packet takes a long time
2969 // on Android. The value of 1min was arrived at empirically.
2970 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00002971 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002972 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002973 do
2974 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002975 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002976 if (!DecodeProcessInfoResponse (response, process_info))
2977 break;
2978 process_infos.Append(process_info);
2979 response.GetStringRef().clear();
2980 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002981 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002982 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002983 else
2984 {
2985 m_supports_qfProcessInfo = false;
2986 return 0;
2987 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002988 }
2989 return process_infos.GetSize();
2990
2991}
2992
2993bool
2994GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2995{
2996 if (m_supports_qUserName)
2997 {
2998 char packet[32];
2999 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003000 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003001 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003002 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003003 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003004 if (response.IsNormalResponse())
3005 {
3006 // Make sure we parsed the right number of characters. The response is
3007 // the hex encoded user name and should make up the entire packet.
3008 // If there are any non-hex ASCII bytes, the length won't match below..
3009 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3010 return true;
3011 }
3012 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003013 else
3014 {
3015 m_supports_qUserName = false;
3016 return false;
3017 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003018 }
3019 return false;
3020
3021}
3022
3023bool
3024GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3025{
3026 if (m_supports_qGroupName)
3027 {
3028 char packet[32];
3029 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003030 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003031 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003032 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003033 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003034 if (response.IsNormalResponse())
3035 {
3036 // Make sure we parsed the right number of characters. The response is
3037 // the hex encoded group name and should make up the entire packet.
3038 // If there are any non-hex ASCII bytes, the length won't match below..
3039 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3040 return true;
3041 }
3042 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003043 else
3044 {
3045 m_supports_qGroupName = false;
3046 return false;
3047 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003048 }
3049 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003050}
Greg Clayton32e0a752011-03-30 18:16:51 +00003051
Ewan Crawford78baa192015-05-13 09:18:18 +00003052bool
3053GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3054{
3055 // Form non-stop packet request
3056 char packet[32];
3057 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3058 assert(packet_len < (int)sizeof(packet));
3059
3060 StringExtractorGDBRemote response;
3061 // Send to target
3062 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3063 if (response.IsOKResponse())
3064 return true;
3065
3066 // Failed or not supported
3067 return false;
3068
3069}
3070
Greg Claytone034a042015-05-21 20:52:06 +00003071static void
3072MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3073{
3074 packet.Clear();
3075 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3076 uint32_t bytes_left = send_size;
3077 while (bytes_left > 0)
3078 {
3079 if (bytes_left >= 26)
3080 {
3081 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3082 bytes_left -= 26;
3083 }
3084 else
3085 {
3086 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3087 bytes_left = 0;
3088 }
3089 }
3090}
3091
3092template<typename T>
3093T calculate_standard_deviation(const std::vector<T> &v)
3094{
3095 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3096 T mean = sum / (T)v.size();
3097 T accum = T(0);
3098 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3099 T delta = d - mean;
3100 accum += delta * delta;
3101 });
3102
3103 T stdev = sqrt(accum / (v.size()-1));
3104 return stdev;
3105}
3106
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003107void
Greg Claytone034a042015-05-21 20:52:06 +00003108GDBRemoteCommunicationClient::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 +00003109{
3110 uint32_t i;
3111 TimeValue start_time, end_time;
3112 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003113 if (SendSpeedTestPacket (0, 0))
3114 {
Greg Claytone034a042015-05-21 20:52:06 +00003115 StreamString packet;
3116 if (json)
3117 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3118 else
3119 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3120 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00003121
Greg Claytone034a042015-05-21 20:52:06 +00003122 uint32_t result_idx = 0;
3123 uint32_t send_size;
3124 std::vector<float> packet_times;
3125
3126 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3127 {
3128 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3129 {
3130 MakeSpeedTestPacket (packet, send_size, recv_size);
3131
3132 packet_times.clear();
3133 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00003134 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00003135 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00003136 {
Greg Claytone034a042015-05-21 20:52:06 +00003137 TimeValue packet_start_time = TimeValue::Now();
3138 StringExtractorGDBRemote response;
3139 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3140 TimeValue packet_end_time = TimeValue::Now();
3141 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3142 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003143 }
3144 end_time = TimeValue::Now();
3145 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00003146
3147 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3148 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3149 float average_ms_per_packet = total_ms / num_packets;
3150 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3151 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00003152 {
Greg Claytone034a042015-05-21 20:52:06 +00003153 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);
3154 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00003155 }
3156 else
3157 {
Greg Claytone034a042015-05-21 20:52:06 +00003158 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",
3159 send_size,
3160 recv_size,
3161 total_time_nsec / TimeValue::NanoSecPerSec,
3162 total_time_nsec % TimeValue::NanoSecPerSec,
3163 packets_per_second,
3164 average_ms_per_packet,
3165 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00003166 }
Greg Claytone034a042015-05-21 20:52:06 +00003167 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003168 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003169 }
Greg Claytone034a042015-05-21 20:52:06 +00003170
3171 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3172
3173 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3174 if (json)
3175 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3176 else
3177 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3178 strm.Flush();
3179 send_size = 0;
3180 result_idx = 0;
3181 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3182 {
3183 MakeSpeedTestPacket (packet, send_size, recv_size);
3184
3185 // If we have a receive size, test how long it takes to receive 4MB of data
3186 if (recv_size > 0)
3187 {
3188 start_time = TimeValue::Now();
3189 uint32_t bytes_read = 0;
3190 uint32_t packet_count = 0;
3191 while (bytes_read < k_recv_amount)
3192 {
3193 StringExtractorGDBRemote response;
3194 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3195 bytes_read += recv_size;
3196 ++packet_count;
3197 }
3198 end_time = TimeValue::Now();
3199 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3200 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3201 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3202 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3203 float average_ms_per_packet = total_ms / packet_count;
3204
3205 if (json)
3206 {
3207 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);
3208 ++result_idx;
3209 }
3210 else
3211 {
3212 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",
3213 send_size,
3214 recv_size,
3215 packet_count,
3216 k_recv_amount_mb,
3217 total_time_nsec / TimeValue::NanoSecPerSec,
3218 total_time_nsec % TimeValue::NanoSecPerSec,
3219 mb_second,
3220 packets_per_second,
3221 average_ms_per_packet);
3222 }
3223 strm.Flush();
3224 }
3225 }
3226 if (json)
3227 strm.Printf("\n ]\n }\n}\n");
3228 else
3229 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003230 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003231}
3232
3233bool
3234GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3235{
3236 StreamString packet;
3237 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3238 uint32_t bytes_left = send_size;
3239 while (bytes_left > 0)
3240 {
3241 if (bytes_left >= 26)
3242 {
3243 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3244 bytes_left -= 26;
3245 }
3246 else
3247 {
3248 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3249 bytes_left = 0;
3250 }
3251 }
3252
3253 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003254 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00003255}
Greg Clayton8b82f082011-04-12 05:54:46 +00003256
3257uint16_t
Greg Claytondbf04572013-12-04 19:40:33 +00003258GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
Greg Clayton8b82f082011-04-12 05:54:46 +00003259{
Daniel Maleae0f8f572013-08-26 23:57:52 +00003260 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00003261 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003262 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00003263 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003264 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00003265 if (remote_accept_hostname && remote_accept_hostname[0])
3266 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003267 else
3268 {
Zachary Turner97a14e62014-08-19 17:18:29 +00003269 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00003270 {
3271 // Make the GDB server we launch only accept connections from this host
3272 stream.Printf("host:%s;", hostname.c_str());
3273 }
3274 else
3275 {
3276 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3277 stream.Printf("host:*;");
3278 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003279 }
3280 const char *packet = stream.GetData();
3281 int packet_len = stream.GetSize();
3282
Vince Harron1b5a74e2015-01-21 22:42:49 +00003283 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003284 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
3285
3286 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003287 {
3288 std::string name;
3289 std::string value;
3290 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00003291 while (response.GetNameColonValue(name, value))
3292 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003293 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003294 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003295 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003296 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00003297 }
3298 return port;
3299 }
3300 return 0;
3301}
3302
3303bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003304GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3305{
3306 StreamString stream;
3307 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3308 const char *packet = stream.GetData();
3309 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003310
Daniel Maleae0f8f572013-08-26 23:57:52 +00003311 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003312 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003313 {
3314 if (response.IsOKResponse())
3315 return true;
3316 }
3317 return false;
3318}
3319
3320bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003321GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003322{
3323 if (m_curr_tid == tid)
3324 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003325
Greg Clayton8b82f082011-04-12 05:54:46 +00003326 char packet[32];
3327 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003328 if (tid == UINT64_MAX)
3329 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003330 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003331 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003332 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003333 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003334 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003335 {
3336 if (response.IsOKResponse())
3337 {
3338 m_curr_tid = tid;
3339 return true;
3340 }
3341 }
3342 return false;
3343}
3344
3345bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003346GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003347{
3348 if (m_curr_tid_run == tid)
3349 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003350
Greg Clayton8b82f082011-04-12 05:54:46 +00003351 char packet[32];
3352 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003353 if (tid == UINT64_MAX)
3354 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003355 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003356 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3357
Andy Gibbsa297a972013-06-19 19:04:53 +00003358 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003359 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003360 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003361 {
3362 if (response.IsOKResponse())
3363 {
3364 m_curr_tid_run = tid;
3365 return true;
3366 }
3367 }
3368 return false;
3369}
3370
3371bool
3372GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3373{
Greg Clayton3dedae12013-12-06 21:45:27 +00003374 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003375 return response.IsNormalResponse();
3376 return false;
3377}
3378
3379bool
Greg Claytonf402f782012-10-13 02:11:55 +00003380GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003381{
3382 if (m_supports_qThreadStopInfo)
3383 {
3384 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003385 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003386 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003387 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003388 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003389 if (response.IsUnsupportedResponse())
3390 m_supports_qThreadStopInfo = false;
3391 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003392 return true;
3393 else
3394 return false;
3395 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003396 else
3397 {
3398 m_supports_qThreadStopInfo = false;
3399 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003400 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003401 return false;
3402}
3403
3404
3405uint8_t
3406GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3407{
Todd Fiala616b8272014-10-09 00:55:04 +00003408 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3409 if (log)
3410 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3411 __FUNCTION__, insert ? "add" : "remove", addr);
3412
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003413 // Check if the stub is known not to support this breakpoint type
3414 if (!SupportsGDBStoppointPacket(type))
3415 return UINT8_MAX;
3416 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003417 char packet[64];
3418 const int packet_len = ::snprintf (packet,
3419 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003420 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003421 insert ? 'Z' : 'z',
3422 type,
3423 addr,
3424 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003425 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003426 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003427 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003428 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003429 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003430 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003431 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003432 if (response.IsOKResponse())
3433 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003434
3435 // Error while setting breakpoint, send back specific error
3436 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003437 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003438
3439 // Empty packet informs us that breakpoint is not supported
3440 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003441 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003442 // Disable this breakpoint type since it is unsupported
3443 switch (type)
3444 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003445 case eBreakpointSoftware: m_supports_z0 = false; break;
3446 case eBreakpointHardware: m_supports_z1 = false; break;
3447 case eWatchpointWrite: m_supports_z2 = false; break;
3448 case eWatchpointRead: m_supports_z3 = false; break;
3449 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003450 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003451 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003452 }
3453 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003454 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003455 return UINT8_MAX;
3456}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003457
3458size_t
3459GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3460 bool &sequence_mutex_unavailable)
3461{
3462 Mutex::Locker locker;
3463 thread_ids.clear();
3464
Jim Ingham4ceb9282012-06-08 22:50:40 +00003465 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003466 {
3467 sequence_mutex_unavailable = false;
3468 StringExtractorGDBRemote response;
3469
Greg Clayton3dedae12013-12-06 21:45:27 +00003470 PacketResult packet_result;
3471 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3472 packet_result == PacketResult::Success && response.IsNormalResponse();
3473 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003474 {
3475 char ch = response.GetChar();
3476 if (ch == 'l')
3477 break;
3478 if (ch == 'm')
3479 {
3480 do
3481 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003482 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003483
3484 if (tid != LLDB_INVALID_THREAD_ID)
3485 {
3486 thread_ids.push_back (tid);
3487 }
3488 ch = response.GetChar(); // Skip the command separator
3489 } while (ch == ','); // Make sure we got a comma separator
3490 }
3491 }
3492 }
3493 else
3494 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003495#if defined (LLDB_CONFIGURATION_DEBUG)
3496 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3497#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003498 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003499 if (log)
3500 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003501#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003502 sequence_mutex_unavailable = true;
3503 }
3504 return thread_ids.size();
3505}
Greg Clayton37a0a242012-04-11 00:24:49 +00003506
3507lldb::addr_t
3508GDBRemoteCommunicationClient::GetShlibInfoAddr()
3509{
3510 if (!IsRunning())
3511 {
3512 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003513 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003514 {
3515 if (response.IsNormalResponse())
3516 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3517 }
3518 }
3519 return LLDB_INVALID_ADDRESS;
3520}
3521
Daniel Maleae0f8f572013-08-26 23:57:52 +00003522lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003523GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3524 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3525 int *status_ptr, // Pass NULL if you don't want the process exit status
3526 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3527 std::string *command_output, // Pass NULL if you don't want the command output
3528 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003529{
3530 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003531 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003532 stream.PutBytesAsRawHex8(command, strlen(command));
3533 stream.PutChar(',');
3534 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003535 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003536 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003537 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003538 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003539 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003540 }
3541 const char *packet = stream.GetData();
3542 int packet_len = stream.GetSize();
3543 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003544 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003545 {
3546 if (response.GetChar() != 'F')
3547 return Error("malformed reply");
3548 if (response.GetChar() != ',')
3549 return Error("malformed reply");
3550 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3551 if (exitcode == UINT32_MAX)
3552 return Error("unable to run remote process");
3553 else if (status_ptr)
3554 *status_ptr = exitcode;
3555 if (response.GetChar() != ',')
3556 return Error("malformed reply");
3557 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3558 if (signo_ptr)
3559 *signo_ptr = signo;
3560 if (response.GetChar() != ',')
3561 return Error("malformed reply");
3562 std::string output;
3563 response.GetEscapedBinaryData(output);
3564 if (command_output)
3565 command_output->assign(output);
3566 return Error();
3567 }
3568 return Error("unable to send packet");
3569}
3570
Greg Claytonfbb76342013-11-20 21:07:01 +00003571Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003572GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3573 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003574{
Chaoren Lind3173f32015-05-29 19:52:29 +00003575 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003576 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003577 stream.PutCString("qPlatform_mkdir:");
3578 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003579 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003580 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003581 const char *packet = stream.GetData();
3582 int packet_len = stream.GetSize();
3583 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003584
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003585 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3586 return Error("failed to send '%s' packet", packet);
3587
3588 if (response.GetChar() != 'F')
3589 return Error("invalid response to '%s' packet", packet);
3590
3591 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003592}
3593
Greg Claytonfbb76342013-11-20 21:07:01 +00003594Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003595GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3596 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003597{
Chaoren Lind3173f32015-05-29 19:52:29 +00003598 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003599 lldb_private::StreamString stream;
3600 stream.PutCString("qPlatform_chmod:");
3601 stream.PutHex32(file_permissions);
3602 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003603 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003604 const char *packet = stream.GetData();
3605 int packet_len = stream.GetSize();
3606 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003607
3608 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3609 return Error("failed to send '%s' packet", packet);
3610
3611 if (response.GetChar() != 'F')
3612 return Error("invalid response to '%s' packet", packet);
3613
Chaoren Lince36c4c2015-05-05 18:43:19 +00003614 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003615}
3616
Daniel Maleae0f8f572013-08-26 23:57:52 +00003617static uint64_t
3618ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3619 uint64_t fail_result,
3620 Error &error)
3621{
3622 response.SetFilePos(0);
3623 if (response.GetChar() != 'F')
3624 return fail_result;
3625 int32_t result = response.GetS32 (-2);
3626 if (result == -2)
3627 return fail_result;
3628 if (response.GetChar() == ',')
3629 {
3630 int result_errno = response.GetS32 (-2);
3631 if (result_errno != -2)
3632 error.SetError(result_errno, eErrorTypePOSIX);
3633 else
3634 error.SetError(-1, eErrorTypeGeneric);
3635 }
3636 else
3637 error.Clear();
3638 return result;
3639}
3640lldb::user_id_t
3641GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3642 uint32_t flags,
3643 mode_t mode,
3644 Error &error)
3645{
Chaoren Lind3173f32015-05-29 19:52:29 +00003646 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003647 lldb_private::StreamString stream;
3648 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003649 if (path.empty())
3650 return UINT64_MAX;
3651 stream.PutCStringAsRawHex8(path.c_str());
3652 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003653 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003654 stream.PutChar(',');
3655 stream.PutHex32(mode);
3656 const char* packet = stream.GetData();
3657 int packet_len = stream.GetSize();
3658 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003659 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003660 {
3661 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3662 }
3663 return UINT64_MAX;
3664}
3665
3666bool
3667GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3668 Error &error)
3669{
3670 lldb_private::StreamString stream;
3671 stream.Printf("vFile:close:%i", (int)fd);
3672 const char* packet = stream.GetData();
3673 int packet_len = stream.GetSize();
3674 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003675 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003676 {
3677 return ParseHostIOPacketResponse (response, -1, error) == 0;
3678 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003679 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003680}
3681
3682// Extension of host I/O packets to get the file size.
3683lldb::user_id_t
3684GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3685{
Chaoren Lind3173f32015-05-29 19:52:29 +00003686 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003687 lldb_private::StreamString stream;
3688 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003689 stream.PutCStringAsRawHex8(path.c_str());
3690 const char* packet = stream.GetData();
3691 int packet_len = stream.GetSize();
3692 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003693 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003694 {
3695 if (response.GetChar() != 'F')
3696 return UINT64_MAX;
3697 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3698 return retcode;
3699 }
3700 return UINT64_MAX;
3701}
3702
Greg Claytonfbb76342013-11-20 21:07:01 +00003703Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003704GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3705 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003706{
Chaoren Lind3173f32015-05-29 19:52:29 +00003707 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003708 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003709 lldb_private::StreamString stream;
3710 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003711 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003712 const char* packet = stream.GetData();
3713 int packet_len = stream.GetSize();
3714 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003715 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003716 {
3717 if (response.GetChar() != 'F')
3718 {
3719 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003720 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003721 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003722 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003723 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003724 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003725 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003726 if (response.GetChar() == ',')
3727 {
3728 int response_errno = response.GetS32(-1);
3729 if (response_errno > 0)
3730 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3731 else
3732 error.SetErrorToGenericError();
3733 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003734 else
3735 error.SetErrorToGenericError();
3736 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003737 else
3738 {
3739 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3740 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003741 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003742 }
3743 else
3744 {
3745 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3746 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003747 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003748}
3749
3750uint64_t
3751GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3752 uint64_t offset,
3753 void *dst,
3754 uint64_t dst_len,
3755 Error &error)
3756{
3757 lldb_private::StreamString stream;
3758 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3759 const char* packet = stream.GetData();
3760 int packet_len = stream.GetSize();
3761 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003762 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003763 {
3764 if (response.GetChar() != 'F')
3765 return 0;
3766 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3767 if (retcode == UINT32_MAX)
3768 return retcode;
3769 const char next = (response.Peek() ? *response.Peek() : 0);
3770 if (next == ',')
3771 return 0;
3772 if (next == ';')
3773 {
3774 response.GetChar(); // skip the semicolon
3775 std::string buffer;
3776 if (response.GetEscapedBinaryData(buffer))
3777 {
3778 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3779 if (data_to_write > 0)
3780 memcpy(dst, &buffer[0], data_to_write);
3781 return data_to_write;
3782 }
3783 }
3784 }
3785 return 0;
3786}
3787
3788uint64_t
3789GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3790 uint64_t offset,
3791 const void* src,
3792 uint64_t src_len,
3793 Error &error)
3794{
3795 lldb_private::StreamGDBRemote stream;
3796 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3797 stream.PutEscapedBytes(src, src_len);
3798 const char* packet = stream.GetData();
3799 int packet_len = stream.GetSize();
3800 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003801 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003802 {
3803 if (response.GetChar() != 'F')
3804 {
3805 error.SetErrorStringWithFormat("write file failed");
3806 return 0;
3807 }
3808 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3809 if (bytes_written == UINT64_MAX)
3810 {
3811 error.SetErrorToGenericError();
3812 if (response.GetChar() == ',')
3813 {
3814 int response_errno = response.GetS32(-1);
3815 if (response_errno > 0)
3816 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3817 }
3818 return 0;
3819 }
3820 return bytes_written;
3821 }
3822 else
3823 {
3824 error.SetErrorString ("failed to send vFile:pwrite packet");
3825 }
3826 return 0;
3827}
3828
Greg Claytonfbb76342013-11-20 21:07:01 +00003829Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003830GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003831{
Chaoren Lind3173f32015-05-29 19:52:29 +00003832 std::string src_path{src.GetPath(false)},
3833 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003834 Error error;
3835 lldb_private::StreamGDBRemote stream;
3836 stream.PutCString("vFile:symlink:");
3837 // the unix symlink() command reverses its parameters where the dst if first,
3838 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003839 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003840 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003841 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003842 const char* packet = stream.GetData();
3843 int packet_len = stream.GetSize();
3844 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003845 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003846 {
3847 if (response.GetChar() == 'F')
3848 {
3849 uint32_t result = response.GetU32(UINT32_MAX);
3850 if (result != 0)
3851 {
3852 error.SetErrorToGenericError();
3853 if (response.GetChar() == ',')
3854 {
3855 int response_errno = response.GetS32(-1);
3856 if (response_errno > 0)
3857 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3858 }
3859 }
3860 }
3861 else
3862 {
3863 // Should have returned with 'F<result>[,<errno>]'
3864 error.SetErrorStringWithFormat("symlink failed");
3865 }
3866 }
3867 else
3868 {
3869 error.SetErrorString ("failed to send vFile:symlink packet");
3870 }
3871 return error;
3872}
3873
3874Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003875GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00003876{
Chaoren Lind3173f32015-05-29 19:52:29 +00003877 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003878 Error error;
3879 lldb_private::StreamGDBRemote stream;
3880 stream.PutCString("vFile:unlink:");
3881 // the unix symlink() command reverses its parameters where the dst if first,
3882 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003883 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003884 const char* packet = stream.GetData();
3885 int packet_len = stream.GetSize();
3886 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003887 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003888 {
3889 if (response.GetChar() == 'F')
3890 {
3891 uint32_t result = response.GetU32(UINT32_MAX);
3892 if (result != 0)
3893 {
3894 error.SetErrorToGenericError();
3895 if (response.GetChar() == ',')
3896 {
3897 int response_errno = response.GetS32(-1);
3898 if (response_errno > 0)
3899 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3900 }
3901 }
3902 }
3903 else
3904 {
3905 // Should have returned with 'F<result>[,<errno>]'
3906 error.SetErrorStringWithFormat("unlink failed");
3907 }
3908 }
3909 else
3910 {
3911 error.SetErrorString ("failed to send vFile:unlink packet");
3912 }
3913 return error;
3914}
3915
Daniel Maleae0f8f572013-08-26 23:57:52 +00003916// Extension of host I/O packets to get whether a file exists.
3917bool
3918GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3919{
Chaoren Lind3173f32015-05-29 19:52:29 +00003920 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003921 lldb_private::StreamString stream;
3922 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003923 stream.PutCStringAsRawHex8(path.c_str());
3924 const char* packet = stream.GetData();
3925 int packet_len = stream.GetSize();
3926 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003927 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003928 {
3929 if (response.GetChar() != 'F')
3930 return false;
3931 if (response.GetChar() != ',')
3932 return false;
3933 bool retcode = (response.GetChar() != '0');
3934 return retcode;
3935 }
3936 return false;
3937}
3938
3939bool
3940GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3941 uint64_t &high,
3942 uint64_t &low)
3943{
Chaoren Lind3173f32015-05-29 19:52:29 +00003944 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003945 lldb_private::StreamString stream;
3946 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003947 stream.PutCStringAsRawHex8(path.c_str());
3948 const char* packet = stream.GetData();
3949 int packet_len = stream.GetSize();
3950 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003951 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003952 {
3953 if (response.GetChar() != 'F')
3954 return false;
3955 if (response.GetChar() != ',')
3956 return false;
3957 if (response.Peek() && *response.Peek() == 'x')
3958 return false;
3959 low = response.GetHexMaxU64(false, UINT64_MAX);
3960 high = response.GetHexMaxU64(false, UINT64_MAX);
3961 return true;
3962 }
3963 return false;
3964}
Greg Claytonf74cf862013-11-13 23:28:31 +00003965
3966bool
Jason Molendaa3329782014-03-29 18:54:20 +00003967GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3968{
3969 // Some targets have issues with g/G packets and we need to avoid using them
3970 if (m_avoid_g_packets == eLazyBoolCalculate)
3971 {
3972 if (process)
3973 {
3974 m_avoid_g_packets = eLazyBoolNo;
3975 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3976 if (arch.IsValid()
3977 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3978 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00003979 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00003980 {
3981 m_avoid_g_packets = eLazyBoolYes;
3982 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3983 if (gdb_server_version != 0)
3984 {
3985 const char *gdb_server_name = GetGDBServerProgramName();
3986 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3987 {
3988 if (gdb_server_version >= 310)
3989 m_avoid_g_packets = eLazyBoolNo;
3990 }
3991 }
3992 }
3993 }
3994 }
3995 return m_avoid_g_packets == eLazyBoolYes;
3996}
3997
3998bool
Greg Claytonf74cf862013-11-13 23:28:31 +00003999GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4000{
4001 Mutex::Locker locker;
4002 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4003 {
4004 const bool thread_suffix_supported = GetThreadSuffixSupported();
4005
4006 if (thread_suffix_supported || SetCurrentThread(tid))
4007 {
4008 char packet[64];
4009 int packet_len = 0;
4010 if (thread_suffix_supported)
4011 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4012 else
4013 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4014 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004015 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004016 }
4017 }
4018 return false;
4019
4020}
4021
4022
4023bool
4024GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4025{
4026 Mutex::Locker locker;
4027 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4028 {
4029 const bool thread_suffix_supported = GetThreadSuffixSupported();
4030
4031 if (thread_suffix_supported || SetCurrentThread(tid))
4032 {
4033 char packet[64];
4034 int packet_len = 0;
4035 // Get all registers in one packet
4036 if (thread_suffix_supported)
4037 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4038 else
4039 packet_len = ::snprintf (packet, sizeof(packet), "g");
4040 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004041 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004042 }
4043 }
4044 return false;
4045}
4046bool
4047GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4048{
4049 save_id = 0; // Set to invalid save ID
4050 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4051 return false;
4052
4053 m_supports_QSaveRegisterState = eLazyBoolYes;
4054 Mutex::Locker locker;
4055 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4056 {
4057 const bool thread_suffix_supported = GetThreadSuffixSupported();
4058 if (thread_suffix_supported || SetCurrentThread(tid))
4059 {
4060 char packet[256];
4061 if (thread_suffix_supported)
4062 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4063 else
Ilia K686b1fe2015-02-27 19:43:08 +00004064 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00004065
4066 StringExtractorGDBRemote response;
4067
Greg Clayton3dedae12013-12-06 21:45:27 +00004068 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004069 {
4070 if (response.IsUnsupportedResponse())
4071 {
4072 // This packet isn't supported, don't try calling it again
4073 m_supports_QSaveRegisterState = eLazyBoolNo;
4074 }
4075
4076 const uint32_t response_save_id = response.GetU32(0);
4077 if (response_save_id != 0)
4078 {
4079 save_id = response_save_id;
4080 return true;
4081 }
4082 }
4083 }
4084 }
4085 return false;
4086}
4087
4088bool
4089GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4090{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004091 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00004092 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4093 // order to be useful
4094 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4095 return false;
4096
4097 Mutex::Locker locker;
4098 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4099 {
4100 const bool thread_suffix_supported = GetThreadSuffixSupported();
4101 if (thread_suffix_supported || SetCurrentThread(tid))
4102 {
4103 char packet[256];
4104 if (thread_suffix_supported)
4105 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4106 else
4107 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4108
4109 StringExtractorGDBRemote response;
4110
Greg Clayton3dedae12013-12-06 21:45:27 +00004111 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004112 {
4113 if (response.IsOKResponse())
4114 {
4115 return true;
4116 }
4117 else if (response.IsUnsupportedResponse())
4118 {
4119 // This packet isn't supported, don't try calling this packet or
4120 // QSaveRegisterState again...
4121 m_supports_QSaveRegisterState = eLazyBoolNo;
4122 }
4123 }
4124 }
4125 }
4126 return false;
4127}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004128
4129bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004130GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004131 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004132 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004133{
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00004134 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004135 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004136 return false;
4137
4138 StreamString packet;
4139 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004140 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004141 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00004142 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00004143 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004144
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004145 StringExtractorGDBRemote response;
4146 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4147 return false;
4148
Aidan Doddsdf627e72015-05-05 08:31:55 +00004149 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004150 return false;
4151
4152 std::string name;
4153 std::string value;
4154 bool success;
4155 StringExtractor extractor;
4156
4157 module_spec.Clear ();
4158 module_spec.GetFileSpec () = module_file_spec;
4159
4160 while (response.GetNameColonValue (name, value))
4161 {
4162 if (name == "uuid" || name == "md5")
4163 {
4164 extractor.GetStringRef ().swap (value);
4165 extractor.SetFilePos (0);
4166 extractor.GetHexByteString (value);
4167 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4168 }
4169 else if (name == "triple")
4170 {
4171 extractor.GetStringRef ().swap (value);
4172 extractor.SetFilePos (0);
4173 extractor.GetHexByteString (value);
4174 module_spec.GetArchitecture().SetTriple (value.c_str ());
4175 }
4176 else if (name == "file_offset")
4177 {
4178 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4179 if (success)
4180 module_spec.SetObjectOffset (ival);
4181 }
4182 else if (name == "file_size")
4183 {
4184 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4185 if (success)
4186 module_spec.SetObjectSize (ival);
4187 }
4188 else if (name == "file_path")
4189 {
4190 extractor.GetStringRef ().swap (value);
4191 extractor.SetFilePos (0);
4192 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00004193 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004194 }
4195 }
4196
4197 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004198}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004199
4200// query the target remote for extended information using the qXfer packet
4201//
4202// example: object='features', annex='target.xml', out=<xml output>
4203// return: 'true' on success
4204// 'false' on failure (err set)
4205bool
4206GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4207 const lldb_private::ConstString annex,
4208 std::string & out,
4209 lldb_private::Error & err) {
4210
4211 std::stringstream output;
4212 StringExtractorGDBRemote chunk;
4213
Greg Claytond04f0ed2015-05-26 18:00:51 +00004214 uint64_t size = GetRemoteMaxPacketSize();
4215 if (size == 0)
4216 size = 0x1000;
4217 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4218 int offset = 0;
4219 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004220
4221 // loop until all data has been read
4222 while ( active ) {
4223
4224 // send query extended feature packet
4225 std::stringstream packet;
4226 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00004227 << object.AsCString("") << ":read:"
4228 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00004229 << std::hex << offset << ","
4230 << std::hex << size;
4231
4232 GDBRemoteCommunication::PacketResult res =
4233 SendPacketAndWaitForResponse( packet.str().c_str(),
4234 chunk,
4235 false );
4236
4237 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4238 err.SetErrorString( "Error sending $qXfer packet" );
4239 return false;
4240 }
4241
4242 const std::string & str = chunk.GetStringRef( );
4243 if ( str.length() == 0 ) {
4244 // should have some data in chunk
4245 err.SetErrorString( "Empty response from $qXfer packet" );
4246 return false;
4247 }
4248
4249 // check packet code
4250 switch ( str[0] ) {
4251 // last chunk
4252 case ( 'l' ):
4253 active = false;
Aidan Doddsed9f6122015-04-29 10:08:17 +00004254 // fall through intentional
Colin Rileyc3c95b22015-04-16 15:51:33 +00004255
4256 // more chunks
4257 case ( 'm' ) :
4258 if ( str.length() > 1 )
4259 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00004260 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004261 break;
4262
4263 // unknown chunk
4264 default:
4265 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4266 return false;
4267 }
4268 }
4269
4270 out = output.str( );
4271 err.Success( );
4272 return true;
4273}
Greg Clayton0b90be12015-06-23 21:27:50 +00004274
4275// Notify the target that gdb is prepared to serve symbol lookup requests.
4276// packet: "qSymbol::"
4277// reply:
4278// OK The target does not need to look up any (more) symbols.
4279// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
4280// LLDB may provide the value by sending another qSymbol packet
4281// in the form of"qSymbol:<sym_value>:<sym_name>".
4282
4283void
4284GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4285{
4286 if (m_supports_qSymbol)
4287 {
4288 Mutex::Locker locker;
4289 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4290 {
4291 StreamString packet;
4292 packet.PutCString ("qSymbol::");
4293 while (1)
4294 {
4295 StringExtractorGDBRemote response;
4296 if (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
4297 {
4298 if (response.IsOKResponse())
4299 {
4300 // We are done serving symbols requests
4301 return;
4302 }
4303
4304 if (response.IsUnsupportedResponse())
4305 {
4306 // qSymbol is not supported by the current GDB server we are connected to
4307 m_supports_qSymbol = false;
4308 return;
4309 }
4310 else
4311 {
4312 llvm::StringRef response_str(response.GetStringRef());
4313 if (response_str.startswith("qSymbol:"))
4314 {
4315 response.SetFilePos(strlen("qSymbol:"));
4316 std::string symbol_name;
4317 if (response.GetHexByteString(symbol_name))
4318 {
4319 if (symbol_name.empty())
4320 return;
4321
4322 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4323 lldb_private::SymbolContextList sc_list;
4324 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
4325 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00004326 const size_t num_scs = sc_list.GetSize();
4327 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 +00004328 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00004329 SymbolContext sc;
4330 if (sc_list.GetContextAtIndex(sc_idx, sc))
4331 {
4332 if (sc.symbol)
4333 {
4334 switch (sc.symbol->GetType())
4335 {
4336 case eSymbolTypeInvalid:
4337 case eSymbolTypeAbsolute:
4338 case eSymbolTypeUndefined:
4339 case eSymbolTypeSourceFile:
4340 case eSymbolTypeHeaderFile:
4341 case eSymbolTypeObjectFile:
4342 case eSymbolTypeCommonBlock:
4343 case eSymbolTypeBlock:
4344 case eSymbolTypeLocal:
4345 case eSymbolTypeParam:
4346 case eSymbolTypeVariable:
4347 case eSymbolTypeVariableType:
4348 case eSymbolTypeLineEntry:
4349 case eSymbolTypeLineHeader:
4350 case eSymbolTypeScopeBegin:
4351 case eSymbolTypeScopeEnd:
4352 case eSymbolTypeAdditional:
4353 case eSymbolTypeCompiler:
4354 case eSymbolTypeInstrumentation:
4355 case eSymbolTypeTrampoline:
4356 break;
4357
4358 case eSymbolTypeCode:
4359 case eSymbolTypeResolver:
4360 case eSymbolTypeData:
4361 case eSymbolTypeRuntime:
4362 case eSymbolTypeException:
4363 case eSymbolTypeObjCClass:
4364 case eSymbolTypeObjCMetaClass:
4365 case eSymbolTypeObjCIVar:
4366 case eSymbolTypeReExported:
4367 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4368 break;
4369 }
4370 }
4371 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004372 }
4373 }
4374 // This is the normal path where our symbol lookup was successful and we want
4375 // to send a packet with the new symbol value and see if another lookup needs to be
4376 // done.
4377
4378 // Change "packet" to contain the requested symbol value and name
4379 packet.Clear();
4380 packet.PutCString("qSymbol:");
4381 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
4382 packet.Printf("%" PRIx64, symbol_load_addr);
4383 packet.PutCString(":");
4384 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4385 continue; // go back to the while loop and send "packet" and wait for another response
4386 }
4387 }
4388 }
4389 }
4390 }
4391 // If we make it here, the symbol request packet response wasn't valid or
4392 // our symbol lookup failed so we must abort
4393 return;
4394
4395 }
4396 }
4397}
4398