blob: c0ea9cceea2e480828ef40eeb2fba0628487653a [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#include "GDBRemoteCommunicationClient.h"
12
13// C Includes
Greg Claytone034a042015-05-21 20:52:06 +000014#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000015#include <sys/stat.h>
16
Greg Clayton576d8832011-03-22 04:00:09 +000017// C++ Includes
Han Ming Ong4b6459f2013-01-18 23:11:53 +000018#include <sstream>
Greg Claytone034a042015-05-21 20:52:06 +000019#include <numeric>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000020
Greg Clayton576d8832011-03-22 04:00:09 +000021// Other libraries and framework includes
Saleem Abdulrasool28606952014-06-27 05:17:41 +000022#include "llvm/ADT/STLExtras.h"
Greg Clayton576d8832011-03-22 04:00:09 +000023#include "llvm/ADT/Triple.h"
24#include "lldb/Interpreter/Args.h"
Greg Clayton576d8832011-03-22 04:00:09 +000025#include "lldb/Core/Log.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000026#include "lldb/Core/ModuleSpec.h"
Greg Clayton576d8832011-03-22 04:00:09 +000027#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000028#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000029#include "lldb/Core/StreamString.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000030#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton576d8832011-03-22 04:00:09 +000031#include "lldb/Host/Endian.h"
32#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000033#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000034#include "lldb/Host/StringConvert.h"
Greg Clayton576d8832011-03-22 04:00:09 +000035#include "lldb/Host/TimeValue.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000036#include "lldb/Symbol/Symbol.h"
Jason Molendaa3329782014-03-29 18:54:20 +000037#include "lldb/Target/Target.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000038#include "lldb/Target/MemoryRegionInfo.h"
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +000039#include "lldb/Target/UnixSignals.h"
Greg Clayton576d8832011-03-22 04:00:09 +000040
41// Project includes
42#include "Utility/StringExtractorGDBRemote.h"
43#include "ProcessGDBRemote.h"
44#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000045#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000046
Jason Molenda91ffe0a2015-06-18 21:46:06 +000047#if defined (HAVE_LIBCOMPRESSION)
48#include <compression.h>
49#endif
50
Greg Clayton576d8832011-03-22 04:00:09 +000051using namespace lldb;
52using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000053using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000054
55//----------------------------------------------------------------------
56// GDBRemoteCommunicationClient constructor
57//----------------------------------------------------------------------
Tamas Berghammere13c2732015-02-11 10:29:30 +000058GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() :
59 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet"),
Greg Clayton576d8832011-03-22 04:00:09 +000060 m_supports_not_sending_acks (eLazyBoolCalculate),
61 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000062 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000063 m_supports_vCont_all (eLazyBoolCalculate),
64 m_supports_vCont_any (eLazyBoolCalculate),
65 m_supports_vCont_c (eLazyBoolCalculate),
66 m_supports_vCont_C (eLazyBoolCalculate),
67 m_supports_vCont_s (eLazyBoolCalculate),
68 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000069 m_qHostInfo_is_valid (eLazyBoolCalculate),
Todd Fiala9f72b3a2014-05-07 19:28:21 +000070 m_curr_pid_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000071 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000072 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000073 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000074 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000075 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000076 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000077 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000078 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000079 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000080 m_supports_p (eLazyBoolCalculate),
Jason Molendabdc4f122014-05-06 02:59:39 +000081 m_supports_x (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000082 m_avoid_g_packets (eLazyBoolCalculate),
Greg Claytonf74cf862013-11-13 23:28:31 +000083 m_supports_QSaveRegisterState (eLazyBoolCalculate),
Steve Pucci03904ac2014-03-04 23:18:46 +000084 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000085 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
86 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
Greg Clayton253204e2015-04-16 23:11:06 +000087 m_supports_qXfer_features_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000088 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
Jason Molenda705b1802014-06-13 02:37:02 +000089 m_supports_jThreadExtendedInfo (eLazyBoolCalculate),
Jason Molenda20ee21b2015-07-10 23:15:22 +000090 m_supports_jLoadedDynamicLibrariesInfos (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000091 m_supports_qProcessInfoPID (true),
92 m_supports_qfProcessInfo (true),
93 m_supports_qUserName (true),
94 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000095 m_supports_qThreadStopInfo (true),
96 m_supports_z0 (true),
97 m_supports_z1 (true),
98 m_supports_z2 (true),
99 m_supports_z3 (true),
100 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +0000101 m_supports_QEnvironment (true),
102 m_supports_QEnvironmentHexEncoded (true),
Greg Clayton0b90be12015-06-23 21:27:50 +0000103 m_supports_qSymbol (true),
Jason Molenda50018d32016-01-13 04:08:10 +0000104 m_qSymbol_requests_done (false),
Stephane Sezer6f455292016-01-08 00:00:17 +0000105 m_supports_qModuleInfo (true),
Greg Clayton358cf1e2015-06-25 21:46:34 +0000106 m_supports_jThreadsInfo (true),
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000107 m_curr_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton8b82f082011-04-12 05:54:46 +0000108 m_curr_tid (LLDB_INVALID_THREAD_ID),
109 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +0000110 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +0000111 m_async_mutex (Mutex::eMutexTypeRecursive),
112 m_async_packet_predicate (false),
113 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +0000114 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +0000115 m_async_response (),
116 m_async_signal (-1),
Jim Inghamb8cd5752014-04-16 02:24:17 +0000117 m_interrupt_sent (false),
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000118 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +0000119 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000120 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +0000121 m_os_version_major (UINT32_MAX),
122 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000123 m_os_version_update (UINT32_MAX),
124 m_os_build (),
125 m_os_kernel (),
126 m_hostname (),
Jason Molendaa3329782014-03-29 18:54:20 +0000127 m_gdb_server_name(),
128 m_gdb_server_version(UINT32_MAX),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000129 m_default_packet_timeout (0),
130 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000131{
Greg Clayton576d8832011-03-22 04:00:09 +0000132}
133
134//----------------------------------------------------------------------
135// Destructor
136//----------------------------------------------------------------------
137GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
138{
Greg Clayton576d8832011-03-22 04:00:09 +0000139 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000140 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000141}
142
143bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000144GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
145{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000146 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000147
Greg Clayton1cb64962011-03-24 04:28:38 +0000148 // Start the read thread after we send the handshake ack since if we
149 // fail to send the handshake ack, there is no reason to continue...
150 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000151 {
Ed Maste48f986f2013-12-18 15:31:45 +0000152 // Wait for any responses that might have been queued up in the remote
153 // GDB server and flush them all
154 StringExtractorGDBRemote response;
155 PacketResult packet_result = PacketResult::Success;
156 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
157 while (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000158 packet_result = ReadPacket (response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000159
Greg Claytonfb909312013-11-23 01:58:15 +0000160 // The return value from QueryNoAckModeSupported() is true if the packet
161 // was sent and _any_ response (including UNIMPLEMENTED) was received),
162 // or false if no response was received. This quickly tells us if we have
163 // a live connection to a remote GDB server...
164 if (QueryNoAckModeSupported())
165 {
166 return true;
167 }
168 else
169 {
170 if (error_ptr)
171 error_ptr->SetErrorString("failed to get reply to handshake packet");
172 }
173 }
174 else
175 {
176 if (error_ptr)
177 error_ptr->SetErrorString("failed to send the handshake ack");
178 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000179 return false;
180}
181
Greg Claytonfb909312013-11-23 01:58:15 +0000182bool
Greg Claytonb30c50c2015-05-29 00:01:55 +0000183GDBRemoteCommunicationClient::GetEchoSupported ()
184{
185 if (m_supports_qEcho == eLazyBoolCalculate)
186 {
187 GetRemoteQSupported();
188 }
189 return m_supports_qEcho == eLazyBoolYes;
190}
191
192
193bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000194GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
195{
196 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
197 {
198 GetRemoteQSupported();
199 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000200 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000201}
202
203bool
204GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
205{
206 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
207 {
208 GetRemoteQSupported();
209 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000210 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000211}
212
213bool
214GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
215{
216 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
217 {
218 GetRemoteQSupported();
219 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000220 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000221}
222
Steve Pucci03904ac2014-03-04 23:18:46 +0000223bool
224GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
225{
226 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
227 {
228 GetRemoteQSupported();
229 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000230 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000231}
232
Colin Rileyc3c95b22015-04-16 15:51:33 +0000233bool
234GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
235{
236 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
237 {
238 GetRemoteQSupported();
239 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000240 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000241}
242
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000243uint64_t
244GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
245{
246 if (m_max_packet_size == 0)
247 {
248 GetRemoteQSupported();
249 }
250 return m_max_packet_size;
251}
252
253bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000254GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000255{
256 if (m_supports_not_sending_acks == eLazyBoolCalculate)
257 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000258 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000259 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000260
Jason Molenda36a216e2014-07-24 01:36:24 +0000261 // This is the first real packet that we'll send in a debug session and it may take a little
262 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
263
264 const uint32_t minimum_timeout = 6;
265 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000266 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000267
Greg Clayton1cb64962011-03-24 04:28:38 +0000268 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000269 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000270 {
271 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000272 {
273 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000274 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000275 }
Greg Claytonfb909312013-11-23 01:58:15 +0000276 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000277 }
278 }
Greg Claytonfb909312013-11-23 01:58:15 +0000279 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000280}
281
282void
Greg Clayton44633992012-04-10 03:22:03 +0000283GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
284{
285 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
286 {
287 m_supports_threads_in_stop_reply = eLazyBoolNo;
288
289 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000290 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000291 {
292 if (response.IsOKResponse())
293 m_supports_threads_in_stop_reply = eLazyBoolYes;
294 }
295 }
296}
297
Jim Inghamcd16df92012-07-20 21:37:13 +0000298bool
299GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
300{
301 if (m_attach_or_wait_reply == eLazyBoolCalculate)
302 {
303 m_attach_or_wait_reply = eLazyBoolNo;
304
305 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000306 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000307 {
308 if (response.IsOKResponse())
309 m_attach_or_wait_reply = eLazyBoolYes;
310 }
311 }
312 if (m_attach_or_wait_reply == eLazyBoolYes)
313 return true;
314 else
315 return false;
316}
317
Jim Ingham279ceec2012-07-25 21:12:43 +0000318bool
319GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
320{
321 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
322 {
323 m_prepare_for_reg_writing_reply = eLazyBoolNo;
324
325 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000326 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000327 {
328 if (response.IsOKResponse())
329 m_prepare_for_reg_writing_reply = eLazyBoolYes;
330 }
331 }
332 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
333 return true;
334 else
335 return false;
336}
337
Greg Clayton44633992012-04-10 03:22:03 +0000338
339void
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000340GDBRemoteCommunicationClient::ResetDiscoverableSettings (bool did_exec)
Greg Clayton576d8832011-03-22 04:00:09 +0000341{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000342 if (did_exec == false)
343 {
344 // Hard reset everything, this is when we first connect to a GDB server
345 m_supports_not_sending_acks = eLazyBoolCalculate;
346 m_supports_thread_suffix = eLazyBoolCalculate;
347 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
348 m_supports_vCont_c = eLazyBoolCalculate;
349 m_supports_vCont_C = eLazyBoolCalculate;
350 m_supports_vCont_s = eLazyBoolCalculate;
351 m_supports_vCont_S = eLazyBoolCalculate;
352 m_supports_p = eLazyBoolCalculate;
353 m_supports_x = eLazyBoolCalculate;
354 m_supports_QSaveRegisterState = eLazyBoolCalculate;
355 m_qHostInfo_is_valid = eLazyBoolCalculate;
356 m_curr_pid_is_valid = eLazyBoolCalculate;
357 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
358 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
359 m_supports_memory_region_info = eLazyBoolCalculate;
360 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
361 m_attach_or_wait_reply = eLazyBoolCalculate;
362 m_avoid_g_packets = eLazyBoolCalculate;
363 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
364 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
365 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
366 m_supports_qXfer_features_read = eLazyBoolCalculate;
367 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
368 m_supports_qProcessInfoPID = true;
369 m_supports_qfProcessInfo = true;
370 m_supports_qUserName = true;
371 m_supports_qGroupName = true;
372 m_supports_qThreadStopInfo = true;
373 m_supports_z0 = true;
374 m_supports_z1 = true;
375 m_supports_z2 = true;
376 m_supports_z3 = true;
377 m_supports_z4 = true;
378 m_supports_QEnvironment = true;
379 m_supports_QEnvironmentHexEncoded = true;
380 m_supports_qSymbol = true;
Jason Molenda50018d32016-01-13 04:08:10 +0000381 m_qSymbol_requests_done = false;
Stephane Sezer6f455292016-01-08 00:00:17 +0000382 m_supports_qModuleInfo = true;
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000383 m_host_arch.Clear();
384 m_os_version_major = UINT32_MAX;
385 m_os_version_minor = UINT32_MAX;
386 m_os_version_update = UINT32_MAX;
387 m_os_build.clear();
388 m_os_kernel.clear();
389 m_hostname.clear();
390 m_gdb_server_name.clear();
391 m_gdb_server_version = UINT32_MAX;
392 m_default_packet_timeout = 0;
393 m_max_packet_size = 0;
394 }
395
396 // These flags should be reset when we first connect to a GDB server
397 // and when our inferior process execs
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000398 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000399 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000400}
401
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000402void
403GDBRemoteCommunicationClient::GetRemoteQSupported ()
404{
405 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000406 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000407 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000408 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000409 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000410 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000411 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
412
Colin Rileyc3c95b22015-04-16 15:51:33 +0000413 // build the qSupported packet
414 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
415 StreamString packet;
416 packet.PutCString( "qSupported" );
417 for ( uint32_t i = 0; i < features.size( ); ++i )
418 {
419 packet.PutCString( i==0 ? ":" : ";");
420 packet.PutCString( features[i].c_str( ) );
421 }
422
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000423 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000424 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000425 response,
426 /*send_async=*/false) == PacketResult::Success)
427 {
428 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000429 if (::strstr (response_cstr, "qXfer:auxv:read+"))
430 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000431 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
432 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
433 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
434 {
435 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
436 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
437 }
438 if (::strstr (response_cstr, "qXfer:libraries:read+"))
439 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000440 if (::strstr (response_cstr, "qXfer:features:read+"))
441 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000442
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000443
444 // Look for a list of compressions in the features list e.g.
445 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
446 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
447 if (features_list)
448 {
449 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
450 if (compressions)
451 {
452 std::vector<std::string> supported_compressions;
453 compressions += sizeof ("SupportedCompressions=") - 1;
454 const char *end_of_compressions = strchr (compressions, ';');
455 if (end_of_compressions == NULL)
456 {
457 end_of_compressions = strchr (compressions, '\0');
458 }
459 const char *current_compression = compressions;
460 while (current_compression < end_of_compressions)
461 {
462 const char *next_compression_name = strchr (current_compression, ',');
463 const char *end_of_this_word = next_compression_name;
464 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
465 {
466 end_of_this_word = end_of_compressions;
467 }
468
469 if (end_of_this_word)
470 {
471 if (end_of_this_word == current_compression)
472 {
473 current_compression++;
474 }
475 else
476 {
477 std::string this_compression (current_compression, end_of_this_word - current_compression);
478 supported_compressions.push_back (this_compression);
479 current_compression = end_of_this_word + 1;
480 }
481 }
482 else
483 {
484 supported_compressions.push_back (current_compression);
485 current_compression = end_of_compressions;
486 }
487 }
488
489 if (supported_compressions.size() > 0)
490 {
491 MaybeEnableCompression (supported_compressions);
492 }
493 }
494 }
495
Greg Claytonb30c50c2015-05-29 00:01:55 +0000496 if (::strstr (response_cstr, "qEcho"))
497 m_supports_qEcho = eLazyBoolYes;
498 else
499 m_supports_qEcho = eLazyBoolNo;
500
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000501 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
502 if (packet_size_str)
503 {
504 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
505 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
506 if (m_max_packet_size == 0)
507 {
508 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
509 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
510 if (log)
511 log->Printf ("Garbled PacketSize spec in qSupported response");
512 }
513 }
514 }
515}
Greg Clayton576d8832011-03-22 04:00:09 +0000516
517bool
518GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
519{
520 if (m_supports_thread_suffix == eLazyBoolCalculate)
521 {
522 StringExtractorGDBRemote response;
523 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000524 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000525 {
526 if (response.IsOKResponse())
527 m_supports_thread_suffix = eLazyBoolYes;
528 }
529 }
530 return m_supports_thread_suffix;
531}
532bool
533GDBRemoteCommunicationClient::GetVContSupported (char flavor)
534{
535 if (m_supports_vCont_c == eLazyBoolCalculate)
536 {
537 StringExtractorGDBRemote response;
538 m_supports_vCont_any = eLazyBoolNo;
539 m_supports_vCont_all = eLazyBoolNo;
540 m_supports_vCont_c = eLazyBoolNo;
541 m_supports_vCont_C = eLazyBoolNo;
542 m_supports_vCont_s = eLazyBoolNo;
543 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000544 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000545 {
546 const char *response_cstr = response.GetStringRef().c_str();
547 if (::strstr (response_cstr, ";c"))
548 m_supports_vCont_c = eLazyBoolYes;
549
550 if (::strstr (response_cstr, ";C"))
551 m_supports_vCont_C = eLazyBoolYes;
552
553 if (::strstr (response_cstr, ";s"))
554 m_supports_vCont_s = eLazyBoolYes;
555
556 if (::strstr (response_cstr, ";S"))
557 m_supports_vCont_S = eLazyBoolYes;
558
559 if (m_supports_vCont_c == eLazyBoolYes &&
560 m_supports_vCont_C == eLazyBoolYes &&
561 m_supports_vCont_s == eLazyBoolYes &&
562 m_supports_vCont_S == eLazyBoolYes)
563 {
564 m_supports_vCont_all = eLazyBoolYes;
565 }
566
567 if (m_supports_vCont_c == eLazyBoolYes ||
568 m_supports_vCont_C == eLazyBoolYes ||
569 m_supports_vCont_s == eLazyBoolYes ||
570 m_supports_vCont_S == eLazyBoolYes)
571 {
572 m_supports_vCont_any = eLazyBoolYes;
573 }
574 }
575 }
576
577 switch (flavor)
578 {
579 case 'a': return m_supports_vCont_any;
580 case 'A': return m_supports_vCont_all;
581 case 'c': return m_supports_vCont_c;
582 case 'C': return m_supports_vCont_C;
583 case 's': return m_supports_vCont_s;
584 case 'S': return m_supports_vCont_S;
585 default: break;
586 }
587 return false;
588}
589
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000590// Check if the target supports 'p' packet. It sends out a 'p'
591// packet and checks the response. A normal packet will tell us
592// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000593//
594// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000595bool
Sean Callananb1de1142013-09-04 23:24:15 +0000596GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000597{
598 if (m_supports_p == eLazyBoolCalculate)
599 {
600 StringExtractorGDBRemote response;
601 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000602 char packet[256];
603 if (GetThreadSuffixSupported())
604 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
605 else
606 snprintf(packet, sizeof(packet), "p0");
607
Greg Clayton3dedae12013-12-06 21:45:27 +0000608 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000609 {
610 if (response.IsNormalResponse())
611 m_supports_p = eLazyBoolYes;
612 }
613 }
614 return m_supports_p;
615}
Greg Clayton576d8832011-03-22 04:00:09 +0000616
Greg Clayton358cf1e2015-06-25 21:46:34 +0000617StructuredData::ObjectSP
618GDBRemoteCommunicationClient::GetThreadsInfo()
619{
620 // Get information on all threads at one using the "jThreadsInfo" packet
621 StructuredData::ObjectSP object_sp;
622
623 if (m_supports_jThreadsInfo)
624 {
625 StringExtractorGDBRemote response;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000626 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
627 {
628 if (response.IsUnsupportedResponse())
629 {
630 m_supports_jThreadsInfo = false;
631 }
632 else if (!response.Empty())
633 {
634 object_sp = StructuredData::ParseJSON (response.GetStringRef());
635 }
636 }
637 }
638 return object_sp;
639}
640
641
Jason Molendabdc4f122014-05-06 02:59:39 +0000642bool
Jason Molenda705b1802014-06-13 02:37:02 +0000643GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
644{
645 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
646 {
647 StringExtractorGDBRemote response;
648 m_supports_jThreadExtendedInfo = eLazyBoolNo;
649 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
650 {
651 if (response.IsOKResponse())
652 {
653 m_supports_jThreadExtendedInfo = eLazyBoolYes;
654 }
655 }
656 }
657 return m_supports_jThreadExtendedInfo;
658}
659
660bool
Jason Molenda20ee21b2015-07-10 23:15:22 +0000661GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported ()
662{
663 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate)
664 {
665 StringExtractorGDBRemote response;
666 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
667 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", response, false) == PacketResult::Success)
668 {
669 if (response.IsOKResponse())
670 {
671 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
672 }
673 }
674 }
675 return m_supports_jLoadedDynamicLibrariesInfos;
676}
677
678bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000679GDBRemoteCommunicationClient::GetxPacketSupported ()
680{
681 if (m_supports_x == eLazyBoolCalculate)
682 {
683 StringExtractorGDBRemote response;
684 m_supports_x = eLazyBoolNo;
685 char packet[256];
686 snprintf (packet, sizeof (packet), "x0,0");
687 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
688 {
689 if (response.IsOKResponse())
690 m_supports_x = eLazyBoolYes;
691 }
692 }
693 return m_supports_x;
694}
695
Greg Clayton3dedae12013-12-06 21:45:27 +0000696GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000697GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
698(
699 const char *payload_prefix,
700 std::string &response_string
701)
702{
703 Mutex::Locker locker;
704 if (!GetSequenceMutex(locker,
705 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
706 {
707 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
708 if (log)
709 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
710 payload_prefix);
711 return PacketResult::ErrorNoSequenceLock;
712 }
713
714 response_string = "";
715 std::string payload_prefix_str(payload_prefix);
716 unsigned int response_size = 0x1000;
717 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
718 response_size = GetRemoteMaxPacketSize();
719 }
720
721 for (unsigned int offset = 0; true; offset += response_size)
722 {
723 StringExtractorGDBRemote this_response;
724 // Construct payload
725 char sizeDescriptor[128];
726 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
727 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
728 this_response,
729 /*send_async=*/false);
730 if (result != PacketResult::Success)
731 return result;
732
733 const std::string &this_string = this_response.GetStringRef();
734
735 // Check for m or l as first character; l seems to mean this is the last chunk
736 char first_char = *this_string.c_str();
737 if (first_char != 'm' && first_char != 'l')
738 {
739 return PacketResult::ErrorReplyInvalid;
740 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000741 // Concatenate the result so far (skipping 'm' or 'l')
742 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000743 if (first_char == 'l')
744 // We're done
745 return PacketResult::Success;
746 }
747}
748
749GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000750GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
751(
752 const char *payload,
753 StringExtractorGDBRemote &response,
754 bool send_async
755)
756{
757 return SendPacketAndWaitForResponse (payload,
758 ::strlen (payload),
759 response,
760 send_async);
761}
762
Greg Clayton3dedae12013-12-06 21:45:27 +0000763GDBRemoteCommunicationClient::PacketResult
764GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
765 size_t payload_length,
766 StringExtractorGDBRemote &response)
767{
768 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
769 if (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000770 packet_result = ReadPacket (response, GetPacketTimeoutInMicroSeconds (), true);
Greg Clayton3dedae12013-12-06 21:45:27 +0000771 return packet_result;
772}
773
774GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000775GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
776(
777 const char *payload,
778 size_t payload_length,
779 StringExtractorGDBRemote &response,
780 bool send_async
781)
782{
Greg Clayton3dedae12013-12-06 21:45:27 +0000783 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000784 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000785 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000786
787 // In order to stop async notifications from being processed in the middle of the
Bruce Mitchenere171da52015-07-22 00:16:02 +0000788 // send/receive sequence Hijack the broadcast. Then rebroadcast any events when we are done.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000789 static Listener hijack_listener("lldb.NotifyHijacker");
790 HijackBroadcaster(&hijack_listener, eBroadcastBitGdbReadThreadGotNotify);
791
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000792 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000793 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000794 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000795 }
796 else
797 {
798 if (send_async)
799 {
Greg Claytond3544052012-05-31 21:24:20 +0000800 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000801 {
Greg Claytond3544052012-05-31 21:24:20 +0000802 Mutex::Locker async_locker (m_async_mutex);
803 m_async_packet.assign(payload, payload_length);
804 m_async_packet_predicate.SetValue (true, eBroadcastNever);
805
806 if (log)
807 log->Printf ("async: async packet = %s", m_async_packet.c_str());
808
809 bool timed_out = false;
810 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000811 {
Greg Claytond3544052012-05-31 21:24:20 +0000812 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000813 {
Jim Inghambabfc382012-06-06 00:32:39 +0000814 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000815 TimeValue timeout_time;
816 timeout_time = TimeValue::Now();
817 timeout_time.OffsetWithSeconds (m_packet_timeout);
818
Greg Clayton576d8832011-03-22 04:00:09 +0000819 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000820 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000821
Greg Claytond3544052012-05-31 21:24:20 +0000822 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000823 {
Greg Claytond3544052012-05-31 21:24:20 +0000824 if (log)
825 log->Printf ("async: got response");
826
827 // Swap the response buffer to avoid malloc and string copy
828 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000829 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000830 }
831 else
832 {
833 if (log)
834 log->Printf ("async: timed out waiting for response");
835 }
836
837 // Make sure we wait until the continue packet has been sent again...
838 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
839 {
840 if (log)
841 {
842 if (timed_out)
843 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
844 else
845 log->Printf ("async: async packet sent");
846 }
847 }
848 else
849 {
850 if (log)
851 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000852 }
853 }
854 else
855 {
Greg Claytond3544052012-05-31 21:24:20 +0000856 // We had a racy condition where we went to send the interrupt
857 // yet we were able to get the lock, so the process must have
858 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000859 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000860 log->Printf ("async: got lock without sending interrupt");
861 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000862 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000863 }
864 }
865 else
866 {
Greg Clayton644247c2011-07-07 01:59:51 +0000867 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000868 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000869 }
870 }
871 else
872 {
873 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000874 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000875 }
876 }
877 else
878 {
879 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000880 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000881 }
882 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000883
Bruce Mitchenere171da52015-07-22 00:16:02 +0000884 // Remove our Hijacking listener from the broadcast.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000885 RestoreBroadcaster();
886
Bruce Mitchenere171da52015-07-22 00:16:02 +0000887 // If a notification event occurred, rebroadcast since it can now be processed safely.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000888 EventSP event_sp;
889 if (hijack_listener.GetNextEvent(event_sp))
890 BroadcastEvent(event_sp);
891
Greg Clayton3dedae12013-12-06 21:45:27 +0000892 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000893}
894
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000895static const char *end_delimiter = "--end--;";
896static const int end_delimiter_len = 8;
897
898std::string
899GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
900( ProcessGDBRemote *process,
901 StringExtractorGDBRemote& profileDataExtractor
902)
903{
904 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
905 std::stringstream final_output;
906 std::string name, value;
907
908 // Going to assuming thread_used_usec comes first, else bail out.
909 while (profileDataExtractor.GetNameColonValue(name, value))
910 {
911 if (name.compare("thread_used_id") == 0)
912 {
913 StringExtractor threadIDHexExtractor(value.c_str());
914 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
915
916 bool has_used_usec = false;
917 uint32_t curr_used_usec = 0;
918 std::string usec_name, usec_value;
919 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
920 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
921 {
922 if (usec_name.compare("thread_used_usec") == 0)
923 {
924 has_used_usec = true;
925 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
926 }
927 else
928 {
929 // We didn't find what we want, it is probably
930 // an older version. Bail out.
931 profileDataExtractor.SetFilePos(input_file_pos);
932 }
933 }
934
935 if (has_used_usec)
936 {
937 uint32_t prev_used_usec = 0;
938 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
939 if (iterator != m_thread_id_to_used_usec_map.end())
940 {
941 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
942 }
943
944 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
945 // A good first time record is one that runs for at least 0.25 sec
946 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
947 bool good_subsequent_time = (prev_used_usec > 0) &&
948 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
949
950 if (good_first_time || good_subsequent_time)
951 {
952 // We try to avoid doing too many index id reservation,
953 // resulting in fast increase of index ids.
954
955 final_output << name << ":";
956 int32_t index_id = process->AssignIndexIDToThread(thread_id);
957 final_output << index_id << ";";
958
959 final_output << usec_name << ":" << usec_value << ";";
960 }
961 else
962 {
963 // Skip past 'thread_used_name'.
964 std::string local_name, local_value;
965 profileDataExtractor.GetNameColonValue(local_name, local_value);
966 }
967
968 // Store current time as previous time so that they can be compared later.
969 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
970 }
971 else
972 {
973 // Bail out and use old string.
974 final_output << name << ":" << value << ";";
975 }
976 }
977 else
978 {
979 final_output << name << ":" << value << ";";
980 }
981 }
982 final_output << end_delimiter;
983 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
984
985 return final_output.str();
986}
987
Ewan Crawford76df2882015-06-23 12:32:06 +0000988bool
989GDBRemoteCommunicationClient::SendvContPacket
990(
991 ProcessGDBRemote *process,
992 const char *payload,
993 size_t packet_length,
994 StringExtractorGDBRemote &response
995)
996{
997
998 m_curr_tid = LLDB_INVALID_THREAD_ID;
999 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1000 if (log)
1001 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1002
1003 // we want to lock down packet sending while we continue
1004 Mutex::Locker locker(m_sequence_mutex);
1005
1006 // here we broadcast this before we even send the packet!!
1007 // this signals doContinue() to exit
1008 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1009
1010 // set the public state to running
1011 m_public_is_running.SetValue(true, eBroadcastNever);
1012
1013 // Set the starting continue packet into "continue_packet". This packet
1014 // may change if we are interrupted and we continue after an async packet...
1015 std::string continue_packet(payload, packet_length);
1016
1017 if (log)
1018 log->Printf("GDBRemoteCommunicationClient::%s () sending vCont packet: %s", __FUNCTION__, continue_packet.c_str());
1019
1020 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
1021 return false;
1022
1023 // set the private state to running and broadcast this
1024 m_private_is_running.SetValue(true, eBroadcastAlways);
1025
1026 if (log)
1027 log->Printf("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1028
1029 // wait for the response to the vCont
1030 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1031 {
1032 if (response.IsOKResponse())
1033 return true;
1034 }
1035
1036 return false;
1037}
1038
Greg Clayton576d8832011-03-22 04:00:09 +00001039StateType
1040GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
1041(
1042 ProcessGDBRemote *process,
1043 const char *payload,
1044 size_t packet_length,
1045 StringExtractorGDBRemote &response
1046)
1047{
Greg Clayton1f5181a2012-07-02 22:05:25 +00001048 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +00001049 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +00001050 if (log)
1051 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1052
1053 Mutex::Locker locker(m_sequence_mutex);
1054 StateType state = eStateRunning;
1055
Greg Clayton576d8832011-03-22 04:00:09 +00001056 m_public_is_running.SetValue (true, eBroadcastNever);
1057 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +00001058 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +00001059 std::string continue_packet(payload, packet_length);
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001060
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001061 const auto sigstop_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
1062 const auto sigint_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGINT");
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001063
Greg Clayton3f875c52013-02-22 22:23:55 +00001064 bool got_async_packet = false;
Pavel Labath9e131f72015-10-27 09:23:55 +00001065 bool broadcast_sent = false;
Greg Claytonaf247d72011-05-19 03:54:16 +00001066
Greg Clayton576d8832011-03-22 04:00:09 +00001067 while (state == eStateRunning)
1068 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001069 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +00001070 {
1071 if (log)
1072 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +00001073 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +00001074 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +00001075 else
1076 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001077
Pavel Labath9e131f72015-10-27 09:23:55 +00001078 if (! broadcast_sent)
1079 {
1080 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1081 broadcast_sent = true;
1082 }
1083
Greg Claytone889ad62011-10-27 22:04:16 +00001084 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +00001085 }
1086
Greg Clayton3f875c52013-02-22 22:23:55 +00001087 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001088
1089 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001090 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001091
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001092 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001093 {
1094 if (response.Empty())
1095 state = eStateInvalid;
1096 else
1097 {
1098 const char stop_type = response.GetChar();
1099 if (log)
1100 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
1101 switch (stop_type)
1102 {
1103 case 'T':
1104 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +00001105 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001106 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +00001107 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001108 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
1109 {
1110 lldb::pid_t pid = GetCurrentProcessID ();
1111 if (pid != LLDB_INVALID_PROCESS_ID)
1112 process->SetID (pid);
1113 }
1114 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +00001115 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001116
1117 // Privately notify any internal threads that we have stopped
1118 // in case we wanted to interrupt our process, yet we might
1119 // send a packet and continue without returning control to the
1120 // user.
1121 m_private_is_running.SetValue (false, eBroadcastAlways);
1122
1123 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1124
Jim Inghambabfc382012-06-06 00:32:39 +00001125 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1126 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +00001127 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001128 // We sent an interrupt packet to stop the inferior process
1129 // for an async signal or to send an async packet while running
1130 // but we might have been single stepping and received the
1131 // stop packet for the step instead of for the interrupt packet.
1132 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1133 // is used, so if we get anything else, we need to try and
1134 // get another stop reply packet that may have been sent
1135 // due to sending the interrupt when the target is stopped
1136 // which will just re-send a copy of the last stop reply
1137 // packet. If we don't do this, then the reply for our
1138 // async packet will be the repeat stop reply packet and cause
1139 // a lot of trouble for us!
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001140 if (signo != sigint_signo && signo != sigstop_signo)
Greg Clayton2687cd12012-03-29 01:55:41 +00001141 {
Greg Claytonfb72fde2012-05-15 02:50:49 +00001142 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001143
Bruce Mitchenera868c132015-07-02 18:48:40 +00001144 // We didn't get a SIGINT or SIGSTOP, so try for a
Jason Molendada9765b2015-08-26 04:07:30 +00001145 // very brief time (0.1s) to get another stop reply
Greg Clayton2687cd12012-03-29 01:55:41 +00001146 // packet to make sure it doesn't get in the way
1147 StringExtractorGDBRemote extra_stop_reply_packet;
Jason Molendada9765b2015-08-26 04:07:30 +00001148 uint32_t timeout_usec = 100000;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001149 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +00001150 {
1151 switch (extra_stop_reply_packet.GetChar())
1152 {
1153 case 'T':
1154 case 'S':
1155 // We did get an extra stop reply, which means
1156 // our interrupt didn't stop the target so we
1157 // shouldn't continue after the async signal
1158 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +00001159 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001160 break;
1161 }
1162 }
1163 }
1164 }
1165
1166 if (m_async_signal != -1)
1167 {
1168 if (log)
1169 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1170
1171 // Save off the async signal we are supposed to send
1172 const int async_signal = m_async_signal;
1173 // Clear the async signal member so we don't end up
1174 // sending the signal multiple times...
1175 m_async_signal = -1;
1176 // Check which signal we stopped with
1177 if (signo == async_signal)
1178 {
1179 if (log)
1180 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1181
1182 // We already stopped with a signal that we wanted
1183 // to stop with, so we are done
1184 }
1185 else
1186 {
1187 // We stopped with a different signal that the one
1188 // we wanted to stop with, so now we must resume
1189 // with the signal we want
1190 char signal_packet[32];
1191 int signal_packet_len = 0;
1192 signal_packet_len = ::snprintf (signal_packet,
1193 sizeof (signal_packet),
1194 "C%2.2x",
1195 async_signal);
1196
1197 if (log)
1198 log->Printf ("async: stopped with signal %s, resume with %s",
1199 Host::GetSignalAsCString (signo),
1200 Host::GetSignalAsCString (async_signal));
1201
1202 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001203 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001204 continue_packet.assign(signal_packet, signal_packet_len);
1205 continue;
1206 }
1207 }
1208 else if (m_async_packet_predicate.GetValue())
1209 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001210 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001211
1212 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001213 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001214 m_async_response.Clear();
1215 if (m_async_packet.empty())
1216 {
Jim Inghama6195b72013-12-18 01:24:33 +00001217 m_async_result = PacketResult::ErrorSendFailed;
1218 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001219 packet_log->Printf ("async: error: empty async packet");
1220
1221 }
1222 else
1223 {
1224 if (packet_log)
1225 packet_log->Printf ("async: sending packet");
1226
Jim Inghama6195b72013-12-18 01:24:33 +00001227 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1228 m_async_packet.size(),
1229 m_async_response,
1230 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001231 }
1232 // Let the other thread that was trying to send the async
1233 // packet know that the packet has been sent and response is
1234 // ready...
1235 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1236
1237 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001238 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001239
1240 // Set the continue packet to resume if our interrupt
1241 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001242 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001243 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001244 // Reverting this for now as it is causing deadlocks
1245 // in programs (<rdar://problem/11529853>). In the future
1246 // we should check our thread list and "do the right thing"
1247 // for new threads that show up while we stop and run async
1248 // packets. Setting the packet to 'c' to continue all threads
1249 // is the right thing to do 99.99% of the time because if a
1250 // thread was single stepping, and we sent an interrupt, we
1251 // will notice above that we didn't stop due to an interrupt
1252 // but stopped due to stepping and we would _not_ continue.
1253 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001254 continue;
1255 }
1256 }
1257 // Stop with signal and thread info
1258 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001259 }
Greg Clayton576d8832011-03-22 04:00:09 +00001260 break;
1261
1262 case 'W':
1263 case 'X':
1264 // process exited
1265 state = eStateExited;
1266 break;
1267
1268 case 'O':
1269 // STDOUT
1270 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001271 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001272 std::string inferior_stdout;
1273 inferior_stdout.reserve(response.GetBytesLeft () / 2);
Dawn Perchik554a8572015-09-17 17:55:32 +00001274
1275 uint8_t ch;
1276 while (response.GetHexU8Ex(ch))
1277 {
1278 if (ch != 0)
1279 inferior_stdout.append(1, (char)ch);
1280 }
Greg Clayton576d8832011-03-22 04:00:09 +00001281 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1282 }
1283 break;
1284
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001285 case 'A':
1286 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1287 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001288 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001289 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1290 if (m_partial_profile_data.length() > 0)
1291 {
1292 m_partial_profile_data.append(input);
1293 input = m_partial_profile_data;
1294 m_partial_profile_data.clear();
1295 }
1296
1297 size_t found, pos = 0, len = input.length();
1298 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1299 {
1300 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001301 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1302 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001303
1304 pos = found + end_delimiter_len;
1305 }
1306
1307 if (pos < len)
1308 {
1309 // Last incomplete chunk.
1310 m_partial_profile_data = input.substr(pos);
1311 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001312 }
1313 break;
1314
Greg Clayton576d8832011-03-22 04:00:09 +00001315 case 'E':
1316 // ERROR
1317 state = eStateInvalid;
1318 break;
1319
1320 default:
1321 if (log)
1322 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1323 state = eStateInvalid;
1324 break;
1325 }
1326 }
1327 }
1328 else
1329 {
1330 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001331 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
Greg Clayton576d8832011-03-22 04:00:09 +00001332 state = eStateInvalid;
1333 }
1334 }
1335 if (log)
1336 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1337 response.SetFilePos(0);
1338 m_private_is_running.SetValue (false, eBroadcastAlways);
1339 m_public_is_running.SetValue (false, eBroadcastAlways);
1340 return state;
1341}
1342
1343bool
1344GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1345{
Greg Clayton2687cd12012-03-29 01:55:41 +00001346 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001347 m_async_signal = signo;
1348 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001349 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001350 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001351 return true;
1352 m_async_signal = -1;
1353 return false;
1354}
1355
Greg Clayton37a0a242012-04-11 00:24:49 +00001356// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001357// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1358// (the expected result), then it will send the halt packet. If it does succeed
1359// then the caller that requested the interrupt will want to keep the sequence
1360// locked down so that no one else can send packets while the caller has control.
1361// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001362// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001363// else (like read/write memory), so we need to interrupt the running process
1364// (gdb remote protocol requires this), and do what we need to do, then resume.
1365
1366bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001367GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001368(
1369 Mutex::Locker& locker,
1370 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001371 bool &timed_out
1372)
1373{
Greg Clayton576d8832011-03-22 04:00:09 +00001374 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001375 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001376
1377 if (IsRunning())
1378 {
1379 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001380 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001381 {
1382 if (log)
1383 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1384 }
1385 else
Greg Clayton576d8832011-03-22 04:00:09 +00001386 {
1387 // Someone has the mutex locked waiting for a response or for the
1388 // inferior to stop, so send the interrupt on the down low...
1389 char ctrl_c = '\x03';
1390 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001391 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001392 if (log)
1393 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001394 if (bytes_written > 0)
1395 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001396 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001397 if (seconds_to_wait_for_stop)
1398 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001399 TimeValue timeout;
1400 if (seconds_to_wait_for_stop)
1401 {
1402 timeout = TimeValue::Now();
1403 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1404 }
Greg Clayton576d8832011-03-22 04:00:09 +00001405 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1406 {
1407 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001408 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001409 return true;
1410 }
1411 else
1412 {
1413 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001414 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001415 }
1416 }
1417 else
1418 {
1419 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001420 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001421 return true;
1422 }
1423 }
1424 else
1425 {
1426 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001427 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001428 }
1429 return false;
1430 }
Greg Clayton576d8832011-03-22 04:00:09 +00001431 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001432 else
1433 {
1434 if (log)
1435 log->Printf ("SendInterrupt () - not running");
1436 }
Greg Clayton576d8832011-03-22 04:00:09 +00001437 return true;
1438}
1439
1440lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001441GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001442{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001443 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001444 return m_curr_pid;
1445
1446 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001447 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001448 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001449 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001450 // We really got it.
1451 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001452 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001453 else
1454 {
Todd Fialae24614f2014-05-14 00:15:32 +00001455 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1456 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1457 // The gdb remote protocol documents $qC as returning the thread id, which newer
1458 // debugserver and lldb-gdbserver stubs return correctly.
1459 StringExtractorGDBRemote response;
1460 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001461 {
Todd Fialae24614f2014-05-14 00:15:32 +00001462 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001463 {
Todd Fialae24614f2014-05-14 00:15:32 +00001464 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001465 {
Todd Fialae24614f2014-05-14 00:15:32 +00001466 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1467 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001468 {
Todd Fialae24614f2014-05-14 00:15:32 +00001469 m_curr_pid_is_valid = eLazyBoolYes;
1470 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001471 }
1472 }
1473 }
1474 }
Jaydeep Patil1142f832015-08-13 03:46:36 +00001475
1476 // If we don't get a response for $qC, check if $qfThreadID gives us a result.
1477 if (m_curr_pid == LLDB_INVALID_PROCESS_ID)
1478 {
1479 std::vector<lldb::tid_t> thread_ids;
1480 bool sequence_mutex_unavailable;
1481 size_t size;
1482 size = GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1483 if (size && sequence_mutex_unavailable == false)
1484 {
1485 m_curr_pid = thread_ids.front();
1486 m_curr_pid_is_valid = eLazyBoolYes;
1487 return m_curr_pid;
1488 }
1489 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001490 }
1491
Greg Clayton576d8832011-03-22 04:00:09 +00001492 return LLDB_INVALID_PROCESS_ID;
1493}
1494
1495bool
1496GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1497{
1498 error_str.clear();
1499 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001500 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001501 {
1502 if (response.IsOKResponse())
1503 return true;
1504 if (response.GetChar() == 'E')
1505 {
1506 // A string the describes what failed when launching...
1507 error_str = response.GetStringRef().substr(1);
1508 }
1509 else
1510 {
1511 error_str.assign ("unknown error occurred launching process");
1512 }
1513 }
1514 else
1515 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001516 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001517 }
1518 return false;
1519}
1520
1521int
Greg Claytonfbb76342013-11-20 21:07:01 +00001522GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001523{
Greg Claytonfbb76342013-11-20 21:07:01 +00001524 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001525 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001526 std::vector<const char *> argv;
1527 FileSpec exe_file = launch_info.GetExecutableFile();
1528 std::string exe_path;
1529 const char *arg = NULL;
1530 const Args &launch_args = launch_info.GetArguments();
1531 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +00001532 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +00001533 else
1534 {
1535 arg = launch_args.GetArgumentAtIndex(0);
1536 if (arg)
1537 exe_path = arg;
1538 }
1539 if (!exe_path.empty())
1540 {
1541 argv.push_back(exe_path.c_str());
1542 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1543 {
1544 if (arg)
1545 argv.push_back(arg);
1546 }
1547 }
1548 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001549 {
1550 StreamString packet;
1551 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001552 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001553 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001554 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001555 const int arg_len = strlen(arg);
1556 if (i > 0)
1557 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001558 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001559 packet.PutBytesAsRawHex8 (arg, arg_len);
1560 }
1561
1562 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001563 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001564 {
1565 if (response.IsOKResponse())
1566 return 0;
1567 uint8_t error = response.GetError();
1568 if (error)
1569 return error;
1570 }
1571 }
1572 return -1;
1573}
1574
1575int
1576GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1577{
1578 if (name_equal_value && name_equal_value[0])
1579 {
1580 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001581 bool send_hex_encoding = false;
1582 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001583 {
Greg Clayton89600582013-10-10 17:53:50 +00001584 if (isprint(*p))
1585 {
1586 switch (*p)
1587 {
1588 case '$':
1589 case '#':
Jason Molenda60bdafb2015-11-05 23:51:05 +00001590 case '*':
Tim Northover974ff612015-11-09 22:05:05 +00001591 case '}':
Greg Clayton89600582013-10-10 17:53:50 +00001592 send_hex_encoding = true;
1593 break;
1594 default:
1595 break;
1596 }
1597 }
1598 else
1599 {
1600 // We have non printable characters, lets hex encode this...
1601 send_hex_encoding = true;
1602 }
1603 }
1604
1605 StringExtractorGDBRemote response;
1606 if (send_hex_encoding)
1607 {
1608 if (m_supports_QEnvironmentHexEncoded)
1609 {
1610 packet.PutCString("QEnvironmentHexEncoded:");
1611 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001612 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001613 {
1614 if (response.IsOKResponse())
1615 return 0;
1616 uint8_t error = response.GetError();
1617 if (error)
1618 return error;
1619 if (response.IsUnsupportedResponse())
1620 m_supports_QEnvironmentHexEncoded = false;
1621 }
1622 }
1623
1624 }
1625 else if (m_supports_QEnvironment)
1626 {
1627 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001628 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001629 {
1630 if (response.IsOKResponse())
1631 return 0;
1632 uint8_t error = response.GetError();
1633 if (error)
1634 return error;
1635 if (response.IsUnsupportedResponse())
1636 m_supports_QEnvironment = false;
1637 }
Greg Clayton576d8832011-03-22 04:00:09 +00001638 }
1639 }
1640 return -1;
1641}
1642
Greg Claytonc4103b32011-05-08 04:53:50 +00001643int
1644GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1645{
1646 if (arch && arch[0])
1647 {
1648 StreamString packet;
1649 packet.Printf("QLaunchArch:%s", arch);
1650 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001651 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001652 {
1653 if (response.IsOKResponse())
1654 return 0;
1655 uint8_t error = response.GetError();
1656 if (error)
1657 return error;
1658 }
1659 }
1660 return -1;
1661}
1662
Jason Molendaa3329782014-03-29 18:54:20 +00001663int
1664GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1665{
1666 if (data && *data != '\0')
1667 {
1668 StreamString packet;
1669 packet.Printf("QSetProcessEvent:%s", data);
1670 StringExtractorGDBRemote response;
1671 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1672 {
1673 if (response.IsOKResponse())
1674 {
1675 if (was_supported)
1676 *was_supported = true;
1677 return 0;
1678 }
1679 else if (response.IsUnsupportedResponse())
1680 {
1681 if (was_supported)
1682 *was_supported = false;
1683 return -1;
1684 }
1685 else
1686 {
1687 uint8_t error = response.GetError();
1688 if (was_supported)
1689 *was_supported = true;
1690 if (error)
1691 return error;
1692 }
1693 }
1694 }
1695 return -1;
1696}
1697
Greg Clayton576d8832011-03-22 04:00:09 +00001698bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001699GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1700 uint32_t &minor,
1701 uint32_t &update)
1702{
1703 if (GetHostInfo ())
1704 {
1705 if (m_os_version_major != UINT32_MAX)
1706 {
1707 major = m_os_version_major;
1708 minor = m_os_version_minor;
1709 update = m_os_version_update;
1710 return true;
1711 }
1712 }
1713 return false;
1714}
1715
1716bool
1717GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1718{
1719 if (GetHostInfo ())
1720 {
1721 if (!m_os_build.empty())
1722 {
1723 s = m_os_build;
1724 return true;
1725 }
1726 }
1727 s.clear();
1728 return false;
1729}
1730
1731
1732bool
1733GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1734{
1735 if (GetHostInfo ())
1736 {
1737 if (!m_os_kernel.empty())
1738 {
1739 s = m_os_kernel;
1740 return true;
1741 }
1742 }
1743 s.clear();
1744 return false;
1745}
1746
1747bool
1748GDBRemoteCommunicationClient::GetHostname (std::string &s)
1749{
1750 if (GetHostInfo ())
1751 {
1752 if (!m_hostname.empty())
1753 {
1754 s = m_hostname;
1755 return true;
1756 }
1757 }
1758 s.clear();
1759 return false;
1760}
1761
1762ArchSpec
1763GDBRemoteCommunicationClient::GetSystemArchitecture ()
1764{
1765 if (GetHostInfo ())
1766 return m_host_arch;
1767 return ArchSpec();
1768}
1769
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001770const lldb_private::ArchSpec &
1771GDBRemoteCommunicationClient::GetProcessArchitecture ()
1772{
1773 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1774 GetCurrentProcessInfo ();
1775 return m_process_arch;
1776}
1777
Jason Molendaa3329782014-03-29 18:54:20 +00001778bool
1779GDBRemoteCommunicationClient::GetGDBServerVersion()
1780{
1781 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1782 {
1783 m_gdb_server_name.clear();
1784 m_gdb_server_version = 0;
1785 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1786
1787 StringExtractorGDBRemote response;
1788 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1789 {
1790 if (response.IsNormalResponse())
1791 {
1792 std::string name;
1793 std::string value;
1794 bool success = false;
1795 while (response.GetNameColonValue(name, value))
1796 {
1797 if (name.compare("name") == 0)
1798 {
1799 success = true;
1800 m_gdb_server_name.swap(value);
1801 }
1802 else if (name.compare("version") == 0)
1803 {
1804 size_t dot_pos = value.find('.');
1805 if (dot_pos != std::string::npos)
1806 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001807 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001808 if (version != UINT32_MAX)
1809 {
1810 success = true;
1811 m_gdb_server_version = version;
1812 }
1813 }
1814 }
1815 if (success)
1816 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1817 }
1818 }
1819 }
1820 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1821}
1822
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001823void
1824GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1825{
1826 CompressionType avail_type = CompressionType::None;
1827 std::string avail_name;
1828
1829#if defined (HAVE_LIBCOMPRESSION)
1830 // libcompression is weak linked so test if compression_decode_buffer() is available
1831 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1832 {
1833 for (auto compression : supported_compressions)
1834 {
1835 if (compression == "lzfse")
1836 {
1837 avail_type = CompressionType::LZFSE;
1838 avail_name = compression;
1839 break;
1840 }
1841 }
1842 }
1843#endif
1844
1845#if defined (HAVE_LIBCOMPRESSION)
1846 // libcompression is weak linked so test if compression_decode_buffer() is available
1847 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1848 {
1849 for (auto compression : supported_compressions)
1850 {
1851 if (compression == "zlib-deflate")
1852 {
1853 avail_type = CompressionType::ZlibDeflate;
1854 avail_name = compression;
1855 break;
1856 }
1857 }
1858 }
1859#endif
1860
1861#if defined (HAVE_LIBZ)
1862 if (avail_type == CompressionType::None)
1863 {
1864 for (auto compression : supported_compressions)
1865 {
1866 if (compression == "zlib-deflate")
1867 {
1868 avail_type = CompressionType::ZlibDeflate;
1869 avail_name = compression;
1870 break;
1871 }
1872 }
1873 }
1874#endif
1875
1876#if defined (HAVE_LIBCOMPRESSION)
1877 // libcompression is weak linked so test if compression_decode_buffer() is available
1878 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1879 {
1880 for (auto compression : supported_compressions)
1881 {
1882 if (compression == "lz4")
1883 {
1884 avail_type = CompressionType::LZ4;
1885 avail_name = compression;
1886 break;
1887 }
1888 }
1889 }
1890#endif
1891
1892#if defined (HAVE_LIBCOMPRESSION)
1893 // libcompression is weak linked so test if compression_decode_buffer() is available
1894 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1895 {
1896 for (auto compression : supported_compressions)
1897 {
1898 if (compression == "lzma")
1899 {
1900 avail_type = CompressionType::LZMA;
1901 avail_name = compression;
1902 break;
1903 }
1904 }
1905 }
1906#endif
1907
1908 if (avail_type != CompressionType::None)
1909 {
1910 StringExtractorGDBRemote response;
1911 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1912 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1913 return;
1914
1915 if (response.IsOKResponse())
1916 {
1917 m_compression_type = avail_type;
1918 }
1919 }
1920}
1921
Jason Molendaa3329782014-03-29 18:54:20 +00001922const char *
1923GDBRemoteCommunicationClient::GetGDBServerProgramName()
1924{
1925 if (GetGDBServerVersion())
1926 {
1927 if (!m_gdb_server_name.empty())
1928 return m_gdb_server_name.c_str();
1929 }
1930 return NULL;
1931}
1932
1933uint32_t
1934GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1935{
1936 if (GetGDBServerVersion())
1937 return m_gdb_server_version;
1938 return 0;
1939}
Greg Clayton1cb64962011-03-24 04:28:38 +00001940
1941bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001942GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1943{
1944 StringExtractorGDBRemote response;
1945 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1946 return false;
1947
1948 if (!response.IsNormalResponse())
1949 return false;
1950
1951 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1952 tid = response.GetHexMaxU32(true, -1);
1953
1954 return true;
1955}
1956
1957bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001958GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001959{
Todd Fialaaf245d12014-06-30 21:05:18 +00001960 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1961
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001962 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001963 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001964 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001965 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001966 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001967 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001968 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001969 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001970 std::string name;
1971 std::string value;
1972 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1973 uint32_t sub = 0;
1974 std::string arch_name;
1975 std::string os_name;
1976 std::string vendor_name;
1977 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001978 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001979 uint32_t pointer_byte_size = 0;
1980 StringExtractor extractor;
1981 ByteOrder byte_order = eByteOrderInvalid;
1982 uint32_t num_keys_decoded = 0;
1983 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001984 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001985 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001986 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001987 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001988 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001989 if (cpu != LLDB_INVALID_CPUTYPE)
1990 ++num_keys_decoded;
1991 }
1992 else if (name.compare("cpusubtype") == 0)
1993 {
1994 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001995 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001996 if (sub != 0)
1997 ++num_keys_decoded;
1998 }
1999 else if (name.compare("arch") == 0)
2000 {
2001 arch_name.swap (value);
2002 ++num_keys_decoded;
2003 }
2004 else if (name.compare("triple") == 0)
2005 {
Greg Clayton44272a42014-09-18 00:18:32 +00002006 extractor.GetStringRef ().swap (value);
2007 extractor.SetFilePos(0);
2008 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00002009 ++num_keys_decoded;
2010 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00002011 else if (name.compare ("distribution_id") == 0)
2012 {
2013 extractor.GetStringRef ().swap (value);
2014 extractor.SetFilePos (0);
2015 extractor.GetHexByteString (distribution_id);
2016 ++num_keys_decoded;
2017 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002018 else if (name.compare("os_build") == 0)
2019 {
2020 extractor.GetStringRef().swap(value);
2021 extractor.SetFilePos(0);
2022 extractor.GetHexByteString (m_os_build);
2023 ++num_keys_decoded;
2024 }
2025 else if (name.compare("hostname") == 0)
2026 {
2027 extractor.GetStringRef().swap(value);
2028 extractor.SetFilePos(0);
2029 extractor.GetHexByteString (m_hostname);
2030 ++num_keys_decoded;
2031 }
2032 else if (name.compare("os_kernel") == 0)
2033 {
2034 extractor.GetStringRef().swap(value);
2035 extractor.SetFilePos(0);
2036 extractor.GetHexByteString (m_os_kernel);
2037 ++num_keys_decoded;
2038 }
2039 else if (name.compare("ostype") == 0)
2040 {
2041 os_name.swap (value);
2042 ++num_keys_decoded;
2043 }
2044 else if (name.compare("vendor") == 0)
2045 {
2046 vendor_name.swap(value);
2047 ++num_keys_decoded;
2048 }
2049 else if (name.compare("endian") == 0)
2050 {
2051 ++num_keys_decoded;
2052 if (value.compare("little") == 0)
2053 byte_order = eByteOrderLittle;
2054 else if (value.compare("big") == 0)
2055 byte_order = eByteOrderBig;
2056 else if (value.compare("pdp") == 0)
2057 byte_order = eByteOrderPDP;
2058 else
2059 --num_keys_decoded;
2060 }
2061 else if (name.compare("ptrsize") == 0)
2062 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002063 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002064 if (pointer_byte_size != 0)
2065 ++num_keys_decoded;
2066 }
2067 else if (name.compare("os_version") == 0)
2068 {
2069 Args::StringToVersion (value.c_str(),
2070 m_os_version_major,
2071 m_os_version_minor,
2072 m_os_version_update);
2073 if (m_os_version_major != UINT32_MAX)
2074 ++num_keys_decoded;
2075 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002076 else if (name.compare("watchpoint_exceptions_received") == 0)
2077 {
2078 ++num_keys_decoded;
2079 if (strcmp(value.c_str(),"before") == 0)
2080 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2081 else if (strcmp(value.c_str(),"after") == 0)
2082 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
2083 else
2084 --num_keys_decoded;
2085 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002086 else if (name.compare("default_packet_timeout") == 0)
2087 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002088 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002089 if (m_default_packet_timeout > 0)
2090 {
2091 SetPacketTimeout(m_default_packet_timeout);
2092 ++num_keys_decoded;
2093 }
2094 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002095
Greg Clayton32e0a752011-03-30 18:16:51 +00002096 }
2097
2098 if (num_keys_decoded > 0)
2099 m_qHostInfo_is_valid = eLazyBoolYes;
2100
2101 if (triple.empty())
2102 {
2103 if (arch_name.empty())
2104 {
2105 if (cpu != LLDB_INVALID_CPUTYPE)
2106 {
2107 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2108 if (pointer_byte_size)
2109 {
2110 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2111 }
2112 if (byte_order != eByteOrderInvalid)
2113 {
2114 assert (byte_order == m_host_arch.GetByteOrder());
2115 }
Greg Clayton70512312012-05-08 01:45:38 +00002116
2117 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
2118 {
2119 switch (m_host_arch.GetMachine())
2120 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002121 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002122 case llvm::Triple::arm:
2123 case llvm::Triple::thumb:
2124 os_name = "ios";
2125 break;
2126 default:
2127 os_name = "macosx";
2128 break;
2129 }
2130 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002131 if (!vendor_name.empty())
2132 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2133 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00002134 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00002135
2136 }
2137 }
2138 else
2139 {
2140 std::string triple;
2141 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00002142 if (!vendor_name.empty() || !os_name.empty())
2143 {
2144 triple += '-';
2145 if (vendor_name.empty())
2146 triple += "unknown";
2147 else
2148 triple += vendor_name;
2149 triple += '-';
2150 if (os_name.empty())
2151 triple += "unknown";
2152 else
2153 triple += os_name;
2154 }
2155 m_host_arch.SetTriple (triple.c_str());
2156
2157 llvm::Triple &host_triple = m_host_arch.GetTriple();
2158 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2159 {
2160 switch (m_host_arch.GetMachine())
2161 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002162 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002163 case llvm::Triple::arm:
2164 case llvm::Triple::thumb:
2165 host_triple.setOS(llvm::Triple::IOS);
2166 break;
2167 default:
2168 host_triple.setOS(llvm::Triple::MacOSX);
2169 break;
2170 }
2171 }
Greg Clayton1cb64962011-03-24 04:28:38 +00002172 if (pointer_byte_size)
2173 {
2174 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2175 }
2176 if (byte_order != eByteOrderInvalid)
2177 {
2178 assert (byte_order == m_host_arch.GetByteOrder());
2179 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002180
Greg Clayton1cb64962011-03-24 04:28:38 +00002181 }
2182 }
2183 else
2184 {
Greg Clayton70512312012-05-08 01:45:38 +00002185 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00002186 if (pointer_byte_size)
2187 {
2188 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2189 }
2190 if (byte_order != eByteOrderInvalid)
2191 {
2192 assert (byte_order == m_host_arch.GetByteOrder());
2193 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002194
2195 if (log)
2196 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 +00002197 }
2198 if (!distribution_id.empty ())
2199 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00002200 }
Greg Clayton576d8832011-03-22 04:00:09 +00002201 }
2202 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002203 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00002204}
2205
2206int
2207GDBRemoteCommunicationClient::SendAttach
2208(
2209 lldb::pid_t pid,
2210 StringExtractorGDBRemote& response
2211)
2212{
2213 if (pid != LLDB_INVALID_PROCESS_ID)
2214 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002215 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002216 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002217 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002218 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002219 {
2220 if (response.IsErrorResponse())
2221 return response.GetError();
2222 return 0;
2223 }
2224 }
2225 return -1;
2226}
2227
Vince Harrone0be4252015-02-06 18:32:57 +00002228int
2229GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2230{
2231 StreamString packet;
2232 packet.PutCString("I");
2233 packet.PutBytesAsRawHex8(data, data_len);
2234 StringExtractorGDBRemote response;
2235 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2236 {
2237 return 0;
2238 }
2239 return response.GetError();
2240
2241}
2242
Greg Clayton576d8832011-03-22 04:00:09 +00002243const lldb_private::ArchSpec &
2244GDBRemoteCommunicationClient::GetHostArchitecture ()
2245{
Greg Clayton32e0a752011-03-30 18:16:51 +00002246 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00002247 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00002248 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00002249}
2250
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002251uint32_t
2252GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2253{
2254 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2255 GetHostInfo ();
2256 return m_default_packet_timeout;
2257}
2258
Greg Clayton576d8832011-03-22 04:00:09 +00002259addr_t
2260GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2261{
Greg Clayton70b57652011-05-15 01:25:55 +00002262 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002263 {
Greg Clayton70b57652011-05-15 01:25:55 +00002264 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002265 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002266 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00002267 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00002268 permissions & lldb::ePermissionsReadable ? "r" : "",
2269 permissions & lldb::ePermissionsWritable ? "w" : "",
2270 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00002271 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002272 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002273 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002274 {
Todd Fialaf105f582014-06-21 00:48:09 +00002275 if (response.IsUnsupportedResponse())
2276 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2277 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002278 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2279 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002280 else
2281 {
2282 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2283 }
Greg Clayton576d8832011-03-22 04:00:09 +00002284 }
2285 return LLDB_INVALID_ADDRESS;
2286}
2287
2288bool
2289GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2290{
Greg Clayton70b57652011-05-15 01:25:55 +00002291 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002292 {
Greg Clayton70b57652011-05-15 01:25:55 +00002293 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002294 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002295 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002296 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002297 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002298 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002299 {
Todd Fialaf105f582014-06-21 00:48:09 +00002300 if (response.IsUnsupportedResponse())
2301 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2302 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002303 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002304 }
2305 else
2306 {
2307 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00002308 }
Greg Clayton576d8832011-03-22 04:00:09 +00002309 }
2310 return false;
2311}
2312
Jim Inghamacff8952013-05-02 00:27:30 +00002313Error
2314GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00002315{
Jim Inghamacff8952013-05-02 00:27:30 +00002316 Error error;
2317
2318 if (keep_stopped)
2319 {
2320 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2321 {
2322 char packet[64];
2323 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002324 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002325 StringExtractorGDBRemote response;
Jim Ingham4920a4e2015-07-15 00:59:25 +00002326 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success
2327 && response.IsOKResponse())
Jim Inghamacff8952013-05-02 00:27:30 +00002328 {
2329 m_supports_detach_stay_stopped = eLazyBoolYes;
2330 }
2331 else
2332 {
2333 m_supports_detach_stay_stopped = eLazyBoolNo;
2334 }
2335 }
2336
2337 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2338 {
2339 error.SetErrorString("Stays stopped not supported by this target.");
2340 return error;
2341 }
2342 else
2343 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002344 StringExtractorGDBRemote response;
Jason Molenda2a667382015-07-15 00:16:09 +00002345 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002346 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002347 error.SetErrorString ("Sending extended disconnect packet failed.");
2348 }
2349 }
2350 else
2351 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002352 StringExtractorGDBRemote response;
2353 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002354 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002355 error.SetErrorString ("Sending disconnect packet failed.");
2356 }
2357 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002358}
2359
Greg Clayton46fb5582011-11-18 07:03:08 +00002360Error
2361GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2362 lldb_private::MemoryRegionInfo &region_info)
2363{
2364 Error error;
2365 region_info.Clear();
2366
2367 if (m_supports_memory_region_info != eLazyBoolNo)
2368 {
2369 m_supports_memory_region_info = eLazyBoolYes;
2370 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002371 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002372 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002373 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002374 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002375 {
2376 std::string name;
2377 std::string value;
2378 addr_t addr_value;
2379 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002380 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002381 while (success && response.GetNameColonValue(name, value))
2382 {
2383 if (name.compare ("start") == 0)
2384 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002385 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002386 if (success)
2387 region_info.GetRange().SetRangeBase(addr_value);
2388 }
2389 else if (name.compare ("size") == 0)
2390 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002391 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002392 if (success)
2393 region_info.GetRange().SetByteSize (addr_value);
2394 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002395 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002396 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002397 saw_permissions = true;
2398 if (region_info.GetRange().Contains (addr))
2399 {
2400 if (value.find('r') != std::string::npos)
2401 region_info.SetReadable (MemoryRegionInfo::eYes);
2402 else
2403 region_info.SetReadable (MemoryRegionInfo::eNo);
2404
2405 if (value.find('w') != std::string::npos)
2406 region_info.SetWritable (MemoryRegionInfo::eYes);
2407 else
2408 region_info.SetWritable (MemoryRegionInfo::eNo);
2409
2410 if (value.find('x') != std::string::npos)
2411 region_info.SetExecutable (MemoryRegionInfo::eYes);
2412 else
2413 region_info.SetExecutable (MemoryRegionInfo::eNo);
2414 }
2415 else
2416 {
2417 // The reported region does not contain this address -- we're looking at an unmapped page
2418 region_info.SetReadable (MemoryRegionInfo::eNo);
2419 region_info.SetWritable (MemoryRegionInfo::eNo);
2420 region_info.SetExecutable (MemoryRegionInfo::eNo);
2421 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002422 }
2423 else if (name.compare ("error") == 0)
2424 {
2425 StringExtractorGDBRemote name_extractor;
2426 // Swap "value" over into "name_extractor"
2427 name_extractor.GetStringRef().swap(value);
2428 // Now convert the HEX bytes into a string value
2429 name_extractor.GetHexByteString (value);
2430 error.SetErrorString(value.c_str());
2431 }
2432 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002433
2434 // We got a valid address range back but no permissions -- which means this is an unmapped page
2435 if (region_info.GetRange().IsValid() && saw_permissions == false)
2436 {
2437 region_info.SetReadable (MemoryRegionInfo::eNo);
2438 region_info.SetWritable (MemoryRegionInfo::eNo);
2439 region_info.SetExecutable (MemoryRegionInfo::eNo);
2440 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002441 }
2442 else
2443 {
2444 m_supports_memory_region_info = eLazyBoolNo;
2445 }
2446 }
2447
2448 if (m_supports_memory_region_info == eLazyBoolNo)
2449 {
2450 error.SetErrorString("qMemoryRegionInfo is not supported");
2451 }
2452 if (error.Fail())
2453 region_info.Clear();
2454 return error;
2455
2456}
2457
Johnny Chen64637202012-05-23 21:09:52 +00002458Error
2459GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2460{
2461 Error error;
2462
2463 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2464 {
2465 num = m_num_supported_hardware_watchpoints;
2466 return error;
2467 }
2468
2469 // Set num to 0 first.
2470 num = 0;
2471 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2472 {
2473 char packet[64];
2474 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002475 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002476 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002477 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002478 {
2479 m_supports_watchpoint_support_info = eLazyBoolYes;
2480 std::string name;
2481 std::string value;
2482 while (response.GetNameColonValue(name, value))
2483 {
2484 if (name.compare ("num") == 0)
2485 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002486 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002487 m_num_supported_hardware_watchpoints = num;
2488 }
2489 }
2490 }
2491 else
2492 {
2493 m_supports_watchpoint_support_info = eLazyBoolNo;
2494 }
2495 }
2496
2497 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2498 {
2499 error.SetErrorString("qWatchpointSupportInfo is not supported");
2500 }
2501 return error;
2502
2503}
Greg Clayton46fb5582011-11-18 07:03:08 +00002504
Enrico Granataf04a2192012-07-13 23:18:48 +00002505lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002506GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002507{
2508 Error error(GetWatchpointSupportInfo(num));
2509 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00002510 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00002511 return error;
2512}
2513
2514lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002515GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002516{
2517 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00002518 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00002519
2520 // we assume watchpoints will happen after running the relevant opcode
2521 // and we only want to override this behavior if we have explicitly
2522 // received a qHostInfo telling us otherwise
2523 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00002524 {
2525 // On targets like MIPS, watchpoint exceptions are always generated
2526 // before the instruction is executed. The connected target may not
2527 // support qHostInfo or qWatchpointSupportInfo packets.
2528 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2529 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
2530 after = false;
2531 else
2532 after = true;
2533 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002534 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00002535 {
2536 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
2537 // if it is not calculated before.
2538 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
2539 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2540 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
2541 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2542
Enrico Granataf04a2192012-07-13 23:18:48 +00002543 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00002544 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002545 return error;
2546}
2547
Greg Clayton576d8832011-03-22 04:00:09 +00002548int
Chaoren Lind3173f32015-05-29 19:52:29 +00002549GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002550{
Chaoren Lind3173f32015-05-29 19:52:29 +00002551 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002552 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002553 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002554 StreamString packet;
2555 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002556 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00002557
2558 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002559 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002560 {
2561 if (response.IsOKResponse())
2562 return 0;
2563 uint8_t error = response.GetError();
2564 if (error)
2565 return error;
2566 }
2567 }
2568 return -1;
2569}
2570
2571int
Chaoren Lind3173f32015-05-29 19:52:29 +00002572GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002573{
Chaoren Lind3173f32015-05-29 19:52:29 +00002574 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002575 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002576 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002577 StreamString packet;
2578 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002579 packet.PutCStringAsRawHex8(path.c_str());
2580
Greg Clayton576d8832011-03-22 04:00:09 +00002581 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002582 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002583 {
2584 if (response.IsOKResponse())
2585 return 0;
2586 uint8_t error = response.GetError();
2587 if (error)
2588 return error;
2589 }
2590 }
2591 return -1;
2592}
2593
2594int
Chaoren Lind3173f32015-05-29 19:52:29 +00002595GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002596{
Chaoren Lind3173f32015-05-29 19:52:29 +00002597 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002598 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002599 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002600 StreamString packet;
2601 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002602 packet.PutCStringAsRawHex8(path.c_str());
2603
Greg Clayton576d8832011-03-22 04:00:09 +00002604 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002605 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002606 {
2607 if (response.IsOKResponse())
2608 return 0;
2609 uint8_t error = response.GetError();
2610 if (error)
2611 return error;
2612 }
2613 }
2614 return -1;
2615}
2616
Greg Claytonfbb76342013-11-20 21:07:01 +00002617bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002618GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00002619{
2620 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002621 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002622 {
2623 if (response.IsUnsupportedResponse())
2624 return false;
2625 if (response.IsErrorResponse())
2626 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00002627 std::string cwd;
2628 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00002629 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00002630 return !cwd.empty();
2631 }
2632 return false;
2633}
2634
Greg Clayton576d8832011-03-22 04:00:09 +00002635int
Chaoren Lind3173f32015-05-29 19:52:29 +00002636GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002637{
Chaoren Lind3173f32015-05-29 19:52:29 +00002638 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002639 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002640 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002641 StreamString packet;
2642 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002643 packet.PutCStringAsRawHex8(path.c_str());
2644
Greg Clayton576d8832011-03-22 04:00:09 +00002645 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002646 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002647 {
2648 if (response.IsOKResponse())
2649 return 0;
2650 uint8_t error = response.GetError();
2651 if (error)
2652 return error;
2653 }
2654 }
2655 return -1;
2656}
2657
2658int
2659GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2660{
Greg Clayton32e0a752011-03-30 18:16:51 +00002661 char packet[32];
2662 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002663 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002664 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002665 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002666 {
2667 if (response.IsOKResponse())
2668 return 0;
2669 uint8_t error = response.GetError();
2670 if (error)
2671 return error;
2672 }
2673 return -1;
2674}
Greg Clayton32e0a752011-03-30 18:16:51 +00002675
Jim Ingham106d0282014-06-25 02:32:56 +00002676int
2677GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2678{
2679 char packet[32];
2680 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2681 assert (packet_len < (int)sizeof(packet));
2682 StringExtractorGDBRemote response;
2683 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2684 {
2685 if (response.IsOKResponse())
2686 return 0;
2687 uint8_t error = response.GetError();
2688 if (error)
2689 return error;
2690 }
2691 return -1;
2692}
2693
2694
Greg Clayton32e0a752011-03-30 18:16:51 +00002695bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002696GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002697{
2698 if (response.IsNormalResponse())
2699 {
2700 std::string name;
2701 std::string value;
2702 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002703
2704 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2705 uint32_t sub = 0;
2706 std::string vendor;
2707 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002708
2709 while (response.GetNameColonValue(name, value))
2710 {
2711 if (name.compare("pid") == 0)
2712 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002713 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002714 }
2715 else if (name.compare("ppid") == 0)
2716 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002717 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002718 }
2719 else if (name.compare("uid") == 0)
2720 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002721 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002722 }
2723 else if (name.compare("euid") == 0)
2724 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002725 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002726 }
2727 else if (name.compare("gid") == 0)
2728 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002729 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002730 }
2731 else if (name.compare("egid") == 0)
2732 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002733 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002734 }
2735 else if (name.compare("triple") == 0)
2736 {
Greg Clayton44272a42014-09-18 00:18:32 +00002737 StringExtractor extractor;
2738 extractor.GetStringRef().swap(value);
2739 extractor.SetFilePos(0);
2740 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002741 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002742 }
2743 else if (name.compare("name") == 0)
2744 {
2745 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002746 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002747 // control the characters in a process name
2748 extractor.GetStringRef().swap(value);
2749 extractor.SetFilePos(0);
2750 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002751 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002752 }
Jason Molenda89c37492014-01-27 22:23:20 +00002753 else if (name.compare("cputype") == 0)
2754 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002755 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002756 }
2757 else if (name.compare("cpusubtype") == 0)
2758 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002759 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002760 }
2761 else if (name.compare("vendor") == 0)
2762 {
2763 vendor = value;
2764 }
2765 else if (name.compare("ostype") == 0)
2766 {
2767 os_type = value;
2768 }
2769 }
2770
2771 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2772 {
2773 if (vendor == "apple")
2774 {
2775 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2776 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2777 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2778 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002779 }
2780
2781 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2782 return true;
2783 }
2784 return false;
2785}
2786
2787bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002788GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002789{
2790 process_info.Clear();
2791
2792 if (m_supports_qProcessInfoPID)
2793 {
2794 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002795 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002796 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002797 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002798 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002799 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002800 return DecodeProcessInfoResponse (response, process_info);
2801 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002802 else
2803 {
2804 m_supports_qProcessInfoPID = false;
2805 return false;
2806 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002807 }
2808 return false;
2809}
2810
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002811bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002812GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002813{
Todd Fiala3daa1762014-09-15 16:01:29 +00002814 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2815
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002816 if (allow_lazy)
2817 {
2818 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2819 return true;
2820 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2821 return false;
2822 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002823
2824 GetHostInfo ();
2825
2826 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002827 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002828 {
2829 if (response.IsNormalResponse())
2830 {
2831 std::string name;
2832 std::string value;
2833 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2834 uint32_t sub = 0;
2835 std::string arch_name;
2836 std::string os_name;
2837 std::string vendor_name;
2838 std::string triple;
2839 uint32_t pointer_byte_size = 0;
2840 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002841 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002842 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002843 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002844 while (response.GetNameColonValue(name, value))
2845 {
2846 if (name.compare("cputype") == 0)
2847 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002848 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002849 if (cpu != LLDB_INVALID_CPUTYPE)
2850 ++num_keys_decoded;
2851 }
2852 else if (name.compare("cpusubtype") == 0)
2853 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002854 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002855 if (sub != 0)
2856 ++num_keys_decoded;
2857 }
Todd Fialac540dd02014-08-26 18:21:02 +00002858 else if (name.compare("triple") == 0)
2859 {
Greg Clayton44272a42014-09-18 00:18:32 +00002860 StringExtractor extractor;
2861 extractor.GetStringRef().swap(value);
2862 extractor.SetFilePos(0);
2863 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002864 ++num_keys_decoded;
2865 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002866 else if (name.compare("ostype") == 0)
2867 {
2868 os_name.swap (value);
2869 ++num_keys_decoded;
2870 }
2871 else if (name.compare("vendor") == 0)
2872 {
2873 vendor_name.swap(value);
2874 ++num_keys_decoded;
2875 }
2876 else if (name.compare("endian") == 0)
2877 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002878 ++num_keys_decoded;
2879 if (value.compare("little") == 0)
2880 byte_order = eByteOrderLittle;
2881 else if (value.compare("big") == 0)
2882 byte_order = eByteOrderBig;
2883 else if (value.compare("pdp") == 0)
2884 byte_order = eByteOrderPDP;
2885 else
2886 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002887 }
2888 else if (name.compare("ptrsize") == 0)
2889 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002890 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002891 if (pointer_byte_size != 0)
2892 ++num_keys_decoded;
2893 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002894 else if (name.compare("pid") == 0)
2895 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002896 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002897 if (pid != LLDB_INVALID_PROCESS_ID)
2898 ++num_keys_decoded;
2899 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002900 }
2901 if (num_keys_decoded > 0)
2902 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002903 if (pid != LLDB_INVALID_PROCESS_ID)
2904 {
2905 m_curr_pid_is_valid = eLazyBoolYes;
2906 m_curr_pid = pid;
2907 }
Todd Fialac540dd02014-08-26 18:21:02 +00002908
2909 // Set the ArchSpec from the triple if we have it.
2910 if (!triple.empty ())
2911 {
2912 m_process_arch.SetTriple (triple.c_str ());
2913 if (pointer_byte_size)
2914 {
2915 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2916 }
2917 }
2918 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002919 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002920 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2921
2922 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2923 switch (triple.getObjectFormat()) {
2924 case llvm::Triple::MachO:
2925 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2926 break;
2927 case llvm::Triple::ELF:
2928 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2929 break;
2930 case llvm::Triple::COFF:
2931 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2932 break;
2933 case llvm::Triple::UnknownObjectFormat:
2934 if (log)
2935 log->Printf("error: failed to determine target architecture");
2936 return false;
2937 }
2938
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002939 if (pointer_byte_size)
2940 {
2941 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2942 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002943 if (byte_order != eByteOrderInvalid)
2944 {
2945 assert (byte_order == m_process_arch.GetByteOrder());
2946 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002947 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002948 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002949 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2950 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002951 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002952 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002953 }
2954 }
2955 else
2956 {
2957 m_qProcessInfo_is_valid = eLazyBoolNo;
2958 }
2959
2960 return false;
2961}
2962
2963
Greg Clayton32e0a752011-03-30 18:16:51 +00002964uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002965GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2966 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002967{
2968 process_infos.Clear();
2969
2970 if (m_supports_qfProcessInfo)
2971 {
2972 StreamString packet;
2973 packet.PutCString ("qfProcessInfo");
2974 if (!match_info.MatchAllProcesses())
2975 {
2976 packet.PutChar (':');
2977 const char *name = match_info.GetProcessInfo().GetName();
2978 bool has_name_match = false;
2979 if (name && name[0])
2980 {
2981 has_name_match = true;
2982 NameMatchType name_match_type = match_info.GetNameMatchType();
2983 switch (name_match_type)
2984 {
2985 case eNameMatchIgnore:
2986 has_name_match = false;
2987 break;
2988
2989 case eNameMatchEquals:
2990 packet.PutCString ("name_match:equals;");
2991 break;
2992
2993 case eNameMatchContains:
2994 packet.PutCString ("name_match:contains;");
2995 break;
2996
2997 case eNameMatchStartsWith:
2998 packet.PutCString ("name_match:starts_with;");
2999 break;
3000
3001 case eNameMatchEndsWith:
3002 packet.PutCString ("name_match:ends_with;");
3003 break;
3004
3005 case eNameMatchRegularExpression:
3006 packet.PutCString ("name_match:regex;");
3007 break;
3008 }
3009 if (has_name_match)
3010 {
3011 packet.PutCString ("name:");
3012 packet.PutBytesAsRawHex8(name, ::strlen(name));
3013 packet.PutChar (';');
3014 }
3015 }
3016
3017 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003018 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003019 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003020 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00003021 if (match_info.GetProcessInfo().UserIDIsValid())
3022 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
3023 if (match_info.GetProcessInfo().GroupIDIsValid())
3024 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003025 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
3026 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
3027 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3028 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
3029 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3030 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
3031 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
3032 {
3033 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
3034 const llvm::Triple &triple = match_arch.GetTriple();
3035 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00003036 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00003037 packet.PutChar (';');
3038 }
3039 }
3040 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00003041 // Increase timeout as the first qfProcessInfo packet takes a long time
3042 // on Android. The value of 1min was arrived at empirically.
3043 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00003044 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003045 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003046 do
3047 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003048 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00003049 if (!DecodeProcessInfoResponse (response, process_info))
3050 break;
3051 process_infos.Append(process_info);
3052 response.GetStringRef().clear();
3053 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00003054 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00003055 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003056 else
3057 {
3058 m_supports_qfProcessInfo = false;
3059 return 0;
3060 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003061 }
3062 return process_infos.GetSize();
3063
3064}
3065
3066bool
3067GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
3068{
3069 if (m_supports_qUserName)
3070 {
3071 char packet[32];
3072 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003073 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003074 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003075 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003076 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003077 if (response.IsNormalResponse())
3078 {
3079 // Make sure we parsed the right number of characters. The response is
3080 // the hex encoded user name and should make up the entire packet.
3081 // If there are any non-hex ASCII bytes, the length won't match below..
3082 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3083 return true;
3084 }
3085 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003086 else
3087 {
3088 m_supports_qUserName = false;
3089 return false;
3090 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003091 }
3092 return false;
3093
3094}
3095
3096bool
3097GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3098{
3099 if (m_supports_qGroupName)
3100 {
3101 char packet[32];
3102 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003103 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003104 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003105 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003106 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003107 if (response.IsNormalResponse())
3108 {
3109 // Make sure we parsed the right number of characters. The response is
3110 // the hex encoded group name and should make up the entire packet.
3111 // If there are any non-hex ASCII bytes, the length won't match below..
3112 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3113 return true;
3114 }
3115 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003116 else
3117 {
3118 m_supports_qGroupName = false;
3119 return false;
3120 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003121 }
3122 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003123}
Greg Clayton32e0a752011-03-30 18:16:51 +00003124
Ewan Crawford78baa192015-05-13 09:18:18 +00003125bool
3126GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3127{
3128 // Form non-stop packet request
3129 char packet[32];
3130 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3131 assert(packet_len < (int)sizeof(packet));
3132
3133 StringExtractorGDBRemote response;
3134 // Send to target
3135 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3136 if (response.IsOKResponse())
3137 return true;
3138
3139 // Failed or not supported
3140 return false;
3141
3142}
3143
Greg Claytone034a042015-05-21 20:52:06 +00003144static void
3145MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3146{
3147 packet.Clear();
3148 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3149 uint32_t bytes_left = send_size;
3150 while (bytes_left > 0)
3151 {
3152 if (bytes_left >= 26)
3153 {
3154 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3155 bytes_left -= 26;
3156 }
3157 else
3158 {
3159 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3160 bytes_left = 0;
3161 }
3162 }
3163}
3164
3165template<typename T>
3166T calculate_standard_deviation(const std::vector<T> &v)
3167{
3168 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3169 T mean = sum / (T)v.size();
3170 T accum = T(0);
3171 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3172 T delta = d - mean;
3173 accum += delta * delta;
3174 });
3175
3176 T stdev = sqrt(accum / (v.size()-1));
3177 return stdev;
3178}
3179
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003180void
Greg Claytone034a042015-05-21 20:52:06 +00003181GDBRemoteCommunicationClient::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 +00003182{
3183 uint32_t i;
3184 TimeValue start_time, end_time;
3185 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003186 if (SendSpeedTestPacket (0, 0))
3187 {
Greg Claytone034a042015-05-21 20:52:06 +00003188 StreamString packet;
3189 if (json)
3190 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3191 else
3192 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3193 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00003194
Greg Claytone034a042015-05-21 20:52:06 +00003195 uint32_t result_idx = 0;
3196 uint32_t send_size;
3197 std::vector<float> packet_times;
3198
3199 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3200 {
3201 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3202 {
3203 MakeSpeedTestPacket (packet, send_size, recv_size);
3204
3205 packet_times.clear();
3206 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00003207 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00003208 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00003209 {
Greg Claytone034a042015-05-21 20:52:06 +00003210 TimeValue packet_start_time = TimeValue::Now();
3211 StringExtractorGDBRemote response;
3212 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3213 TimeValue packet_end_time = TimeValue::Now();
3214 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3215 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003216 }
3217 end_time = TimeValue::Now();
3218 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00003219
3220 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3221 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3222 float average_ms_per_packet = total_ms / num_packets;
3223 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3224 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00003225 {
Greg Claytone034a042015-05-21 20:52:06 +00003226 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);
3227 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00003228 }
3229 else
3230 {
Greg Claytone034a042015-05-21 20:52:06 +00003231 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",
3232 send_size,
3233 recv_size,
3234 total_time_nsec / TimeValue::NanoSecPerSec,
3235 total_time_nsec % TimeValue::NanoSecPerSec,
3236 packets_per_second,
3237 average_ms_per_packet,
3238 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00003239 }
Greg Claytone034a042015-05-21 20:52:06 +00003240 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003241 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003242 }
Greg Claytone034a042015-05-21 20:52:06 +00003243
3244 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3245
3246 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3247 if (json)
3248 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3249 else
3250 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3251 strm.Flush();
3252 send_size = 0;
3253 result_idx = 0;
3254 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3255 {
3256 MakeSpeedTestPacket (packet, send_size, recv_size);
3257
3258 // If we have a receive size, test how long it takes to receive 4MB of data
3259 if (recv_size > 0)
3260 {
3261 start_time = TimeValue::Now();
3262 uint32_t bytes_read = 0;
3263 uint32_t packet_count = 0;
3264 while (bytes_read < k_recv_amount)
3265 {
3266 StringExtractorGDBRemote response;
3267 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3268 bytes_read += recv_size;
3269 ++packet_count;
3270 }
3271 end_time = TimeValue::Now();
3272 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3273 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3274 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3275 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3276 float average_ms_per_packet = total_ms / packet_count;
3277
3278 if (json)
3279 {
3280 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);
3281 ++result_idx;
3282 }
3283 else
3284 {
3285 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",
3286 send_size,
3287 recv_size,
3288 packet_count,
3289 k_recv_amount_mb,
3290 total_time_nsec / TimeValue::NanoSecPerSec,
3291 total_time_nsec % TimeValue::NanoSecPerSec,
3292 mb_second,
3293 packets_per_second,
3294 average_ms_per_packet);
3295 }
3296 strm.Flush();
3297 }
3298 }
3299 if (json)
3300 strm.Printf("\n ]\n }\n}\n");
3301 else
3302 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003303 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003304}
3305
3306bool
3307GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3308{
3309 StreamString packet;
3310 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3311 uint32_t bytes_left = send_size;
3312 while (bytes_left > 0)
3313 {
3314 if (bytes_left >= 26)
3315 {
3316 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3317 bytes_left -= 26;
3318 }
3319 else
3320 {
3321 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3322 bytes_left = 0;
3323 }
3324 }
3325
3326 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003327 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00003328}
Greg Clayton8b82f082011-04-12 05:54:46 +00003329
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003330bool
3331GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
3332 lldb::pid_t &pid,
3333 uint16_t &port,
3334 std::string &socket_name)
Greg Clayton8b82f082011-04-12 05:54:46 +00003335{
Daniel Maleae0f8f572013-08-26 23:57:52 +00003336 pid = LLDB_INVALID_PROCESS_ID;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003337 port = 0;
3338 socket_name.clear();
3339
Greg Clayton8b82f082011-04-12 05:54:46 +00003340 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003341 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00003342 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003343 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00003344 if (remote_accept_hostname && remote_accept_hostname[0])
3345 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003346 else
3347 {
Zachary Turner97a14e62014-08-19 17:18:29 +00003348 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00003349 {
3350 // Make the GDB server we launch only accept connections from this host
3351 stream.Printf("host:%s;", hostname.c_str());
3352 }
3353 else
3354 {
3355 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3356 stream.Printf("host:*;");
3357 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003358 }
3359 const char *packet = stream.GetData();
3360 int packet_len = stream.GetSize();
3361
Vince Harron1b5a74e2015-01-21 22:42:49 +00003362 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003363 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003364
Tamas Berghammer912800c2015-02-24 10:23:39 +00003365 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003366 {
3367 std::string name;
3368 std::string value;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003369 StringExtractor extractor;
Greg Clayton8b82f082011-04-12 05:54:46 +00003370 while (response.GetNameColonValue(name, value))
3371 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003372 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003373 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003374 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003375 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003376 else if (name.compare("socket_name") == 0)
3377 {
3378 extractor.GetStringRef().swap(value);
3379 extractor.SetFilePos(0);
3380 extractor.GetHexByteString(value);
3381
3382 socket_name = value;
3383 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003384 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003385 return true;
Greg Clayton8b82f082011-04-12 05:54:46 +00003386 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003387 return false;
Greg Clayton8b82f082011-04-12 05:54:46 +00003388}
3389
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00003390size_t
3391GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls)
3392{
3393 connection_urls.clear();
3394
3395 StringExtractorGDBRemote response;
3396 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success)
3397 return 0;
3398
3399 StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef());
3400 if (!data)
3401 return 0;
3402
3403 StructuredData::Array* array = data->GetAsArray();
3404 if (!array)
3405 return 0;
3406
3407 for (size_t i = 0, count = array->GetSize(); i < count; ++i)
3408 {
3409 StructuredData::Dictionary* element = nullptr;
3410 if (!array->GetItemAtIndexAsDictionary(i, element))
3411 continue;
3412
3413 uint16_t port = 0;
3414 if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port")))
3415 port = port_osp->GetIntegerValue(0);
3416
3417 std::string socket_name;
3418 if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name")))
3419 socket_name = socket_name_osp->GetStringValue();
3420
3421 if (port != 0 || !socket_name.empty())
3422 connection_urls.emplace_back(port, socket_name);
3423 }
3424 return connection_urls.size();
3425}
3426
Greg Clayton8b82f082011-04-12 05:54:46 +00003427bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003428GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3429{
3430 StreamString stream;
3431 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3432 const char *packet = stream.GetData();
3433 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003434
Daniel Maleae0f8f572013-08-26 23:57:52 +00003435 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003436 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003437 {
3438 if (response.IsOKResponse())
3439 return true;
3440 }
3441 return false;
3442}
3443
3444bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003445GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003446{
3447 if (m_curr_tid == tid)
3448 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003449
Greg Clayton8b82f082011-04-12 05:54:46 +00003450 char packet[32];
3451 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003452 if (tid == UINT64_MAX)
3453 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003454 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003455 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003456 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003457 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003458 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003459 {
3460 if (response.IsOKResponse())
3461 {
3462 m_curr_tid = tid;
3463 return true;
3464 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003465
3466 /*
3467 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
3468 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3469 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3470 */
3471 if (response.IsUnsupportedResponse() && IsConnected())
3472 {
3473 m_curr_tid = 1;
3474 return true;
3475 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003476 }
3477 return false;
3478}
3479
3480bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003481GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003482{
3483 if (m_curr_tid_run == tid)
3484 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003485
Greg Clayton8b82f082011-04-12 05:54:46 +00003486 char packet[32];
3487 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003488 if (tid == UINT64_MAX)
3489 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003490 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003491 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3492
Andy Gibbsa297a972013-06-19 19:04:53 +00003493 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003494 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003495 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003496 {
3497 if (response.IsOKResponse())
3498 {
3499 m_curr_tid_run = tid;
3500 return true;
3501 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003502
3503 /*
3504 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
3505 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3506 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3507 */
3508 if (response.IsUnsupportedResponse() && IsConnected())
3509 {
3510 m_curr_tid_run = 1;
3511 return true;
3512 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003513 }
3514 return false;
3515}
3516
3517bool
3518GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3519{
Greg Clayton3dedae12013-12-06 21:45:27 +00003520 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003521 return response.IsNormalResponse();
3522 return false;
3523}
3524
3525bool
Greg Claytonf402f782012-10-13 02:11:55 +00003526GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003527{
3528 if (m_supports_qThreadStopInfo)
3529 {
3530 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003531 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003532 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003533 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003534 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003535 if (response.IsUnsupportedResponse())
3536 m_supports_qThreadStopInfo = false;
3537 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003538 return true;
3539 else
3540 return false;
3541 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003542 else
3543 {
3544 m_supports_qThreadStopInfo = false;
3545 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003546 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003547 return false;
3548}
3549
3550
3551uint8_t
3552GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3553{
Todd Fiala616b8272014-10-09 00:55:04 +00003554 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3555 if (log)
3556 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3557 __FUNCTION__, insert ? "add" : "remove", addr);
3558
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003559 // Check if the stub is known not to support this breakpoint type
3560 if (!SupportsGDBStoppointPacket(type))
3561 return UINT8_MAX;
3562 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003563 char packet[64];
3564 const int packet_len = ::snprintf (packet,
3565 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003566 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003567 insert ? 'Z' : 'z',
3568 type,
3569 addr,
3570 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003571 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003572 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003573 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003574 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003575 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003576 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003577 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003578 if (response.IsOKResponse())
3579 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003580
3581 // Error while setting breakpoint, send back specific error
3582 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003583 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003584
3585 // Empty packet informs us that breakpoint is not supported
3586 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003587 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003588 // Disable this breakpoint type since it is unsupported
3589 switch (type)
3590 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003591 case eBreakpointSoftware: m_supports_z0 = false; break;
3592 case eBreakpointHardware: m_supports_z1 = false; break;
3593 case eWatchpointWrite: m_supports_z2 = false; break;
3594 case eWatchpointRead: m_supports_z3 = false; break;
3595 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003596 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003597 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003598 }
3599 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003600 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003601 return UINT8_MAX;
3602}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003603
3604size_t
3605GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3606 bool &sequence_mutex_unavailable)
3607{
3608 Mutex::Locker locker;
3609 thread_ids.clear();
3610
Jim Ingham4ceb9282012-06-08 22:50:40 +00003611 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003612 {
3613 sequence_mutex_unavailable = false;
3614 StringExtractorGDBRemote response;
3615
Greg Clayton3dedae12013-12-06 21:45:27 +00003616 PacketResult packet_result;
3617 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3618 packet_result == PacketResult::Success && response.IsNormalResponse();
3619 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003620 {
3621 char ch = response.GetChar();
3622 if (ch == 'l')
3623 break;
3624 if (ch == 'm')
3625 {
3626 do
3627 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003628 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003629
3630 if (tid != LLDB_INVALID_THREAD_ID)
3631 {
3632 thread_ids.push_back (tid);
3633 }
3634 ch = response.GetChar(); // Skip the command separator
3635 } while (ch == ','); // Make sure we got a comma separator
3636 }
3637 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003638
3639 /*
3640 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3641 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
3642 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
3643 * Assume pid=tid=1 in such cases.
3644 */
3645 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
3646 {
3647 thread_ids.push_back (1);
3648 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00003649 }
3650 else
3651 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003652#if defined (LLDB_CONFIGURATION_DEBUG)
3653 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3654#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003655 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003656 if (log)
3657 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003658#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003659 sequence_mutex_unavailable = true;
3660 }
3661 return thread_ids.size();
3662}
Greg Clayton37a0a242012-04-11 00:24:49 +00003663
3664lldb::addr_t
3665GDBRemoteCommunicationClient::GetShlibInfoAddr()
3666{
3667 if (!IsRunning())
3668 {
3669 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003670 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003671 {
3672 if (response.IsNormalResponse())
3673 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3674 }
3675 }
3676 return LLDB_INVALID_ADDRESS;
3677}
3678
Daniel Maleae0f8f572013-08-26 23:57:52 +00003679lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003680GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3681 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3682 int *status_ptr, // Pass NULL if you don't want the process exit status
3683 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3684 std::string *command_output, // Pass NULL if you don't want the command output
3685 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003686{
3687 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003688 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003689 stream.PutBytesAsRawHex8(command, strlen(command));
3690 stream.PutChar(',');
3691 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003692 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003693 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003694 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003695 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003696 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003697 }
3698 const char *packet = stream.GetData();
3699 int packet_len = stream.GetSize();
3700 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003701 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003702 {
3703 if (response.GetChar() != 'F')
3704 return Error("malformed reply");
3705 if (response.GetChar() != ',')
3706 return Error("malformed reply");
3707 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3708 if (exitcode == UINT32_MAX)
3709 return Error("unable to run remote process");
3710 else if (status_ptr)
3711 *status_ptr = exitcode;
3712 if (response.GetChar() != ',')
3713 return Error("malformed reply");
3714 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3715 if (signo_ptr)
3716 *signo_ptr = signo;
3717 if (response.GetChar() != ',')
3718 return Error("malformed reply");
3719 std::string output;
3720 response.GetEscapedBinaryData(output);
3721 if (command_output)
3722 command_output->assign(output);
3723 return Error();
3724 }
3725 return Error("unable to send packet");
3726}
3727
Greg Claytonfbb76342013-11-20 21:07:01 +00003728Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003729GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3730 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003731{
Chaoren Lind3173f32015-05-29 19:52:29 +00003732 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003733 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003734 stream.PutCString("qPlatform_mkdir:");
3735 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003736 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003737 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003738 const char *packet = stream.GetData();
3739 int packet_len = stream.GetSize();
3740 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003741
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003742 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3743 return Error("failed to send '%s' packet", packet);
3744
3745 if (response.GetChar() != 'F')
3746 return Error("invalid response to '%s' packet", packet);
3747
3748 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003749}
3750
Greg Claytonfbb76342013-11-20 21:07:01 +00003751Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003752GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3753 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003754{
Chaoren Lind3173f32015-05-29 19:52:29 +00003755 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003756 lldb_private::StreamString stream;
3757 stream.PutCString("qPlatform_chmod:");
3758 stream.PutHex32(file_permissions);
3759 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003760 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003761 const char *packet = stream.GetData();
3762 int packet_len = stream.GetSize();
3763 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003764
3765 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3766 return Error("failed to send '%s' packet", packet);
3767
3768 if (response.GetChar() != 'F')
3769 return Error("invalid response to '%s' packet", packet);
3770
Chaoren Lince36c4c2015-05-05 18:43:19 +00003771 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003772}
3773
Daniel Maleae0f8f572013-08-26 23:57:52 +00003774static uint64_t
3775ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3776 uint64_t fail_result,
3777 Error &error)
3778{
3779 response.SetFilePos(0);
3780 if (response.GetChar() != 'F')
3781 return fail_result;
3782 int32_t result = response.GetS32 (-2);
3783 if (result == -2)
3784 return fail_result;
3785 if (response.GetChar() == ',')
3786 {
3787 int result_errno = response.GetS32 (-2);
3788 if (result_errno != -2)
3789 error.SetError(result_errno, eErrorTypePOSIX);
3790 else
3791 error.SetError(-1, eErrorTypeGeneric);
3792 }
3793 else
3794 error.Clear();
3795 return result;
3796}
3797lldb::user_id_t
3798GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3799 uint32_t flags,
3800 mode_t mode,
3801 Error &error)
3802{
Chaoren Lind3173f32015-05-29 19:52:29 +00003803 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003804 lldb_private::StreamString stream;
3805 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003806 if (path.empty())
3807 return UINT64_MAX;
3808 stream.PutCStringAsRawHex8(path.c_str());
3809 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003810 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003811 stream.PutChar(',');
3812 stream.PutHex32(mode);
3813 const char* packet = stream.GetData();
3814 int packet_len = stream.GetSize();
3815 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003816 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003817 {
3818 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3819 }
3820 return UINT64_MAX;
3821}
3822
3823bool
3824GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3825 Error &error)
3826{
3827 lldb_private::StreamString stream;
3828 stream.Printf("vFile:close:%i", (int)fd);
3829 const char* packet = stream.GetData();
3830 int packet_len = stream.GetSize();
3831 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003832 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003833 {
3834 return ParseHostIOPacketResponse (response, -1, error) == 0;
3835 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003836 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003837}
3838
3839// Extension of host I/O packets to get the file size.
3840lldb::user_id_t
3841GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3842{
Chaoren Lind3173f32015-05-29 19:52:29 +00003843 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003844 lldb_private::StreamString stream;
3845 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003846 stream.PutCStringAsRawHex8(path.c_str());
3847 const char* packet = stream.GetData();
3848 int packet_len = stream.GetSize();
3849 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003850 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003851 {
3852 if (response.GetChar() != 'F')
3853 return UINT64_MAX;
3854 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3855 return retcode;
3856 }
3857 return UINT64_MAX;
3858}
3859
Greg Claytonfbb76342013-11-20 21:07:01 +00003860Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003861GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3862 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003863{
Chaoren Lind3173f32015-05-29 19:52:29 +00003864 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003865 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003866 lldb_private::StreamString stream;
3867 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003868 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003869 const char* packet = stream.GetData();
3870 int packet_len = stream.GetSize();
3871 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003872 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003873 {
3874 if (response.GetChar() != 'F')
3875 {
3876 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003877 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003878 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003879 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003880 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003881 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003882 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003883 if (response.GetChar() == ',')
3884 {
3885 int response_errno = response.GetS32(-1);
3886 if (response_errno > 0)
3887 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3888 else
3889 error.SetErrorToGenericError();
3890 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003891 else
3892 error.SetErrorToGenericError();
3893 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003894 else
3895 {
3896 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3897 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003898 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003899 }
3900 else
3901 {
3902 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3903 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003904 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003905}
3906
3907uint64_t
3908GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3909 uint64_t offset,
3910 void *dst,
3911 uint64_t dst_len,
3912 Error &error)
3913{
3914 lldb_private::StreamString stream;
3915 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3916 const char* packet = stream.GetData();
3917 int packet_len = stream.GetSize();
3918 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003919 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003920 {
3921 if (response.GetChar() != 'F')
3922 return 0;
3923 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3924 if (retcode == UINT32_MAX)
3925 return retcode;
3926 const char next = (response.Peek() ? *response.Peek() : 0);
3927 if (next == ',')
3928 return 0;
3929 if (next == ';')
3930 {
3931 response.GetChar(); // skip the semicolon
3932 std::string buffer;
3933 if (response.GetEscapedBinaryData(buffer))
3934 {
3935 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3936 if (data_to_write > 0)
3937 memcpy(dst, &buffer[0], data_to_write);
3938 return data_to_write;
3939 }
3940 }
3941 }
3942 return 0;
3943}
3944
3945uint64_t
3946GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3947 uint64_t offset,
3948 const void* src,
3949 uint64_t src_len,
3950 Error &error)
3951{
3952 lldb_private::StreamGDBRemote stream;
3953 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3954 stream.PutEscapedBytes(src, src_len);
3955 const char* packet = stream.GetData();
3956 int packet_len = stream.GetSize();
3957 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003958 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003959 {
3960 if (response.GetChar() != 'F')
3961 {
3962 error.SetErrorStringWithFormat("write file failed");
3963 return 0;
3964 }
3965 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3966 if (bytes_written == UINT64_MAX)
3967 {
3968 error.SetErrorToGenericError();
3969 if (response.GetChar() == ',')
3970 {
3971 int response_errno = response.GetS32(-1);
3972 if (response_errno > 0)
3973 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3974 }
3975 return 0;
3976 }
3977 return bytes_written;
3978 }
3979 else
3980 {
3981 error.SetErrorString ("failed to send vFile:pwrite packet");
3982 }
3983 return 0;
3984}
3985
Greg Claytonfbb76342013-11-20 21:07:01 +00003986Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003987GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003988{
Chaoren Lind3173f32015-05-29 19:52:29 +00003989 std::string src_path{src.GetPath(false)},
3990 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003991 Error error;
3992 lldb_private::StreamGDBRemote stream;
3993 stream.PutCString("vFile:symlink:");
3994 // the unix symlink() command reverses its parameters where the dst if first,
3995 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003996 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003997 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003998 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003999 const char* packet = stream.GetData();
4000 int packet_len = stream.GetSize();
4001 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004002 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00004003 {
4004 if (response.GetChar() == 'F')
4005 {
4006 uint32_t result = response.GetU32(UINT32_MAX);
4007 if (result != 0)
4008 {
4009 error.SetErrorToGenericError();
4010 if (response.GetChar() == ',')
4011 {
4012 int response_errno = response.GetS32(-1);
4013 if (response_errno > 0)
4014 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4015 }
4016 }
4017 }
4018 else
4019 {
4020 // Should have returned with 'F<result>[,<errno>]'
4021 error.SetErrorStringWithFormat("symlink failed");
4022 }
4023 }
4024 else
4025 {
4026 error.SetErrorString ("failed to send vFile:symlink packet");
4027 }
4028 return error;
4029}
4030
4031Error
Chaoren Lind3173f32015-05-29 19:52:29 +00004032GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00004033{
Chaoren Lind3173f32015-05-29 19:52:29 +00004034 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00004035 Error error;
4036 lldb_private::StreamGDBRemote stream;
4037 stream.PutCString("vFile:unlink:");
4038 // the unix symlink() command reverses its parameters where the dst if first,
4039 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00004040 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00004041 const char* packet = stream.GetData();
4042 int packet_len = stream.GetSize();
4043 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004044 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00004045 {
4046 if (response.GetChar() == 'F')
4047 {
4048 uint32_t result = response.GetU32(UINT32_MAX);
4049 if (result != 0)
4050 {
4051 error.SetErrorToGenericError();
4052 if (response.GetChar() == ',')
4053 {
4054 int response_errno = response.GetS32(-1);
4055 if (response_errno > 0)
4056 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4057 }
4058 }
4059 }
4060 else
4061 {
4062 // Should have returned with 'F<result>[,<errno>]'
4063 error.SetErrorStringWithFormat("unlink failed");
4064 }
4065 }
4066 else
4067 {
4068 error.SetErrorString ("failed to send vFile:unlink packet");
4069 }
4070 return error;
4071}
4072
Daniel Maleae0f8f572013-08-26 23:57:52 +00004073// Extension of host I/O packets to get whether a file exists.
4074bool
4075GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
4076{
Chaoren Lind3173f32015-05-29 19:52:29 +00004077 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004078 lldb_private::StreamString stream;
4079 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004080 stream.PutCStringAsRawHex8(path.c_str());
4081 const char* packet = stream.GetData();
4082 int packet_len = stream.GetSize();
4083 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004084 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004085 {
4086 if (response.GetChar() != 'F')
4087 return false;
4088 if (response.GetChar() != ',')
4089 return false;
4090 bool retcode = (response.GetChar() != '0');
4091 return retcode;
4092 }
4093 return false;
4094}
4095
4096bool
4097GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
4098 uint64_t &high,
4099 uint64_t &low)
4100{
Chaoren Lind3173f32015-05-29 19:52:29 +00004101 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004102 lldb_private::StreamString stream;
4103 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004104 stream.PutCStringAsRawHex8(path.c_str());
4105 const char* packet = stream.GetData();
4106 int packet_len = stream.GetSize();
4107 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004108 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004109 {
4110 if (response.GetChar() != 'F')
4111 return false;
4112 if (response.GetChar() != ',')
4113 return false;
4114 if (response.Peek() && *response.Peek() == 'x')
4115 return false;
4116 low = response.GetHexMaxU64(false, UINT64_MAX);
4117 high = response.GetHexMaxU64(false, UINT64_MAX);
4118 return true;
4119 }
4120 return false;
4121}
Greg Claytonf74cf862013-11-13 23:28:31 +00004122
4123bool
Jason Molendaa3329782014-03-29 18:54:20 +00004124GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
4125{
4126 // Some targets have issues with g/G packets and we need to avoid using them
4127 if (m_avoid_g_packets == eLazyBoolCalculate)
4128 {
4129 if (process)
4130 {
4131 m_avoid_g_packets = eLazyBoolNo;
4132 const ArchSpec &arch = process->GetTarget().GetArchitecture();
4133 if (arch.IsValid()
4134 && arch.GetTriple().getVendor() == llvm::Triple::Apple
4135 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00004136 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00004137 {
4138 m_avoid_g_packets = eLazyBoolYes;
4139 uint32_t gdb_server_version = GetGDBServerProgramVersion();
4140 if (gdb_server_version != 0)
4141 {
4142 const char *gdb_server_name = GetGDBServerProgramName();
4143 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
4144 {
4145 if (gdb_server_version >= 310)
4146 m_avoid_g_packets = eLazyBoolNo;
4147 }
4148 }
4149 }
4150 }
4151 }
4152 return m_avoid_g_packets == eLazyBoolYes;
4153}
4154
4155bool
Greg Claytonf74cf862013-11-13 23:28:31 +00004156GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4157{
4158 Mutex::Locker locker;
4159 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4160 {
4161 const bool thread_suffix_supported = GetThreadSuffixSupported();
4162
4163 if (thread_suffix_supported || SetCurrentThread(tid))
4164 {
4165 char packet[64];
4166 int packet_len = 0;
4167 if (thread_suffix_supported)
4168 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4169 else
4170 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4171 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004172 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004173 }
4174 }
4175 return false;
4176
4177}
4178
4179
4180bool
4181GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4182{
4183 Mutex::Locker locker;
4184 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4185 {
4186 const bool thread_suffix_supported = GetThreadSuffixSupported();
4187
4188 if (thread_suffix_supported || SetCurrentThread(tid))
4189 {
4190 char packet[64];
4191 int packet_len = 0;
4192 // Get all registers in one packet
4193 if (thread_suffix_supported)
4194 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4195 else
4196 packet_len = ::snprintf (packet, sizeof(packet), "g");
4197 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004198 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004199 }
4200 }
4201 return false;
4202}
4203bool
4204GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4205{
4206 save_id = 0; // Set to invalid save ID
4207 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4208 return false;
4209
4210 m_supports_QSaveRegisterState = eLazyBoolYes;
4211 Mutex::Locker locker;
4212 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4213 {
4214 const bool thread_suffix_supported = GetThreadSuffixSupported();
4215 if (thread_suffix_supported || SetCurrentThread(tid))
4216 {
4217 char packet[256];
4218 if (thread_suffix_supported)
4219 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4220 else
Ilia K686b1fe2015-02-27 19:43:08 +00004221 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00004222
4223 StringExtractorGDBRemote response;
4224
Greg Clayton3dedae12013-12-06 21:45:27 +00004225 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004226 {
4227 if (response.IsUnsupportedResponse())
4228 {
4229 // This packet isn't supported, don't try calling it again
4230 m_supports_QSaveRegisterState = eLazyBoolNo;
4231 }
4232
4233 const uint32_t response_save_id = response.GetU32(0);
4234 if (response_save_id != 0)
4235 {
4236 save_id = response_save_id;
4237 return true;
4238 }
4239 }
4240 }
4241 }
4242 return false;
4243}
4244
4245bool
4246GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4247{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004248 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00004249 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4250 // order to be useful
4251 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4252 return false;
4253
4254 Mutex::Locker locker;
4255 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4256 {
4257 const bool thread_suffix_supported = GetThreadSuffixSupported();
4258 if (thread_suffix_supported || SetCurrentThread(tid))
4259 {
4260 char packet[256];
4261 if (thread_suffix_supported)
4262 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4263 else
4264 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4265
4266 StringExtractorGDBRemote response;
4267
Greg Clayton3dedae12013-12-06 21:45:27 +00004268 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004269 {
4270 if (response.IsOKResponse())
4271 {
4272 return true;
4273 }
4274 else if (response.IsUnsupportedResponse())
4275 {
4276 // This packet isn't supported, don't try calling this packet or
4277 // QSaveRegisterState again...
4278 m_supports_QSaveRegisterState = eLazyBoolNo;
4279 }
4280 }
4281 }
4282 }
4283 return false;
4284}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004285
4286bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004287GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004288 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004289 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004290{
Stephane Sezer6f455292016-01-08 00:00:17 +00004291 if (!m_supports_qModuleInfo)
4292 return false;
4293
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00004294 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004295 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004296 return false;
4297
4298 StreamString packet;
4299 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004300 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004301 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00004302 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00004303 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004304
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004305 StringExtractorGDBRemote response;
4306 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4307 return false;
4308
Stephane Sezer6f455292016-01-08 00:00:17 +00004309 if (response.IsErrorResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004310 return false;
4311
Stephane Sezer6f455292016-01-08 00:00:17 +00004312 if (response.IsUnsupportedResponse ())
4313 {
4314 m_supports_qModuleInfo = false;
4315 return false;
4316 }
4317
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004318 std::string name;
4319 std::string value;
4320 bool success;
4321 StringExtractor extractor;
4322
4323 module_spec.Clear ();
4324 module_spec.GetFileSpec () = module_file_spec;
4325
4326 while (response.GetNameColonValue (name, value))
4327 {
4328 if (name == "uuid" || name == "md5")
4329 {
4330 extractor.GetStringRef ().swap (value);
4331 extractor.SetFilePos (0);
4332 extractor.GetHexByteString (value);
4333 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4334 }
4335 else if (name == "triple")
4336 {
4337 extractor.GetStringRef ().swap (value);
4338 extractor.SetFilePos (0);
4339 extractor.GetHexByteString (value);
4340 module_spec.GetArchitecture().SetTriple (value.c_str ());
4341 }
4342 else if (name == "file_offset")
4343 {
4344 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4345 if (success)
4346 module_spec.SetObjectOffset (ival);
4347 }
4348 else if (name == "file_size")
4349 {
4350 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4351 if (success)
4352 module_spec.SetObjectSize (ival);
4353 }
4354 else if (name == "file_path")
4355 {
4356 extractor.GetStringRef ().swap (value);
4357 extractor.SetFilePos (0);
4358 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00004359 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004360 }
4361 }
4362
4363 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004364}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004365
4366// query the target remote for extended information using the qXfer packet
4367//
4368// example: object='features', annex='target.xml', out=<xml output>
4369// return: 'true' on success
4370// 'false' on failure (err set)
4371bool
4372GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4373 const lldb_private::ConstString annex,
4374 std::string & out,
4375 lldb_private::Error & err) {
4376
4377 std::stringstream output;
4378 StringExtractorGDBRemote chunk;
4379
Greg Claytond04f0ed2015-05-26 18:00:51 +00004380 uint64_t size = GetRemoteMaxPacketSize();
4381 if (size == 0)
4382 size = 0x1000;
4383 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4384 int offset = 0;
4385 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004386
4387 // loop until all data has been read
4388 while ( active ) {
4389
4390 // send query extended feature packet
4391 std::stringstream packet;
4392 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00004393 << object.AsCString("") << ":read:"
4394 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00004395 << std::hex << offset << ","
4396 << std::hex << size;
4397
4398 GDBRemoteCommunication::PacketResult res =
4399 SendPacketAndWaitForResponse( packet.str().c_str(),
4400 chunk,
4401 false );
4402
4403 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4404 err.SetErrorString( "Error sending $qXfer packet" );
4405 return false;
4406 }
4407
4408 const std::string & str = chunk.GetStringRef( );
4409 if ( str.length() == 0 ) {
4410 // should have some data in chunk
4411 err.SetErrorString( "Empty response from $qXfer packet" );
4412 return false;
4413 }
4414
4415 // check packet code
4416 switch ( str[0] ) {
4417 // last chunk
4418 case ( 'l' ):
4419 active = false;
Aidan Doddsed9f6122015-04-29 10:08:17 +00004420 // fall through intentional
Colin Rileyc3c95b22015-04-16 15:51:33 +00004421
4422 // more chunks
4423 case ( 'm' ) :
4424 if ( str.length() > 1 )
4425 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00004426 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004427 break;
4428
4429 // unknown chunk
4430 default:
4431 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4432 return false;
4433 }
4434 }
4435
4436 out = output.str( );
4437 err.Success( );
4438 return true;
4439}
Greg Clayton0b90be12015-06-23 21:27:50 +00004440
4441// Notify the target that gdb is prepared to serve symbol lookup requests.
4442// packet: "qSymbol::"
4443// reply:
4444// OK The target does not need to look up any (more) symbols.
4445// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
4446// LLDB may provide the value by sending another qSymbol packet
4447// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00004448//
4449// Three examples:
4450//
4451// lldb sends: qSymbol::
4452// lldb receives: OK
4453// Remote gdb stub does not need to know the addresses of any symbols, lldb does not
4454// need to ask again in this session.
4455//
4456// lldb sends: qSymbol::
4457// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4458// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4459// lldb receives: OK
4460// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does not know
4461// the address at this time. lldb needs to send qSymbol:: again when it has more
4462// solibs loaded.
4463//
4464// lldb sends: qSymbol::
4465// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4466// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4467// lldb receives: OK
4468// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says that it
4469// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it does not
4470// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00004471
4472void
4473GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4474{
Jason Molenda50018d32016-01-13 04:08:10 +00004475 // Set to true once we've resolved a symbol to an address for the remote stub.
4476 // If we get an 'OK' response after this, the remote stub doesn't need any more
4477 // symbols and we can stop asking.
4478 bool symbol_response_provided = false;
4479
4480 // Is this the inital qSymbol:: packet?
4481 bool first_qsymbol_query = true;
4482
4483 if (m_supports_qSymbol && m_qSymbol_requests_done == false)
Greg Clayton0b90be12015-06-23 21:27:50 +00004484 {
4485 Mutex::Locker locker;
4486 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4487 {
4488 StreamString packet;
4489 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00004490 StringExtractorGDBRemote response;
4491 while (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00004492 {
Greg Clayton42b01482015-08-11 22:07:46 +00004493 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00004494 {
Jason Molenda50018d32016-01-13 04:08:10 +00004495 if (symbol_response_provided || first_qsymbol_query)
4496 {
4497 m_qSymbol_requests_done = true;
4498 }
4499
Greg Clayton42b01482015-08-11 22:07:46 +00004500 // We are done serving symbols requests
4501 return;
4502 }
Jason Molenda50018d32016-01-13 04:08:10 +00004503 first_qsymbol_query = false;
Greg Clayton0b90be12015-06-23 21:27:50 +00004504
Greg Clayton42b01482015-08-11 22:07:46 +00004505 if (response.IsUnsupportedResponse())
4506 {
4507 // qSymbol is not supported by the current GDB server we are connected to
4508 m_supports_qSymbol = false;
4509 return;
4510 }
4511 else
4512 {
4513 llvm::StringRef response_str(response.GetStringRef());
4514 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00004515 {
Greg Clayton42b01482015-08-11 22:07:46 +00004516 response.SetFilePos(strlen("qSymbol:"));
4517 std::string symbol_name;
4518 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00004519 {
Greg Clayton42b01482015-08-11 22:07:46 +00004520 if (symbol_name.empty())
4521 return;
4522
4523 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4524 lldb_private::SymbolContextList sc_list;
4525 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00004526 {
Greg Clayton42b01482015-08-11 22:07:46 +00004527 const size_t num_scs = sc_list.GetSize();
4528 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 +00004529 {
Greg Clayton42b01482015-08-11 22:07:46 +00004530 SymbolContext sc;
4531 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00004532 {
Greg Clayton42b01482015-08-11 22:07:46 +00004533 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00004534 {
Greg Clayton42b01482015-08-11 22:07:46 +00004535 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00004536 {
Greg Clayton42b01482015-08-11 22:07:46 +00004537 case eSymbolTypeInvalid:
4538 case eSymbolTypeAbsolute:
4539 case eSymbolTypeUndefined:
4540 case eSymbolTypeSourceFile:
4541 case eSymbolTypeHeaderFile:
4542 case eSymbolTypeObjectFile:
4543 case eSymbolTypeCommonBlock:
4544 case eSymbolTypeBlock:
4545 case eSymbolTypeLocal:
4546 case eSymbolTypeParam:
4547 case eSymbolTypeVariable:
4548 case eSymbolTypeVariableType:
4549 case eSymbolTypeLineEntry:
4550 case eSymbolTypeLineHeader:
4551 case eSymbolTypeScopeBegin:
4552 case eSymbolTypeScopeEnd:
4553 case eSymbolTypeAdditional:
4554 case eSymbolTypeCompiler:
4555 case eSymbolTypeInstrumentation:
4556 case eSymbolTypeTrampoline:
4557 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004558
Greg Clayton42b01482015-08-11 22:07:46 +00004559 case eSymbolTypeCode:
4560 case eSymbolTypeResolver:
4561 case eSymbolTypeData:
4562 case eSymbolTypeRuntime:
4563 case eSymbolTypeException:
4564 case eSymbolTypeObjCClass:
4565 case eSymbolTypeObjCMetaClass:
4566 case eSymbolTypeObjCIVar:
4567 case eSymbolTypeReExported:
4568 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4569 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004570 }
4571 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004572 }
4573 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004574 }
Greg Clayton42b01482015-08-11 22:07:46 +00004575 // This is the normal path where our symbol lookup was successful and we want
4576 // to send a packet with the new symbol value and see if another lookup needs to be
4577 // done.
4578
4579 // Change "packet" to contain the requested symbol value and name
4580 packet.Clear();
4581 packet.PutCString("qSymbol:");
4582 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
Jason Molenda50018d32016-01-13 04:08:10 +00004583 {
Greg Clayton42b01482015-08-11 22:07:46 +00004584 packet.Printf("%" PRIx64, symbol_load_addr);
Jason Molenda50018d32016-01-13 04:08:10 +00004585 symbol_response_provided = true;
4586 }
4587 else
4588 {
4589 symbol_response_provided = false;
4590 }
Greg Clayton42b01482015-08-11 22:07:46 +00004591 packet.PutCString(":");
4592 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4593 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00004594 }
4595 }
4596 }
4597 }
4598 // If we make it here, the symbol request packet response wasn't valid or
4599 // our symbol lookup failed so we must abort
4600 return;
4601
4602 }
4603 }
4604}
4605