blob: e3183fca1db0c48d849632df8b63ef0bedcb9220 [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
14// C++ Includes
Han Ming Ong4b6459f2013-01-18 23:11:53 +000015#include <sstream>
16
Greg Clayton576d8832011-03-22 04:00:09 +000017// Other libraries and framework includes
18#include "llvm/ADT/Triple.h"
19#include "lldb/Interpreter/Args.h"
20#include "lldb/Core/ConnectionFileDescriptor.h"
21#include "lldb/Core/Log.h"
22#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000023#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000024#include "lldb/Core/StreamString.h"
25#include "lldb/Host/Endian.h"
26#include "lldb/Host/Host.h"
27#include "lldb/Host/TimeValue.h"
28
29// Project includes
30#include "Utility/StringExtractorGDBRemote.h"
31#include "ProcessGDBRemote.h"
32#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000033#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000034
35using namespace lldb;
36using namespace lldb_private;
37
Virgile Bellob2f1fb22013-08-23 12:44:05 +000038#ifdef LLDB_DISABLE_POSIX
39#define SIGSTOP 17
40#endif
41
Greg Clayton576d8832011-03-22 04:00:09 +000042//----------------------------------------------------------------------
43// GDBRemoteCommunicationClient constructor
44//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000045GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
46 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
Greg Clayton576d8832011-03-22 04:00:09 +000047 m_supports_not_sending_acks (eLazyBoolCalculate),
48 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000049 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000050 m_supports_vCont_all (eLazyBoolCalculate),
51 m_supports_vCont_any (eLazyBoolCalculate),
52 m_supports_vCont_c (eLazyBoolCalculate),
53 m_supports_vCont_C (eLazyBoolCalculate),
54 m_supports_vCont_s (eLazyBoolCalculate),
55 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000056 m_qHostInfo_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000057 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000058 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000059 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000060 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000061 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000062 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000063 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000064 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000065 m_supports_qProcessInfoPID (true),
66 m_supports_qfProcessInfo (true),
67 m_supports_qUserName (true),
68 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000069 m_supports_qThreadStopInfo (true),
70 m_supports_z0 (true),
71 m_supports_z1 (true),
72 m_supports_z2 (true),
73 m_supports_z3 (true),
74 m_supports_z4 (true),
75 m_curr_tid (LLDB_INVALID_THREAD_ID),
76 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +000077 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +000078 m_async_mutex (Mutex::eMutexTypeRecursive),
79 m_async_packet_predicate (false),
80 m_async_packet (),
81 m_async_response (),
82 m_async_signal (-1),
Han Ming Ong4b6459f2013-01-18 23:11:53 +000083 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +000084 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000085 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +000086 m_os_version_major (UINT32_MAX),
87 m_os_version_minor (UINT32_MAX),
88 m_os_version_update (UINT32_MAX)
Greg Clayton576d8832011-03-22 04:00:09 +000089{
Greg Clayton576d8832011-03-22 04:00:09 +000090}
91
92//----------------------------------------------------------------------
93// Destructor
94//----------------------------------------------------------------------
95GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
96{
Greg Clayton576d8832011-03-22 04:00:09 +000097 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +000098 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +000099}
100
101bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000102GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
103{
104 // Start the read thread after we send the handshake ack since if we
105 // fail to send the handshake ack, there is no reason to continue...
106 if (SendAck())
Greg Clayton73bf5db2011-06-17 01:22:15 +0000107 return true;
Greg Clayton1cb64962011-03-24 04:28:38 +0000108
109 if (error_ptr)
110 error_ptr->SetErrorString("failed to send the handshake ack");
111 return false;
112}
113
114void
115GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000116{
117 if (m_supports_not_sending_acks == eLazyBoolCalculate)
118 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000119 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000120 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000121
122 StringExtractorGDBRemote response;
Greg Clayton576d8832011-03-22 04:00:09 +0000123 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
124 {
125 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000126 {
127 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000128 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000129 }
Greg Clayton576d8832011-03-22 04:00:09 +0000130 }
131 }
Greg Clayton576d8832011-03-22 04:00:09 +0000132}
133
134void
Greg Clayton44633992012-04-10 03:22:03 +0000135GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
136{
137 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
138 {
139 m_supports_threads_in_stop_reply = eLazyBoolNo;
140
141 StringExtractorGDBRemote response;
142 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false))
143 {
144 if (response.IsOKResponse())
145 m_supports_threads_in_stop_reply = eLazyBoolYes;
146 }
147 }
148}
149
Jim Inghamcd16df92012-07-20 21:37:13 +0000150bool
151GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
152{
153 if (m_attach_or_wait_reply == eLazyBoolCalculate)
154 {
155 m_attach_or_wait_reply = eLazyBoolNo;
156
157 StringExtractorGDBRemote response;
158 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false))
159 {
160 if (response.IsOKResponse())
161 m_attach_or_wait_reply = eLazyBoolYes;
162 }
163 }
164 if (m_attach_or_wait_reply == eLazyBoolYes)
165 return true;
166 else
167 return false;
168}
169
Jim Ingham279ceec2012-07-25 21:12:43 +0000170bool
171GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
172{
173 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
174 {
175 m_prepare_for_reg_writing_reply = eLazyBoolNo;
176
177 StringExtractorGDBRemote response;
178 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false))
179 {
180 if (response.IsOKResponse())
181 m_prepare_for_reg_writing_reply = eLazyBoolYes;
182 }
183 }
184 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
185 return true;
186 else
187 return false;
188}
189
Greg Clayton44633992012-04-10 03:22:03 +0000190
191void
Greg Clayton576d8832011-03-22 04:00:09 +0000192GDBRemoteCommunicationClient::ResetDiscoverableSettings()
193{
194 m_supports_not_sending_acks = eLazyBoolCalculate;
195 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000196 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000197 m_supports_vCont_c = eLazyBoolCalculate;
198 m_supports_vCont_C = eLazyBoolCalculate;
199 m_supports_vCont_s = eLazyBoolCalculate;
200 m_supports_vCont_S = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000201 m_qHostInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000202 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000203 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000204 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000205 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
206 m_attach_or_wait_reply = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000207
Greg Clayton32e0a752011-03-30 18:16:51 +0000208 m_supports_qProcessInfoPID = true;
209 m_supports_qfProcessInfo = true;
210 m_supports_qUserName = true;
211 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000212 m_supports_qThreadStopInfo = true;
213 m_supports_z0 = true;
214 m_supports_z1 = true;
215 m_supports_z2 = true;
216 m_supports_z3 = true;
217 m_supports_z4 = true;
Greg Claytond314e812011-03-23 00:09:55 +0000218 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000219 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000220}
221
222
223bool
224GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
225{
226 if (m_supports_thread_suffix == eLazyBoolCalculate)
227 {
228 StringExtractorGDBRemote response;
229 m_supports_thread_suffix = eLazyBoolNo;
230 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
231 {
232 if (response.IsOKResponse())
233 m_supports_thread_suffix = eLazyBoolYes;
234 }
235 }
236 return m_supports_thread_suffix;
237}
238bool
239GDBRemoteCommunicationClient::GetVContSupported (char flavor)
240{
241 if (m_supports_vCont_c == eLazyBoolCalculate)
242 {
243 StringExtractorGDBRemote response;
244 m_supports_vCont_any = eLazyBoolNo;
245 m_supports_vCont_all = eLazyBoolNo;
246 m_supports_vCont_c = eLazyBoolNo;
247 m_supports_vCont_C = eLazyBoolNo;
248 m_supports_vCont_s = eLazyBoolNo;
249 m_supports_vCont_S = eLazyBoolNo;
250 if (SendPacketAndWaitForResponse("vCont?", response, false))
251 {
252 const char *response_cstr = response.GetStringRef().c_str();
253 if (::strstr (response_cstr, ";c"))
254 m_supports_vCont_c = eLazyBoolYes;
255
256 if (::strstr (response_cstr, ";C"))
257 m_supports_vCont_C = eLazyBoolYes;
258
259 if (::strstr (response_cstr, ";s"))
260 m_supports_vCont_s = eLazyBoolYes;
261
262 if (::strstr (response_cstr, ";S"))
263 m_supports_vCont_S = eLazyBoolYes;
264
265 if (m_supports_vCont_c == eLazyBoolYes &&
266 m_supports_vCont_C == eLazyBoolYes &&
267 m_supports_vCont_s == eLazyBoolYes &&
268 m_supports_vCont_S == eLazyBoolYes)
269 {
270 m_supports_vCont_all = eLazyBoolYes;
271 }
272
273 if (m_supports_vCont_c == eLazyBoolYes ||
274 m_supports_vCont_C == eLazyBoolYes ||
275 m_supports_vCont_s == eLazyBoolYes ||
276 m_supports_vCont_S == eLazyBoolYes)
277 {
278 m_supports_vCont_any = eLazyBoolYes;
279 }
280 }
281 }
282
283 switch (flavor)
284 {
285 case 'a': return m_supports_vCont_any;
286 case 'A': return m_supports_vCont_all;
287 case 'c': return m_supports_vCont_c;
288 case 'C': return m_supports_vCont_C;
289 case 's': return m_supports_vCont_s;
290 case 'S': return m_supports_vCont_S;
291 default: break;
292 }
293 return false;
294}
295
296
297size_t
298GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
299(
300 const char *payload,
301 StringExtractorGDBRemote &response,
302 bool send_async
303)
304{
305 return SendPacketAndWaitForResponse (payload,
306 ::strlen (payload),
307 response,
308 send_async);
309}
310
311size_t
312GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
313(
314 const char *payload,
315 size_t payload_length,
316 StringExtractorGDBRemote &response,
317 bool send_async
318)
319{
320 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000321 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton644247c2011-07-07 01:59:51 +0000322 size_t response_len = 0;
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000323 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000324 {
Greg Clayton5fe15d22011-05-20 03:15:54 +0000325 if (SendPacketNoLock (payload, payload_length))
Greg Clayton644247c2011-07-07 01:59:51 +0000326 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
327 else
328 {
329 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000330 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000331 }
Greg Clayton576d8832011-03-22 04:00:09 +0000332 }
333 else
334 {
335 if (send_async)
336 {
Greg Claytond3544052012-05-31 21:24:20 +0000337 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000338 {
Greg Claytond3544052012-05-31 21:24:20 +0000339 Mutex::Locker async_locker (m_async_mutex);
340 m_async_packet.assign(payload, payload_length);
341 m_async_packet_predicate.SetValue (true, eBroadcastNever);
342
343 if (log)
344 log->Printf ("async: async packet = %s", m_async_packet.c_str());
345
346 bool timed_out = false;
347 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000348 {
Greg Claytond3544052012-05-31 21:24:20 +0000349 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000350 {
Jim Inghambabfc382012-06-06 00:32:39 +0000351 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000352 TimeValue timeout_time;
353 timeout_time = TimeValue::Now();
354 timeout_time.OffsetWithSeconds (m_packet_timeout);
355
Greg Clayton576d8832011-03-22 04:00:09 +0000356 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000357 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000358
Greg Claytond3544052012-05-31 21:24:20 +0000359 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000360 {
Greg Claytond3544052012-05-31 21:24:20 +0000361 if (log)
362 log->Printf ("async: got response");
363
364 // Swap the response buffer to avoid malloc and string copy
365 response.GetStringRef().swap (m_async_response.GetStringRef());
366 response_len = response.GetStringRef().size();
367 }
368 else
369 {
370 if (log)
371 log->Printf ("async: timed out waiting for response");
372 }
373
374 // Make sure we wait until the continue packet has been sent again...
375 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
376 {
377 if (log)
378 {
379 if (timed_out)
380 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
381 else
382 log->Printf ("async: async packet sent");
383 }
384 }
385 else
386 {
387 if (log)
388 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000389 }
390 }
391 else
392 {
Greg Claytond3544052012-05-31 21:24:20 +0000393 // We had a racy condition where we went to send the interrupt
394 // yet we were able to get the lock, so the process must have
395 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000396 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000397 log->Printf ("async: got lock without sending interrupt");
398 // Send the packet normally since we got the lock
399 if (SendPacketNoLock (payload, payload_length))
400 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
401 else
402 {
403 if (log)
404 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
405 }
Greg Clayton576d8832011-03-22 04:00:09 +0000406 }
407 }
408 else
409 {
Greg Clayton644247c2011-07-07 01:59:51 +0000410 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000411 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000412 }
413 }
414 else
415 {
416 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000417 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000418 }
419 }
420 else
421 {
422 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000423 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000424 }
425 }
Greg Clayton644247c2011-07-07 01:59:51 +0000426 if (response_len == 0)
427 {
428 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000429 log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000430 }
431 return response_len;
Greg Clayton576d8832011-03-22 04:00:09 +0000432}
433
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000434static const char *end_delimiter = "--end--;";
435static const int end_delimiter_len = 8;
436
437std::string
438GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
439( ProcessGDBRemote *process,
440 StringExtractorGDBRemote& profileDataExtractor
441)
442{
443 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
444 std::stringstream final_output;
445 std::string name, value;
446
447 // Going to assuming thread_used_usec comes first, else bail out.
448 while (profileDataExtractor.GetNameColonValue(name, value))
449 {
450 if (name.compare("thread_used_id") == 0)
451 {
452 StringExtractor threadIDHexExtractor(value.c_str());
453 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
454
455 bool has_used_usec = false;
456 uint32_t curr_used_usec = 0;
457 std::string usec_name, usec_value;
458 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
459 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
460 {
461 if (usec_name.compare("thread_used_usec") == 0)
462 {
463 has_used_usec = true;
464 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
465 }
466 else
467 {
468 // We didn't find what we want, it is probably
469 // an older version. Bail out.
470 profileDataExtractor.SetFilePos(input_file_pos);
471 }
472 }
473
474 if (has_used_usec)
475 {
476 uint32_t prev_used_usec = 0;
477 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
478 if (iterator != m_thread_id_to_used_usec_map.end())
479 {
480 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
481 }
482
483 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
484 // A good first time record is one that runs for at least 0.25 sec
485 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
486 bool good_subsequent_time = (prev_used_usec > 0) &&
487 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
488
489 if (good_first_time || good_subsequent_time)
490 {
491 // We try to avoid doing too many index id reservation,
492 // resulting in fast increase of index ids.
493
494 final_output << name << ":";
495 int32_t index_id = process->AssignIndexIDToThread(thread_id);
496 final_output << index_id << ";";
497
498 final_output << usec_name << ":" << usec_value << ";";
499 }
500 else
501 {
502 // Skip past 'thread_used_name'.
503 std::string local_name, local_value;
504 profileDataExtractor.GetNameColonValue(local_name, local_value);
505 }
506
507 // Store current time as previous time so that they can be compared later.
508 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
509 }
510 else
511 {
512 // Bail out and use old string.
513 final_output << name << ":" << value << ";";
514 }
515 }
516 else
517 {
518 final_output << name << ":" << value << ";";
519 }
520 }
521 final_output << end_delimiter;
522 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
523
524 return final_output.str();
525}
526
Greg Clayton576d8832011-03-22 04:00:09 +0000527StateType
528GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
529(
530 ProcessGDBRemote *process,
531 const char *payload,
532 size_t packet_length,
533 StringExtractorGDBRemote &response
534)
535{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000536 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000537 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000538 if (log)
539 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
540
541 Mutex::Locker locker(m_sequence_mutex);
542 StateType state = eStateRunning;
543
544 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
545 m_public_is_running.SetValue (true, eBroadcastNever);
546 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000547 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000548 std::string continue_packet(payload, packet_length);
549
Greg Clayton3f875c52013-02-22 22:23:55 +0000550 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000551
Greg Clayton576d8832011-03-22 04:00:09 +0000552 while (state == eStateRunning)
553 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000554 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000555 {
556 if (log)
557 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +0000558 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) == 0)
Greg Claytonaf247d72011-05-19 03:54:16 +0000559 state = eStateInvalid;
Greg Clayton576d8832011-03-22 04:00:09 +0000560
Greg Claytone889ad62011-10-27 22:04:16 +0000561 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000562 }
563
Greg Clayton3f875c52013-02-22 22:23:55 +0000564 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000565
566 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000567 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000568
Greg Clayton37a0a242012-04-11 00:24:49 +0000569 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX))
Greg Clayton576d8832011-03-22 04:00:09 +0000570 {
571 if (response.Empty())
572 state = eStateInvalid;
573 else
574 {
575 const char stop_type = response.GetChar();
576 if (log)
577 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
578 switch (stop_type)
579 {
580 case 'T':
581 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000582 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000583 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000584 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000585 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
586 {
587 lldb::pid_t pid = GetCurrentProcessID ();
588 if (pid != LLDB_INVALID_PROCESS_ID)
589 process->SetID (pid);
590 }
591 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000592 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000593
594 // Privately notify any internal threads that we have stopped
595 // in case we wanted to interrupt our process, yet we might
596 // send a packet and continue without returning control to the
597 // user.
598 m_private_is_running.SetValue (false, eBroadcastAlways);
599
600 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
601
Jim Inghambabfc382012-06-06 00:32:39 +0000602 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
603 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000604 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000605 // We sent an interrupt packet to stop the inferior process
606 // for an async signal or to send an async packet while running
607 // but we might have been single stepping and received the
608 // stop packet for the step instead of for the interrupt packet.
609 // Typically when an interrupt is sent a SIGINT or SIGSTOP
610 // is used, so if we get anything else, we need to try and
611 // get another stop reply packet that may have been sent
612 // due to sending the interrupt when the target is stopped
613 // which will just re-send a copy of the last stop reply
614 // packet. If we don't do this, then the reply for our
615 // async packet will be the repeat stop reply packet and cause
616 // a lot of trouble for us!
617 if (signo != SIGINT && signo != SIGSTOP)
618 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000619 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000620
621 // We didn't get a a SIGINT or SIGSTOP, so try for a
622 // very brief time (1 ms) to get another stop reply
623 // packet to make sure it doesn't get in the way
624 StringExtractorGDBRemote extra_stop_reply_packet;
625 uint32_t timeout_usec = 1000;
626 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec))
627 {
628 switch (extra_stop_reply_packet.GetChar())
629 {
630 case 'T':
631 case 'S':
632 // We did get an extra stop reply, which means
633 // our interrupt didn't stop the target so we
634 // shouldn't continue after the async signal
635 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000636 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000637 break;
638 }
639 }
640 }
641 }
642
643 if (m_async_signal != -1)
644 {
645 if (log)
646 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
647
648 // Save off the async signal we are supposed to send
649 const int async_signal = m_async_signal;
650 // Clear the async signal member so we don't end up
651 // sending the signal multiple times...
652 m_async_signal = -1;
653 // Check which signal we stopped with
654 if (signo == async_signal)
655 {
656 if (log)
657 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
658
659 // We already stopped with a signal that we wanted
660 // to stop with, so we are done
661 }
662 else
663 {
664 // We stopped with a different signal that the one
665 // we wanted to stop with, so now we must resume
666 // with the signal we want
667 char signal_packet[32];
668 int signal_packet_len = 0;
669 signal_packet_len = ::snprintf (signal_packet,
670 sizeof (signal_packet),
671 "C%2.2x",
672 async_signal);
673
674 if (log)
675 log->Printf ("async: stopped with signal %s, resume with %s",
676 Host::GetSignalAsCString (signo),
677 Host::GetSignalAsCString (async_signal));
678
679 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +0000680 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000681 continue_packet.assign(signal_packet, signal_packet_len);
682 continue;
683 }
684 }
685 else if (m_async_packet_predicate.GetValue())
686 {
Greg Clayton5160ce52013-03-27 23:08:40 +0000687 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +0000688
689 // We are supposed to send an asynchronous packet while
690 // we are running.
691 m_async_response.Clear();
692 if (m_async_packet.empty())
693 {
694 if (packet_log)
695 packet_log->Printf ("async: error: empty async packet");
696
697 }
698 else
699 {
700 if (packet_log)
701 packet_log->Printf ("async: sending packet");
702
703 SendPacketAndWaitForResponse (&m_async_packet[0],
704 m_async_packet.size(),
705 m_async_response,
706 false);
707 }
708 // Let the other thread that was trying to send the async
709 // packet know that the packet has been sent and response is
710 // ready...
711 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
712
713 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +0000714 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +0000715
716 // Set the continue packet to resume if our interrupt
717 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +0000718 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000719 {
Greg Claytonf1186de2012-05-24 23:42:14 +0000720 // Reverting this for now as it is causing deadlocks
721 // in programs (<rdar://problem/11529853>). In the future
722 // we should check our thread list and "do the right thing"
723 // for new threads that show up while we stop and run async
724 // packets. Setting the packet to 'c' to continue all threads
725 // is the right thing to do 99.99% of the time because if a
726 // thread was single stepping, and we sent an interrupt, we
727 // will notice above that we didn't stop due to an interrupt
728 // but stopped due to stepping and we would _not_ continue.
729 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +0000730 continue;
731 }
732 }
733 // Stop with signal and thread info
734 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +0000735 }
Greg Clayton576d8832011-03-22 04:00:09 +0000736 break;
737
738 case 'W':
739 case 'X':
740 // process exited
741 state = eStateExited;
742 break;
743
744 case 'O':
745 // STDOUT
746 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000747 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000748 std::string inferior_stdout;
749 inferior_stdout.reserve(response.GetBytesLeft () / 2);
750 char ch;
751 while ((ch = response.GetHexU8()) != '\0')
752 inferior_stdout.append(1, ch);
753 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
754 }
755 break;
756
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000757 case 'A':
758 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
759 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000760 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000761 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
762 if (m_partial_profile_data.length() > 0)
763 {
764 m_partial_profile_data.append(input);
765 input = m_partial_profile_data;
766 m_partial_profile_data.clear();
767 }
768
769 size_t found, pos = 0, len = input.length();
770 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
771 {
772 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +0000773 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
774 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000775
776 pos = found + end_delimiter_len;
777 }
778
779 if (pos < len)
780 {
781 // Last incomplete chunk.
782 m_partial_profile_data = input.substr(pos);
783 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000784 }
785 break;
786
Greg Clayton576d8832011-03-22 04:00:09 +0000787 case 'E':
788 // ERROR
789 state = eStateInvalid;
790 break;
791
792 default:
793 if (log)
794 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
795 state = eStateInvalid;
796 break;
797 }
798 }
799 }
800 else
801 {
802 if (log)
803 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
804 state = eStateInvalid;
805 }
806 }
807 if (log)
808 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
809 response.SetFilePos(0);
810 m_private_is_running.SetValue (false, eBroadcastAlways);
811 m_public_is_running.SetValue (false, eBroadcastAlways);
812 return state;
813}
814
815bool
816GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
817{
Greg Clayton2687cd12012-03-29 01:55:41 +0000818 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +0000819 m_async_signal = signo;
820 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000821 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +0000822 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000823 return true;
824 m_async_signal = -1;
825 return false;
826}
827
Greg Clayton37a0a242012-04-11 00:24:49 +0000828// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +0000829// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
830// (the expected result), then it will send the halt packet. If it does succeed
831// then the caller that requested the interrupt will want to keep the sequence
832// locked down so that no one else can send packets while the caller has control.
833// This function usually gets called when we are running and need to stop the
834// target. It can also be used when we are running and and we need to do something
835// else (like read/write memory), so we need to interrupt the running process
836// (gdb remote protocol requires this), and do what we need to do, then resume.
837
838bool
Greg Clayton2687cd12012-03-29 01:55:41 +0000839GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +0000840(
841 Mutex::Locker& locker,
842 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +0000843 bool &timed_out
844)
845{
Greg Clayton576d8832011-03-22 04:00:09 +0000846 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +0000847 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +0000848
849 if (IsRunning())
850 {
851 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000852 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +0000853 {
854 if (log)
855 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
856 }
857 else
Greg Clayton576d8832011-03-22 04:00:09 +0000858 {
859 // Someone has the mutex locked waiting for a response or for the
860 // inferior to stop, so send the interrupt on the down low...
861 char ctrl_c = '\x03';
862 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +0000863 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +0000864 if (log)
865 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +0000866 if (bytes_written > 0)
867 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000868 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000869 if (seconds_to_wait_for_stop)
870 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000871 TimeValue timeout;
872 if (seconds_to_wait_for_stop)
873 {
874 timeout = TimeValue::Now();
875 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
876 }
Greg Clayton576d8832011-03-22 04:00:09 +0000877 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
878 {
879 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000880 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +0000881 return true;
882 }
883 else
884 {
885 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000886 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +0000887 }
888 }
889 else
890 {
891 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000892 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +0000893 return true;
894 }
895 }
896 else
897 {
898 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000899 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000900 }
901 return false;
902 }
Greg Clayton576d8832011-03-22 04:00:09 +0000903 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000904 else
905 {
906 if (log)
907 log->Printf ("SendInterrupt () - not running");
908 }
Greg Clayton576d8832011-03-22 04:00:09 +0000909 return true;
910}
911
912lldb::pid_t
913GDBRemoteCommunicationClient::GetCurrentProcessID ()
914{
915 StringExtractorGDBRemote response;
916 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
917 {
918 if (response.GetChar() == 'Q')
919 if (response.GetChar() == 'C')
920 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
921 }
922 return LLDB_INVALID_PROCESS_ID;
923}
924
925bool
926GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
927{
928 error_str.clear();
929 StringExtractorGDBRemote response;
930 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
931 {
932 if (response.IsOKResponse())
933 return true;
934 if (response.GetChar() == 'E')
935 {
936 // A string the describes what failed when launching...
937 error_str = response.GetStringRef().substr(1);
938 }
939 else
940 {
941 error_str.assign ("unknown error occurred launching process");
942 }
943 }
944 else
945 {
Jim Ingham98d6da52012-06-28 20:30:23 +0000946 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +0000947 }
948 return false;
949}
950
951int
952GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[])
953{
954 if (argv && argv[0])
955 {
956 StreamString packet;
957 packet.PutChar('A');
958 const char *arg;
959 for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
960 {
961 const int arg_len = strlen(arg);
962 if (i > 0)
963 packet.PutChar(',');
964 packet.Printf("%i,%i,", arg_len * 2, i);
965 packet.PutBytesAsRawHex8 (arg, arg_len);
966 }
967
968 StringExtractorGDBRemote response;
969 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
970 {
971 if (response.IsOKResponse())
972 return 0;
973 uint8_t error = response.GetError();
974 if (error)
975 return error;
976 }
977 }
978 return -1;
979}
980
981int
982GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
983{
984 if (name_equal_value && name_equal_value[0])
985 {
986 StreamString packet;
987 packet.Printf("QEnvironment:%s", name_equal_value);
988 StringExtractorGDBRemote response;
989 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
990 {
991 if (response.IsOKResponse())
992 return 0;
993 uint8_t error = response.GetError();
994 if (error)
995 return error;
996 }
997 }
998 return -1;
999}
1000
Greg Claytonc4103b32011-05-08 04:53:50 +00001001int
1002GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1003{
1004 if (arch && arch[0])
1005 {
1006 StreamString packet;
1007 packet.Printf("QLaunchArch:%s", arch);
1008 StringExtractorGDBRemote response;
1009 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1010 {
1011 if (response.IsOKResponse())
1012 return 0;
1013 uint8_t error = response.GetError();
1014 if (error)
1015 return error;
1016 }
1017 }
1018 return -1;
1019}
1020
Greg Clayton576d8832011-03-22 04:00:09 +00001021bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001022GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1023 uint32_t &minor,
1024 uint32_t &update)
1025{
1026 if (GetHostInfo ())
1027 {
1028 if (m_os_version_major != UINT32_MAX)
1029 {
1030 major = m_os_version_major;
1031 minor = m_os_version_minor;
1032 update = m_os_version_update;
1033 return true;
1034 }
1035 }
1036 return false;
1037}
1038
1039bool
1040GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1041{
1042 if (GetHostInfo ())
1043 {
1044 if (!m_os_build.empty())
1045 {
1046 s = m_os_build;
1047 return true;
1048 }
1049 }
1050 s.clear();
1051 return false;
1052}
1053
1054
1055bool
1056GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1057{
1058 if (GetHostInfo ())
1059 {
1060 if (!m_os_kernel.empty())
1061 {
1062 s = m_os_kernel;
1063 return true;
1064 }
1065 }
1066 s.clear();
1067 return false;
1068}
1069
1070bool
1071GDBRemoteCommunicationClient::GetHostname (std::string &s)
1072{
1073 if (GetHostInfo ())
1074 {
1075 if (!m_hostname.empty())
1076 {
1077 s = m_hostname;
1078 return true;
1079 }
1080 }
1081 s.clear();
1082 return false;
1083}
1084
1085ArchSpec
1086GDBRemoteCommunicationClient::GetSystemArchitecture ()
1087{
1088 if (GetHostInfo ())
1089 return m_host_arch;
1090 return ArchSpec();
1091}
1092
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001093const lldb_private::ArchSpec &
1094GDBRemoteCommunicationClient::GetProcessArchitecture ()
1095{
1096 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1097 GetCurrentProcessInfo ();
1098 return m_process_arch;
1099}
1100
Greg Clayton1cb64962011-03-24 04:28:38 +00001101
1102bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001103GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001104{
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001105 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001106 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001107 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001108 StringExtractorGDBRemote response;
1109 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
1110 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001111 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001112 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001113 std::string name;
1114 std::string value;
1115 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1116 uint32_t sub = 0;
1117 std::string arch_name;
1118 std::string os_name;
1119 std::string vendor_name;
1120 std::string triple;
1121 uint32_t pointer_byte_size = 0;
1122 StringExtractor extractor;
1123 ByteOrder byte_order = eByteOrderInvalid;
1124 uint32_t num_keys_decoded = 0;
1125 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001126 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001127 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001128 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001129 // exception type in big endian hex
1130 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1131 if (cpu != LLDB_INVALID_CPUTYPE)
1132 ++num_keys_decoded;
1133 }
1134 else if (name.compare("cpusubtype") == 0)
1135 {
1136 // exception count in big endian hex
1137 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1138 if (sub != 0)
1139 ++num_keys_decoded;
1140 }
1141 else if (name.compare("arch") == 0)
1142 {
1143 arch_name.swap (value);
1144 ++num_keys_decoded;
1145 }
1146 else if (name.compare("triple") == 0)
1147 {
1148 // The triple comes as ASCII hex bytes since it contains '-' chars
1149 extractor.GetStringRef().swap(value);
1150 extractor.SetFilePos(0);
1151 extractor.GetHexByteString (triple);
1152 ++num_keys_decoded;
1153 }
1154 else if (name.compare("os_build") == 0)
1155 {
1156 extractor.GetStringRef().swap(value);
1157 extractor.SetFilePos(0);
1158 extractor.GetHexByteString (m_os_build);
1159 ++num_keys_decoded;
1160 }
1161 else if (name.compare("hostname") == 0)
1162 {
1163 extractor.GetStringRef().swap(value);
1164 extractor.SetFilePos(0);
1165 extractor.GetHexByteString (m_hostname);
1166 ++num_keys_decoded;
1167 }
1168 else if (name.compare("os_kernel") == 0)
1169 {
1170 extractor.GetStringRef().swap(value);
1171 extractor.SetFilePos(0);
1172 extractor.GetHexByteString (m_os_kernel);
1173 ++num_keys_decoded;
1174 }
1175 else if (name.compare("ostype") == 0)
1176 {
1177 os_name.swap (value);
1178 ++num_keys_decoded;
1179 }
1180 else if (name.compare("vendor") == 0)
1181 {
1182 vendor_name.swap(value);
1183 ++num_keys_decoded;
1184 }
1185 else if (name.compare("endian") == 0)
1186 {
1187 ++num_keys_decoded;
1188 if (value.compare("little") == 0)
1189 byte_order = eByteOrderLittle;
1190 else if (value.compare("big") == 0)
1191 byte_order = eByteOrderBig;
1192 else if (value.compare("pdp") == 0)
1193 byte_order = eByteOrderPDP;
1194 else
1195 --num_keys_decoded;
1196 }
1197 else if (name.compare("ptrsize") == 0)
1198 {
1199 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1200 if (pointer_byte_size != 0)
1201 ++num_keys_decoded;
1202 }
1203 else if (name.compare("os_version") == 0)
1204 {
1205 Args::StringToVersion (value.c_str(),
1206 m_os_version_major,
1207 m_os_version_minor,
1208 m_os_version_update);
1209 if (m_os_version_major != UINT32_MAX)
1210 ++num_keys_decoded;
1211 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001212 else if (name.compare("watchpoint_exceptions_received") == 0)
1213 {
1214 ++num_keys_decoded;
1215 if (strcmp(value.c_str(),"before") == 0)
1216 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1217 else if (strcmp(value.c_str(),"after") == 0)
1218 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1219 else
1220 --num_keys_decoded;
1221 }
1222
Greg Clayton32e0a752011-03-30 18:16:51 +00001223 }
1224
1225 if (num_keys_decoded > 0)
1226 m_qHostInfo_is_valid = eLazyBoolYes;
1227
1228 if (triple.empty())
1229 {
1230 if (arch_name.empty())
1231 {
1232 if (cpu != LLDB_INVALID_CPUTYPE)
1233 {
1234 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1235 if (pointer_byte_size)
1236 {
1237 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1238 }
1239 if (byte_order != eByteOrderInvalid)
1240 {
1241 assert (byte_order == m_host_arch.GetByteOrder());
1242 }
Greg Clayton70512312012-05-08 01:45:38 +00001243
1244 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1245 {
1246 switch (m_host_arch.GetMachine())
1247 {
1248 case llvm::Triple::arm:
1249 case llvm::Triple::thumb:
1250 os_name = "ios";
1251 break;
1252 default:
1253 os_name = "macosx";
1254 break;
1255 }
1256 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001257 if (!vendor_name.empty())
1258 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1259 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001260 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001261
1262 }
1263 }
1264 else
1265 {
1266 std::string triple;
1267 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001268 if (!vendor_name.empty() || !os_name.empty())
1269 {
1270 triple += '-';
1271 if (vendor_name.empty())
1272 triple += "unknown";
1273 else
1274 triple += vendor_name;
1275 triple += '-';
1276 if (os_name.empty())
1277 triple += "unknown";
1278 else
1279 triple += os_name;
1280 }
1281 m_host_arch.SetTriple (triple.c_str());
1282
1283 llvm::Triple &host_triple = m_host_arch.GetTriple();
1284 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1285 {
1286 switch (m_host_arch.GetMachine())
1287 {
1288 case llvm::Triple::arm:
1289 case llvm::Triple::thumb:
1290 host_triple.setOS(llvm::Triple::IOS);
1291 break;
1292 default:
1293 host_triple.setOS(llvm::Triple::MacOSX);
1294 break;
1295 }
1296 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001297 if (pointer_byte_size)
1298 {
1299 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1300 }
1301 if (byte_order != eByteOrderInvalid)
1302 {
1303 assert (byte_order == m_host_arch.GetByteOrder());
1304 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001305
Greg Clayton1cb64962011-03-24 04:28:38 +00001306 }
1307 }
1308 else
1309 {
Greg Clayton70512312012-05-08 01:45:38 +00001310 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001311 if (pointer_byte_size)
1312 {
1313 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1314 }
1315 if (byte_order != eByteOrderInvalid)
1316 {
1317 assert (byte_order == m_host_arch.GetByteOrder());
1318 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001319 }
Greg Claytond314e812011-03-23 00:09:55 +00001320 }
Greg Clayton576d8832011-03-22 04:00:09 +00001321 }
1322 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001323 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001324}
1325
1326int
1327GDBRemoteCommunicationClient::SendAttach
1328(
1329 lldb::pid_t pid,
1330 StringExtractorGDBRemote& response
1331)
1332{
1333 if (pid != LLDB_INVALID_PROCESS_ID)
1334 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001335 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001336 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001337 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001338 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001339 {
1340 if (response.IsErrorResponse())
1341 return response.GetError();
1342 return 0;
1343 }
1344 }
1345 return -1;
1346}
1347
1348const lldb_private::ArchSpec &
1349GDBRemoteCommunicationClient::GetHostArchitecture ()
1350{
Greg Clayton32e0a752011-03-30 18:16:51 +00001351 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001352 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001353 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001354}
1355
1356addr_t
1357GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1358{
Greg Clayton70b57652011-05-15 01:25:55 +00001359 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001360 {
Greg Clayton70b57652011-05-15 01:25:55 +00001361 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001362 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001363 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001364 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001365 permissions & lldb::ePermissionsReadable ? "r" : "",
1366 permissions & lldb::ePermissionsWritable ? "w" : "",
1367 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001368 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001369 StringExtractorGDBRemote response;
1370 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1371 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001372 if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001373 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1374 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001375 else
1376 {
1377 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1378 }
Greg Clayton576d8832011-03-22 04:00:09 +00001379 }
1380 return LLDB_INVALID_ADDRESS;
1381}
1382
1383bool
1384GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1385{
Greg Clayton70b57652011-05-15 01:25:55 +00001386 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001387 {
Greg Clayton70b57652011-05-15 01:25:55 +00001388 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001389 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001390 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001391 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001392 StringExtractorGDBRemote response;
1393 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1394 {
1395 if (response.IsOKResponse())
1396 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001397 }
1398 else
1399 {
1400 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001401 }
Greg Clayton576d8832011-03-22 04:00:09 +00001402 }
1403 return false;
1404}
1405
Jim Inghamacff8952013-05-02 00:27:30 +00001406Error
1407GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001408{
Jim Inghamacff8952013-05-02 00:27:30 +00001409 Error error;
1410
1411 if (keep_stopped)
1412 {
1413 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1414 {
1415 char packet[64];
1416 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001417 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001418 StringExtractorGDBRemote response;
1419 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1420 {
1421 m_supports_detach_stay_stopped = eLazyBoolYes;
1422 }
1423 else
1424 {
1425 m_supports_detach_stay_stopped = eLazyBoolNo;
1426 }
1427 }
1428
1429 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1430 {
1431 error.SetErrorString("Stays stopped not supported by this target.");
1432 return error;
1433 }
1434 else
1435 {
1436 size_t num_sent = SendPacket ("D1", 2);
1437 if (num_sent == 0)
1438 error.SetErrorString ("Sending extended disconnect packet failed.");
1439 }
1440 }
1441 else
1442 {
1443 size_t num_sent = SendPacket ("D", 1);
1444 if (num_sent == 0)
1445 error.SetErrorString ("Sending disconnect packet failed.");
1446 }
1447 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001448}
1449
Greg Clayton46fb5582011-11-18 07:03:08 +00001450Error
1451GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1452 lldb_private::MemoryRegionInfo &region_info)
1453{
1454 Error error;
1455 region_info.Clear();
1456
1457 if (m_supports_memory_region_info != eLazyBoolNo)
1458 {
1459 m_supports_memory_region_info = eLazyBoolYes;
1460 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001461 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001462 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001463 StringExtractorGDBRemote response;
1464 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1465 {
1466 std::string name;
1467 std::string value;
1468 addr_t addr_value;
1469 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001470 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001471 while (success && response.GetNameColonValue(name, value))
1472 {
1473 if (name.compare ("start") == 0)
1474 {
1475 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1476 if (success)
1477 region_info.GetRange().SetRangeBase(addr_value);
1478 }
1479 else if (name.compare ("size") == 0)
1480 {
1481 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1482 if (success)
1483 region_info.GetRange().SetByteSize (addr_value);
1484 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001485 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001486 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001487 saw_permissions = true;
1488 if (region_info.GetRange().Contains (addr))
1489 {
1490 if (value.find('r') != std::string::npos)
1491 region_info.SetReadable (MemoryRegionInfo::eYes);
1492 else
1493 region_info.SetReadable (MemoryRegionInfo::eNo);
1494
1495 if (value.find('w') != std::string::npos)
1496 region_info.SetWritable (MemoryRegionInfo::eYes);
1497 else
1498 region_info.SetWritable (MemoryRegionInfo::eNo);
1499
1500 if (value.find('x') != std::string::npos)
1501 region_info.SetExecutable (MemoryRegionInfo::eYes);
1502 else
1503 region_info.SetExecutable (MemoryRegionInfo::eNo);
1504 }
1505 else
1506 {
1507 // The reported region does not contain this address -- we're looking at an unmapped page
1508 region_info.SetReadable (MemoryRegionInfo::eNo);
1509 region_info.SetWritable (MemoryRegionInfo::eNo);
1510 region_info.SetExecutable (MemoryRegionInfo::eNo);
1511 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001512 }
1513 else if (name.compare ("error") == 0)
1514 {
1515 StringExtractorGDBRemote name_extractor;
1516 // Swap "value" over into "name_extractor"
1517 name_extractor.GetStringRef().swap(value);
1518 // Now convert the HEX bytes into a string value
1519 name_extractor.GetHexByteString (value);
1520 error.SetErrorString(value.c_str());
1521 }
1522 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001523
1524 // We got a valid address range back but no permissions -- which means this is an unmapped page
1525 if (region_info.GetRange().IsValid() && saw_permissions == false)
1526 {
1527 region_info.SetReadable (MemoryRegionInfo::eNo);
1528 region_info.SetWritable (MemoryRegionInfo::eNo);
1529 region_info.SetExecutable (MemoryRegionInfo::eNo);
1530 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001531 }
1532 else
1533 {
1534 m_supports_memory_region_info = eLazyBoolNo;
1535 }
1536 }
1537
1538 if (m_supports_memory_region_info == eLazyBoolNo)
1539 {
1540 error.SetErrorString("qMemoryRegionInfo is not supported");
1541 }
1542 if (error.Fail())
1543 region_info.Clear();
1544 return error;
1545
1546}
1547
Johnny Chen64637202012-05-23 21:09:52 +00001548Error
1549GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1550{
1551 Error error;
1552
1553 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1554 {
1555 num = m_num_supported_hardware_watchpoints;
1556 return error;
1557 }
1558
1559 // Set num to 0 first.
1560 num = 0;
1561 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1562 {
1563 char packet[64];
1564 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001565 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00001566 StringExtractorGDBRemote response;
1567 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1568 {
1569 m_supports_watchpoint_support_info = eLazyBoolYes;
1570 std::string name;
1571 std::string value;
1572 while (response.GetNameColonValue(name, value))
1573 {
1574 if (name.compare ("num") == 0)
1575 {
1576 num = Args::StringToUInt32(value.c_str(), 0, 0);
1577 m_num_supported_hardware_watchpoints = num;
1578 }
1579 }
1580 }
1581 else
1582 {
1583 m_supports_watchpoint_support_info = eLazyBoolNo;
1584 }
1585 }
1586
1587 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1588 {
1589 error.SetErrorString("qWatchpointSupportInfo is not supported");
1590 }
1591 return error;
1592
1593}
Greg Clayton46fb5582011-11-18 07:03:08 +00001594
Enrico Granataf04a2192012-07-13 23:18:48 +00001595lldb_private::Error
1596GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1597{
1598 Error error(GetWatchpointSupportInfo(num));
1599 if (error.Success())
1600 error = GetWatchpointsTriggerAfterInstruction(after);
1601 return error;
1602}
1603
1604lldb_private::Error
1605GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1606{
1607 Error error;
1608
1609 // we assume watchpoints will happen after running the relevant opcode
1610 // and we only want to override this behavior if we have explicitly
1611 // received a qHostInfo telling us otherwise
1612 if (m_qHostInfo_is_valid != eLazyBoolYes)
1613 after = true;
1614 else
1615 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1616 return error;
1617}
1618
Greg Clayton576d8832011-03-22 04:00:09 +00001619int
1620GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1621{
1622 if (path && path[0])
1623 {
1624 StreamString packet;
1625 packet.PutCString("QSetSTDIN:");
1626 packet.PutBytesAsRawHex8(path, strlen(path));
1627
1628 StringExtractorGDBRemote response;
1629 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1630 {
1631 if (response.IsOKResponse())
1632 return 0;
1633 uint8_t error = response.GetError();
1634 if (error)
1635 return error;
1636 }
1637 }
1638 return -1;
1639}
1640
1641int
1642GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1643{
1644 if (path && path[0])
1645 {
1646 StreamString packet;
1647 packet.PutCString("QSetSTDOUT:");
1648 packet.PutBytesAsRawHex8(path, strlen(path));
1649
1650 StringExtractorGDBRemote response;
1651 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1652 {
1653 if (response.IsOKResponse())
1654 return 0;
1655 uint8_t error = response.GetError();
1656 if (error)
1657 return error;
1658 }
1659 }
1660 return -1;
1661}
1662
1663int
1664GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1665{
1666 if (path && path[0])
1667 {
1668 StreamString packet;
1669 packet.PutCString("QSetSTDERR:");
1670 packet.PutBytesAsRawHex8(path, strlen(path));
1671
1672 StringExtractorGDBRemote response;
1673 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1674 {
1675 if (response.IsOKResponse())
1676 return 0;
1677 uint8_t error = response.GetError();
1678 if (error)
1679 return error;
1680 }
1681 }
1682 return -1;
1683}
1684
1685int
1686GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1687{
1688 if (path && path[0])
1689 {
1690 StreamString packet;
1691 packet.PutCString("QSetWorkingDir:");
1692 packet.PutBytesAsRawHex8(path, strlen(path));
1693
1694 StringExtractorGDBRemote response;
1695 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1696 {
1697 if (response.IsOKResponse())
1698 return 0;
1699 uint8_t error = response.GetError();
1700 if (error)
1701 return error;
1702 }
1703 }
1704 return -1;
1705}
1706
1707int
1708GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1709{
Greg Clayton32e0a752011-03-30 18:16:51 +00001710 char packet[32];
1711 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00001712 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00001713 StringExtractorGDBRemote response;
Greg Clayton32e0a752011-03-30 18:16:51 +00001714 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001715 {
1716 if (response.IsOKResponse())
1717 return 0;
1718 uint8_t error = response.GetError();
1719 if (error)
1720 return error;
1721 }
1722 return -1;
1723}
Greg Clayton32e0a752011-03-30 18:16:51 +00001724
1725bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001726GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001727{
1728 if (response.IsNormalResponse())
1729 {
1730 std::string name;
1731 std::string value;
1732 StringExtractor extractor;
1733
1734 while (response.GetNameColonValue(name, value))
1735 {
1736 if (name.compare("pid") == 0)
1737 {
1738 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1739 }
1740 else if (name.compare("ppid") == 0)
1741 {
1742 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1743 }
1744 else if (name.compare("uid") == 0)
1745 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001746 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001747 }
1748 else if (name.compare("euid") == 0)
1749 {
1750 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1751 }
1752 else if (name.compare("gid") == 0)
1753 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001754 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001755 }
1756 else if (name.compare("egid") == 0)
1757 {
1758 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1759 }
1760 else if (name.compare("triple") == 0)
1761 {
1762 // The triple comes as ASCII hex bytes since it contains '-' chars
1763 extractor.GetStringRef().swap(value);
1764 extractor.SetFilePos(0);
1765 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00001766 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001767 }
1768 else if (name.compare("name") == 0)
1769 {
1770 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00001771 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00001772 // control the characters in a process name
1773 extractor.GetStringRef().swap(value);
1774 extractor.SetFilePos(0);
1775 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001776 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001777 }
1778 }
1779
1780 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1781 return true;
1782 }
1783 return false;
1784}
1785
1786bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001787GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001788{
1789 process_info.Clear();
1790
1791 if (m_supports_qProcessInfoPID)
1792 {
1793 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00001794 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001795 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001796 StringExtractorGDBRemote response;
1797 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1798 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001799 return DecodeProcessInfoResponse (response, process_info);
1800 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001801 else
1802 {
1803 m_supports_qProcessInfoPID = false;
1804 return false;
1805 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001806 }
1807 return false;
1808}
1809
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001810bool
1811GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
1812{
1813 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1814 return true;
1815 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1816 return false;
1817
1818 GetHostInfo ();
1819
1820 StringExtractorGDBRemote response;
1821 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false))
1822 {
1823 if (response.IsNormalResponse())
1824 {
1825 std::string name;
1826 std::string value;
1827 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1828 uint32_t sub = 0;
1829 std::string arch_name;
1830 std::string os_name;
1831 std::string vendor_name;
1832 std::string triple;
1833 uint32_t pointer_byte_size = 0;
1834 StringExtractor extractor;
1835 ByteOrder byte_order = eByteOrderInvalid;
1836 uint32_t num_keys_decoded = 0;
1837 while (response.GetNameColonValue(name, value))
1838 {
1839 if (name.compare("cputype") == 0)
1840 {
1841 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
1842 if (cpu != LLDB_INVALID_CPUTYPE)
1843 ++num_keys_decoded;
1844 }
1845 else if (name.compare("cpusubtype") == 0)
1846 {
1847 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
1848 if (sub != 0)
1849 ++num_keys_decoded;
1850 }
1851 else if (name.compare("ostype") == 0)
1852 {
1853 os_name.swap (value);
1854 ++num_keys_decoded;
1855 }
1856 else if (name.compare("vendor") == 0)
1857 {
1858 vendor_name.swap(value);
1859 ++num_keys_decoded;
1860 }
1861 else if (name.compare("endian") == 0)
1862 {
1863 ++num_keys_decoded;
1864 if (value.compare("little") == 0)
1865 byte_order = eByteOrderLittle;
1866 else if (value.compare("big") == 0)
1867 byte_order = eByteOrderBig;
1868 else if (value.compare("pdp") == 0)
1869 byte_order = eByteOrderPDP;
1870 else
1871 --num_keys_decoded;
1872 }
1873 else if (name.compare("ptrsize") == 0)
1874 {
1875 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
1876 if (pointer_byte_size != 0)
1877 ++num_keys_decoded;
1878 }
1879 }
1880 if (num_keys_decoded > 0)
1881 m_qProcessInfo_is_valid = eLazyBoolYes;
1882 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
1883 {
1884 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1885 if (pointer_byte_size)
1886 {
1887 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
1888 }
1889 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1890 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1891 return true;
1892 }
1893 }
1894 }
1895 else
1896 {
1897 m_qProcessInfo_is_valid = eLazyBoolNo;
1898 }
1899
1900 return false;
1901}
1902
1903
Greg Clayton32e0a752011-03-30 18:16:51 +00001904uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001905GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1906 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00001907{
1908 process_infos.Clear();
1909
1910 if (m_supports_qfProcessInfo)
1911 {
1912 StreamString packet;
1913 packet.PutCString ("qfProcessInfo");
1914 if (!match_info.MatchAllProcesses())
1915 {
1916 packet.PutChar (':');
1917 const char *name = match_info.GetProcessInfo().GetName();
1918 bool has_name_match = false;
1919 if (name && name[0])
1920 {
1921 has_name_match = true;
1922 NameMatchType name_match_type = match_info.GetNameMatchType();
1923 switch (name_match_type)
1924 {
1925 case eNameMatchIgnore:
1926 has_name_match = false;
1927 break;
1928
1929 case eNameMatchEquals:
1930 packet.PutCString ("name_match:equals;");
1931 break;
1932
1933 case eNameMatchContains:
1934 packet.PutCString ("name_match:contains;");
1935 break;
1936
1937 case eNameMatchStartsWith:
1938 packet.PutCString ("name_match:starts_with;");
1939 break;
1940
1941 case eNameMatchEndsWith:
1942 packet.PutCString ("name_match:ends_with;");
1943 break;
1944
1945 case eNameMatchRegularExpression:
1946 packet.PutCString ("name_match:regex;");
1947 break;
1948 }
1949 if (has_name_match)
1950 {
1951 packet.PutCString ("name:");
1952 packet.PutBytesAsRawHex8(name, ::strlen(name));
1953 packet.PutChar (';');
1954 }
1955 }
1956
1957 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00001958 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00001959 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00001960 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00001961 if (match_info.GetProcessInfo().UserIDIsValid())
1962 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
1963 if (match_info.GetProcessInfo().GroupIDIsValid())
1964 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00001965 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
1966 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
1967 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1968 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
1969 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1970 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
1971 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
1972 {
1973 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
1974 const llvm::Triple &triple = match_arch.GetTriple();
1975 packet.PutCString("triple:");
1976 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
1977 packet.PutChar (';');
1978 }
1979 }
1980 StringExtractorGDBRemote response;
1981 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1982 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001983 do
1984 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001985 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001986 if (!DecodeProcessInfoResponse (response, process_info))
1987 break;
1988 process_infos.Append(process_info);
1989 response.GetStringRef().clear();
1990 response.SetFilePos(0);
1991 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
1992 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001993 else
1994 {
1995 m_supports_qfProcessInfo = false;
1996 return 0;
1997 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001998 }
1999 return process_infos.GetSize();
2000
2001}
2002
2003bool
2004GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2005{
2006 if (m_supports_qUserName)
2007 {
2008 char packet[32];
2009 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002010 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002011 StringExtractorGDBRemote response;
2012 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2013 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002014 if (response.IsNormalResponse())
2015 {
2016 // Make sure we parsed the right number of characters. The response is
2017 // the hex encoded user name and should make up the entire packet.
2018 // If there are any non-hex ASCII bytes, the length won't match below..
2019 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2020 return true;
2021 }
2022 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002023 else
2024 {
2025 m_supports_qUserName = false;
2026 return false;
2027 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002028 }
2029 return false;
2030
2031}
2032
2033bool
2034GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2035{
2036 if (m_supports_qGroupName)
2037 {
2038 char packet[32];
2039 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002040 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002041 StringExtractorGDBRemote response;
2042 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2043 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002044 if (response.IsNormalResponse())
2045 {
2046 // Make sure we parsed the right number of characters. The response is
2047 // the hex encoded group name and should make up the entire packet.
2048 // If there are any non-hex ASCII bytes, the length won't match below..
2049 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2050 return true;
2051 }
2052 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002053 else
2054 {
2055 m_supports_qGroupName = false;
2056 return false;
2057 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002058 }
2059 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002060}
Greg Clayton32e0a752011-03-30 18:16:51 +00002061
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002062void
2063GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2064{
2065 uint32_t i;
2066 TimeValue start_time, end_time;
2067 uint64_t total_time_nsec;
2068 float packets_per_second;
2069 if (SendSpeedTestPacket (0, 0))
2070 {
2071 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
2072 {
2073 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
2074 {
2075 start_time = TimeValue::Now();
2076 for (i=0; i<num_packets; ++i)
2077 {
2078 SendSpeedTestPacket (send_size, recv_size);
2079 }
2080 end_time = TimeValue::Now();
2081 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002082 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002083 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002084 num_packets,
2085 send_size,
2086 recv_size,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002087 total_time_nsec / TimeValue::NanoSecPerSec,
2088 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002089 packets_per_second);
2090 if (recv_size == 0)
2091 recv_size = 32;
2092 }
2093 if (send_size == 0)
2094 send_size = 32;
2095 }
2096 }
2097 else
2098 {
2099 start_time = TimeValue::Now();
2100 for (i=0; i<num_packets; ++i)
2101 {
2102 GetCurrentProcessID ();
2103 }
2104 end_time = TimeValue::Now();
2105 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002106 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002107 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n",
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002108 num_packets,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002109 total_time_nsec / TimeValue::NanoSecPerSec,
2110 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002111 packets_per_second);
2112 }
2113}
2114
2115bool
2116GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2117{
2118 StreamString packet;
2119 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2120 uint32_t bytes_left = send_size;
2121 while (bytes_left > 0)
2122 {
2123 if (bytes_left >= 26)
2124 {
2125 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2126 bytes_left -= 26;
2127 }
2128 else
2129 {
2130 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2131 bytes_left = 0;
2132 }
2133 }
2134
2135 StringExtractorGDBRemote response;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002136 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002137 return false;
Greg Clayton32e0a752011-03-30 18:16:51 +00002138}
Greg Clayton8b82f082011-04-12 05:54:46 +00002139
2140uint16_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002141GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002142{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002143 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002144 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002145 StreamString stream;
2146 stream.PutCString("qLaunchGDBServer:port:0;");
2147 std::string hostname;
2148 if (Host::GetHostname (hostname))
2149 {
2150 // Make the GDB server we launch only accept connections from this host
2151 stream.Printf("host:%s;", hostname.c_str());
2152 }
2153 else
2154 {
2155 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2156 stream.Printf("host:*;");
2157 }
2158 const char *packet = stream.GetData();
2159 int packet_len = stream.GetSize();
2160
2161 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
Greg Clayton8b82f082011-04-12 05:54:46 +00002162 {
2163 std::string name;
2164 std::string value;
2165 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002166 while (response.GetNameColonValue(name, value))
2167 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002168 if (name.compare("port") == 0)
Greg Clayton8b82f082011-04-12 05:54:46 +00002169 port = Args::StringToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002170 else if (name.compare("pid") == 0)
2171 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00002172 }
2173 return port;
2174 }
2175 return 0;
2176}
2177
2178bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002179GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2180{
2181 StreamString stream;
2182 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2183 const char *packet = stream.GetData();
2184 int packet_len = stream.GetSize();
2185 pid = LLDB_INVALID_PROCESS_ID;
2186 StringExtractorGDBRemote response;
2187 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2188 {
2189 if (response.IsOKResponse())
2190 return true;
2191 }
2192 return false;
2193}
2194
2195bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002196GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002197{
2198 if (m_curr_tid == tid)
2199 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002200
Greg Clayton8b82f082011-04-12 05:54:46 +00002201 char packet[32];
2202 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002203 if (tid == UINT64_MAX)
2204 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002205 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002206 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002207 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002208 StringExtractorGDBRemote response;
2209 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2210 {
2211 if (response.IsOKResponse())
2212 {
2213 m_curr_tid = tid;
2214 return true;
2215 }
2216 }
2217 return false;
2218}
2219
2220bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002221GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002222{
2223 if (m_curr_tid_run == tid)
2224 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002225
Greg Clayton8b82f082011-04-12 05:54:46 +00002226 char packet[32];
2227 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002228 if (tid == UINT64_MAX)
2229 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002230 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002231 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2232
Andy Gibbsa297a972013-06-19 19:04:53 +00002233 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002234 StringExtractorGDBRemote response;
2235 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2236 {
2237 if (response.IsOKResponse())
2238 {
2239 m_curr_tid_run = tid;
2240 return true;
2241 }
2242 }
2243 return false;
2244}
2245
2246bool
2247GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2248{
2249 if (SendPacketAndWaitForResponse("?", 1, response, false))
2250 return response.IsNormalResponse();
2251 return false;
2252}
2253
2254bool
Greg Claytonf402f782012-10-13 02:11:55 +00002255GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002256{
2257 if (m_supports_qThreadStopInfo)
2258 {
2259 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002260 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002261 assert (packet_len < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002262 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2263 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002264 if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002265 return true;
2266 else
2267 return false;
2268 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002269 else
2270 {
2271 m_supports_qThreadStopInfo = false;
2272 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002273 }
Greg Clayton5fe15d22011-05-20 03:15:54 +00002274// if (SetCurrentThread (tid))
2275// return GetStopReply (response);
Greg Clayton8b82f082011-04-12 05:54:46 +00002276 return false;
2277}
2278
2279
2280uint8_t
2281GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2282{
2283 switch (type)
2284 {
2285 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
2286 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
2287 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
2288 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
2289 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
Greg Clayton8b82f082011-04-12 05:54:46 +00002290 }
2291
2292 char packet[64];
2293 const int packet_len = ::snprintf (packet,
2294 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002295 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002296 insert ? 'Z' : 'z',
2297 type,
2298 addr,
2299 length);
2300
Andy Gibbsa297a972013-06-19 19:04:53 +00002301 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002302 StringExtractorGDBRemote response;
2303 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
2304 {
2305 if (response.IsOKResponse())
2306 return 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002307 else if (response.IsErrorResponse())
2308 return response.GetError();
2309 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002310 else
2311 {
2312 switch (type)
2313 {
2314 case eBreakpointSoftware: m_supports_z0 = false; break;
2315 case eBreakpointHardware: m_supports_z1 = false; break;
2316 case eWatchpointWrite: m_supports_z2 = false; break;
2317 case eWatchpointRead: m_supports_z3 = false; break;
2318 case eWatchpointReadWrite: m_supports_z4 = false; break;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002319 }
2320 }
2321
Greg Clayton8b82f082011-04-12 05:54:46 +00002322 return UINT8_MAX;
2323}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002324
2325size_t
2326GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2327 bool &sequence_mutex_unavailable)
2328{
2329 Mutex::Locker locker;
2330 thread_ids.clear();
2331
Jim Ingham4ceb9282012-06-08 22:50:40 +00002332 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002333 {
2334 sequence_mutex_unavailable = false;
2335 StringExtractorGDBRemote response;
2336
Greg Clayton73bf5db2011-06-17 01:22:15 +00002337 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
Greg Claytonadc00cb2011-05-20 23:38:13 +00002338 response.IsNormalResponse();
Greg Clayton73bf5db2011-06-17 01:22:15 +00002339 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002340 {
2341 char ch = response.GetChar();
2342 if (ch == 'l')
2343 break;
2344 if (ch == 'm')
2345 {
2346 do
2347 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002348 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002349
2350 if (tid != LLDB_INVALID_THREAD_ID)
2351 {
2352 thread_ids.push_back (tid);
2353 }
2354 ch = response.GetChar(); // Skip the command separator
2355 } while (ch == ','); // Make sure we got a comma separator
2356 }
2357 }
2358 }
2359 else
2360 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002361#if defined (LLDB_CONFIGURATION_DEBUG)
2362 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2363#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002364 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002365 if (log)
2366 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002367#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002368 sequence_mutex_unavailable = true;
2369 }
2370 return thread_ids.size();
2371}
Greg Clayton37a0a242012-04-11 00:24:49 +00002372
2373lldb::addr_t
2374GDBRemoteCommunicationClient::GetShlibInfoAddr()
2375{
2376 if (!IsRunning())
2377 {
2378 StringExtractorGDBRemote response;
2379 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
2380 {
2381 if (response.IsNormalResponse())
2382 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2383 }
2384 }
2385 return LLDB_INVALID_ADDRESS;
2386}
2387
Daniel Maleae0f8f572013-08-26 23:57:52 +00002388lldb_private::Error
2389GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
2390 const char *working_dir, // Pass NULL to use the current working directory
2391 int *status_ptr, // Pass NULL if you don't want the process exit status
2392 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
2393 std::string *command_output, // Pass NULL if you don't want the command output
2394 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
2395{
2396 lldb_private::StreamString stream;
2397 stream.PutCString("qPlatform_RunCommand:");
2398 stream.PutBytesAsRawHex8(command, strlen(command));
2399 stream.PutChar(',');
2400 stream.PutHex32(timeout_sec);
2401 if (working_dir && *working_dir)
2402 {
2403 stream.PutChar(',');
2404 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2405 }
2406 const char *packet = stream.GetData();
2407 int packet_len = stream.GetSize();
2408 StringExtractorGDBRemote response;
2409 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2410 {
2411 if (response.GetChar() != 'F')
2412 return Error("malformed reply");
2413 if (response.GetChar() != ',')
2414 return Error("malformed reply");
2415 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2416 if (exitcode == UINT32_MAX)
2417 return Error("unable to run remote process");
2418 else if (status_ptr)
2419 *status_ptr = exitcode;
2420 if (response.GetChar() != ',')
2421 return Error("malformed reply");
2422 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2423 if (signo_ptr)
2424 *signo_ptr = signo;
2425 if (response.GetChar() != ',')
2426 return Error("malformed reply");
2427 std::string output;
2428 response.GetEscapedBinaryData(output);
2429 if (command_output)
2430 command_output->assign(output);
2431 return Error();
2432 }
2433 return Error("unable to send packet");
2434}
2435
2436uint32_t
2437GDBRemoteCommunicationClient::MakeDirectory (const std::string &path,
2438 mode_t mode)
2439{
2440 lldb_private::StreamString stream;
2441 stream.PutCString("qPlatform_IO_MkDir:");
2442 stream.PutHex32(mode);
2443 stream.PutChar(',');
2444 stream.PutBytesAsRawHex8(path.c_str(), path.size());
2445 const char *packet = stream.GetData();
2446 int packet_len = stream.GetSize();
2447 StringExtractorGDBRemote response;
2448 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2449 {
2450 return response.GetHexMaxU32(false, UINT32_MAX);
2451 }
2452 return UINT32_MAX;
2453
2454}
2455
2456static uint64_t
2457ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
2458 uint64_t fail_result,
2459 Error &error)
2460{
2461 response.SetFilePos(0);
2462 if (response.GetChar() != 'F')
2463 return fail_result;
2464 int32_t result = response.GetS32 (-2);
2465 if (result == -2)
2466 return fail_result;
2467 if (response.GetChar() == ',')
2468 {
2469 int result_errno = response.GetS32 (-2);
2470 if (result_errno != -2)
2471 error.SetError(result_errno, eErrorTypePOSIX);
2472 else
2473 error.SetError(-1, eErrorTypeGeneric);
2474 }
2475 else
2476 error.Clear();
2477 return result;
2478}
2479lldb::user_id_t
2480GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
2481 uint32_t flags,
2482 mode_t mode,
2483 Error &error)
2484{
2485 lldb_private::StreamString stream;
2486 stream.PutCString("vFile:open:");
2487 std::string path (file_spec.GetPath());
2488 if (path.empty())
2489 return UINT64_MAX;
2490 stream.PutCStringAsRawHex8(path.c_str());
2491 stream.PutChar(',');
2492 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
2493 stream.PutHex32(posix_open_flags);
2494 stream.PutChar(',');
2495 stream.PutHex32(mode);
2496 const char* packet = stream.GetData();
2497 int packet_len = stream.GetSize();
2498 StringExtractorGDBRemote response;
2499 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2500 {
2501 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
2502 }
2503 return UINT64_MAX;
2504}
2505
2506bool
2507GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
2508 Error &error)
2509{
2510 lldb_private::StreamString stream;
2511 stream.Printf("vFile:close:%i", (int)fd);
2512 const char* packet = stream.GetData();
2513 int packet_len = stream.GetSize();
2514 StringExtractorGDBRemote response;
2515 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2516 {
2517 return ParseHostIOPacketResponse (response, -1, error) == 0;
2518 }
2519 return UINT64_MAX;
2520}
2521
2522// Extension of host I/O packets to get the file size.
2523lldb::user_id_t
2524GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
2525{
2526 lldb_private::StreamString stream;
2527 stream.PutCString("vFile:size:");
2528 std::string path (file_spec.GetPath());
2529 stream.PutCStringAsRawHex8(path.c_str());
2530 const char* packet = stream.GetData();
2531 int packet_len = stream.GetSize();
2532 StringExtractorGDBRemote response;
2533 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2534 {
2535 if (response.GetChar() != 'F')
2536 return UINT64_MAX;
2537 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2538 return retcode;
2539 }
2540 return UINT64_MAX;
2541}
2542
2543uint32_t
2544GDBRemoteCommunicationClient::GetFilePermissions(const lldb_private::FileSpec& file_spec, Error &error)
2545{
2546 lldb_private::StreamString stream;
2547 stream.PutCString("vFile:mode:");
2548 std::string path (file_spec.GetPath());
2549 stream.PutCStringAsRawHex8(path.c_str());
2550 const char* packet = stream.GetData();
2551 int packet_len = stream.GetSize();
2552 StringExtractorGDBRemote response;
2553 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2554 {
2555 if (response.GetChar() != 'F')
2556 {
2557 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
2558 return 0;
2559 }
2560 const uint32_t mode = response.GetS32(-1);
2561 if (mode == -1)
2562 {
2563 if (response.GetChar() == ',')
2564 {
2565 int response_errno = response.GetS32(-1);
2566 if (response_errno > 0)
2567 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2568 else
2569 error.SetErrorToGenericError();
2570 }
2571 }
2572 else
2573 error.Clear();
2574 return mode & (S_IRWXU|S_IRWXG|S_IRWXO);
2575 }
2576 else
2577 {
2578 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
2579 }
2580 return 0;
2581}
2582
2583uint64_t
2584GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
2585 uint64_t offset,
2586 void *dst,
2587 uint64_t dst_len,
2588 Error &error)
2589{
2590 lldb_private::StreamString stream;
2591 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
2592 const char* packet = stream.GetData();
2593 int packet_len = stream.GetSize();
2594 StringExtractorGDBRemote response;
2595 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2596 {
2597 if (response.GetChar() != 'F')
2598 return 0;
2599 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2600 if (retcode == UINT32_MAX)
2601 return retcode;
2602 const char next = (response.Peek() ? *response.Peek() : 0);
2603 if (next == ',')
2604 return 0;
2605 if (next == ';')
2606 {
2607 response.GetChar(); // skip the semicolon
2608 std::string buffer;
2609 if (response.GetEscapedBinaryData(buffer))
2610 {
2611 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
2612 if (data_to_write > 0)
2613 memcpy(dst, &buffer[0], data_to_write);
2614 return data_to_write;
2615 }
2616 }
2617 }
2618 return 0;
2619}
2620
2621uint64_t
2622GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
2623 uint64_t offset,
2624 const void* src,
2625 uint64_t src_len,
2626 Error &error)
2627{
2628 lldb_private::StreamGDBRemote stream;
2629 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2630 stream.PutEscapedBytes(src, src_len);
2631 const char* packet = stream.GetData();
2632 int packet_len = stream.GetSize();
2633 StringExtractorGDBRemote response;
2634 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2635 {
2636 if (response.GetChar() != 'F')
2637 {
2638 error.SetErrorStringWithFormat("write file failed");
2639 return 0;
2640 }
2641 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2642 if (bytes_written == UINT64_MAX)
2643 {
2644 error.SetErrorToGenericError();
2645 if (response.GetChar() == ',')
2646 {
2647 int response_errno = response.GetS32(-1);
2648 if (response_errno > 0)
2649 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2650 }
2651 return 0;
2652 }
2653 return bytes_written;
2654 }
2655 else
2656 {
2657 error.SetErrorString ("failed to send vFile:pwrite packet");
2658 }
2659 return 0;
2660}
2661
2662// Extension of host I/O packets to get whether a file exists.
2663bool
2664GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
2665{
2666 lldb_private::StreamString stream;
2667 stream.PutCString("vFile:exists:");
2668 std::string path (file_spec.GetPath());
2669 stream.PutCStringAsRawHex8(path.c_str());
2670 const char* packet = stream.GetData();
2671 int packet_len = stream.GetSize();
2672 StringExtractorGDBRemote response;
2673 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2674 {
2675 if (response.GetChar() != 'F')
2676 return false;
2677 if (response.GetChar() != ',')
2678 return false;
2679 bool retcode = (response.GetChar() != '0');
2680 return retcode;
2681 }
2682 return false;
2683}
2684
2685bool
2686GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
2687 uint64_t &high,
2688 uint64_t &low)
2689{
2690 lldb_private::StreamString stream;
2691 stream.PutCString("vFile:MD5:");
2692 std::string path (file_spec.GetPath());
2693 stream.PutCStringAsRawHex8(path.c_str());
2694 const char* packet = stream.GetData();
2695 int packet_len = stream.GetSize();
2696 StringExtractorGDBRemote response;
2697 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2698 {
2699 if (response.GetChar() != 'F')
2700 return false;
2701 if (response.GetChar() != ',')
2702 return false;
2703 if (response.Peek() && *response.Peek() == 'x')
2704 return false;
2705 low = response.GetHexMaxU64(false, UINT64_MAX);
2706 high = response.GetHexMaxU64(false, UINT64_MAX);
2707 return true;
2708 }
2709 return false;
2710}