blob: d2a15b3152edefce1b02de89c1a79eee94352e57 [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"
Jason Molendaa3329782014-03-29 18:54:20 +000036#include "lldb/Target/Target.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000037#include "lldb/Target/MemoryRegionInfo.h"
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +000038#include "lldb/Target/UnixSignals.h"
Greg Clayton576d8832011-03-22 04:00:09 +000039
40// Project includes
41#include "Utility/StringExtractorGDBRemote.h"
42#include "ProcessGDBRemote.h"
43#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000044#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000045
Jason Molenda91ffe0a2015-06-18 21:46:06 +000046#if defined (HAVE_LIBCOMPRESSION)
47#include <compression.h>
48#endif
49
Greg Clayton576d8832011-03-22 04:00:09 +000050using namespace lldb;
51using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000052using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000053
54//----------------------------------------------------------------------
55// GDBRemoteCommunicationClient constructor
56//----------------------------------------------------------------------
Tamas Berghammere13c2732015-02-11 10:29:30 +000057GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() :
58 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet"),
Greg Clayton576d8832011-03-22 04:00:09 +000059 m_supports_not_sending_acks (eLazyBoolCalculate),
60 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000061 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000062 m_supports_vCont_all (eLazyBoolCalculate),
63 m_supports_vCont_any (eLazyBoolCalculate),
64 m_supports_vCont_c (eLazyBoolCalculate),
65 m_supports_vCont_C (eLazyBoolCalculate),
66 m_supports_vCont_s (eLazyBoolCalculate),
67 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000068 m_qHostInfo_is_valid (eLazyBoolCalculate),
Todd Fiala9f72b3a2014-05-07 19:28:21 +000069 m_curr_pid_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000070 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000071 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000072 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000073 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000074 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000075 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000076 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000077 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000078 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000079 m_supports_p (eLazyBoolCalculate),
Jason Molendabdc4f122014-05-06 02:59:39 +000080 m_supports_x (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000081 m_avoid_g_packets (eLazyBoolCalculate),
Greg Claytonf74cf862013-11-13 23:28:31 +000082 m_supports_QSaveRegisterState (eLazyBoolCalculate),
Steve Pucci03904ac2014-03-04 23:18:46 +000083 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000084 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
85 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
Greg Clayton253204e2015-04-16 23:11:06 +000086 m_supports_qXfer_features_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000087 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
Jason Molenda705b1802014-06-13 02:37:02 +000088 m_supports_jThreadExtendedInfo (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000089 m_supports_qProcessInfoPID (true),
90 m_supports_qfProcessInfo (true),
91 m_supports_qUserName (true),
92 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000093 m_supports_qThreadStopInfo (true),
94 m_supports_z0 (true),
95 m_supports_z1 (true),
96 m_supports_z2 (true),
97 m_supports_z3 (true),
98 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +000099 m_supports_QEnvironment (true),
100 m_supports_QEnvironmentHexEncoded (true),
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000101 m_curr_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton8b82f082011-04-12 05:54:46 +0000102 m_curr_tid (LLDB_INVALID_THREAD_ID),
103 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +0000104 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +0000105 m_async_mutex (Mutex::eMutexTypeRecursive),
106 m_async_packet_predicate (false),
107 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +0000108 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +0000109 m_async_response (),
110 m_async_signal (-1),
Jim Inghamb8cd5752014-04-16 02:24:17 +0000111 m_interrupt_sent (false),
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000112 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +0000113 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000114 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +0000115 m_os_version_major (UINT32_MAX),
116 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000117 m_os_version_update (UINT32_MAX),
118 m_os_build (),
119 m_os_kernel (),
120 m_hostname (),
Jason Molendaa3329782014-03-29 18:54:20 +0000121 m_gdb_server_name(),
122 m_gdb_server_version(UINT32_MAX),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000123 m_default_packet_timeout (0),
124 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000125{
Greg Clayton576d8832011-03-22 04:00:09 +0000126}
127
128//----------------------------------------------------------------------
129// Destructor
130//----------------------------------------------------------------------
131GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
132{
Greg Clayton576d8832011-03-22 04:00:09 +0000133 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000134 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000135}
136
137bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000138GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
139{
Greg Claytonfb909312013-11-23 01:58:15 +0000140 ResetDiscoverableSettings();
141
Greg Clayton1cb64962011-03-24 04:28:38 +0000142 // Start the read thread after we send the handshake ack since if we
143 // fail to send the handshake ack, there is no reason to continue...
144 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000145 {
Ed Maste48f986f2013-12-18 15:31:45 +0000146 // Wait for any responses that might have been queued up in the remote
147 // GDB server and flush them all
148 StringExtractorGDBRemote response;
149 PacketResult packet_result = PacketResult::Success;
150 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
151 while (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000152 packet_result = ReadPacket (response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000153
Greg Claytonfb909312013-11-23 01:58:15 +0000154 // The return value from QueryNoAckModeSupported() is true if the packet
155 // was sent and _any_ response (including UNIMPLEMENTED) was received),
156 // or false if no response was received. This quickly tells us if we have
157 // a live connection to a remote GDB server...
158 if (QueryNoAckModeSupported())
159 {
160 return true;
161 }
162 else
163 {
164 if (error_ptr)
165 error_ptr->SetErrorString("failed to get reply to handshake packet");
166 }
167 }
168 else
169 {
170 if (error_ptr)
171 error_ptr->SetErrorString("failed to send the handshake ack");
172 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000173 return false;
174}
175
Greg Claytonfb909312013-11-23 01:58:15 +0000176bool
Greg Claytonb30c50c2015-05-29 00:01:55 +0000177GDBRemoteCommunicationClient::GetEchoSupported ()
178{
179 if (m_supports_qEcho == eLazyBoolCalculate)
180 {
181 GetRemoteQSupported();
182 }
183 return m_supports_qEcho == eLazyBoolYes;
184}
185
186
187bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000188GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
189{
190 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
191 {
192 GetRemoteQSupported();
193 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000194 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000195}
196
197bool
198GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
199{
200 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
201 {
202 GetRemoteQSupported();
203 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000204 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000205}
206
207bool
208GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
209{
210 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
211 {
212 GetRemoteQSupported();
213 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000214 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000215}
216
Steve Pucci03904ac2014-03-04 23:18:46 +0000217bool
218GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
219{
220 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
221 {
222 GetRemoteQSupported();
223 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000224 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000225}
226
Colin Rileyc3c95b22015-04-16 15:51:33 +0000227bool
228GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
229{
230 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
231 {
232 GetRemoteQSupported();
233 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000234 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000235}
236
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000237uint64_t
238GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
239{
240 if (m_max_packet_size == 0)
241 {
242 GetRemoteQSupported();
243 }
244 return m_max_packet_size;
245}
246
247bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000248GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000249{
250 if (m_supports_not_sending_acks == eLazyBoolCalculate)
251 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000252 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000253 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000254
Jason Molenda36a216e2014-07-24 01:36:24 +0000255 // This is the first real packet that we'll send in a debug session and it may take a little
256 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
257
258 const uint32_t minimum_timeout = 6;
259 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000260 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000261
Greg Clayton1cb64962011-03-24 04:28:38 +0000262 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000263 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000264 {
265 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000266 {
267 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000268 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000269 }
Greg Claytonfb909312013-11-23 01:58:15 +0000270 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000271 }
272 }
Greg Claytonfb909312013-11-23 01:58:15 +0000273 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000274}
275
276void
Greg Clayton44633992012-04-10 03:22:03 +0000277GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
278{
279 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
280 {
281 m_supports_threads_in_stop_reply = eLazyBoolNo;
282
283 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000284 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000285 {
286 if (response.IsOKResponse())
287 m_supports_threads_in_stop_reply = eLazyBoolYes;
288 }
289 }
290}
291
Jim Inghamcd16df92012-07-20 21:37:13 +0000292bool
293GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
294{
295 if (m_attach_or_wait_reply == eLazyBoolCalculate)
296 {
297 m_attach_or_wait_reply = eLazyBoolNo;
298
299 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000300 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000301 {
302 if (response.IsOKResponse())
303 m_attach_or_wait_reply = eLazyBoolYes;
304 }
305 }
306 if (m_attach_or_wait_reply == eLazyBoolYes)
307 return true;
308 else
309 return false;
310}
311
Jim Ingham279ceec2012-07-25 21:12:43 +0000312bool
313GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
314{
315 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
316 {
317 m_prepare_for_reg_writing_reply = eLazyBoolNo;
318
319 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000320 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000321 {
322 if (response.IsOKResponse())
323 m_prepare_for_reg_writing_reply = eLazyBoolYes;
324 }
325 }
326 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
327 return true;
328 else
329 return false;
330}
331
Greg Clayton44633992012-04-10 03:22:03 +0000332
333void
Greg Clayton576d8832011-03-22 04:00:09 +0000334GDBRemoteCommunicationClient::ResetDiscoverableSettings()
335{
336 m_supports_not_sending_acks = eLazyBoolCalculate;
337 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000338 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000339 m_supports_vCont_c = eLazyBoolCalculate;
340 m_supports_vCont_C = eLazyBoolCalculate;
341 m_supports_vCont_s = eLazyBoolCalculate;
342 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000343 m_supports_p = eLazyBoolCalculate;
Jason Molendabdc4f122014-05-06 02:59:39 +0000344 m_supports_x = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000345 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000346 m_qHostInfo_is_valid = eLazyBoolCalculate;
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000347 m_curr_pid_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000348 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000349 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000350 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000351 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000352 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
353 m_attach_or_wait_reply = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000354 m_avoid_g_packets = eLazyBoolCalculate;
Steve Pucci03904ac2014-03-04 23:18:46 +0000355 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000356 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
357 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000358 m_supports_qXfer_features_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000359 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000360
Greg Clayton32e0a752011-03-30 18:16:51 +0000361 m_supports_qProcessInfoPID = true;
362 m_supports_qfProcessInfo = true;
363 m_supports_qUserName = true;
364 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000365 m_supports_qThreadStopInfo = true;
366 m_supports_z0 = true;
367 m_supports_z1 = true;
368 m_supports_z2 = true;
369 m_supports_z3 = true;
370 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000371 m_supports_QEnvironment = true;
372 m_supports_QEnvironmentHexEncoded = true;
Jason Molendaa3329782014-03-29 18:54:20 +0000373
Greg Claytond314e812011-03-23 00:09:55 +0000374 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000375 m_process_arch.Clear();
Jason Molendaa3329782014-03-29 18:54:20 +0000376 m_os_version_major = UINT32_MAX;
377 m_os_version_minor = UINT32_MAX;
378 m_os_version_update = UINT32_MAX;
379 m_os_build.clear();
380 m_os_kernel.clear();
381 m_hostname.clear();
382 m_gdb_server_name.clear();
383 m_gdb_server_version = UINT32_MAX;
384 m_default_packet_timeout = 0;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000385
386 m_max_packet_size = 0;
Greg Clayton576d8832011-03-22 04:00:09 +0000387}
388
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000389void
390GDBRemoteCommunicationClient::GetRemoteQSupported ()
391{
392 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000393 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000394 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000395 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000396 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000397 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000398 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
399
Colin Rileyc3c95b22015-04-16 15:51:33 +0000400 // build the qSupported packet
401 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
402 StreamString packet;
403 packet.PutCString( "qSupported" );
404 for ( uint32_t i = 0; i < features.size( ); ++i )
405 {
406 packet.PutCString( i==0 ? ":" : ";");
407 packet.PutCString( features[i].c_str( ) );
408 }
409
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000410 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000411 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000412 response,
413 /*send_async=*/false) == PacketResult::Success)
414 {
415 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000416 if (::strstr (response_cstr, "qXfer:auxv:read+"))
417 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000418 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
419 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
420 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
421 {
422 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
423 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
424 }
425 if (::strstr (response_cstr, "qXfer:libraries:read+"))
426 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000427 if (::strstr (response_cstr, "qXfer:features:read+"))
428 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000429
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000430
431 // Look for a list of compressions in the features list e.g.
432 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
433 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
434 if (features_list)
435 {
436 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
437 if (compressions)
438 {
439 std::vector<std::string> supported_compressions;
440 compressions += sizeof ("SupportedCompressions=") - 1;
441 const char *end_of_compressions = strchr (compressions, ';');
442 if (end_of_compressions == NULL)
443 {
444 end_of_compressions = strchr (compressions, '\0');
445 }
446 const char *current_compression = compressions;
447 while (current_compression < end_of_compressions)
448 {
449 const char *next_compression_name = strchr (current_compression, ',');
450 const char *end_of_this_word = next_compression_name;
451 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
452 {
453 end_of_this_word = end_of_compressions;
454 }
455
456 if (end_of_this_word)
457 {
458 if (end_of_this_word == current_compression)
459 {
460 current_compression++;
461 }
462 else
463 {
464 std::string this_compression (current_compression, end_of_this_word - current_compression);
465 supported_compressions.push_back (this_compression);
466 current_compression = end_of_this_word + 1;
467 }
468 }
469 else
470 {
471 supported_compressions.push_back (current_compression);
472 current_compression = end_of_compressions;
473 }
474 }
475
476 if (supported_compressions.size() > 0)
477 {
478 MaybeEnableCompression (supported_compressions);
479 }
480 }
481 }
482
Greg Claytonb30c50c2015-05-29 00:01:55 +0000483 if (::strstr (response_cstr, "qEcho"))
484 m_supports_qEcho = eLazyBoolYes;
485 else
486 m_supports_qEcho = eLazyBoolNo;
487
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000488 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
489 if (packet_size_str)
490 {
491 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
492 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
493 if (m_max_packet_size == 0)
494 {
495 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
496 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
497 if (log)
498 log->Printf ("Garbled PacketSize spec in qSupported response");
499 }
500 }
501 }
502}
Greg Clayton576d8832011-03-22 04:00:09 +0000503
504bool
505GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
506{
507 if (m_supports_thread_suffix == eLazyBoolCalculate)
508 {
509 StringExtractorGDBRemote response;
510 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000511 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000512 {
513 if (response.IsOKResponse())
514 m_supports_thread_suffix = eLazyBoolYes;
515 }
516 }
517 return m_supports_thread_suffix;
518}
519bool
520GDBRemoteCommunicationClient::GetVContSupported (char flavor)
521{
522 if (m_supports_vCont_c == eLazyBoolCalculate)
523 {
524 StringExtractorGDBRemote response;
525 m_supports_vCont_any = eLazyBoolNo;
526 m_supports_vCont_all = eLazyBoolNo;
527 m_supports_vCont_c = eLazyBoolNo;
528 m_supports_vCont_C = eLazyBoolNo;
529 m_supports_vCont_s = eLazyBoolNo;
530 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000531 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000532 {
533 const char *response_cstr = response.GetStringRef().c_str();
534 if (::strstr (response_cstr, ";c"))
535 m_supports_vCont_c = eLazyBoolYes;
536
537 if (::strstr (response_cstr, ";C"))
538 m_supports_vCont_C = eLazyBoolYes;
539
540 if (::strstr (response_cstr, ";s"))
541 m_supports_vCont_s = eLazyBoolYes;
542
543 if (::strstr (response_cstr, ";S"))
544 m_supports_vCont_S = eLazyBoolYes;
545
546 if (m_supports_vCont_c == eLazyBoolYes &&
547 m_supports_vCont_C == eLazyBoolYes &&
548 m_supports_vCont_s == eLazyBoolYes &&
549 m_supports_vCont_S == eLazyBoolYes)
550 {
551 m_supports_vCont_all = eLazyBoolYes;
552 }
553
554 if (m_supports_vCont_c == eLazyBoolYes ||
555 m_supports_vCont_C == eLazyBoolYes ||
556 m_supports_vCont_s == eLazyBoolYes ||
557 m_supports_vCont_S == eLazyBoolYes)
558 {
559 m_supports_vCont_any = eLazyBoolYes;
560 }
561 }
562 }
563
564 switch (flavor)
565 {
566 case 'a': return m_supports_vCont_any;
567 case 'A': return m_supports_vCont_all;
568 case 'c': return m_supports_vCont_c;
569 case 'C': return m_supports_vCont_C;
570 case 's': return m_supports_vCont_s;
571 case 'S': return m_supports_vCont_S;
572 default: break;
573 }
574 return false;
575}
576
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000577// Check if the target supports 'p' packet. It sends out a 'p'
578// packet and checks the response. A normal packet will tell us
579// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000580//
581// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000582bool
Sean Callananb1de1142013-09-04 23:24:15 +0000583GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000584{
585 if (m_supports_p == eLazyBoolCalculate)
586 {
587 StringExtractorGDBRemote response;
588 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000589 char packet[256];
590 if (GetThreadSuffixSupported())
591 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
592 else
593 snprintf(packet, sizeof(packet), "p0");
594
Greg Clayton3dedae12013-12-06 21:45:27 +0000595 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000596 {
597 if (response.IsNormalResponse())
598 m_supports_p = eLazyBoolYes;
599 }
600 }
601 return m_supports_p;
602}
Greg Clayton576d8832011-03-22 04:00:09 +0000603
Jason Molendabdc4f122014-05-06 02:59:39 +0000604bool
Jason Molenda705b1802014-06-13 02:37:02 +0000605GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
606{
607 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
608 {
609 StringExtractorGDBRemote response;
610 m_supports_jThreadExtendedInfo = eLazyBoolNo;
611 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
612 {
613 if (response.IsOKResponse())
614 {
615 m_supports_jThreadExtendedInfo = eLazyBoolYes;
616 }
617 }
618 }
619 return m_supports_jThreadExtendedInfo;
620}
621
622bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000623GDBRemoteCommunicationClient::GetxPacketSupported ()
624{
625 if (m_supports_x == eLazyBoolCalculate)
626 {
627 StringExtractorGDBRemote response;
628 m_supports_x = eLazyBoolNo;
629 char packet[256];
630 snprintf (packet, sizeof (packet), "x0,0");
631 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
632 {
633 if (response.IsOKResponse())
634 m_supports_x = eLazyBoolYes;
635 }
636 }
637 return m_supports_x;
638}
639
Greg Clayton3dedae12013-12-06 21:45:27 +0000640GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000641GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
642(
643 const char *payload_prefix,
644 std::string &response_string
645)
646{
647 Mutex::Locker locker;
648 if (!GetSequenceMutex(locker,
649 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
650 {
651 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
652 if (log)
653 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
654 payload_prefix);
655 return PacketResult::ErrorNoSequenceLock;
656 }
657
658 response_string = "";
659 std::string payload_prefix_str(payload_prefix);
660 unsigned int response_size = 0x1000;
661 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
662 response_size = GetRemoteMaxPacketSize();
663 }
664
665 for (unsigned int offset = 0; true; offset += response_size)
666 {
667 StringExtractorGDBRemote this_response;
668 // Construct payload
669 char sizeDescriptor[128];
670 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
671 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
672 this_response,
673 /*send_async=*/false);
674 if (result != PacketResult::Success)
675 return result;
676
677 const std::string &this_string = this_response.GetStringRef();
678
679 // Check for m or l as first character; l seems to mean this is the last chunk
680 char first_char = *this_string.c_str();
681 if (first_char != 'm' && first_char != 'l')
682 {
683 return PacketResult::ErrorReplyInvalid;
684 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000685 // Concatenate the result so far (skipping 'm' or 'l')
686 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000687 if (first_char == 'l')
688 // We're done
689 return PacketResult::Success;
690 }
691}
692
693GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000694GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
695(
696 const char *payload,
697 StringExtractorGDBRemote &response,
698 bool send_async
699)
700{
701 return SendPacketAndWaitForResponse (payload,
702 ::strlen (payload),
703 response,
704 send_async);
705}
706
Greg Clayton3dedae12013-12-06 21:45:27 +0000707GDBRemoteCommunicationClient::PacketResult
708GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
709 size_t payload_length,
710 StringExtractorGDBRemote &response)
711{
712 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
713 if (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000714 packet_result = ReadPacket (response, GetPacketTimeoutInMicroSeconds (), true);
Greg Clayton3dedae12013-12-06 21:45:27 +0000715 return packet_result;
716}
717
718GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000719GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
720(
721 const char *payload,
722 size_t payload_length,
723 StringExtractorGDBRemote &response,
724 bool send_async
725)
726{
Greg Clayton3dedae12013-12-06 21:45:27 +0000727 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000728 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000729 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000730
731 // In order to stop async notifications from being processed in the middle of the
732 // send/recieve sequence Hijack the broadcast. Then rebroadcast any events when we are done.
733 static Listener hijack_listener("lldb.NotifyHijacker");
734 HijackBroadcaster(&hijack_listener, eBroadcastBitGdbReadThreadGotNotify);
735
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000736 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000737 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000738 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000739 }
740 else
741 {
742 if (send_async)
743 {
Greg Claytond3544052012-05-31 21:24:20 +0000744 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000745 {
Greg Claytond3544052012-05-31 21:24:20 +0000746 Mutex::Locker async_locker (m_async_mutex);
747 m_async_packet.assign(payload, payload_length);
748 m_async_packet_predicate.SetValue (true, eBroadcastNever);
749
750 if (log)
751 log->Printf ("async: async packet = %s", m_async_packet.c_str());
752
753 bool timed_out = false;
754 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000755 {
Greg Claytond3544052012-05-31 21:24:20 +0000756 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000757 {
Jim Inghambabfc382012-06-06 00:32:39 +0000758 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000759 TimeValue timeout_time;
760 timeout_time = TimeValue::Now();
761 timeout_time.OffsetWithSeconds (m_packet_timeout);
762
Greg Clayton576d8832011-03-22 04:00:09 +0000763 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000764 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000765
Greg Claytond3544052012-05-31 21:24:20 +0000766 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000767 {
Greg Claytond3544052012-05-31 21:24:20 +0000768 if (log)
769 log->Printf ("async: got response");
770
771 // Swap the response buffer to avoid malloc and string copy
772 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000773 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000774 }
775 else
776 {
777 if (log)
778 log->Printf ("async: timed out waiting for response");
779 }
780
781 // Make sure we wait until the continue packet has been sent again...
782 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
783 {
784 if (log)
785 {
786 if (timed_out)
787 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
788 else
789 log->Printf ("async: async packet sent");
790 }
791 }
792 else
793 {
794 if (log)
795 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000796 }
797 }
798 else
799 {
Greg Claytond3544052012-05-31 21:24:20 +0000800 // We had a racy condition where we went to send the interrupt
801 // yet we were able to get the lock, so the process must have
802 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000803 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000804 log->Printf ("async: got lock without sending interrupt");
805 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000806 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000807 }
808 }
809 else
810 {
Greg Clayton644247c2011-07-07 01:59:51 +0000811 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000812 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000813 }
814 }
815 else
816 {
817 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000818 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000819 }
820 }
821 else
822 {
823 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000824 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000825 }
826 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000827
828 // Remove our Hijacking listner from the broadcast.
829 RestoreBroadcaster();
830
831 // If a notification event occured, rebroadcast since it can now be processed safely.
832 EventSP event_sp;
833 if (hijack_listener.GetNextEvent(event_sp))
834 BroadcastEvent(event_sp);
835
Greg Clayton3dedae12013-12-06 21:45:27 +0000836 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000837}
838
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000839static const char *end_delimiter = "--end--;";
840static const int end_delimiter_len = 8;
841
842std::string
843GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
844( ProcessGDBRemote *process,
845 StringExtractorGDBRemote& profileDataExtractor
846)
847{
848 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
849 std::stringstream final_output;
850 std::string name, value;
851
852 // Going to assuming thread_used_usec comes first, else bail out.
853 while (profileDataExtractor.GetNameColonValue(name, value))
854 {
855 if (name.compare("thread_used_id") == 0)
856 {
857 StringExtractor threadIDHexExtractor(value.c_str());
858 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
859
860 bool has_used_usec = false;
861 uint32_t curr_used_usec = 0;
862 std::string usec_name, usec_value;
863 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
864 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
865 {
866 if (usec_name.compare("thread_used_usec") == 0)
867 {
868 has_used_usec = true;
869 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
870 }
871 else
872 {
873 // We didn't find what we want, it is probably
874 // an older version. Bail out.
875 profileDataExtractor.SetFilePos(input_file_pos);
876 }
877 }
878
879 if (has_used_usec)
880 {
881 uint32_t prev_used_usec = 0;
882 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
883 if (iterator != m_thread_id_to_used_usec_map.end())
884 {
885 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
886 }
887
888 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
889 // A good first time record is one that runs for at least 0.25 sec
890 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
891 bool good_subsequent_time = (prev_used_usec > 0) &&
892 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
893
894 if (good_first_time || good_subsequent_time)
895 {
896 // We try to avoid doing too many index id reservation,
897 // resulting in fast increase of index ids.
898
899 final_output << name << ":";
900 int32_t index_id = process->AssignIndexIDToThread(thread_id);
901 final_output << index_id << ";";
902
903 final_output << usec_name << ":" << usec_value << ";";
904 }
905 else
906 {
907 // Skip past 'thread_used_name'.
908 std::string local_name, local_value;
909 profileDataExtractor.GetNameColonValue(local_name, local_value);
910 }
911
912 // Store current time as previous time so that they can be compared later.
913 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
914 }
915 else
916 {
917 // Bail out and use old string.
918 final_output << name << ":" << value << ";";
919 }
920 }
921 else
922 {
923 final_output << name << ":" << value << ";";
924 }
925 }
926 final_output << end_delimiter;
927 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
928
929 return final_output.str();
930}
931
Greg Clayton576d8832011-03-22 04:00:09 +0000932StateType
933GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
934(
935 ProcessGDBRemote *process,
936 const char *payload,
937 size_t packet_length,
938 StringExtractorGDBRemote &response
939)
940{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000941 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000942 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000943 if (log)
944 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
945
946 Mutex::Locker locker(m_sequence_mutex);
947 StateType state = eStateRunning;
948
949 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
950 m_public_is_running.SetValue (true, eBroadcastNever);
951 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000952 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000953 std::string continue_packet(payload, packet_length);
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +0000954
955 const auto sigstop_signo = process->GetUnixSignals().GetSignalNumberFromName("SIGSTOP");
956 const auto sigint_signo = process->GetUnixSignals().GetSignalNumberFromName("SIGINT");
957
Greg Clayton3f875c52013-02-22 22:23:55 +0000958 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000959
Greg Clayton576d8832011-03-22 04:00:09 +0000960 while (state == eStateRunning)
961 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000962 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000963 {
964 if (log)
965 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +0000966 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +0000967 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +0000968 else
969 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000970
Greg Claytone889ad62011-10-27 22:04:16 +0000971 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000972 }
973
Greg Clayton3f875c52013-02-22 22:23:55 +0000974 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000975
976 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000977 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000978
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000979 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000980 {
981 if (response.Empty())
982 state = eStateInvalid;
983 else
984 {
985 const char stop_type = response.GetChar();
986 if (log)
987 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
988 switch (stop_type)
989 {
990 case 'T':
991 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000992 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000993 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000994 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000995 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
996 {
997 lldb::pid_t pid = GetCurrentProcessID ();
998 if (pid != LLDB_INVALID_PROCESS_ID)
999 process->SetID (pid);
1000 }
1001 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +00001002 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001003
1004 // Privately notify any internal threads that we have stopped
1005 // in case we wanted to interrupt our process, yet we might
1006 // send a packet and continue without returning control to the
1007 // user.
1008 m_private_is_running.SetValue (false, eBroadcastAlways);
1009
1010 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1011
Jim Inghambabfc382012-06-06 00:32:39 +00001012 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1013 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +00001014 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001015 // We sent an interrupt packet to stop the inferior process
1016 // for an async signal or to send an async packet while running
1017 // but we might have been single stepping and received the
1018 // stop packet for the step instead of for the interrupt packet.
1019 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1020 // is used, so if we get anything else, we need to try and
1021 // get another stop reply packet that may have been sent
1022 // due to sending the interrupt when the target is stopped
1023 // which will just re-send a copy of the last stop reply
1024 // packet. If we don't do this, then the reply for our
1025 // async packet will be the repeat stop reply packet and cause
1026 // a lot of trouble for us!
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001027 if (signo != sigint_signo && signo != sigstop_signo)
Greg Clayton2687cd12012-03-29 01:55:41 +00001028 {
Greg Claytonfb72fde2012-05-15 02:50:49 +00001029 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001030
1031 // We didn't get a a SIGINT or SIGSTOP, so try for a
1032 // very brief time (1 ms) to get another stop reply
1033 // packet to make sure it doesn't get in the way
1034 StringExtractorGDBRemote extra_stop_reply_packet;
1035 uint32_t timeout_usec = 1000;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001036 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +00001037 {
1038 switch (extra_stop_reply_packet.GetChar())
1039 {
1040 case 'T':
1041 case 'S':
1042 // We did get an extra stop reply, which means
1043 // our interrupt didn't stop the target so we
1044 // shouldn't continue after the async signal
1045 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +00001046 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001047 break;
1048 }
1049 }
1050 }
1051 }
1052
1053 if (m_async_signal != -1)
1054 {
1055 if (log)
1056 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1057
1058 // Save off the async signal we are supposed to send
1059 const int async_signal = m_async_signal;
1060 // Clear the async signal member so we don't end up
1061 // sending the signal multiple times...
1062 m_async_signal = -1;
1063 // Check which signal we stopped with
1064 if (signo == async_signal)
1065 {
1066 if (log)
1067 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1068
1069 // We already stopped with a signal that we wanted
1070 // to stop with, so we are done
1071 }
1072 else
1073 {
1074 // We stopped with a different signal that the one
1075 // we wanted to stop with, so now we must resume
1076 // with the signal we want
1077 char signal_packet[32];
1078 int signal_packet_len = 0;
1079 signal_packet_len = ::snprintf (signal_packet,
1080 sizeof (signal_packet),
1081 "C%2.2x",
1082 async_signal);
1083
1084 if (log)
1085 log->Printf ("async: stopped with signal %s, resume with %s",
1086 Host::GetSignalAsCString (signo),
1087 Host::GetSignalAsCString (async_signal));
1088
1089 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001090 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001091 continue_packet.assign(signal_packet, signal_packet_len);
1092 continue;
1093 }
1094 }
1095 else if (m_async_packet_predicate.GetValue())
1096 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001097 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001098
1099 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001100 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001101 m_async_response.Clear();
1102 if (m_async_packet.empty())
1103 {
Jim Inghama6195b72013-12-18 01:24:33 +00001104 m_async_result = PacketResult::ErrorSendFailed;
1105 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001106 packet_log->Printf ("async: error: empty async packet");
1107
1108 }
1109 else
1110 {
1111 if (packet_log)
1112 packet_log->Printf ("async: sending packet");
1113
Jim Inghama6195b72013-12-18 01:24:33 +00001114 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1115 m_async_packet.size(),
1116 m_async_response,
1117 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001118 }
1119 // Let the other thread that was trying to send the async
1120 // packet know that the packet has been sent and response is
1121 // ready...
1122 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1123
1124 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001125 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001126
1127 // Set the continue packet to resume if our interrupt
1128 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001129 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001130 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001131 // Reverting this for now as it is causing deadlocks
1132 // in programs (<rdar://problem/11529853>). In the future
1133 // we should check our thread list and "do the right thing"
1134 // for new threads that show up while we stop and run async
1135 // packets. Setting the packet to 'c' to continue all threads
1136 // is the right thing to do 99.99% of the time because if a
1137 // thread was single stepping, and we sent an interrupt, we
1138 // will notice above that we didn't stop due to an interrupt
1139 // but stopped due to stepping and we would _not_ continue.
1140 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001141 continue;
1142 }
1143 }
1144 // Stop with signal and thread info
1145 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001146 }
Greg Clayton576d8832011-03-22 04:00:09 +00001147 break;
1148
1149 case 'W':
1150 case 'X':
1151 // process exited
1152 state = eStateExited;
1153 break;
1154
1155 case 'O':
1156 // STDOUT
1157 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001158 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001159 std::string inferior_stdout;
1160 inferior_stdout.reserve(response.GetBytesLeft () / 2);
1161 char ch;
1162 while ((ch = response.GetHexU8()) != '\0')
1163 inferior_stdout.append(1, ch);
1164 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1165 }
1166 break;
1167
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001168 case 'A':
1169 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1170 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001171 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001172 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1173 if (m_partial_profile_data.length() > 0)
1174 {
1175 m_partial_profile_data.append(input);
1176 input = m_partial_profile_data;
1177 m_partial_profile_data.clear();
1178 }
1179
1180 size_t found, pos = 0, len = input.length();
1181 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1182 {
1183 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001184 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1185 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001186
1187 pos = found + end_delimiter_len;
1188 }
1189
1190 if (pos < len)
1191 {
1192 // Last incomplete chunk.
1193 m_partial_profile_data = input.substr(pos);
1194 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001195 }
1196 break;
1197
Greg Clayton576d8832011-03-22 04:00:09 +00001198 case 'E':
1199 // ERROR
1200 state = eStateInvalid;
1201 break;
1202
1203 default:
1204 if (log)
1205 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1206 state = eStateInvalid;
1207 break;
1208 }
1209 }
1210 }
1211 else
1212 {
1213 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001214 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
Greg Clayton576d8832011-03-22 04:00:09 +00001215 state = eStateInvalid;
1216 }
1217 }
1218 if (log)
1219 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1220 response.SetFilePos(0);
1221 m_private_is_running.SetValue (false, eBroadcastAlways);
1222 m_public_is_running.SetValue (false, eBroadcastAlways);
1223 return state;
1224}
1225
1226bool
1227GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1228{
Greg Clayton2687cd12012-03-29 01:55:41 +00001229 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001230 m_async_signal = signo;
1231 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001232 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001233 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001234 return true;
1235 m_async_signal = -1;
1236 return false;
1237}
1238
Greg Clayton37a0a242012-04-11 00:24:49 +00001239// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001240// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1241// (the expected result), then it will send the halt packet. If it does succeed
1242// then the caller that requested the interrupt will want to keep the sequence
1243// locked down so that no one else can send packets while the caller has control.
1244// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001245// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001246// else (like read/write memory), so we need to interrupt the running process
1247// (gdb remote protocol requires this), and do what we need to do, then resume.
1248
1249bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001250GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001251(
1252 Mutex::Locker& locker,
1253 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001254 bool &timed_out
1255)
1256{
Greg Clayton576d8832011-03-22 04:00:09 +00001257 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001258 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001259
1260 if (IsRunning())
1261 {
1262 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001263 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001264 {
1265 if (log)
1266 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1267 }
1268 else
Greg Clayton576d8832011-03-22 04:00:09 +00001269 {
1270 // Someone has the mutex locked waiting for a response or for the
1271 // inferior to stop, so send the interrupt on the down low...
1272 char ctrl_c = '\x03';
1273 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001274 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001275 if (log)
1276 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001277 if (bytes_written > 0)
1278 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001279 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001280 if (seconds_to_wait_for_stop)
1281 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001282 TimeValue timeout;
1283 if (seconds_to_wait_for_stop)
1284 {
1285 timeout = TimeValue::Now();
1286 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1287 }
Greg Clayton576d8832011-03-22 04:00:09 +00001288 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1289 {
1290 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001291 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001292 return true;
1293 }
1294 else
1295 {
1296 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001297 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001298 }
1299 }
1300 else
1301 {
1302 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001303 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001304 return true;
1305 }
1306 }
1307 else
1308 {
1309 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001310 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001311 }
1312 return false;
1313 }
Greg Clayton576d8832011-03-22 04:00:09 +00001314 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001315 else
1316 {
1317 if (log)
1318 log->Printf ("SendInterrupt () - not running");
1319 }
Greg Clayton576d8832011-03-22 04:00:09 +00001320 return true;
1321}
1322
1323lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001324GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001325{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001326 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001327 return m_curr_pid;
1328
1329 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001330 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001331 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001332 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001333 // We really got it.
1334 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001335 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001336 else
1337 {
Todd Fialae24614f2014-05-14 00:15:32 +00001338 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1339 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1340 // The gdb remote protocol documents $qC as returning the thread id, which newer
1341 // debugserver and lldb-gdbserver stubs return correctly.
1342 StringExtractorGDBRemote response;
1343 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001344 {
Todd Fialae24614f2014-05-14 00:15:32 +00001345 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001346 {
Todd Fialae24614f2014-05-14 00:15:32 +00001347 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001348 {
Todd Fialae24614f2014-05-14 00:15:32 +00001349 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1350 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001351 {
Todd Fialae24614f2014-05-14 00:15:32 +00001352 m_curr_pid_is_valid = eLazyBoolYes;
1353 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001354 }
1355 }
1356 }
1357 }
1358 }
1359
Greg Clayton576d8832011-03-22 04:00:09 +00001360 return LLDB_INVALID_PROCESS_ID;
1361}
1362
1363bool
1364GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1365{
1366 error_str.clear();
1367 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001368 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001369 {
1370 if (response.IsOKResponse())
1371 return true;
1372 if (response.GetChar() == 'E')
1373 {
1374 // A string the describes what failed when launching...
1375 error_str = response.GetStringRef().substr(1);
1376 }
1377 else
1378 {
1379 error_str.assign ("unknown error occurred launching process");
1380 }
1381 }
1382 else
1383 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001384 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001385 }
1386 return false;
1387}
1388
1389int
Greg Claytonfbb76342013-11-20 21:07:01 +00001390GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001391{
Greg Claytonfbb76342013-11-20 21:07:01 +00001392 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001393 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001394 std::vector<const char *> argv;
1395 FileSpec exe_file = launch_info.GetExecutableFile();
1396 std::string exe_path;
1397 const char *arg = NULL;
1398 const Args &launch_args = launch_info.GetArguments();
1399 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +00001400 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +00001401 else
1402 {
1403 arg = launch_args.GetArgumentAtIndex(0);
1404 if (arg)
1405 exe_path = arg;
1406 }
1407 if (!exe_path.empty())
1408 {
1409 argv.push_back(exe_path.c_str());
1410 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1411 {
1412 if (arg)
1413 argv.push_back(arg);
1414 }
1415 }
1416 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001417 {
1418 StreamString packet;
1419 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001420 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001421 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001422 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001423 const int arg_len = strlen(arg);
1424 if (i > 0)
1425 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001426 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001427 packet.PutBytesAsRawHex8 (arg, arg_len);
1428 }
1429
1430 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001431 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001432 {
1433 if (response.IsOKResponse())
1434 return 0;
1435 uint8_t error = response.GetError();
1436 if (error)
1437 return error;
1438 }
1439 }
1440 return -1;
1441}
1442
1443int
1444GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1445{
1446 if (name_equal_value && name_equal_value[0])
1447 {
1448 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001449 bool send_hex_encoding = false;
1450 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001451 {
Greg Clayton89600582013-10-10 17:53:50 +00001452 if (isprint(*p))
1453 {
1454 switch (*p)
1455 {
1456 case '$':
1457 case '#':
1458 send_hex_encoding = true;
1459 break;
1460 default:
1461 break;
1462 }
1463 }
1464 else
1465 {
1466 // We have non printable characters, lets hex encode this...
1467 send_hex_encoding = true;
1468 }
1469 }
1470
1471 StringExtractorGDBRemote response;
1472 if (send_hex_encoding)
1473 {
1474 if (m_supports_QEnvironmentHexEncoded)
1475 {
1476 packet.PutCString("QEnvironmentHexEncoded:");
1477 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001478 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001479 {
1480 if (response.IsOKResponse())
1481 return 0;
1482 uint8_t error = response.GetError();
1483 if (error)
1484 return error;
1485 if (response.IsUnsupportedResponse())
1486 m_supports_QEnvironmentHexEncoded = false;
1487 }
1488 }
1489
1490 }
1491 else if (m_supports_QEnvironment)
1492 {
1493 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001494 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001495 {
1496 if (response.IsOKResponse())
1497 return 0;
1498 uint8_t error = response.GetError();
1499 if (error)
1500 return error;
1501 if (response.IsUnsupportedResponse())
1502 m_supports_QEnvironment = false;
1503 }
Greg Clayton576d8832011-03-22 04:00:09 +00001504 }
1505 }
1506 return -1;
1507}
1508
Greg Claytonc4103b32011-05-08 04:53:50 +00001509int
1510GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1511{
1512 if (arch && arch[0])
1513 {
1514 StreamString packet;
1515 packet.Printf("QLaunchArch:%s", arch);
1516 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001517 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001518 {
1519 if (response.IsOKResponse())
1520 return 0;
1521 uint8_t error = response.GetError();
1522 if (error)
1523 return error;
1524 }
1525 }
1526 return -1;
1527}
1528
Jason Molendaa3329782014-03-29 18:54:20 +00001529int
1530GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1531{
1532 if (data && *data != '\0')
1533 {
1534 StreamString packet;
1535 packet.Printf("QSetProcessEvent:%s", data);
1536 StringExtractorGDBRemote response;
1537 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1538 {
1539 if (response.IsOKResponse())
1540 {
1541 if (was_supported)
1542 *was_supported = true;
1543 return 0;
1544 }
1545 else if (response.IsUnsupportedResponse())
1546 {
1547 if (was_supported)
1548 *was_supported = false;
1549 return -1;
1550 }
1551 else
1552 {
1553 uint8_t error = response.GetError();
1554 if (was_supported)
1555 *was_supported = true;
1556 if (error)
1557 return error;
1558 }
1559 }
1560 }
1561 return -1;
1562}
1563
Greg Clayton576d8832011-03-22 04:00:09 +00001564bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001565GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1566 uint32_t &minor,
1567 uint32_t &update)
1568{
1569 if (GetHostInfo ())
1570 {
1571 if (m_os_version_major != UINT32_MAX)
1572 {
1573 major = m_os_version_major;
1574 minor = m_os_version_minor;
1575 update = m_os_version_update;
1576 return true;
1577 }
1578 }
1579 return false;
1580}
1581
1582bool
1583GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1584{
1585 if (GetHostInfo ())
1586 {
1587 if (!m_os_build.empty())
1588 {
1589 s = m_os_build;
1590 return true;
1591 }
1592 }
1593 s.clear();
1594 return false;
1595}
1596
1597
1598bool
1599GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1600{
1601 if (GetHostInfo ())
1602 {
1603 if (!m_os_kernel.empty())
1604 {
1605 s = m_os_kernel;
1606 return true;
1607 }
1608 }
1609 s.clear();
1610 return false;
1611}
1612
1613bool
1614GDBRemoteCommunicationClient::GetHostname (std::string &s)
1615{
1616 if (GetHostInfo ())
1617 {
1618 if (!m_hostname.empty())
1619 {
1620 s = m_hostname;
1621 return true;
1622 }
1623 }
1624 s.clear();
1625 return false;
1626}
1627
1628ArchSpec
1629GDBRemoteCommunicationClient::GetSystemArchitecture ()
1630{
1631 if (GetHostInfo ())
1632 return m_host_arch;
1633 return ArchSpec();
1634}
1635
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001636const lldb_private::ArchSpec &
1637GDBRemoteCommunicationClient::GetProcessArchitecture ()
1638{
1639 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1640 GetCurrentProcessInfo ();
1641 return m_process_arch;
1642}
1643
Jason Molendaa3329782014-03-29 18:54:20 +00001644bool
1645GDBRemoteCommunicationClient::GetGDBServerVersion()
1646{
1647 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1648 {
1649 m_gdb_server_name.clear();
1650 m_gdb_server_version = 0;
1651 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1652
1653 StringExtractorGDBRemote response;
1654 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1655 {
1656 if (response.IsNormalResponse())
1657 {
1658 std::string name;
1659 std::string value;
1660 bool success = false;
1661 while (response.GetNameColonValue(name, value))
1662 {
1663 if (name.compare("name") == 0)
1664 {
1665 success = true;
1666 m_gdb_server_name.swap(value);
1667 }
1668 else if (name.compare("version") == 0)
1669 {
1670 size_t dot_pos = value.find('.');
1671 if (dot_pos != std::string::npos)
1672 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001673 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001674 if (version != UINT32_MAX)
1675 {
1676 success = true;
1677 m_gdb_server_version = version;
1678 }
1679 }
1680 }
1681 if (success)
1682 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1683 }
1684 }
1685 }
1686 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1687}
1688
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001689void
1690GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1691{
1692 CompressionType avail_type = CompressionType::None;
1693 std::string avail_name;
1694
1695#if defined (HAVE_LIBCOMPRESSION)
1696 // libcompression is weak linked so test if compression_decode_buffer() is available
1697 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1698 {
1699 for (auto compression : supported_compressions)
1700 {
1701 if (compression == "lzfse")
1702 {
1703 avail_type = CompressionType::LZFSE;
1704 avail_name = compression;
1705 break;
1706 }
1707 }
1708 }
1709#endif
1710
1711#if defined (HAVE_LIBCOMPRESSION)
1712 // libcompression is weak linked so test if compression_decode_buffer() is available
1713 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1714 {
1715 for (auto compression : supported_compressions)
1716 {
1717 if (compression == "zlib-deflate")
1718 {
1719 avail_type = CompressionType::ZlibDeflate;
1720 avail_name = compression;
1721 break;
1722 }
1723 }
1724 }
1725#endif
1726
1727#if defined (HAVE_LIBZ)
1728 if (avail_type == CompressionType::None)
1729 {
1730 for (auto compression : supported_compressions)
1731 {
1732 if (compression == "zlib-deflate")
1733 {
1734 avail_type = CompressionType::ZlibDeflate;
1735 avail_name = compression;
1736 break;
1737 }
1738 }
1739 }
1740#endif
1741
1742#if defined (HAVE_LIBCOMPRESSION)
1743 // libcompression is weak linked so test if compression_decode_buffer() is available
1744 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1745 {
1746 for (auto compression : supported_compressions)
1747 {
1748 if (compression == "lz4")
1749 {
1750 avail_type = CompressionType::LZ4;
1751 avail_name = compression;
1752 break;
1753 }
1754 }
1755 }
1756#endif
1757
1758#if defined (HAVE_LIBCOMPRESSION)
1759 // libcompression is weak linked so test if compression_decode_buffer() is available
1760 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1761 {
1762 for (auto compression : supported_compressions)
1763 {
1764 if (compression == "lzma")
1765 {
1766 avail_type = CompressionType::LZMA;
1767 avail_name = compression;
1768 break;
1769 }
1770 }
1771 }
1772#endif
1773
1774 if (avail_type != CompressionType::None)
1775 {
1776 StringExtractorGDBRemote response;
1777 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1778 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1779 return;
1780
1781 if (response.IsOKResponse())
1782 {
1783 m_compression_type = avail_type;
1784 }
1785 }
1786}
1787
Jason Molendaa3329782014-03-29 18:54:20 +00001788const char *
1789GDBRemoteCommunicationClient::GetGDBServerProgramName()
1790{
1791 if (GetGDBServerVersion())
1792 {
1793 if (!m_gdb_server_name.empty())
1794 return m_gdb_server_name.c_str();
1795 }
1796 return NULL;
1797}
1798
1799uint32_t
1800GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1801{
1802 if (GetGDBServerVersion())
1803 return m_gdb_server_version;
1804 return 0;
1805}
Greg Clayton1cb64962011-03-24 04:28:38 +00001806
1807bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001808GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1809{
1810 StringExtractorGDBRemote response;
1811 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1812 return false;
1813
1814 if (!response.IsNormalResponse())
1815 return false;
1816
1817 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1818 tid = response.GetHexMaxU32(true, -1);
1819
1820 return true;
1821}
1822
1823bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001824GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001825{
Todd Fialaaf245d12014-06-30 21:05:18 +00001826 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1827
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001828 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001829 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001830 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001831 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001832 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001833 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001834 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001835 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001836 std::string name;
1837 std::string value;
1838 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1839 uint32_t sub = 0;
1840 std::string arch_name;
1841 std::string os_name;
1842 std::string vendor_name;
1843 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001844 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001845 uint32_t pointer_byte_size = 0;
1846 StringExtractor extractor;
1847 ByteOrder byte_order = eByteOrderInvalid;
1848 uint32_t num_keys_decoded = 0;
1849 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001850 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001851 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001852 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001853 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001854 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001855 if (cpu != LLDB_INVALID_CPUTYPE)
1856 ++num_keys_decoded;
1857 }
1858 else if (name.compare("cpusubtype") == 0)
1859 {
1860 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001861 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001862 if (sub != 0)
1863 ++num_keys_decoded;
1864 }
1865 else if (name.compare("arch") == 0)
1866 {
1867 arch_name.swap (value);
1868 ++num_keys_decoded;
1869 }
1870 else if (name.compare("triple") == 0)
1871 {
Greg Clayton44272a42014-09-18 00:18:32 +00001872 extractor.GetStringRef ().swap (value);
1873 extractor.SetFilePos(0);
1874 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001875 ++num_keys_decoded;
1876 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001877 else if (name.compare ("distribution_id") == 0)
1878 {
1879 extractor.GetStringRef ().swap (value);
1880 extractor.SetFilePos (0);
1881 extractor.GetHexByteString (distribution_id);
1882 ++num_keys_decoded;
1883 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001884 else if (name.compare("os_build") == 0)
1885 {
1886 extractor.GetStringRef().swap(value);
1887 extractor.SetFilePos(0);
1888 extractor.GetHexByteString (m_os_build);
1889 ++num_keys_decoded;
1890 }
1891 else if (name.compare("hostname") == 0)
1892 {
1893 extractor.GetStringRef().swap(value);
1894 extractor.SetFilePos(0);
1895 extractor.GetHexByteString (m_hostname);
1896 ++num_keys_decoded;
1897 }
1898 else if (name.compare("os_kernel") == 0)
1899 {
1900 extractor.GetStringRef().swap(value);
1901 extractor.SetFilePos(0);
1902 extractor.GetHexByteString (m_os_kernel);
1903 ++num_keys_decoded;
1904 }
1905 else if (name.compare("ostype") == 0)
1906 {
1907 os_name.swap (value);
1908 ++num_keys_decoded;
1909 }
1910 else if (name.compare("vendor") == 0)
1911 {
1912 vendor_name.swap(value);
1913 ++num_keys_decoded;
1914 }
1915 else if (name.compare("endian") == 0)
1916 {
1917 ++num_keys_decoded;
1918 if (value.compare("little") == 0)
1919 byte_order = eByteOrderLittle;
1920 else if (value.compare("big") == 0)
1921 byte_order = eByteOrderBig;
1922 else if (value.compare("pdp") == 0)
1923 byte_order = eByteOrderPDP;
1924 else
1925 --num_keys_decoded;
1926 }
1927 else if (name.compare("ptrsize") == 0)
1928 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001929 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001930 if (pointer_byte_size != 0)
1931 ++num_keys_decoded;
1932 }
1933 else if (name.compare("os_version") == 0)
1934 {
1935 Args::StringToVersion (value.c_str(),
1936 m_os_version_major,
1937 m_os_version_minor,
1938 m_os_version_update);
1939 if (m_os_version_major != UINT32_MAX)
1940 ++num_keys_decoded;
1941 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001942 else if (name.compare("watchpoint_exceptions_received") == 0)
1943 {
1944 ++num_keys_decoded;
1945 if (strcmp(value.c_str(),"before") == 0)
1946 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1947 else if (strcmp(value.c_str(),"after") == 0)
1948 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1949 else
1950 --num_keys_decoded;
1951 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001952 else if (name.compare("default_packet_timeout") == 0)
1953 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001954 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001955 if (m_default_packet_timeout > 0)
1956 {
1957 SetPacketTimeout(m_default_packet_timeout);
1958 ++num_keys_decoded;
1959 }
1960 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001961
Greg Clayton32e0a752011-03-30 18:16:51 +00001962 }
1963
1964 if (num_keys_decoded > 0)
1965 m_qHostInfo_is_valid = eLazyBoolYes;
1966
1967 if (triple.empty())
1968 {
1969 if (arch_name.empty())
1970 {
1971 if (cpu != LLDB_INVALID_CPUTYPE)
1972 {
1973 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1974 if (pointer_byte_size)
1975 {
1976 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1977 }
1978 if (byte_order != eByteOrderInvalid)
1979 {
1980 assert (byte_order == m_host_arch.GetByteOrder());
1981 }
Greg Clayton70512312012-05-08 01:45:38 +00001982
1983 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1984 {
1985 switch (m_host_arch.GetMachine())
1986 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001987 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001988 case llvm::Triple::arm:
1989 case llvm::Triple::thumb:
1990 os_name = "ios";
1991 break;
1992 default:
1993 os_name = "macosx";
1994 break;
1995 }
1996 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001997 if (!vendor_name.empty())
1998 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1999 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00002000 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00002001
2002 }
2003 }
2004 else
2005 {
2006 std::string triple;
2007 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00002008 if (!vendor_name.empty() || !os_name.empty())
2009 {
2010 triple += '-';
2011 if (vendor_name.empty())
2012 triple += "unknown";
2013 else
2014 triple += vendor_name;
2015 triple += '-';
2016 if (os_name.empty())
2017 triple += "unknown";
2018 else
2019 triple += os_name;
2020 }
2021 m_host_arch.SetTriple (triple.c_str());
2022
2023 llvm::Triple &host_triple = m_host_arch.GetTriple();
2024 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2025 {
2026 switch (m_host_arch.GetMachine())
2027 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002028 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002029 case llvm::Triple::arm:
2030 case llvm::Triple::thumb:
2031 host_triple.setOS(llvm::Triple::IOS);
2032 break;
2033 default:
2034 host_triple.setOS(llvm::Triple::MacOSX);
2035 break;
2036 }
2037 }
Greg Clayton1cb64962011-03-24 04:28:38 +00002038 if (pointer_byte_size)
2039 {
2040 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2041 }
2042 if (byte_order != eByteOrderInvalid)
2043 {
2044 assert (byte_order == m_host_arch.GetByteOrder());
2045 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002046
Greg Clayton1cb64962011-03-24 04:28:38 +00002047 }
2048 }
2049 else
2050 {
Greg Clayton70512312012-05-08 01:45:38 +00002051 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00002052 if (pointer_byte_size)
2053 {
2054 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2055 }
2056 if (byte_order != eByteOrderInvalid)
2057 {
2058 assert (byte_order == m_host_arch.GetByteOrder());
2059 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002060
2061 if (log)
2062 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 +00002063 }
2064 if (!distribution_id.empty ())
2065 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00002066 }
Greg Clayton576d8832011-03-22 04:00:09 +00002067 }
2068 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002069 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00002070}
2071
2072int
2073GDBRemoteCommunicationClient::SendAttach
2074(
2075 lldb::pid_t pid,
2076 StringExtractorGDBRemote& response
2077)
2078{
2079 if (pid != LLDB_INVALID_PROCESS_ID)
2080 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002081 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002082 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002083 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002084 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002085 {
2086 if (response.IsErrorResponse())
2087 return response.GetError();
2088 return 0;
2089 }
2090 }
2091 return -1;
2092}
2093
Vince Harrone0be4252015-02-06 18:32:57 +00002094int
2095GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2096{
2097 StreamString packet;
2098 packet.PutCString("I");
2099 packet.PutBytesAsRawHex8(data, data_len);
2100 StringExtractorGDBRemote response;
2101 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2102 {
2103 return 0;
2104 }
2105 return response.GetError();
2106
2107}
2108
Greg Clayton576d8832011-03-22 04:00:09 +00002109const lldb_private::ArchSpec &
2110GDBRemoteCommunicationClient::GetHostArchitecture ()
2111{
Greg Clayton32e0a752011-03-30 18:16:51 +00002112 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00002113 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00002114 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00002115}
2116
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002117uint32_t
2118GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2119{
2120 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2121 GetHostInfo ();
2122 return m_default_packet_timeout;
2123}
2124
Greg Clayton576d8832011-03-22 04:00:09 +00002125addr_t
2126GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2127{
Greg Clayton70b57652011-05-15 01:25:55 +00002128 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002129 {
Greg Clayton70b57652011-05-15 01:25:55 +00002130 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002131 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002132 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00002133 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00002134 permissions & lldb::ePermissionsReadable ? "r" : "",
2135 permissions & lldb::ePermissionsWritable ? "w" : "",
2136 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00002137 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002138 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002139 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002140 {
Todd Fialaf105f582014-06-21 00:48:09 +00002141 if (response.IsUnsupportedResponse())
2142 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2143 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002144 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2145 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002146 else
2147 {
2148 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2149 }
Greg Clayton576d8832011-03-22 04:00:09 +00002150 }
2151 return LLDB_INVALID_ADDRESS;
2152}
2153
2154bool
2155GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2156{
Greg Clayton70b57652011-05-15 01:25:55 +00002157 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002158 {
Greg Clayton70b57652011-05-15 01:25:55 +00002159 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002160 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002161 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002162 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002163 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002164 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002165 {
Todd Fialaf105f582014-06-21 00:48:09 +00002166 if (response.IsUnsupportedResponse())
2167 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2168 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002169 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002170 }
2171 else
2172 {
2173 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00002174 }
Greg Clayton576d8832011-03-22 04:00:09 +00002175 }
2176 return false;
2177}
2178
Jim Inghamacff8952013-05-02 00:27:30 +00002179Error
2180GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00002181{
Jim Inghamacff8952013-05-02 00:27:30 +00002182 Error error;
2183
2184 if (keep_stopped)
2185 {
2186 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2187 {
2188 char packet[64];
2189 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002190 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002191 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002192 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002193 {
2194 m_supports_detach_stay_stopped = eLazyBoolYes;
2195 }
2196 else
2197 {
2198 m_supports_detach_stay_stopped = eLazyBoolNo;
2199 }
2200 }
2201
2202 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2203 {
2204 error.SetErrorString("Stays stopped not supported by this target.");
2205 return error;
2206 }
2207 else
2208 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002209 StringExtractorGDBRemote response;
2210 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002211 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002212 error.SetErrorString ("Sending extended disconnect packet failed.");
2213 }
2214 }
2215 else
2216 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002217 StringExtractorGDBRemote response;
2218 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002219 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002220 error.SetErrorString ("Sending disconnect packet failed.");
2221 }
2222 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002223}
2224
Greg Clayton46fb5582011-11-18 07:03:08 +00002225Error
2226GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2227 lldb_private::MemoryRegionInfo &region_info)
2228{
2229 Error error;
2230 region_info.Clear();
2231
2232 if (m_supports_memory_region_info != eLazyBoolNo)
2233 {
2234 m_supports_memory_region_info = eLazyBoolYes;
2235 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002236 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002237 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002238 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002239 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002240 {
2241 std::string name;
2242 std::string value;
2243 addr_t addr_value;
2244 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002245 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002246 while (success && response.GetNameColonValue(name, value))
2247 {
2248 if (name.compare ("start") == 0)
2249 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002250 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002251 if (success)
2252 region_info.GetRange().SetRangeBase(addr_value);
2253 }
2254 else if (name.compare ("size") == 0)
2255 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002256 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002257 if (success)
2258 region_info.GetRange().SetByteSize (addr_value);
2259 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002260 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002261 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002262 saw_permissions = true;
2263 if (region_info.GetRange().Contains (addr))
2264 {
2265 if (value.find('r') != std::string::npos)
2266 region_info.SetReadable (MemoryRegionInfo::eYes);
2267 else
2268 region_info.SetReadable (MemoryRegionInfo::eNo);
2269
2270 if (value.find('w') != std::string::npos)
2271 region_info.SetWritable (MemoryRegionInfo::eYes);
2272 else
2273 region_info.SetWritable (MemoryRegionInfo::eNo);
2274
2275 if (value.find('x') != std::string::npos)
2276 region_info.SetExecutable (MemoryRegionInfo::eYes);
2277 else
2278 region_info.SetExecutable (MemoryRegionInfo::eNo);
2279 }
2280 else
2281 {
2282 // The reported region does not contain this address -- we're looking at an unmapped page
2283 region_info.SetReadable (MemoryRegionInfo::eNo);
2284 region_info.SetWritable (MemoryRegionInfo::eNo);
2285 region_info.SetExecutable (MemoryRegionInfo::eNo);
2286 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002287 }
2288 else if (name.compare ("error") == 0)
2289 {
2290 StringExtractorGDBRemote name_extractor;
2291 // Swap "value" over into "name_extractor"
2292 name_extractor.GetStringRef().swap(value);
2293 // Now convert the HEX bytes into a string value
2294 name_extractor.GetHexByteString (value);
2295 error.SetErrorString(value.c_str());
2296 }
2297 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002298
2299 // We got a valid address range back but no permissions -- which means this is an unmapped page
2300 if (region_info.GetRange().IsValid() && saw_permissions == false)
2301 {
2302 region_info.SetReadable (MemoryRegionInfo::eNo);
2303 region_info.SetWritable (MemoryRegionInfo::eNo);
2304 region_info.SetExecutable (MemoryRegionInfo::eNo);
2305 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002306 }
2307 else
2308 {
2309 m_supports_memory_region_info = eLazyBoolNo;
2310 }
2311 }
2312
2313 if (m_supports_memory_region_info == eLazyBoolNo)
2314 {
2315 error.SetErrorString("qMemoryRegionInfo is not supported");
2316 }
2317 if (error.Fail())
2318 region_info.Clear();
2319 return error;
2320
2321}
2322
Johnny Chen64637202012-05-23 21:09:52 +00002323Error
2324GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2325{
2326 Error error;
2327
2328 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2329 {
2330 num = m_num_supported_hardware_watchpoints;
2331 return error;
2332 }
2333
2334 // Set num to 0 first.
2335 num = 0;
2336 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2337 {
2338 char packet[64];
2339 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002340 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002341 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002342 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002343 {
2344 m_supports_watchpoint_support_info = eLazyBoolYes;
2345 std::string name;
2346 std::string value;
2347 while (response.GetNameColonValue(name, value))
2348 {
2349 if (name.compare ("num") == 0)
2350 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002351 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002352 m_num_supported_hardware_watchpoints = num;
2353 }
2354 }
2355 }
2356 else
2357 {
2358 m_supports_watchpoint_support_info = eLazyBoolNo;
2359 }
2360 }
2361
2362 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2363 {
2364 error.SetErrorString("qWatchpointSupportInfo is not supported");
2365 }
2366 return error;
2367
2368}
Greg Clayton46fb5582011-11-18 07:03:08 +00002369
Enrico Granataf04a2192012-07-13 23:18:48 +00002370lldb_private::Error
2371GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2372{
2373 Error error(GetWatchpointSupportInfo(num));
2374 if (error.Success())
2375 error = GetWatchpointsTriggerAfterInstruction(after);
2376 return error;
2377}
2378
2379lldb_private::Error
2380GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2381{
2382 Error error;
2383
2384 // we assume watchpoints will happen after running the relevant opcode
2385 // and we only want to override this behavior if we have explicitly
2386 // received a qHostInfo telling us otherwise
2387 if (m_qHostInfo_is_valid != eLazyBoolYes)
2388 after = true;
2389 else
2390 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2391 return error;
2392}
2393
Greg Clayton576d8832011-03-22 04:00:09 +00002394int
Chaoren Lind3173f32015-05-29 19:52:29 +00002395GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002396{
Chaoren Lind3173f32015-05-29 19:52:29 +00002397 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002398 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002399 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002400 StreamString packet;
2401 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002402 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00002403
2404 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002405 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002406 {
2407 if (response.IsOKResponse())
2408 return 0;
2409 uint8_t error = response.GetError();
2410 if (error)
2411 return error;
2412 }
2413 }
2414 return -1;
2415}
2416
2417int
Chaoren Lind3173f32015-05-29 19:52:29 +00002418GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002419{
Chaoren Lind3173f32015-05-29 19:52:29 +00002420 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002421 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002422 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002423 StreamString packet;
2424 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002425 packet.PutCStringAsRawHex8(path.c_str());
2426
Greg Clayton576d8832011-03-22 04:00:09 +00002427 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002428 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002429 {
2430 if (response.IsOKResponse())
2431 return 0;
2432 uint8_t error = response.GetError();
2433 if (error)
2434 return error;
2435 }
2436 }
2437 return -1;
2438}
2439
2440int
Chaoren Lind3173f32015-05-29 19:52:29 +00002441GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002442{
Chaoren Lind3173f32015-05-29 19:52:29 +00002443 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002444 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002445 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002446 StreamString packet;
2447 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002448 packet.PutCStringAsRawHex8(path.c_str());
2449
Greg Clayton576d8832011-03-22 04:00:09 +00002450 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002451 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002452 {
2453 if (response.IsOKResponse())
2454 return 0;
2455 uint8_t error = response.GetError();
2456 if (error)
2457 return error;
2458 }
2459 }
2460 return -1;
2461}
2462
Greg Claytonfbb76342013-11-20 21:07:01 +00002463bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002464GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00002465{
2466 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002467 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002468 {
2469 if (response.IsUnsupportedResponse())
2470 return false;
2471 if (response.IsErrorResponse())
2472 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00002473 std::string cwd;
2474 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00002475 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00002476 return !cwd.empty();
2477 }
2478 return false;
2479}
2480
Greg Clayton576d8832011-03-22 04:00:09 +00002481int
Chaoren Lind3173f32015-05-29 19:52:29 +00002482GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002483{
Chaoren Lind3173f32015-05-29 19:52:29 +00002484 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002485 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002486 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002487 StreamString packet;
2488 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002489 packet.PutCStringAsRawHex8(path.c_str());
2490
Greg Clayton576d8832011-03-22 04:00:09 +00002491 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002492 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002493 {
2494 if (response.IsOKResponse())
2495 return 0;
2496 uint8_t error = response.GetError();
2497 if (error)
2498 return error;
2499 }
2500 }
2501 return -1;
2502}
2503
2504int
2505GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2506{
Greg Clayton32e0a752011-03-30 18:16:51 +00002507 char packet[32];
2508 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002509 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002510 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002511 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002512 {
2513 if (response.IsOKResponse())
2514 return 0;
2515 uint8_t error = response.GetError();
2516 if (error)
2517 return error;
2518 }
2519 return -1;
2520}
Greg Clayton32e0a752011-03-30 18:16:51 +00002521
Jim Ingham106d0282014-06-25 02:32:56 +00002522int
2523GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2524{
2525 char packet[32];
2526 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2527 assert (packet_len < (int)sizeof(packet));
2528 StringExtractorGDBRemote response;
2529 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2530 {
2531 if (response.IsOKResponse())
2532 return 0;
2533 uint8_t error = response.GetError();
2534 if (error)
2535 return error;
2536 }
2537 return -1;
2538}
2539
2540
Greg Clayton32e0a752011-03-30 18:16:51 +00002541bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002542GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002543{
2544 if (response.IsNormalResponse())
2545 {
2546 std::string name;
2547 std::string value;
2548 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002549
2550 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2551 uint32_t sub = 0;
2552 std::string vendor;
2553 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002554
2555 while (response.GetNameColonValue(name, value))
2556 {
2557 if (name.compare("pid") == 0)
2558 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002559 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002560 }
2561 else if (name.compare("ppid") == 0)
2562 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002563 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002564 }
2565 else if (name.compare("uid") == 0)
2566 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002567 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002568 }
2569 else if (name.compare("euid") == 0)
2570 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002571 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002572 }
2573 else if (name.compare("gid") == 0)
2574 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002575 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002576 }
2577 else if (name.compare("egid") == 0)
2578 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002579 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002580 }
2581 else if (name.compare("triple") == 0)
2582 {
Greg Clayton44272a42014-09-18 00:18:32 +00002583 StringExtractor extractor;
2584 extractor.GetStringRef().swap(value);
2585 extractor.SetFilePos(0);
2586 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002587 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002588 }
2589 else if (name.compare("name") == 0)
2590 {
2591 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002592 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002593 // control the characters in a process name
2594 extractor.GetStringRef().swap(value);
2595 extractor.SetFilePos(0);
2596 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002597 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002598 }
Jason Molenda89c37492014-01-27 22:23:20 +00002599 else if (name.compare("cputype") == 0)
2600 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002601 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002602 }
2603 else if (name.compare("cpusubtype") == 0)
2604 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002605 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002606 }
2607 else if (name.compare("vendor") == 0)
2608 {
2609 vendor = value;
2610 }
2611 else if (name.compare("ostype") == 0)
2612 {
2613 os_type = value;
2614 }
2615 }
2616
2617 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2618 {
2619 if (vendor == "apple")
2620 {
2621 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2622 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2623 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2624 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002625 }
2626
2627 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2628 return true;
2629 }
2630 return false;
2631}
2632
2633bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002634GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002635{
2636 process_info.Clear();
2637
2638 if (m_supports_qProcessInfoPID)
2639 {
2640 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002641 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002642 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002643 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002644 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002645 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002646 return DecodeProcessInfoResponse (response, process_info);
2647 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002648 else
2649 {
2650 m_supports_qProcessInfoPID = false;
2651 return false;
2652 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002653 }
2654 return false;
2655}
2656
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002657bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002658GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002659{
Todd Fiala3daa1762014-09-15 16:01:29 +00002660 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2661
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002662 if (allow_lazy)
2663 {
2664 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2665 return true;
2666 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2667 return false;
2668 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002669
2670 GetHostInfo ();
2671
2672 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002673 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002674 {
2675 if (response.IsNormalResponse())
2676 {
2677 std::string name;
2678 std::string value;
2679 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2680 uint32_t sub = 0;
2681 std::string arch_name;
2682 std::string os_name;
2683 std::string vendor_name;
2684 std::string triple;
2685 uint32_t pointer_byte_size = 0;
2686 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002687 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002688 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002689 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002690 while (response.GetNameColonValue(name, value))
2691 {
2692 if (name.compare("cputype") == 0)
2693 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002694 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002695 if (cpu != LLDB_INVALID_CPUTYPE)
2696 ++num_keys_decoded;
2697 }
2698 else if (name.compare("cpusubtype") == 0)
2699 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002700 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002701 if (sub != 0)
2702 ++num_keys_decoded;
2703 }
Todd Fialac540dd02014-08-26 18:21:02 +00002704 else if (name.compare("triple") == 0)
2705 {
Greg Clayton44272a42014-09-18 00:18:32 +00002706 StringExtractor extractor;
2707 extractor.GetStringRef().swap(value);
2708 extractor.SetFilePos(0);
2709 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002710 ++num_keys_decoded;
2711 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002712 else if (name.compare("ostype") == 0)
2713 {
2714 os_name.swap (value);
2715 ++num_keys_decoded;
2716 }
2717 else if (name.compare("vendor") == 0)
2718 {
2719 vendor_name.swap(value);
2720 ++num_keys_decoded;
2721 }
2722 else if (name.compare("endian") == 0)
2723 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002724 ++num_keys_decoded;
2725 if (value.compare("little") == 0)
2726 byte_order = eByteOrderLittle;
2727 else if (value.compare("big") == 0)
2728 byte_order = eByteOrderBig;
2729 else if (value.compare("pdp") == 0)
2730 byte_order = eByteOrderPDP;
2731 else
2732 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002733 }
2734 else if (name.compare("ptrsize") == 0)
2735 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002736 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002737 if (pointer_byte_size != 0)
2738 ++num_keys_decoded;
2739 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002740 else if (name.compare("pid") == 0)
2741 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002742 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002743 if (pid != LLDB_INVALID_PROCESS_ID)
2744 ++num_keys_decoded;
2745 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002746 }
2747 if (num_keys_decoded > 0)
2748 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002749 if (pid != LLDB_INVALID_PROCESS_ID)
2750 {
2751 m_curr_pid_is_valid = eLazyBoolYes;
2752 m_curr_pid = pid;
2753 }
Todd Fialac540dd02014-08-26 18:21:02 +00002754
2755 // Set the ArchSpec from the triple if we have it.
2756 if (!triple.empty ())
2757 {
2758 m_process_arch.SetTriple (triple.c_str ());
2759 if (pointer_byte_size)
2760 {
2761 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2762 }
2763 }
2764 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002765 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002766 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2767
2768 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2769 switch (triple.getObjectFormat()) {
2770 case llvm::Triple::MachO:
2771 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2772 break;
2773 case llvm::Triple::ELF:
2774 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2775 break;
2776 case llvm::Triple::COFF:
2777 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2778 break;
2779 case llvm::Triple::UnknownObjectFormat:
2780 if (log)
2781 log->Printf("error: failed to determine target architecture");
2782 return false;
2783 }
2784
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002785 if (pointer_byte_size)
2786 {
2787 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2788 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002789 if (byte_order != eByteOrderInvalid)
2790 {
2791 assert (byte_order == m_process_arch.GetByteOrder());
2792 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002793 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002794 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002795 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2796 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002797 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002798 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002799 }
2800 }
2801 else
2802 {
2803 m_qProcessInfo_is_valid = eLazyBoolNo;
2804 }
2805
2806 return false;
2807}
2808
2809
Greg Clayton32e0a752011-03-30 18:16:51 +00002810uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002811GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2812 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002813{
2814 process_infos.Clear();
2815
2816 if (m_supports_qfProcessInfo)
2817 {
2818 StreamString packet;
2819 packet.PutCString ("qfProcessInfo");
2820 if (!match_info.MatchAllProcesses())
2821 {
2822 packet.PutChar (':');
2823 const char *name = match_info.GetProcessInfo().GetName();
2824 bool has_name_match = false;
2825 if (name && name[0])
2826 {
2827 has_name_match = true;
2828 NameMatchType name_match_type = match_info.GetNameMatchType();
2829 switch (name_match_type)
2830 {
2831 case eNameMatchIgnore:
2832 has_name_match = false;
2833 break;
2834
2835 case eNameMatchEquals:
2836 packet.PutCString ("name_match:equals;");
2837 break;
2838
2839 case eNameMatchContains:
2840 packet.PutCString ("name_match:contains;");
2841 break;
2842
2843 case eNameMatchStartsWith:
2844 packet.PutCString ("name_match:starts_with;");
2845 break;
2846
2847 case eNameMatchEndsWith:
2848 packet.PutCString ("name_match:ends_with;");
2849 break;
2850
2851 case eNameMatchRegularExpression:
2852 packet.PutCString ("name_match:regex;");
2853 break;
2854 }
2855 if (has_name_match)
2856 {
2857 packet.PutCString ("name:");
2858 packet.PutBytesAsRawHex8(name, ::strlen(name));
2859 packet.PutChar (';');
2860 }
2861 }
2862
2863 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002864 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002865 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002866 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002867 if (match_info.GetProcessInfo().UserIDIsValid())
2868 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2869 if (match_info.GetProcessInfo().GroupIDIsValid())
2870 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002871 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2872 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2873 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2874 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2875 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2876 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2877 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2878 {
2879 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2880 const llvm::Triple &triple = match_arch.GetTriple();
2881 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00002882 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002883 packet.PutChar (';');
2884 }
2885 }
2886 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00002887 // Increase timeout as the first qfProcessInfo packet takes a long time
2888 // on Android. The value of 1min was arrived at empirically.
2889 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00002890 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002891 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002892 do
2893 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002894 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002895 if (!DecodeProcessInfoResponse (response, process_info))
2896 break;
2897 process_infos.Append(process_info);
2898 response.GetStringRef().clear();
2899 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002900 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002901 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002902 else
2903 {
2904 m_supports_qfProcessInfo = false;
2905 return 0;
2906 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002907 }
2908 return process_infos.GetSize();
2909
2910}
2911
2912bool
2913GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2914{
2915 if (m_supports_qUserName)
2916 {
2917 char packet[32];
2918 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002919 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002920 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002921 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002922 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002923 if (response.IsNormalResponse())
2924 {
2925 // Make sure we parsed the right number of characters. The response is
2926 // the hex encoded user name and should make up the entire packet.
2927 // If there are any non-hex ASCII bytes, the length won't match below..
2928 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2929 return true;
2930 }
2931 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002932 else
2933 {
2934 m_supports_qUserName = false;
2935 return false;
2936 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002937 }
2938 return false;
2939
2940}
2941
2942bool
2943GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2944{
2945 if (m_supports_qGroupName)
2946 {
2947 char packet[32];
2948 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002949 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002950 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002951 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002952 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002953 if (response.IsNormalResponse())
2954 {
2955 // Make sure we parsed the right number of characters. The response is
2956 // the hex encoded group name and should make up the entire packet.
2957 // If there are any non-hex ASCII bytes, the length won't match below..
2958 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2959 return true;
2960 }
2961 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002962 else
2963 {
2964 m_supports_qGroupName = false;
2965 return false;
2966 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002967 }
2968 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002969}
Greg Clayton32e0a752011-03-30 18:16:51 +00002970
Ewan Crawford78baa192015-05-13 09:18:18 +00002971bool
2972GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
2973{
2974 // Form non-stop packet request
2975 char packet[32];
2976 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2977 assert(packet_len < (int)sizeof(packet));
2978
2979 StringExtractorGDBRemote response;
2980 // Send to target
2981 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2982 if (response.IsOKResponse())
2983 return true;
2984
2985 // Failed or not supported
2986 return false;
2987
2988}
2989
Greg Claytone034a042015-05-21 20:52:06 +00002990static void
2991MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
2992{
2993 packet.Clear();
2994 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2995 uint32_t bytes_left = send_size;
2996 while (bytes_left > 0)
2997 {
2998 if (bytes_left >= 26)
2999 {
3000 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3001 bytes_left -= 26;
3002 }
3003 else
3004 {
3005 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3006 bytes_left = 0;
3007 }
3008 }
3009}
3010
3011template<typename T>
3012T calculate_standard_deviation(const std::vector<T> &v)
3013{
3014 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3015 T mean = sum / (T)v.size();
3016 T accum = T(0);
3017 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3018 T delta = d - mean;
3019 accum += delta * delta;
3020 });
3021
3022 T stdev = sqrt(accum / (v.size()-1));
3023 return stdev;
3024}
3025
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003026void
Greg Claytone034a042015-05-21 20:52:06 +00003027GDBRemoteCommunicationClient::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 +00003028{
3029 uint32_t i;
3030 TimeValue start_time, end_time;
3031 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003032 if (SendSpeedTestPacket (0, 0))
3033 {
Greg Claytone034a042015-05-21 20:52:06 +00003034 StreamString packet;
3035 if (json)
3036 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3037 else
3038 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3039 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00003040
Greg Claytone034a042015-05-21 20:52:06 +00003041 uint32_t result_idx = 0;
3042 uint32_t send_size;
3043 std::vector<float> packet_times;
3044
3045 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3046 {
3047 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3048 {
3049 MakeSpeedTestPacket (packet, send_size, recv_size);
3050
3051 packet_times.clear();
3052 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00003053 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00003054 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00003055 {
Greg Claytone034a042015-05-21 20:52:06 +00003056 TimeValue packet_start_time = TimeValue::Now();
3057 StringExtractorGDBRemote response;
3058 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3059 TimeValue packet_end_time = TimeValue::Now();
3060 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3061 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003062 }
3063 end_time = TimeValue::Now();
3064 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00003065
3066 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3067 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3068 float average_ms_per_packet = total_ms / num_packets;
3069 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3070 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00003071 {
Greg Claytone034a042015-05-21 20:52:06 +00003072 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);
3073 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00003074 }
3075 else
3076 {
Greg Claytone034a042015-05-21 20:52:06 +00003077 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",
3078 send_size,
3079 recv_size,
3080 total_time_nsec / TimeValue::NanoSecPerSec,
3081 total_time_nsec % TimeValue::NanoSecPerSec,
3082 packets_per_second,
3083 average_ms_per_packet,
3084 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00003085 }
Greg Claytone034a042015-05-21 20:52:06 +00003086 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003087 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003088 }
Greg Claytone034a042015-05-21 20:52:06 +00003089
3090 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3091
3092 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3093 if (json)
3094 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3095 else
3096 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3097 strm.Flush();
3098 send_size = 0;
3099 result_idx = 0;
3100 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3101 {
3102 MakeSpeedTestPacket (packet, send_size, recv_size);
3103
3104 // If we have a receive size, test how long it takes to receive 4MB of data
3105 if (recv_size > 0)
3106 {
3107 start_time = TimeValue::Now();
3108 uint32_t bytes_read = 0;
3109 uint32_t packet_count = 0;
3110 while (bytes_read < k_recv_amount)
3111 {
3112 StringExtractorGDBRemote response;
3113 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3114 bytes_read += recv_size;
3115 ++packet_count;
3116 }
3117 end_time = TimeValue::Now();
3118 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3119 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3120 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3121 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3122 float average_ms_per_packet = total_ms / packet_count;
3123
3124 if (json)
3125 {
3126 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);
3127 ++result_idx;
3128 }
3129 else
3130 {
3131 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",
3132 send_size,
3133 recv_size,
3134 packet_count,
3135 k_recv_amount_mb,
3136 total_time_nsec / TimeValue::NanoSecPerSec,
3137 total_time_nsec % TimeValue::NanoSecPerSec,
3138 mb_second,
3139 packets_per_second,
3140 average_ms_per_packet);
3141 }
3142 strm.Flush();
3143 }
3144 }
3145 if (json)
3146 strm.Printf("\n ]\n }\n}\n");
3147 else
3148 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003149 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003150}
3151
3152bool
3153GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3154{
3155 StreamString packet;
3156 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3157 uint32_t bytes_left = send_size;
3158 while (bytes_left > 0)
3159 {
3160 if (bytes_left >= 26)
3161 {
3162 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3163 bytes_left -= 26;
3164 }
3165 else
3166 {
3167 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3168 bytes_left = 0;
3169 }
3170 }
3171
3172 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003173 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00003174}
Greg Clayton8b82f082011-04-12 05:54:46 +00003175
3176uint16_t
Greg Claytondbf04572013-12-04 19:40:33 +00003177GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
Greg Clayton8b82f082011-04-12 05:54:46 +00003178{
Daniel Maleae0f8f572013-08-26 23:57:52 +00003179 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00003180 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003181 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00003182 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003183 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00003184 if (remote_accept_hostname && remote_accept_hostname[0])
3185 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003186 else
3187 {
Zachary Turner97a14e62014-08-19 17:18:29 +00003188 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00003189 {
3190 // Make the GDB server we launch only accept connections from this host
3191 stream.Printf("host:%s;", hostname.c_str());
3192 }
3193 else
3194 {
3195 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3196 stream.Printf("host:*;");
3197 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003198 }
3199 const char *packet = stream.GetData();
3200 int packet_len = stream.GetSize();
3201
Vince Harron1b5a74e2015-01-21 22:42:49 +00003202 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003203 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
3204
3205 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003206 {
3207 std::string name;
3208 std::string value;
3209 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00003210 while (response.GetNameColonValue(name, value))
3211 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003212 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003213 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003214 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003215 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00003216 }
3217 return port;
3218 }
3219 return 0;
3220}
3221
3222bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003223GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3224{
3225 StreamString stream;
3226 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3227 const char *packet = stream.GetData();
3228 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003229
Daniel Maleae0f8f572013-08-26 23:57:52 +00003230 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003231 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003232 {
3233 if (response.IsOKResponse())
3234 return true;
3235 }
3236 return false;
3237}
3238
3239bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003240GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003241{
3242 if (m_curr_tid == tid)
3243 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003244
Greg Clayton8b82f082011-04-12 05:54:46 +00003245 char packet[32];
3246 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003247 if (tid == UINT64_MAX)
3248 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003249 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003250 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003251 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003252 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003253 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003254 {
3255 if (response.IsOKResponse())
3256 {
3257 m_curr_tid = tid;
3258 return true;
3259 }
3260 }
3261 return false;
3262}
3263
3264bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003265GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003266{
3267 if (m_curr_tid_run == tid)
3268 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003269
Greg Clayton8b82f082011-04-12 05:54:46 +00003270 char packet[32];
3271 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003272 if (tid == UINT64_MAX)
3273 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003274 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003275 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3276
Andy Gibbsa297a972013-06-19 19:04:53 +00003277 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003278 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003279 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003280 {
3281 if (response.IsOKResponse())
3282 {
3283 m_curr_tid_run = tid;
3284 return true;
3285 }
3286 }
3287 return false;
3288}
3289
3290bool
3291GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3292{
Greg Clayton3dedae12013-12-06 21:45:27 +00003293 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003294 return response.IsNormalResponse();
3295 return false;
3296}
3297
3298bool
Greg Claytonf402f782012-10-13 02:11:55 +00003299GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003300{
3301 if (m_supports_qThreadStopInfo)
3302 {
3303 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003304 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003305 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003306 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003307 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003308 if (response.IsUnsupportedResponse())
3309 m_supports_qThreadStopInfo = false;
3310 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003311 return true;
3312 else
3313 return false;
3314 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003315 else
3316 {
3317 m_supports_qThreadStopInfo = false;
3318 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003319 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003320 return false;
3321}
3322
3323
3324uint8_t
3325GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3326{
Todd Fiala616b8272014-10-09 00:55:04 +00003327 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3328 if (log)
3329 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3330 __FUNCTION__, insert ? "add" : "remove", addr);
3331
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003332 // Check if the stub is known not to support this breakpoint type
3333 if (!SupportsGDBStoppointPacket(type))
3334 return UINT8_MAX;
3335 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003336 char packet[64];
3337 const int packet_len = ::snprintf (packet,
3338 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003339 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003340 insert ? 'Z' : 'z',
3341 type,
3342 addr,
3343 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003344 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003345 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003346 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003347 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003348 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003349 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003350 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003351 if (response.IsOKResponse())
3352 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003353
3354 // Error while setting breakpoint, send back specific error
3355 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003356 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003357
3358 // Empty packet informs us that breakpoint is not supported
3359 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003360 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003361 // Disable this breakpoint type since it is unsupported
3362 switch (type)
3363 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003364 case eBreakpointSoftware: m_supports_z0 = false; break;
3365 case eBreakpointHardware: m_supports_z1 = false; break;
3366 case eWatchpointWrite: m_supports_z2 = false; break;
3367 case eWatchpointRead: m_supports_z3 = false; break;
3368 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003369 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003370 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003371 }
3372 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003373 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003374 return UINT8_MAX;
3375}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003376
3377size_t
3378GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3379 bool &sequence_mutex_unavailable)
3380{
3381 Mutex::Locker locker;
3382 thread_ids.clear();
3383
Jim Ingham4ceb9282012-06-08 22:50:40 +00003384 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003385 {
3386 sequence_mutex_unavailable = false;
3387 StringExtractorGDBRemote response;
3388
Greg Clayton3dedae12013-12-06 21:45:27 +00003389 PacketResult packet_result;
3390 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3391 packet_result == PacketResult::Success && response.IsNormalResponse();
3392 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003393 {
3394 char ch = response.GetChar();
3395 if (ch == 'l')
3396 break;
3397 if (ch == 'm')
3398 {
3399 do
3400 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003401 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003402
3403 if (tid != LLDB_INVALID_THREAD_ID)
3404 {
3405 thread_ids.push_back (tid);
3406 }
3407 ch = response.GetChar(); // Skip the command separator
3408 } while (ch == ','); // Make sure we got a comma separator
3409 }
3410 }
3411 }
3412 else
3413 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003414#if defined (LLDB_CONFIGURATION_DEBUG)
3415 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3416#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003417 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003418 if (log)
3419 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003420#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003421 sequence_mutex_unavailable = true;
3422 }
3423 return thread_ids.size();
3424}
Greg Clayton37a0a242012-04-11 00:24:49 +00003425
3426lldb::addr_t
3427GDBRemoteCommunicationClient::GetShlibInfoAddr()
3428{
3429 if (!IsRunning())
3430 {
3431 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003432 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003433 {
3434 if (response.IsNormalResponse())
3435 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3436 }
3437 }
3438 return LLDB_INVALID_ADDRESS;
3439}
3440
Daniel Maleae0f8f572013-08-26 23:57:52 +00003441lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003442GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3443 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3444 int *status_ptr, // Pass NULL if you don't want the process exit status
3445 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3446 std::string *command_output, // Pass NULL if you don't want the command output
3447 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003448{
3449 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003450 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003451 stream.PutBytesAsRawHex8(command, strlen(command));
3452 stream.PutChar(',');
3453 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003454 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003455 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003456 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003457 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003458 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003459 }
3460 const char *packet = stream.GetData();
3461 int packet_len = stream.GetSize();
3462 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003463 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003464 {
3465 if (response.GetChar() != 'F')
3466 return Error("malformed reply");
3467 if (response.GetChar() != ',')
3468 return Error("malformed reply");
3469 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3470 if (exitcode == UINT32_MAX)
3471 return Error("unable to run remote process");
3472 else if (status_ptr)
3473 *status_ptr = exitcode;
3474 if (response.GetChar() != ',')
3475 return Error("malformed reply");
3476 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3477 if (signo_ptr)
3478 *signo_ptr = signo;
3479 if (response.GetChar() != ',')
3480 return Error("malformed reply");
3481 std::string output;
3482 response.GetEscapedBinaryData(output);
3483 if (command_output)
3484 command_output->assign(output);
3485 return Error();
3486 }
3487 return Error("unable to send packet");
3488}
3489
Greg Claytonfbb76342013-11-20 21:07:01 +00003490Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003491GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3492 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003493{
Chaoren Lind3173f32015-05-29 19:52:29 +00003494 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003495 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003496 stream.PutCString("qPlatform_mkdir:");
3497 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003498 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003499 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003500 const char *packet = stream.GetData();
3501 int packet_len = stream.GetSize();
3502 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003503
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003504 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3505 return Error("failed to send '%s' packet", packet);
3506
3507 if (response.GetChar() != 'F')
3508 return Error("invalid response to '%s' packet", packet);
3509
3510 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003511}
3512
Greg Claytonfbb76342013-11-20 21:07:01 +00003513Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003514GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3515 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003516{
Chaoren Lind3173f32015-05-29 19:52:29 +00003517 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003518 lldb_private::StreamString stream;
3519 stream.PutCString("qPlatform_chmod:");
3520 stream.PutHex32(file_permissions);
3521 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003522 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003523 const char *packet = stream.GetData();
3524 int packet_len = stream.GetSize();
3525 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003526
3527 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3528 return Error("failed to send '%s' packet", packet);
3529
3530 if (response.GetChar() != 'F')
3531 return Error("invalid response to '%s' packet", packet);
3532
Chaoren Lince36c4c2015-05-05 18:43:19 +00003533 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003534}
3535
Daniel Maleae0f8f572013-08-26 23:57:52 +00003536static uint64_t
3537ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3538 uint64_t fail_result,
3539 Error &error)
3540{
3541 response.SetFilePos(0);
3542 if (response.GetChar() != 'F')
3543 return fail_result;
3544 int32_t result = response.GetS32 (-2);
3545 if (result == -2)
3546 return fail_result;
3547 if (response.GetChar() == ',')
3548 {
3549 int result_errno = response.GetS32 (-2);
3550 if (result_errno != -2)
3551 error.SetError(result_errno, eErrorTypePOSIX);
3552 else
3553 error.SetError(-1, eErrorTypeGeneric);
3554 }
3555 else
3556 error.Clear();
3557 return result;
3558}
3559lldb::user_id_t
3560GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3561 uint32_t flags,
3562 mode_t mode,
3563 Error &error)
3564{
Chaoren Lind3173f32015-05-29 19:52:29 +00003565 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003566 lldb_private::StreamString stream;
3567 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003568 if (path.empty())
3569 return UINT64_MAX;
3570 stream.PutCStringAsRawHex8(path.c_str());
3571 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003572 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003573 stream.PutChar(',');
3574 stream.PutHex32(mode);
3575 const char* packet = stream.GetData();
3576 int packet_len = stream.GetSize();
3577 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003578 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003579 {
3580 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3581 }
3582 return UINT64_MAX;
3583}
3584
3585bool
3586GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3587 Error &error)
3588{
3589 lldb_private::StreamString stream;
3590 stream.Printf("vFile:close:%i", (int)fd);
3591 const char* packet = stream.GetData();
3592 int packet_len = stream.GetSize();
3593 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003594 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003595 {
3596 return ParseHostIOPacketResponse (response, -1, error) == 0;
3597 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003598 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003599}
3600
3601// Extension of host I/O packets to get the file size.
3602lldb::user_id_t
3603GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3604{
Chaoren Lind3173f32015-05-29 19:52:29 +00003605 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003606 lldb_private::StreamString stream;
3607 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003608 stream.PutCStringAsRawHex8(path.c_str());
3609 const char* packet = stream.GetData();
3610 int packet_len = stream.GetSize();
3611 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003612 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003613 {
3614 if (response.GetChar() != 'F')
3615 return UINT64_MAX;
3616 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3617 return retcode;
3618 }
3619 return UINT64_MAX;
3620}
3621
Greg Claytonfbb76342013-11-20 21:07:01 +00003622Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003623GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3624 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003625{
Chaoren Lind3173f32015-05-29 19:52:29 +00003626 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003627 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003628 lldb_private::StreamString stream;
3629 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003630 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003631 const char* packet = stream.GetData();
3632 int packet_len = stream.GetSize();
3633 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003634 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003635 {
3636 if (response.GetChar() != 'F')
3637 {
3638 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003639 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003640 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003641 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003642 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003643 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003644 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003645 if (response.GetChar() == ',')
3646 {
3647 int response_errno = response.GetS32(-1);
3648 if (response_errno > 0)
3649 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3650 else
3651 error.SetErrorToGenericError();
3652 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003653 else
3654 error.SetErrorToGenericError();
3655 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003656 else
3657 {
3658 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3659 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003660 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003661 }
3662 else
3663 {
3664 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3665 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003666 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003667}
3668
3669uint64_t
3670GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3671 uint64_t offset,
3672 void *dst,
3673 uint64_t dst_len,
3674 Error &error)
3675{
3676 lldb_private::StreamString stream;
3677 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3678 const char* packet = stream.GetData();
3679 int packet_len = stream.GetSize();
3680 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003681 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003682 {
3683 if (response.GetChar() != 'F')
3684 return 0;
3685 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3686 if (retcode == UINT32_MAX)
3687 return retcode;
3688 const char next = (response.Peek() ? *response.Peek() : 0);
3689 if (next == ',')
3690 return 0;
3691 if (next == ';')
3692 {
3693 response.GetChar(); // skip the semicolon
3694 std::string buffer;
3695 if (response.GetEscapedBinaryData(buffer))
3696 {
3697 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3698 if (data_to_write > 0)
3699 memcpy(dst, &buffer[0], data_to_write);
3700 return data_to_write;
3701 }
3702 }
3703 }
3704 return 0;
3705}
3706
3707uint64_t
3708GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3709 uint64_t offset,
3710 const void* src,
3711 uint64_t src_len,
3712 Error &error)
3713{
3714 lldb_private::StreamGDBRemote stream;
3715 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3716 stream.PutEscapedBytes(src, src_len);
3717 const char* packet = stream.GetData();
3718 int packet_len = stream.GetSize();
3719 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003720 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003721 {
3722 if (response.GetChar() != 'F')
3723 {
3724 error.SetErrorStringWithFormat("write file failed");
3725 return 0;
3726 }
3727 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3728 if (bytes_written == UINT64_MAX)
3729 {
3730 error.SetErrorToGenericError();
3731 if (response.GetChar() == ',')
3732 {
3733 int response_errno = response.GetS32(-1);
3734 if (response_errno > 0)
3735 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3736 }
3737 return 0;
3738 }
3739 return bytes_written;
3740 }
3741 else
3742 {
3743 error.SetErrorString ("failed to send vFile:pwrite packet");
3744 }
3745 return 0;
3746}
3747
Greg Claytonfbb76342013-11-20 21:07:01 +00003748Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003749GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003750{
Chaoren Lind3173f32015-05-29 19:52:29 +00003751 std::string src_path{src.GetPath(false)},
3752 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003753 Error error;
3754 lldb_private::StreamGDBRemote stream;
3755 stream.PutCString("vFile:symlink:");
3756 // the unix symlink() command reverses its parameters where the dst if first,
3757 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003758 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003759 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003760 stream.PutCStringAsRawHex8(src_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;
Greg Clayton3dedae12013-12-06 21:45:27 +00003764 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003765 {
3766 if (response.GetChar() == 'F')
3767 {
3768 uint32_t result = response.GetU32(UINT32_MAX);
3769 if (result != 0)
3770 {
3771 error.SetErrorToGenericError();
3772 if (response.GetChar() == ',')
3773 {
3774 int response_errno = response.GetS32(-1);
3775 if (response_errno > 0)
3776 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3777 }
3778 }
3779 }
3780 else
3781 {
3782 // Should have returned with 'F<result>[,<errno>]'
3783 error.SetErrorStringWithFormat("symlink failed");
3784 }
3785 }
3786 else
3787 {
3788 error.SetErrorString ("failed to send vFile:symlink packet");
3789 }
3790 return error;
3791}
3792
3793Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003794GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00003795{
Chaoren Lind3173f32015-05-29 19:52:29 +00003796 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003797 Error error;
3798 lldb_private::StreamGDBRemote stream;
3799 stream.PutCString("vFile:unlink:");
3800 // the unix symlink() command reverses its parameters where the dst if first,
3801 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003802 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003803 const char* packet = stream.GetData();
3804 int packet_len = stream.GetSize();
3805 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003806 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003807 {
3808 if (response.GetChar() == 'F')
3809 {
3810 uint32_t result = response.GetU32(UINT32_MAX);
3811 if (result != 0)
3812 {
3813 error.SetErrorToGenericError();
3814 if (response.GetChar() == ',')
3815 {
3816 int response_errno = response.GetS32(-1);
3817 if (response_errno > 0)
3818 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3819 }
3820 }
3821 }
3822 else
3823 {
3824 // Should have returned with 'F<result>[,<errno>]'
3825 error.SetErrorStringWithFormat("unlink failed");
3826 }
3827 }
3828 else
3829 {
3830 error.SetErrorString ("failed to send vFile:unlink packet");
3831 }
3832 return error;
3833}
3834
Daniel Maleae0f8f572013-08-26 23:57:52 +00003835// Extension of host I/O packets to get whether a file exists.
3836bool
3837GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3838{
Chaoren Lind3173f32015-05-29 19:52:29 +00003839 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003840 lldb_private::StreamString stream;
3841 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003842 stream.PutCStringAsRawHex8(path.c_str());
3843 const char* packet = stream.GetData();
3844 int packet_len = stream.GetSize();
3845 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003846 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003847 {
3848 if (response.GetChar() != 'F')
3849 return false;
3850 if (response.GetChar() != ',')
3851 return false;
3852 bool retcode = (response.GetChar() != '0');
3853 return retcode;
3854 }
3855 return false;
3856}
3857
3858bool
3859GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3860 uint64_t &high,
3861 uint64_t &low)
3862{
Chaoren Lind3173f32015-05-29 19:52:29 +00003863 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003864 lldb_private::StreamString stream;
3865 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003866 stream.PutCStringAsRawHex8(path.c_str());
3867 const char* packet = stream.GetData();
3868 int packet_len = stream.GetSize();
3869 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003870 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003871 {
3872 if (response.GetChar() != 'F')
3873 return false;
3874 if (response.GetChar() != ',')
3875 return false;
3876 if (response.Peek() && *response.Peek() == 'x')
3877 return false;
3878 low = response.GetHexMaxU64(false, UINT64_MAX);
3879 high = response.GetHexMaxU64(false, UINT64_MAX);
3880 return true;
3881 }
3882 return false;
3883}
Greg Claytonf74cf862013-11-13 23:28:31 +00003884
3885bool
Jason Molendaa3329782014-03-29 18:54:20 +00003886GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3887{
3888 // Some targets have issues with g/G packets and we need to avoid using them
3889 if (m_avoid_g_packets == eLazyBoolCalculate)
3890 {
3891 if (process)
3892 {
3893 m_avoid_g_packets = eLazyBoolNo;
3894 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3895 if (arch.IsValid()
3896 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3897 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00003898 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00003899 {
3900 m_avoid_g_packets = eLazyBoolYes;
3901 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3902 if (gdb_server_version != 0)
3903 {
3904 const char *gdb_server_name = GetGDBServerProgramName();
3905 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3906 {
3907 if (gdb_server_version >= 310)
3908 m_avoid_g_packets = eLazyBoolNo;
3909 }
3910 }
3911 }
3912 }
3913 }
3914 return m_avoid_g_packets == eLazyBoolYes;
3915}
3916
3917bool
Greg Claytonf74cf862013-11-13 23:28:31 +00003918GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3919{
3920 Mutex::Locker locker;
3921 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3922 {
3923 const bool thread_suffix_supported = GetThreadSuffixSupported();
3924
3925 if (thread_suffix_supported || SetCurrentThread(tid))
3926 {
3927 char packet[64];
3928 int packet_len = 0;
3929 if (thread_suffix_supported)
3930 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3931 else
3932 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3933 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003934 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003935 }
3936 }
3937 return false;
3938
3939}
3940
3941
3942bool
3943GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3944{
3945 Mutex::Locker locker;
3946 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3947 {
3948 const bool thread_suffix_supported = GetThreadSuffixSupported();
3949
3950 if (thread_suffix_supported || SetCurrentThread(tid))
3951 {
3952 char packet[64];
3953 int packet_len = 0;
3954 // Get all registers in one packet
3955 if (thread_suffix_supported)
3956 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3957 else
3958 packet_len = ::snprintf (packet, sizeof(packet), "g");
3959 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003960 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003961 }
3962 }
3963 return false;
3964}
3965bool
3966GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3967{
3968 save_id = 0; // Set to invalid save ID
3969 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3970 return false;
3971
3972 m_supports_QSaveRegisterState = eLazyBoolYes;
3973 Mutex::Locker locker;
3974 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3975 {
3976 const bool thread_suffix_supported = GetThreadSuffixSupported();
3977 if (thread_suffix_supported || SetCurrentThread(tid))
3978 {
3979 char packet[256];
3980 if (thread_suffix_supported)
3981 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3982 else
Ilia K686b1fe2015-02-27 19:43:08 +00003983 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00003984
3985 StringExtractorGDBRemote response;
3986
Greg Clayton3dedae12013-12-06 21:45:27 +00003987 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003988 {
3989 if (response.IsUnsupportedResponse())
3990 {
3991 // This packet isn't supported, don't try calling it again
3992 m_supports_QSaveRegisterState = eLazyBoolNo;
3993 }
3994
3995 const uint32_t response_save_id = response.GetU32(0);
3996 if (response_save_id != 0)
3997 {
3998 save_id = response_save_id;
3999 return true;
4000 }
4001 }
4002 }
4003 }
4004 return false;
4005}
4006
4007bool
4008GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4009{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004010 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00004011 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4012 // order to be useful
4013 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4014 return false;
4015
4016 Mutex::Locker locker;
4017 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4018 {
4019 const bool thread_suffix_supported = GetThreadSuffixSupported();
4020 if (thread_suffix_supported || SetCurrentThread(tid))
4021 {
4022 char packet[256];
4023 if (thread_suffix_supported)
4024 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4025 else
4026 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4027
4028 StringExtractorGDBRemote response;
4029
Greg Clayton3dedae12013-12-06 21:45:27 +00004030 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004031 {
4032 if (response.IsOKResponse())
4033 {
4034 return true;
4035 }
4036 else if (response.IsUnsupportedResponse())
4037 {
4038 // This packet isn't supported, don't try calling this packet or
4039 // QSaveRegisterState again...
4040 m_supports_QSaveRegisterState = eLazyBoolNo;
4041 }
4042 }
4043 }
4044 }
4045 return false;
4046}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004047
4048bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004049GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004050 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004051 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004052{
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00004053 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004054 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004055 return false;
4056
4057 StreamString packet;
4058 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004059 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004060 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00004061 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00004062 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004063
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004064 StringExtractorGDBRemote response;
4065 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4066 return false;
4067
Aidan Doddsdf627e72015-05-05 08:31:55 +00004068 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004069 return false;
4070
4071 std::string name;
4072 std::string value;
4073 bool success;
4074 StringExtractor extractor;
4075
4076 module_spec.Clear ();
4077 module_spec.GetFileSpec () = module_file_spec;
4078
4079 while (response.GetNameColonValue (name, value))
4080 {
4081 if (name == "uuid" || name == "md5")
4082 {
4083 extractor.GetStringRef ().swap (value);
4084 extractor.SetFilePos (0);
4085 extractor.GetHexByteString (value);
4086 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4087 }
4088 else if (name == "triple")
4089 {
4090 extractor.GetStringRef ().swap (value);
4091 extractor.SetFilePos (0);
4092 extractor.GetHexByteString (value);
4093 module_spec.GetArchitecture().SetTriple (value.c_str ());
4094 }
4095 else if (name == "file_offset")
4096 {
4097 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4098 if (success)
4099 module_spec.SetObjectOffset (ival);
4100 }
4101 else if (name == "file_size")
4102 {
4103 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4104 if (success)
4105 module_spec.SetObjectSize (ival);
4106 }
4107 else if (name == "file_path")
4108 {
4109 extractor.GetStringRef ().swap (value);
4110 extractor.SetFilePos (0);
4111 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00004112 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004113 }
4114 }
4115
4116 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004117}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004118
4119// query the target remote for extended information using the qXfer packet
4120//
4121// example: object='features', annex='target.xml', out=<xml output>
4122// return: 'true' on success
4123// 'false' on failure (err set)
4124bool
4125GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4126 const lldb_private::ConstString annex,
4127 std::string & out,
4128 lldb_private::Error & err) {
4129
4130 std::stringstream output;
4131 StringExtractorGDBRemote chunk;
4132
Greg Claytond04f0ed2015-05-26 18:00:51 +00004133 uint64_t size = GetRemoteMaxPacketSize();
4134 if (size == 0)
4135 size = 0x1000;
4136 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4137 int offset = 0;
4138 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004139
4140 // loop until all data has been read
4141 while ( active ) {
4142
4143 // send query extended feature packet
4144 std::stringstream packet;
4145 packet << "qXfer:"
4146 << object.AsCString( ) << ":read:"
4147 << annex.AsCString( ) << ":"
4148 << std::hex << offset << ","
4149 << std::hex << size;
4150
4151 GDBRemoteCommunication::PacketResult res =
4152 SendPacketAndWaitForResponse( packet.str().c_str(),
4153 chunk,
4154 false );
4155
4156 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4157 err.SetErrorString( "Error sending $qXfer packet" );
4158 return false;
4159 }
4160
4161 const std::string & str = chunk.GetStringRef( );
4162 if ( str.length() == 0 ) {
4163 // should have some data in chunk
4164 err.SetErrorString( "Empty response from $qXfer packet" );
4165 return false;
4166 }
4167
4168 // check packet code
4169 switch ( str[0] ) {
4170 // last chunk
4171 case ( 'l' ):
4172 active = false;
Aidan Doddsed9f6122015-04-29 10:08:17 +00004173 // fall through intentional
Colin Rileyc3c95b22015-04-16 15:51:33 +00004174
4175 // more chunks
4176 case ( 'm' ) :
4177 if ( str.length() > 1 )
4178 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00004179 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004180 break;
4181
4182 // unknown chunk
4183 default:
4184 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4185 return false;
4186 }
4187 }
4188
4189 out = output.str( );
4190 err.Success( );
4191 return true;
4192}