blob: c2f1b7b9fce8abe19be4784ae2ede395160a0183 [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationServer.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
Sylvestre Ledrud28b9932013-09-28 15:23:41 +000010#include <errno.h>
Greg Clayton576d8832011-03-22 04:00:09 +000011
Zachary Turner0ec7baa2014-07-01 00:18:46 +000012#include "lldb/Host/Config.h"
13
Greg Clayton576d8832011-03-22 04:00:09 +000014#include "GDBRemoteCommunicationServer.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000015#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000016
17// C Includes
18// C++ Includes
Todd Fialaaf245d12014-06-30 21:05:18 +000019#include <cstring>
Todd Fiala2850b1b2014-06-30 23:51:35 +000020#include <chrono>
21#include <thread>
Todd Fialaaf245d12014-06-30 21:05:18 +000022
Greg Clayton576d8832011-03-22 04:00:09 +000023// Other libraries and framework includes
24#include "llvm/ADT/Triple.h"
25#include "lldb/Interpreter/Args.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000026#include "lldb/Core/Debugger.h"
Greg Clayton576d8832011-03-22 04:00:09 +000027#include "lldb/Core/Log.h"
28#include "lldb/Core/State.h"
29#include "lldb/Core/StreamString.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000030#include "lldb/Host/ConnectionFileDescriptor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000031#include "lldb/Host/Debug.h"
Enrico Granataf2bbf712011-07-15 02:26:42 +000032#include "lldb/Host/Endian.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000033#include "lldb/Host/File.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000034#include "lldb/Host/FileSystem.h"
Greg Clayton576d8832011-03-22 04:00:09 +000035#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000036#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000037#include "lldb/Host/StringConvert.h"
Greg Clayton576d8832011-03-22 04:00:09 +000038#include "lldb/Host/TimeValue.h"
Zachary Turner696b5282014-08-14 16:01:25 +000039#include "lldb/Target/FileAction.h"
Todd Fialab8b49ec2014-01-28 00:34:23 +000040#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000041#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000042#include "lldb/Target/NativeRegisterContext.h"
Todd Fiala24189d42014-07-14 06:24:44 +000043#include "Host/common/NativeProcessProtocol.h"
44#include "Host/common/NativeThreadProtocol.h"
Greg Clayton576d8832011-03-22 04:00:09 +000045
46// Project includes
47#include "Utility/StringExtractorGDBRemote.h"
Vince Harron1b5a74e2015-01-21 22:42:49 +000048#include "Utility/UriParser.h"
Greg Clayton576d8832011-03-22 04:00:09 +000049#include "ProcessGDBRemote.h"
50#include "ProcessGDBRemoteLog.h"
51
52using namespace lldb;
53using namespace lldb_private;
54
55//----------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +000056// GDBRemote Errors
57//----------------------------------------------------------------------
58
59namespace
60{
61 enum GDBRemoteServerError
62 {
63 // Set to the first unused error number in literal form below
64 eErrorFirst = 29,
65 eErrorNoProcess = eErrorFirst,
66 eErrorResume,
67 eErrorExitStatus
68 };
69}
70
71//----------------------------------------------------------------------
Greg Clayton576d8832011-03-22 04:00:09 +000072// GDBRemoteCommunicationServer constructor
73//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000074GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform) :
75 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
Greg Clayton615eb7e2014-09-19 20:11:50 +000076 m_platform_sp (Platform::GetHostPlatform ()),
Greg Clayton8b82f082011-04-12 05:54:46 +000077 m_async_thread (LLDB_INVALID_HOST_THREAD),
78 m_process_launch_info (),
79 m_process_launch_error (),
Daniel Maleae0f8f572013-08-26 23:57:52 +000080 m_spawned_pids (),
81 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton8b82f082011-04-12 05:54:46 +000082 m_proc_infos (),
83 m_proc_infos_index (0),
Greg Clayton2b98c562013-11-22 18:53:12 +000084 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +000085 m_port_offset(0),
86 m_current_tid (LLDB_INVALID_THREAD_ID),
87 m_continue_tid (LLDB_INVALID_THREAD_ID),
88 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
89 m_debugged_process_sp (),
90 m_debugger_sp (),
91 m_stdio_communication ("process.stdio"),
92 m_exit_now (false),
93 m_inferior_prev_state (StateType::eStateInvalid),
94 m_thread_suffix_supported (false),
95 m_list_threads_in_stop_reply (false),
96 m_active_auxv_buffer_sp (),
97 m_saved_registers_mutex (),
98 m_saved_registers_map (),
99 m_next_saved_registers_id (1)
Greg Clayton576d8832011-03-22 04:00:09 +0000100{
Todd Fialaaf245d12014-06-30 21:05:18 +0000101 assert(is_platform && "must be lldb-platform if debugger is not specified");
Greg Clayton576d8832011-03-22 04:00:09 +0000102}
103
Todd Fialab8b49ec2014-01-28 00:34:23 +0000104GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform,
Todd Fialaaf245d12014-06-30 21:05:18 +0000105 const lldb::PlatformSP& platform_sp,
106 lldb::DebuggerSP &debugger_sp) :
Todd Fialab8b49ec2014-01-28 00:34:23 +0000107 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
108 m_platform_sp (platform_sp),
109 m_async_thread (LLDB_INVALID_HOST_THREAD),
110 m_process_launch_info (),
111 m_process_launch_error (),
112 m_spawned_pids (),
113 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
114 m_proc_infos (),
115 m_proc_infos_index (0),
116 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000117 m_port_offset(0),
118 m_current_tid (LLDB_INVALID_THREAD_ID),
119 m_continue_tid (LLDB_INVALID_THREAD_ID),
120 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
121 m_debugged_process_sp (),
122 m_debugger_sp (debugger_sp),
123 m_stdio_communication ("process.stdio"),
124 m_exit_now (false),
125 m_inferior_prev_state (StateType::eStateInvalid),
126 m_thread_suffix_supported (false),
127 m_list_threads_in_stop_reply (false),
128 m_active_auxv_buffer_sp (),
129 m_saved_registers_mutex (),
130 m_saved_registers_map (),
131 m_next_saved_registers_id (1)
Todd Fialab8b49ec2014-01-28 00:34:23 +0000132{
133 assert(platform_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000134 assert((is_platform || debugger_sp) && "must specify non-NULL debugger_sp when lldb-gdbserver");
Todd Fialab8b49ec2014-01-28 00:34:23 +0000135}
136
Greg Clayton576d8832011-03-22 04:00:09 +0000137//----------------------------------------------------------------------
138// Destructor
139//----------------------------------------------------------------------
140GDBRemoteCommunicationServer::~GDBRemoteCommunicationServer()
141{
142}
143
Todd Fialaaf245d12014-06-30 21:05:18 +0000144GDBRemoteCommunication::PacketResult
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000145GDBRemoteCommunicationServer::GetPacketAndSendResponse (uint32_t timeout_usec,
Greg Clayton1cb64962011-03-24 04:28:38 +0000146 Error &error,
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000147 bool &interrupt,
Greg Claytond314e812011-03-23 00:09:55 +0000148 bool &quit)
Greg Clayton576d8832011-03-22 04:00:09 +0000149{
150 StringExtractorGDBRemote packet;
Todd Fialaaf245d12014-06-30 21:05:18 +0000151
Greg Clayton3dedae12013-12-06 21:45:27 +0000152 PacketResult packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
153 if (packet_result == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000154 {
155 const StringExtractorGDBRemote::ServerPacketType packet_type = packet.GetServerPacketType ();
156 switch (packet_type)
157 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000158 case StringExtractorGDBRemote::eServerPacketType_nack:
159 case StringExtractorGDBRemote::eServerPacketType_ack:
160 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000161
Greg Clayton3dedae12013-12-06 21:45:27 +0000162 case StringExtractorGDBRemote::eServerPacketType_invalid:
163 error.SetErrorString("invalid packet");
164 quit = true;
165 break;
Greg Claytond314e812011-03-23 00:09:55 +0000166
Greg Clayton3dedae12013-12-06 21:45:27 +0000167 default:
168 case StringExtractorGDBRemote::eServerPacketType_unimplemented:
169 packet_result = SendUnimplementedResponse (packet.GetStringRef().c_str());
170 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000171
Greg Clayton3dedae12013-12-06 21:45:27 +0000172 case StringExtractorGDBRemote::eServerPacketType_A:
173 packet_result = Handle_A (packet);
174 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000175
Greg Clayton3dedae12013-12-06 21:45:27 +0000176 case StringExtractorGDBRemote::eServerPacketType_qfProcessInfo:
177 packet_result = Handle_qfProcessInfo (packet);
178 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000179
Greg Clayton3dedae12013-12-06 21:45:27 +0000180 case StringExtractorGDBRemote::eServerPacketType_qsProcessInfo:
181 packet_result = Handle_qsProcessInfo (packet);
182 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000183
Greg Clayton3dedae12013-12-06 21:45:27 +0000184 case StringExtractorGDBRemote::eServerPacketType_qC:
185 packet_result = Handle_qC (packet);
186 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000187
Greg Clayton3dedae12013-12-06 21:45:27 +0000188 case StringExtractorGDBRemote::eServerPacketType_qHostInfo:
189 packet_result = Handle_qHostInfo (packet);
190 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000191
Greg Clayton3dedae12013-12-06 21:45:27 +0000192 case StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer:
193 packet_result = Handle_qLaunchGDBServer (packet);
194 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000195
Greg Clayton3dedae12013-12-06 21:45:27 +0000196 case StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess:
197 packet_result = Handle_qKillSpawnedProcess (packet);
198 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000199
Todd Fiala403edc52014-01-23 22:05:44 +0000200 case StringExtractorGDBRemote::eServerPacketType_k:
201 packet_result = Handle_k (packet);
Todd Fialaaf245d12014-06-30 21:05:18 +0000202 quit = true;
Todd Fiala403edc52014-01-23 22:05:44 +0000203 break;
204
Greg Clayton3dedae12013-12-06 21:45:27 +0000205 case StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess:
206 packet_result = Handle_qLaunchSuccess (packet);
207 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000208
Greg Clayton3dedae12013-12-06 21:45:27 +0000209 case StringExtractorGDBRemote::eServerPacketType_qGroupName:
210 packet_result = Handle_qGroupName (packet);
211 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000212
Todd Fialaaf245d12014-06-30 21:05:18 +0000213 case StringExtractorGDBRemote::eServerPacketType_qProcessInfo:
214 packet_result = Handle_qProcessInfo (packet);
215 break;
216
Greg Clayton3dedae12013-12-06 21:45:27 +0000217 case StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID:
218 packet_result = Handle_qProcessInfoPID (packet);
219 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000220
Greg Clayton3dedae12013-12-06 21:45:27 +0000221 case StringExtractorGDBRemote::eServerPacketType_qSpeedTest:
222 packet_result = Handle_qSpeedTest (packet);
223 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000224
Greg Clayton3dedae12013-12-06 21:45:27 +0000225 case StringExtractorGDBRemote::eServerPacketType_qUserName:
226 packet_result = Handle_qUserName (packet);
227 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000228
Greg Clayton3dedae12013-12-06 21:45:27 +0000229 case StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir:
230 packet_result = Handle_qGetWorkingDir(packet);
231 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000232
Greg Clayton3dedae12013-12-06 21:45:27 +0000233 case StringExtractorGDBRemote::eServerPacketType_QEnvironment:
234 packet_result = Handle_QEnvironment (packet);
235 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000236
Greg Clayton3dedae12013-12-06 21:45:27 +0000237 case StringExtractorGDBRemote::eServerPacketType_QLaunchArch:
238 packet_result = Handle_QLaunchArch (packet);
239 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000240
Greg Clayton3dedae12013-12-06 21:45:27 +0000241 case StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR:
242 packet_result = Handle_QSetDisableASLR (packet);
243 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000244
Jim Ingham106d0282014-06-25 02:32:56 +0000245 case StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError:
246 packet_result = Handle_QSetDetachOnError (packet);
247 break;
248
Greg Clayton3dedae12013-12-06 21:45:27 +0000249 case StringExtractorGDBRemote::eServerPacketType_QSetSTDIN:
250 packet_result = Handle_QSetSTDIN (packet);
251 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000252
Greg Clayton3dedae12013-12-06 21:45:27 +0000253 case StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT:
254 packet_result = Handle_QSetSTDOUT (packet);
255 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000256
Greg Clayton3dedae12013-12-06 21:45:27 +0000257 case StringExtractorGDBRemote::eServerPacketType_QSetSTDERR:
258 packet_result = Handle_QSetSTDERR (packet);
259 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000260
Greg Clayton3dedae12013-12-06 21:45:27 +0000261 case StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir:
262 packet_result = Handle_QSetWorkingDir (packet);
263 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000264
Greg Clayton3dedae12013-12-06 21:45:27 +0000265 case StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode:
266 packet_result = Handle_QStartNoAckMode (packet);
267 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000268
Greg Clayton3dedae12013-12-06 21:45:27 +0000269 case StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir:
270 packet_result = Handle_qPlatform_mkdir (packet);
271 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000272
Greg Clayton3dedae12013-12-06 21:45:27 +0000273 case StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod:
274 packet_result = Handle_qPlatform_chmod (packet);
275 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000276
Greg Clayton3dedae12013-12-06 21:45:27 +0000277 case StringExtractorGDBRemote::eServerPacketType_qPlatform_shell:
278 packet_result = Handle_qPlatform_shell (packet);
279 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000280
Todd Fialaaf245d12014-06-30 21:05:18 +0000281 case StringExtractorGDBRemote::eServerPacketType_C:
282 packet_result = Handle_C (packet);
283 break;
284
285 case StringExtractorGDBRemote::eServerPacketType_c:
286 packet_result = Handle_c (packet);
287 break;
288
289 case StringExtractorGDBRemote::eServerPacketType_vCont:
290 packet_result = Handle_vCont (packet);
291 break;
292
293 case StringExtractorGDBRemote::eServerPacketType_vCont_actions:
294 packet_result = Handle_vCont_actions (packet);
295 break;
296
297 case StringExtractorGDBRemote::eServerPacketType_stop_reason: // ?
298 packet_result = Handle_stop_reason (packet);
299 break;
300
Greg Clayton3dedae12013-12-06 21:45:27 +0000301 case StringExtractorGDBRemote::eServerPacketType_vFile_open:
302 packet_result = Handle_vFile_Open (packet);
303 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000304
Greg Clayton3dedae12013-12-06 21:45:27 +0000305 case StringExtractorGDBRemote::eServerPacketType_vFile_close:
306 packet_result = Handle_vFile_Close (packet);
307 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000308
Greg Clayton3dedae12013-12-06 21:45:27 +0000309 case StringExtractorGDBRemote::eServerPacketType_vFile_pread:
310 packet_result = Handle_vFile_pRead (packet);
311 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000312
Greg Clayton3dedae12013-12-06 21:45:27 +0000313 case StringExtractorGDBRemote::eServerPacketType_vFile_pwrite:
314 packet_result = Handle_vFile_pWrite (packet);
315 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000316
Greg Clayton3dedae12013-12-06 21:45:27 +0000317 case StringExtractorGDBRemote::eServerPacketType_vFile_size:
318 packet_result = Handle_vFile_Size (packet);
319 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000320
Greg Clayton3dedae12013-12-06 21:45:27 +0000321 case StringExtractorGDBRemote::eServerPacketType_vFile_mode:
322 packet_result = Handle_vFile_Mode (packet);
323 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000324
Greg Clayton3dedae12013-12-06 21:45:27 +0000325 case StringExtractorGDBRemote::eServerPacketType_vFile_exists:
326 packet_result = Handle_vFile_Exists (packet);
327 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000328
Greg Clayton3dedae12013-12-06 21:45:27 +0000329 case StringExtractorGDBRemote::eServerPacketType_vFile_stat:
330 packet_result = Handle_vFile_Stat (packet);
331 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000332
Greg Clayton3dedae12013-12-06 21:45:27 +0000333 case StringExtractorGDBRemote::eServerPacketType_vFile_md5:
334 packet_result = Handle_vFile_MD5 (packet);
335 break;
336
337 case StringExtractorGDBRemote::eServerPacketType_vFile_symlink:
338 packet_result = Handle_vFile_symlink (packet);
339 break;
340
341 case StringExtractorGDBRemote::eServerPacketType_vFile_unlink:
342 packet_result = Handle_vFile_unlink (packet);
343 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000344
345 case StringExtractorGDBRemote::eServerPacketType_qRegisterInfo:
346 packet_result = Handle_qRegisterInfo (packet);
347 break;
348
349 case StringExtractorGDBRemote::eServerPacketType_qfThreadInfo:
350 packet_result = Handle_qfThreadInfo (packet);
351 break;
352
353 case StringExtractorGDBRemote::eServerPacketType_qsThreadInfo:
354 packet_result = Handle_qsThreadInfo (packet);
355 break;
356
357 case StringExtractorGDBRemote::eServerPacketType_p:
358 packet_result = Handle_p (packet);
359 break;
360
361 case StringExtractorGDBRemote::eServerPacketType_P:
362 packet_result = Handle_P (packet);
363 break;
364
365 case StringExtractorGDBRemote::eServerPacketType_H:
366 packet_result = Handle_H (packet);
367 break;
368
369 case StringExtractorGDBRemote::eServerPacketType_m:
370 packet_result = Handle_m (packet);
371 break;
372
373 case StringExtractorGDBRemote::eServerPacketType_M:
374 packet_result = Handle_M (packet);
375 break;
376
377 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported:
378 packet_result = Handle_qMemoryRegionInfoSupported (packet);
379 break;
380
381 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo:
382 packet_result = Handle_qMemoryRegionInfo (packet);
383 break;
384
385 case StringExtractorGDBRemote::eServerPacketType_interrupt:
386 if (IsGdbServer ())
387 packet_result = Handle_interrupt (packet);
388 else
389 {
390 error.SetErrorString("interrupt received");
391 interrupt = true;
392 }
393 break;
394
395 case StringExtractorGDBRemote::eServerPacketType_Z:
396 packet_result = Handle_Z (packet);
397 break;
398
399 case StringExtractorGDBRemote::eServerPacketType_z:
400 packet_result = Handle_z (packet);
401 break;
402
403 case StringExtractorGDBRemote::eServerPacketType_s:
404 packet_result = Handle_s (packet);
405 break;
406
407 case StringExtractorGDBRemote::eServerPacketType_qSupported:
408 packet_result = Handle_qSupported (packet);
409 break;
410
411 case StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported:
412 packet_result = Handle_QThreadSuffixSupported (packet);
413 break;
414
415 case StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply:
416 packet_result = Handle_QListThreadsInStopReply (packet);
417 break;
418
419 case StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read:
420 packet_result = Handle_qXfer_auxv_read (packet);
421 break;
422
423 case StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState:
424 packet_result = Handle_QSaveRegisterState (packet);
425 break;
426
427 case StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState:
428 packet_result = Handle_QRestoreRegisterState (packet);
429 break;
Todd Fiala7306cf32014-07-29 22:30:01 +0000430
431 case StringExtractorGDBRemote::eServerPacketType_vAttach:
432 packet_result = Handle_vAttach (packet);
433 break;
Todd Fiala1109ed42014-09-10 21:28:38 +0000434
Oleksiy Vyalov859e4b52014-12-10 01:27:28 +0000435 case StringExtractorGDBRemote::eServerPacketType_D:
436 packet_result = Handle_D (packet);
437 break;
438
Todd Fiala1109ed42014-09-10 21:28:38 +0000439 case StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo:
440 packet_result = Handle_qThreadStopInfo (packet);
441 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000442 }
Greg Clayton576d8832011-03-22 04:00:09 +0000443 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000444 else
445 {
446 if (!IsConnected())
Greg Clayton3dedae12013-12-06 21:45:27 +0000447 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000448 error.SetErrorString("lost connection");
Greg Clayton3dedae12013-12-06 21:45:27 +0000449 quit = true;
450 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000451 else
Greg Clayton3dedae12013-12-06 21:45:27 +0000452 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000453 error.SetErrorString("timeout");
Greg Clayton3dedae12013-12-06 21:45:27 +0000454 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000455 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000456
457 // Check if anything occurred that would force us to want to exit.
458 if (m_exit_now)
459 quit = true;
460
461 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000462}
463
Todd Fiala403edc52014-01-23 22:05:44 +0000464lldb_private::Error
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000465GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc)
Todd Fiala403edc52014-01-23 22:05:44 +0000466{
467 if ((argc < 1) || !args || !args[0] || !args[0][0])
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000468 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
Todd Fiala403edc52014-01-23 22:05:44 +0000469
Todd Fiala403edc52014-01-23 22:05:44 +0000470 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000471 return lldb_private::Error ();
472}
473
474lldb_private::Error
475GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags)
476{
Todd Fiala403edc52014-01-23 22:05:44 +0000477 m_process_launch_info.GetFlags ().Set (launch_flags);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000478 return lldb_private::Error ();
479}
480
481lldb_private::Error
482GDBRemoteCommunicationServer::LaunchProcess ()
483{
Todd Fialaaf245d12014-06-30 21:05:18 +0000484 // FIXME This looks an awful lot like we could override this in
485 // derived classes, one for lldb-platform, the other for lldb-gdbserver.
486 if (IsGdbServer ())
Todd Fiala87bac592014-09-18 21:02:03 +0000487 return LaunchProcessForDebugging ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000488 else
489 return LaunchPlatformProcess ();
490}
491
Todd Fiala75f47c32014-10-11 21:42:09 +0000492bool
493GDBRemoteCommunicationServer::ShouldRedirectInferiorOutputOverGdbRemote (const lldb_private::ProcessLaunchInfo &launch_info) const
494{
495 // Retrieve the file actions specified for stdout and stderr.
496 auto stdout_file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
497 auto stderr_file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
498
499 // If neither stdout and stderr file actions are specified, we're not doing anything special, so
500 // assume we want to redirect stdout/stderr over gdb-remote $O messages.
501 if ((stdout_file_action == nullptr) && (stderr_file_action == nullptr))
502 {
503 // Send stdout/stderr over the gdb-remote protocol.
504 return true;
505 }
506
507 // Any other setting for either stdout or stderr implies we are either suppressing
508 // it (with /dev/null) or we've got it set to a PTY. Either way, we don't want the
509 // output over gdb-remote.
510 return false;
511}
512
Todd Fialaaf245d12014-06-30 21:05:18 +0000513lldb_private::Error
Todd Fiala87bac592014-09-18 21:02:03 +0000514GDBRemoteCommunicationServer::LaunchProcessForDebugging ()
Todd Fialaaf245d12014-06-30 21:05:18 +0000515{
516 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
517
518 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
519 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
520
521 lldb_private::Error error;
522 {
523 Mutex::Locker locker (m_debugged_process_mutex);
524 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
525 error = m_platform_sp->LaunchNativeProcess (
526 m_process_launch_info,
527 *this,
528 m_debugged_process_sp);
529 }
530
531 if (!error.Success ())
532 {
533 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
534 return error;
535 }
536
Todd Fiala75f47c32014-10-11 21:42:09 +0000537 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as needed.
538 // llgs local-process debugging may specify PTYs, which will eliminate the need to reflect inferior
539 // stdout/stderr over the gdb-remote protocol.
540 if (ShouldRedirectInferiorOutputOverGdbRemote (m_process_launch_info))
Todd Fialaaf245d12014-06-30 21:05:18 +0000541 {
542 if (log)
Todd Fiala75f47c32014-10-11 21:42:09 +0000543 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
544
545 // Setup stdout/stderr mapping from inferior to $O
546 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
547 if (terminal_fd >= 0)
548 {
549 if (log)
550 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
551 error = SetSTDIOFileDescriptor (terminal_fd);
552 if (error.Fail ())
553 return error;
554 }
555 else
556 {
557 if (log)
558 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
559 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000560 }
561 else
562 {
563 if (log)
Todd Fiala75f47c32014-10-11 21:42:09 +0000564 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " skipping stdout/stderr redirection via $O: inferior will communicate over client-provided file descriptors", __FUNCTION__, m_debugged_process_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000565 }
566
567 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
568
569 // Add to list of spawned processes.
570 lldb::pid_t pid;
571 if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
572 {
573 // add to spawned pids
Todd Fiala87bac592014-09-18 21:02:03 +0000574 Mutex::Locker locker (m_spawned_pids_mutex);
575 // On an lldb-gdbserver, we would expect there to be only one.
576 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
577 m_spawned_pids.insert (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000578 }
579
580 return error;
581}
582
583lldb_private::Error
584GDBRemoteCommunicationServer::LaunchPlatformProcess ()
585{
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000586 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
587 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
588
589 // specify the process monitor if not already set. This should
590 // generally be what happens since we need to reap started
591 // processes.
592 if (!m_process_launch_info.GetMonitorProcessCallback ())
593 m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false);
Todd Fiala403edc52014-01-23 22:05:44 +0000594
Todd Fialab8b49ec2014-01-28 00:34:23 +0000595 lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
Todd Fiala403edc52014-01-23 22:05:44 +0000596 if (!error.Success ())
597 {
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000598 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
Todd Fiala403edc52014-01-23 22:05:44 +0000599 return error;
600 }
601
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000602 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID());
Todd Fiala403edc52014-01-23 22:05:44 +0000603
604 // add to list of spawned processes. On an lldb-gdbserver, we
605 // would expect there to be only one.
606 lldb::pid_t pid;
607 if ( (pid = m_process_launch_info.GetProcessID()) != LLDB_INVALID_PROCESS_ID )
608 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000609 // add to spawned pids
610 {
611 Mutex::Locker locker (m_spawned_pids_mutex);
612 m_spawned_pids.insert(pid);
613 }
Todd Fiala403edc52014-01-23 22:05:44 +0000614 }
615
616 return error;
617}
618
Todd Fialaaf245d12014-06-30 21:05:18 +0000619lldb_private::Error
620GDBRemoteCommunicationServer::AttachToProcess (lldb::pid_t pid)
621{
622 Error error;
623
624 if (!IsGdbServer ())
625 {
626 error.SetErrorString("cannot AttachToProcess () unless process is lldb-gdbserver");
627 return error;
628 }
629
630 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
631 if (log)
632 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64, __FUNCTION__, pid);
633
634 // Scope for mutex locker.
635 {
636 // Before we try to attach, make sure we aren't already monitoring something else.
637 Mutex::Locker locker (m_spawned_pids_mutex);
638 if (!m_spawned_pids.empty ())
639 {
640 error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
641 return error;
642 }
643
644 // Try to attach.
645 error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp);
646 if (!error.Success ())
647 {
648 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
649 return error;
650 }
651
652 // Setup stdout/stderr mapping from inferior.
653 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
654 if (terminal_fd >= 0)
655 {
656 if (log)
657 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
658 error = SetSTDIOFileDescriptor (terminal_fd);
659 if (error.Fail ())
660 return error;
661 }
662 else
663 {
664 if (log)
665 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
666 }
667
668 printf ("Attached to process %" PRIu64 "...\n", pid);
669
670 // Add to list of spawned processes.
671 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
672 m_spawned_pids.insert (pid);
673
674 return error;
675 }
676}
677
678void
679GDBRemoteCommunicationServer::InitializeDelegate (lldb_private::NativeProcessProtocol *process)
680{
681 assert (process && "process cannot be NULL");
682 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
683 if (log)
684 {
685 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
686 __FUNCTION__,
687 process->GetID (),
688 StateAsCString (process->GetState ()));
689 }
690}
691
692GDBRemoteCommunication::PacketResult
693GDBRemoteCommunicationServer::SendWResponse (lldb_private::NativeProcessProtocol *process)
694{
695 assert (process && "process cannot be NULL");
696 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
697
698 // send W notification
699 ExitType exit_type = ExitType::eExitTypeInvalid;
700 int return_code = 0;
701 std::string exit_description;
702
703 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
704 if (!got_exit_info)
705 {
706 if (log)
707 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
708
709 StreamGDBRemote response;
710 response.PutChar ('E');
711 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
712 return SendPacketNoLock(response.GetData(), response.GetSize());
713 }
714 else
715 {
716 if (log)
717 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", returning exit type %d, return code %d [%s]", __FUNCTION__, process->GetID (), exit_type, return_code, exit_description.c_str ());
718
719 StreamGDBRemote response;
720
721 char return_type_code;
722 switch (exit_type)
723 {
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000724 case ExitType::eExitTypeExit:
725 return_type_code = 'W';
726 break;
727 case ExitType::eExitTypeSignal:
728 return_type_code = 'X';
729 break;
730 case ExitType::eExitTypeStop:
731 return_type_code = 'S';
732 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000733 case ExitType::eExitTypeInvalid:
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000734 return_type_code = 'E';
735 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000736 }
737 response.PutChar (return_type_code);
738
739 // POSIX exit status limited to unsigned 8 bits.
740 response.PutHex8 (return_code);
741
742 return SendPacketNoLock(response.GetData(), response.GetSize());
743 }
744}
745
746static void
747AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
748{
749 int64_t i;
750 if (swap)
751 {
752 for (i = buf_size-1; i >= 0; i--)
753 response.PutHex8 (buf[i]);
754 }
755 else
756 {
757 for (i = 0; i < buf_size; i++)
758 response.PutHex8 (buf[i]);
759 }
760}
761
762static void
763WriteRegisterValueInHexFixedWidth (StreamString &response,
764 NativeRegisterContextSP &reg_ctx_sp,
765 const RegisterInfo &reg_info,
766 const RegisterValue *reg_value_p)
767{
768 RegisterValue reg_value;
769 if (!reg_value_p)
770 {
771 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
772 if (error.Success ())
773 reg_value_p = &reg_value;
774 // else log.
775 }
776
777 if (reg_value_p)
778 {
779 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
780 }
781 else
782 {
783 // Zero-out any unreadable values.
784 if (reg_info.byte_size > 0)
785 {
786 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
787 AppendHexValue (response, zeros.data(), zeros.size(), false);
788 }
789 }
790}
791
792// WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
793
794
795static void
796WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response,
797 NativeRegisterContextSP &reg_ctx_sp,
798 const RegisterInfo &reg_info,
799 const RegisterValue &reg_value)
800{
801 // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
802 // gdb register number, and VVVVVVVV is the correct number of hex bytes
803 // as ASCII for the register value.
804 if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM)
805 return;
806
807 response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]);
808 WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, &reg_value);
809 response.PutChar (';');
810}
811
812
813GDBRemoteCommunication::PacketResult
814GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid)
815{
816 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
817
818 // Ensure we're llgs.
819 if (!IsGdbServer ())
820 {
821 // Only supported on llgs
822 return SendUnimplementedResponse ("");
823 }
824
825 // Ensure we have a debugged process.
826 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
827 return SendErrorResponse (50);
828
829 if (log)
830 log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
831 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
832
833 // Ensure we can get info on the given thread.
834 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
835 if (!thread_sp)
836 return SendErrorResponse (51);
837
838 // Grab the reason this thread stopped.
839 struct ThreadStopInfo tid_stop_info;
840 if (!thread_sp->GetStopReason (tid_stop_info))
841 return SendErrorResponse (52);
842
843 const bool did_exec = tid_stop_info.reason == eStopReasonExec;
844 // FIXME implement register handling for exec'd inferiors.
845 // if (did_exec)
846 // {
847 // const bool force = true;
848 // InitializeRegisters(force);
849 // }
850
851 StreamString response;
852 // Output the T packet with the thread
853 response.PutChar ('T');
854 int signum = tid_stop_info.details.signal.signo;
855 if (log)
856 {
857 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
858 __FUNCTION__,
859 m_debugged_process_sp->GetID (),
860 tid,
861 signum,
862 tid_stop_info.reason,
863 tid_stop_info.details.exception.type);
864 }
865
866 switch (tid_stop_info.reason)
867 {
868 case eStopReasonSignal:
869 case eStopReasonException:
870 signum = thread_sp->TranslateStopInfoToGdbSignal (tid_stop_info);
871 break;
872 default:
873 signum = 0;
874 if (log)
875 {
876 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " has stop reason %d, using signo = 0 in stop reply response",
877 __FUNCTION__,
878 m_debugged_process_sp->GetID (),
879 tid,
880 tid_stop_info.reason);
881 }
882 break;
883 }
884
885 // Print the signal number.
886 response.PutHex8 (signum & 0xff);
887
888 // Include the tid.
889 response.Printf ("thread:%" PRIx64 ";", tid);
890
891 // Include the thread name if there is one.
Todd Fiala7206c6d2014-09-12 22:51:49 +0000892 const std::string thread_name = thread_sp->GetName ();
893 if (!thread_name.empty ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000894 {
Todd Fiala7206c6d2014-09-12 22:51:49 +0000895 size_t thread_name_len = thread_name.length ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000896
Todd Fiala7206c6d2014-09-12 22:51:49 +0000897 if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
Todd Fialaaf245d12014-06-30 21:05:18 +0000898 {
899 response.PutCString ("name:");
Todd Fiala7206c6d2014-09-12 22:51:49 +0000900 response.PutCString (thread_name.c_str ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000901 }
902 else
903 {
904 // The thread name contains special chars, send as hex bytes.
905 response.PutCString ("hexname:");
Todd Fiala7206c6d2014-09-12 22:51:49 +0000906 response.PutCStringAsRawHex8 (thread_name.c_str ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000907 }
908 response.PutChar (';');
909 }
910
911 // FIXME look for analog
912 // thread_identifier_info_data_t thread_ident_info;
913 // if (DNBThreadGetIdentifierInfo (pid, tid, &thread_ident_info))
914 // {
915 // if (thread_ident_info.dispatch_qaddr != 0)
916 // ostrm << std::hex << "qaddr:" << thread_ident_info.dispatch_qaddr << ';';
917 // }
918
919 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
920 // will send all thread IDs back in the "threads" key whose value is
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000921 // a list of hex thread IDs separated by commas:
Todd Fialaaf245d12014-06-30 21:05:18 +0000922 // "threads:10a,10b,10c;"
923 // This will save the debugger from having to send a pair of qfThreadInfo
924 // and qsThreadInfo packets, but it also might take a lot of room in the
925 // stop reply packet, so it must be enabled only on systems where there
926 // are no limits on packet lengths.
927 if (m_list_threads_in_stop_reply)
928 {
929 response.PutCString ("threads:");
930
931 uint32_t thread_index = 0;
932 NativeThreadProtocolSP listed_thread_sp;
933 for (listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index); listed_thread_sp; ++thread_index, listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
934 {
935 if (thread_index > 0)
936 response.PutChar (',');
937 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
938 }
939 response.PutChar (';');
940 }
941
942 //
943 // Expedite registers.
944 //
945
946 // Grab the register context.
947 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
948 if (reg_ctx_sp)
949 {
950 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
951 const RegisterSet *reg_set_p;
952 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
953 {
954 if (log)
955 log->Printf ("GDBRemoteCommunicationServer::%s expediting registers from set '%s' (registers set count: %zu)", __FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>", reg_set_p->num_registers);
956
957 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
958 {
959 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
960 if (reg_info_p == nullptr)
961 {
962 if (log)
963 log->Printf ("GDBRemoteCommunicationServer::%s failed to get register info for register set '%s', register index %" PRIu32, __FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>", *reg_num_p);
964 }
965 else if (reg_info_p->value_regs == nullptr)
966 {
967 // Only expediate registers that are not contained in other registers.
968 RegisterValue reg_value;
969 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
970 if (error.Success ())
971 WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
972 else
973 {
974 if (log)
975 log->Printf ("GDBRemoteCommunicationServer::%s failed to read register '%s' index %" PRIu32 ": %s", __FUNCTION__, reg_info_p->name ? reg_info_p->name : "<unnamed-register>", *reg_num_p, error.AsCString ());
976
977 }
978 }
979 }
980 }
981 }
982
983 if (did_exec)
984 {
985 response.PutCString ("reason:exec;");
986 }
987 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
988 {
989 response.PutCString ("metype:");
990 response.PutHex64 (tid_stop_info.details.exception.type);
991 response.PutCString (";mecount:");
992 response.PutHex32 (tid_stop_info.details.exception.data_count);
993 response.PutChar (';');
994
995 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
996 {
997 response.PutCString ("medata:");
998 response.PutHex64 (tid_stop_info.details.exception.data[i]);
999 response.PutChar (';');
1000 }
1001 }
1002
1003 return SendPacketNoLock (response.GetData(), response.GetSize());
1004}
1005
1006void
1007GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
1008{
1009 assert (process && "process cannot be NULL");
1010
1011 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1012 if (log)
1013 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1014
1015 // Send the exit result, and don't flush output.
1016 // Note: flushing output here would join the inferior stdio reflection thread, which
1017 // would gunk up the waitpid monitor thread that is calling this.
1018 PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
1019 if (result != PacketResult::Success)
1020 {
1021 if (log)
1022 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1023 }
1024
1025 // Remove the process from the list of spawned pids.
1026 {
1027 Mutex::Locker locker (m_spawned_pids_mutex);
1028 if (m_spawned_pids.erase (process->GetID ()) < 1)
1029 {
1030 if (log)
1031 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
1032
1033 }
1034 }
1035
1036 // FIXME can't do this yet - since process state propagation is currently
1037 // synchronous, it is running off the NativeProcessProtocol's innards and
1038 // will tear down the NPP while it still has code to execute.
1039#if 0
1040 // Clear the NativeProcessProtocol pointer.
1041 {
1042 Mutex::Locker locker (m_debugged_process_mutex);
1043 m_debugged_process_sp.reset();
1044 }
1045#endif
1046
1047 // Close the pipe to the inferior terminal i/o if we launched it
1048 // and set one up. Otherwise, 'k' and its flush of stdio could
1049 // end up waiting on a thread join that will never end. Consider
1050 // adding a timeout to the connection thread join call so we
1051 // can avoid that scenario altogether.
1052 MaybeCloseInferiorTerminalConnection ();
1053
1054 // We are ready to exit the debug monitor.
1055 m_exit_now = true;
1056}
1057
1058void
1059GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
1060{
1061 assert (process && "process cannot be NULL");
1062
1063 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1064 if (log)
1065 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1066
1067 // Send the stop reason unless this is the stop after the
1068 // launch or attach.
1069 switch (m_inferior_prev_state)
1070 {
1071 case eStateLaunching:
1072 case eStateAttaching:
1073 // Don't send anything per debugserver behavior.
1074 break;
1075 default:
1076 // In all other cases, send the stop reason.
1077 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
1078 if (result != PacketResult::Success)
1079 {
1080 if (log)
1081 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1082 }
1083 break;
1084 }
1085}
1086
1087void
1088GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
1089{
1090 assert (process && "process cannot be NULL");
1091 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1092 if (log)
1093 {
1094 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
1095 __FUNCTION__,
1096 process->GetID (),
1097 StateAsCString (state));
1098 }
1099
1100 switch (state)
1101 {
1102 case StateType::eStateExited:
1103 HandleInferiorState_Exited (process);
1104 break;
1105
1106 case StateType::eStateStopped:
1107 HandleInferiorState_Stopped (process);
1108 break;
1109
1110 default:
1111 if (log)
1112 {
1113 log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
1114 __FUNCTION__,
1115 process->GetID (),
1116 StateAsCString (state));
1117 }
1118 break;
1119 }
1120
1121 // Remember the previous state reported to us.
1122 m_inferior_prev_state = state;
1123}
1124
Todd Fialaa9882ce2014-08-28 15:46:54 +00001125void
1126GDBRemoteCommunicationServer::DidExec (NativeProcessProtocol *process)
1127{
1128 ClearProcessSpecificData ();
1129}
1130
Todd Fialaaf245d12014-06-30 21:05:18 +00001131GDBRemoteCommunication::PacketResult
1132GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len)
1133{
1134 if ((buffer == nullptr) || (len == 0))
1135 {
1136 // Nothing to send.
1137 return PacketResult::Success;
1138 }
1139
1140 StreamString response;
1141 response.PutChar ('O');
1142 response.PutBytesAsRawHex8 (buffer, len);
1143
1144 return SendPacketNoLock (response.GetData (), response.GetSize ());
1145}
1146
1147lldb_private::Error
1148GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd)
1149{
1150 Error error;
1151
1152 // Set up the Read Thread for reading/handling process I/O
1153 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
1154 if (!conn_up)
1155 {
1156 error.SetErrorString ("failed to create ConnectionFileDescriptor");
1157 return error;
1158 }
1159
1160 m_stdio_communication.SetConnection (conn_up.release());
1161 if (!m_stdio_communication.IsConnected ())
1162 {
1163 error.SetErrorString ("failed to set connection for inferior I/O communication");
1164 return error;
1165 }
1166
1167 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1168 m_stdio_communication.StartReadThread();
1169
1170 return error;
1171}
1172
1173void
1174GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1175{
1176 GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton);
1177 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
1178}
1179
Greg Clayton3dedae12013-12-06 21:45:27 +00001180GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001181GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
Greg Clayton576d8832011-03-22 04:00:09 +00001182{
Greg Clayton32e0a752011-03-30 18:16:51 +00001183 // TODO: Log the packet we aren't handling...
Greg Clayton37a0a242012-04-11 00:24:49 +00001184 return SendPacketNoLock ("", 0);
Greg Clayton576d8832011-03-22 04:00:09 +00001185}
1186
Todd Fialaaf245d12014-06-30 21:05:18 +00001187
Greg Clayton3dedae12013-12-06 21:45:27 +00001188GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001189GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
1190{
1191 char packet[16];
1192 int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
Andy Gibbsa297a972013-06-19 19:04:53 +00001193 assert (packet_len < (int)sizeof(packet));
Greg Clayton37a0a242012-04-11 00:24:49 +00001194 return SendPacketNoLock (packet, packet_len);
Greg Clayton32e0a752011-03-30 18:16:51 +00001195}
1196
Todd Fialaaf245d12014-06-30 21:05:18 +00001197GDBRemoteCommunication::PacketResult
1198GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message)
1199{
1200 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
1201 if (log)
1202 log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : "");
1203 return SendErrorResponse (0x03);
1204}
Greg Clayton32e0a752011-03-30 18:16:51 +00001205
Greg Clayton3dedae12013-12-06 21:45:27 +00001206GDBRemoteCommunication::PacketResult
Greg Clayton1cb64962011-03-24 04:28:38 +00001207GDBRemoteCommunicationServer::SendOKResponse ()
1208{
Greg Clayton37a0a242012-04-11 00:24:49 +00001209 return SendPacketNoLock ("OK", 2);
Greg Clayton1cb64962011-03-24 04:28:38 +00001210}
1211
1212bool
1213GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
1214{
Greg Clayton3dedae12013-12-06 21:45:27 +00001215 return GetAck() == PacketResult::Success;
Greg Clayton1cb64962011-03-24 04:28:38 +00001216}
Greg Clayton576d8832011-03-22 04:00:09 +00001217
Greg Clayton3dedae12013-12-06 21:45:27 +00001218GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001219GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
Greg Clayton576d8832011-03-22 04:00:09 +00001220{
1221 StreamString response;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001222
Greg Clayton576d8832011-03-22 04:00:09 +00001223 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
1224
Zachary Turner13b18262014-08-20 16:42:51 +00001225 ArchSpec host_arch(HostInfo::GetArchitecture());
Greg Clayton576d8832011-03-22 04:00:09 +00001226 const llvm::Triple &host_triple = host_arch.GetTriple();
Greg Clayton1cb64962011-03-24 04:28:38 +00001227 response.PutCString("triple:");
Greg Clayton44272a42014-09-18 00:18:32 +00001228 response.PutCStringAsRawHex8(host_triple.getTriple().c_str());
Greg Clayton1cb64962011-03-24 04:28:38 +00001229 response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001230
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001231 const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
1232 if (distribution_id)
1233 {
1234 response.PutCString("distribution_id:");
1235 response.PutCStringAsRawHex8(distribution_id);
1236 response.PutCString(";");
1237 }
1238
Todd Fialaaf245d12014-06-30 21:05:18 +00001239 // Only send out MachO info when lldb-platform/llgs is running on a MachO host.
1240#if defined(__APPLE__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001241 uint32_t cpu = host_arch.GetMachOCPUType();
1242 uint32_t sub = host_arch.GetMachOCPUSubType();
1243 if (cpu != LLDB_INVALID_CPUTYPE)
1244 response.Printf ("cputype:%u;", cpu);
1245 if (sub != LLDB_INVALID_CPUTYPE)
1246 response.Printf ("cpusubtype:%u;", sub);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001247
Enrico Granata1c5431a2012-07-13 23:55:22 +00001248 if (cpu == ArchSpec::kCore_arm_any)
Enrico Granataf04a2192012-07-13 23:18:48 +00001249 response.Printf("watchpoint_exceptions_received:before;"); // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
1250 else
1251 response.Printf("watchpoint_exceptions_received:after;");
Todd Fialaaf245d12014-06-30 21:05:18 +00001252#else
1253 response.Printf("watchpoint_exceptions_received:after;");
1254#endif
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001255
Greg Clayton576d8832011-03-22 04:00:09 +00001256 switch (lldb::endian::InlHostByteOrder())
1257 {
1258 case eByteOrderBig: response.PutCString ("endian:big;"); break;
1259 case eByteOrderLittle: response.PutCString ("endian:little;"); break;
1260 case eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1261 default: response.PutCString ("endian:unknown;"); break;
1262 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001263
Greg Clayton1cb64962011-03-24 04:28:38 +00001264 uint32_t major = UINT32_MAX;
1265 uint32_t minor = UINT32_MAX;
1266 uint32_t update = UINT32_MAX;
Zachary Turner97a14e62014-08-19 17:18:29 +00001267 if (HostInfo::GetOSVersion(major, minor, update))
Greg Clayton1cb64962011-03-24 04:28:38 +00001268 {
1269 if (major != UINT32_MAX)
1270 {
1271 response.Printf("os_version:%u", major);
1272 if (minor != UINT32_MAX)
1273 {
1274 response.Printf(".%u", minor);
1275 if (update != UINT32_MAX)
1276 response.Printf(".%u", update);
1277 }
1278 response.PutChar(';');
1279 }
1280 }
1281
1282 std::string s;
Zachary Turner97a14e62014-08-19 17:18:29 +00001283 if (HostInfo::GetOSBuildString(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001284 {
1285 response.PutCString ("os_build:");
1286 response.PutCStringAsRawHex8(s.c_str());
1287 response.PutChar(';');
1288 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001289 if (HostInfo::GetOSKernelDescription(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001290 {
1291 response.PutCString ("os_kernel:");
1292 response.PutCStringAsRawHex8(s.c_str());
1293 response.PutChar(';');
1294 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001295
Greg Clayton2b98c562013-11-22 18:53:12 +00001296#if defined(__APPLE__)
1297
Todd Fiala013434e2014-07-09 01:29:05 +00001298#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001299 // For iOS devices, we are connected through a USB Mux so we never pretend
1300 // to actually have a hostname as far as the remote lldb that is connecting
1301 // to this lldb-platform is concerned
1302 response.PutCString ("hostname:");
Greg Clayton16810922014-02-27 19:38:18 +00001303 response.PutCStringAsRawHex8("127.0.0.1");
Greg Clayton2b98c562013-11-22 18:53:12 +00001304 response.PutChar(';');
Todd Fiala013434e2014-07-09 01:29:05 +00001305#else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001306 if (HostInfo::GetHostname(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001307 {
1308 response.PutCString ("hostname:");
1309 response.PutCStringAsRawHex8(s.c_str());
1310 response.PutChar(';');
1311 }
Todd Fiala013434e2014-07-09 01:29:05 +00001312#endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001313
1314#else // #if defined(__APPLE__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001315 if (HostInfo::GetHostname(s))
Greg Clayton2b98c562013-11-22 18:53:12 +00001316 {
1317 response.PutCString ("hostname:");
1318 response.PutCStringAsRawHex8(s.c_str());
1319 response.PutChar(';');
1320 }
1321#endif // #if defined(__APPLE__)
1322
Greg Clayton3dedae12013-12-06 21:45:27 +00001323 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001324}
Greg Clayton1cb64962011-03-24 04:28:38 +00001325
Greg Clayton32e0a752011-03-30 18:16:51 +00001326static void
Greg Clayton8b82f082011-04-12 05:54:46 +00001327CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
Greg Clayton32e0a752011-03-30 18:16:51 +00001328{
Daniel Malead01b2952012-11-29 21:49:15 +00001329 response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
Greg Clayton32e0a752011-03-30 18:16:51 +00001330 proc_info.GetProcessID(),
1331 proc_info.GetParentProcessID(),
Greg Clayton8b82f082011-04-12 05:54:46 +00001332 proc_info.GetUserID(),
1333 proc_info.GetGroupID(),
Greg Clayton32e0a752011-03-30 18:16:51 +00001334 proc_info.GetEffectiveUserID(),
1335 proc_info.GetEffectiveGroupID());
1336 response.PutCString ("name:");
1337 response.PutCStringAsRawHex8(proc_info.GetName());
1338 response.PutChar(';');
1339 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1340 if (proc_arch.IsValid())
1341 {
1342 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1343 response.PutCString("triple:");
Greg Clayton44272a42014-09-18 00:18:32 +00001344 response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001345 response.PutChar(';');
1346 }
1347}
Greg Clayton1cb64962011-03-24 04:28:38 +00001348
Todd Fialaaf245d12014-06-30 21:05:18 +00001349static void
1350CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response)
1351{
1352 response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1353 proc_info.GetProcessID(),
1354 proc_info.GetParentProcessID(),
1355 proc_info.GetUserID(),
1356 proc_info.GetGroupID(),
1357 proc_info.GetEffectiveUserID(),
1358 proc_info.GetEffectiveGroupID());
1359
1360 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1361 if (proc_arch.IsValid())
1362 {
Todd Fialac540dd02014-08-26 18:21:02 +00001363 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1364#if defined(__APPLE__)
1365 // We'll send cputype/cpusubtype.
Todd Fialaaf245d12014-06-30 21:05:18 +00001366 const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1367 if (cpu_type != 0)
1368 response.Printf ("cputype:%" PRIx32 ";", cpu_type);
1369
1370 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1371 if (cpu_subtype != 0)
1372 response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype);
Todd Fialac540dd02014-08-26 18:21:02 +00001373
Todd Fialaaf245d12014-06-30 21:05:18 +00001374
Todd Fialaaf245d12014-06-30 21:05:18 +00001375 const std::string vendor = proc_triple.getVendorName ();
1376 if (!vendor.empty ())
1377 response.Printf ("vendor:%s;", vendor.c_str ());
Todd Fialac540dd02014-08-26 18:21:02 +00001378#else
1379 // We'll send the triple.
Greg Clayton44272a42014-09-18 00:18:32 +00001380 response.PutCString("triple:");
1381 response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1382 response.PutChar(';');
1383
Todd Fialac540dd02014-08-26 18:21:02 +00001384#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001385 std::string ostype = proc_triple.getOSName ();
1386 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1387 if (proc_triple.getVendor () == llvm::Triple::Apple)
1388 {
1389 switch (proc_triple.getArch ())
1390 {
1391 case llvm::Triple::arm:
Todd Fialad8eaa172014-07-23 14:37:35 +00001392 case llvm::Triple::aarch64:
Todd Fialaaf245d12014-06-30 21:05:18 +00001393 ostype = "ios";
1394 break;
1395 default:
1396 // No change.
1397 break;
1398 }
1399 }
1400 response.Printf ("ostype:%s;", ostype.c_str ());
1401
1402
1403 switch (proc_arch.GetByteOrder ())
1404 {
1405 case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break;
1406 case lldb::eByteOrderBig: response.PutCString ("endian:big;"); break;
1407 case lldb::eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1408 default:
1409 // Nothing.
1410 break;
1411 }
1412
1413 if (proc_triple.isArch64Bit ())
1414 response.PutCString ("ptrsize:8;");
1415 else if (proc_triple.isArch32Bit ())
1416 response.PutCString ("ptrsize:4;");
1417 else if (proc_triple.isArch16Bit ())
1418 response.PutCString ("ptrsize:2;");
1419 }
1420
1421}
1422
1423
1424GDBRemoteCommunication::PacketResult
1425GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1426{
1427 // Only the gdb server handles this.
1428 if (!IsGdbServer ())
1429 return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
1430
1431 // Fail if we don't have a current process.
1432 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1433 return SendErrorResponse (68);
1434
1435 ProcessInstanceInfo proc_info;
1436 if (Host::GetProcessInfo (m_debugged_process_sp->GetID (), proc_info))
1437 {
1438 StreamString response;
1439 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1440 return SendPacketNoLock (response.GetData (), response.GetSize ());
1441 }
1442
1443 return SendErrorResponse (1);
1444}
1445
Greg Clayton3dedae12013-12-06 21:45:27 +00001446GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001447GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
Greg Clayton1cb64962011-03-24 04:28:38 +00001448{
Greg Clayton32e0a752011-03-30 18:16:51 +00001449 // Packet format: "qProcessInfoPID:%i" where %i is the pid
Greg Clayton8b82f082011-04-12 05:54:46 +00001450 packet.SetFilePos(::strlen ("qProcessInfoPID:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001451 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
1452 if (pid != LLDB_INVALID_PROCESS_ID)
1453 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001454 ProcessInstanceInfo proc_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001455 if (Host::GetProcessInfo(pid, proc_info))
1456 {
1457 StreamString response;
1458 CreateProcessInfoResponse (proc_info, response);
Greg Clayton37a0a242012-04-11 00:24:49 +00001459 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001460 }
1461 }
1462 return SendErrorResponse (1);
1463}
1464
Greg Clayton3dedae12013-12-06 21:45:27 +00001465GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001466GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
1467{
1468 m_proc_infos_index = 0;
1469 m_proc_infos.Clear();
1470
Greg Clayton8b82f082011-04-12 05:54:46 +00001471 ProcessInstanceInfoMatch match_info;
1472 packet.SetFilePos(::strlen ("qfProcessInfo"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001473 if (packet.GetChar() == ':')
1474 {
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001475
Greg Clayton32e0a752011-03-30 18:16:51 +00001476 std::string key;
1477 std::string value;
1478 while (packet.GetNameColonValue(key, value))
1479 {
1480 bool success = true;
1481 if (key.compare("name") == 0)
1482 {
1483 StringExtractor extractor;
1484 extractor.GetStringRef().swap(value);
1485 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001486 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001487 }
1488 else if (key.compare("name_match") == 0)
1489 {
1490 if (value.compare("equals") == 0)
1491 {
1492 match_info.SetNameMatchType (eNameMatchEquals);
1493 }
1494 else if (value.compare("starts_with") == 0)
1495 {
1496 match_info.SetNameMatchType (eNameMatchStartsWith);
1497 }
1498 else if (value.compare("ends_with") == 0)
1499 {
1500 match_info.SetNameMatchType (eNameMatchEndsWith);
1501 }
1502 else if (value.compare("contains") == 0)
1503 {
1504 match_info.SetNameMatchType (eNameMatchContains);
1505 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001506 else if (value.compare("regex") == 0)
Greg Clayton32e0a752011-03-30 18:16:51 +00001507 {
1508 match_info.SetNameMatchType (eNameMatchRegularExpression);
1509 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001510 else
Greg Clayton32e0a752011-03-30 18:16:51 +00001511 {
1512 success = false;
1513 }
1514 }
1515 else if (key.compare("pid") == 0)
1516 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001517 match_info.GetProcessInfo().SetProcessID (StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001518 }
1519 else if (key.compare("parent_pid") == 0)
1520 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001521 match_info.GetProcessInfo().SetParentProcessID (StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001522 }
1523 else if (key.compare("uid") == 0)
1524 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001525 match_info.GetProcessInfo().SetUserID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001526 }
1527 else if (key.compare("gid") == 0)
1528 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001529 match_info.GetProcessInfo().SetGroupID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001530 }
1531 else if (key.compare("euid") == 0)
1532 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001533 match_info.GetProcessInfo().SetEffectiveUserID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001534 }
1535 else if (key.compare("egid") == 0)
1536 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001537 match_info.GetProcessInfo().SetEffectiveGroupID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001538 }
1539 else if (key.compare("all_users") == 0)
1540 {
1541 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
1542 }
1543 else if (key.compare("triple") == 0)
1544 {
Greg Claytoneb0103f2011-04-07 22:46:35 +00001545 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
Greg Clayton32e0a752011-03-30 18:16:51 +00001546 }
1547 else
1548 {
1549 success = false;
1550 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001551
Greg Clayton32e0a752011-03-30 18:16:51 +00001552 if (!success)
1553 return SendErrorResponse (2);
1554 }
1555 }
1556
1557 if (Host::FindProcesses (match_info, m_proc_infos))
1558 {
1559 // We found something, return the first item by calling the get
1560 // subsequent process info packet handler...
1561 return Handle_qsProcessInfo (packet);
1562 }
1563 return SendErrorResponse (3);
1564}
1565
Greg Clayton3dedae12013-12-06 21:45:27 +00001566GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001567GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
1568{
1569 if (m_proc_infos_index < m_proc_infos.GetSize())
1570 {
1571 StreamString response;
1572 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
1573 ++m_proc_infos_index;
Greg Clayton37a0a242012-04-11 00:24:49 +00001574 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001575 }
1576 return SendErrorResponse (4);
1577}
1578
Greg Clayton3dedae12013-12-06 21:45:27 +00001579GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001580GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
1581{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001582#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001583 // Packet format: "qUserName:%i" where %i is the uid
Greg Clayton8b82f082011-04-12 05:54:46 +00001584 packet.SetFilePos(::strlen ("qUserName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001585 uint32_t uid = packet.GetU32 (UINT32_MAX);
1586 if (uid != UINT32_MAX)
1587 {
1588 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001589 if (HostInfo::LookupUserName(uid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001590 {
1591 StreamString response;
1592 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001593 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001594 }
1595 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001596#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001597 return SendErrorResponse (5);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001598
Greg Clayton32e0a752011-03-30 18:16:51 +00001599}
1600
Greg Clayton3dedae12013-12-06 21:45:27 +00001601GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001602GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
1603{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001604#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001605 // Packet format: "qGroupName:%i" where %i is the gid
Greg Clayton8b82f082011-04-12 05:54:46 +00001606 packet.SetFilePos(::strlen ("qGroupName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001607 uint32_t gid = packet.GetU32 (UINT32_MAX);
1608 if (gid != UINT32_MAX)
1609 {
1610 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001611 if (HostInfo::LookupGroupName(gid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001612 {
1613 StreamString response;
1614 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001615 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001616 }
1617 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001618#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001619 return SendErrorResponse (6);
1620}
1621
Greg Clayton3dedae12013-12-06 21:45:27 +00001622GDBRemoteCommunication::PacketResult
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001623GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
1624{
Greg Clayton8b82f082011-04-12 05:54:46 +00001625 packet.SetFilePos(::strlen ("qSpeedTest:"));
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001626
1627 std::string key;
1628 std::string value;
1629 bool success = packet.GetNameColonValue(key, value);
1630 if (success && key.compare("response_size") == 0)
1631 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001632 uint32_t response_size = StringConvert::ToUInt32(value.c_str(), 0, 0, &success);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001633 if (success)
1634 {
1635 if (response_size == 0)
1636 return SendOKResponse();
1637 StreamString response;
1638 uint32_t bytes_left = response_size;
1639 response.PutCString("data:");
1640 while (bytes_left > 0)
1641 {
1642 if (bytes_left >= 26)
1643 {
1644 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1645 bytes_left -= 26;
1646 }
1647 else
1648 {
1649 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1650 bytes_left = 0;
1651 }
1652 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001653 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001654 }
1655 }
1656 return SendErrorResponse (7);
1657}
Greg Clayton8b82f082011-04-12 05:54:46 +00001658
Greg Clayton8b82f082011-04-12 05:54:46 +00001659//
1660//static bool
1661//WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
1662//{
1663// const int time_delta_usecs = 100000;
1664// const int num_retries = timeout_in_seconds/time_delta_usecs;
1665// for (int i=0; i<num_retries; i++)
1666// {
1667// struct proc_bsdinfo bsd_info;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001668// int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
1669// (uint64_t) 0,
1670// &bsd_info,
Greg Clayton8b82f082011-04-12 05:54:46 +00001671// PROC_PIDTBSDINFO_SIZE);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001672//
Greg Clayton8b82f082011-04-12 05:54:46 +00001673// switch (error)
1674// {
1675// case EINVAL:
1676// case ENOTSUP:
1677// case ESRCH:
1678// case EPERM:
1679// return false;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001680//
Greg Clayton8b82f082011-04-12 05:54:46 +00001681// default:
1682// break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001683//
Greg Clayton8b82f082011-04-12 05:54:46 +00001684// case 0:
1685// if (bsd_info.pbi_status == SSTOP)
1686// return true;
1687// }
1688// ::usleep (time_delta_usecs);
1689// }
1690// return false;
1691//}
1692
Greg Clayton3dedae12013-12-06 21:45:27 +00001693GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001694GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
1695{
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001696 // The 'A' packet is the most over designed packet ever here with
1697 // redundant argument indexes, redundant argument lengths and needed hex
1698 // encoded argument string values. Really all that is needed is a comma
Greg Clayton8b82f082011-04-12 05:54:46 +00001699 // separated hex encoded argument value list, but we will stay true to the
1700 // documented version of the 'A' packet here...
1701
Todd Fialaaf245d12014-06-30 21:05:18 +00001702 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1703 int actual_arg_index = 0;
1704
Greg Clayton8b82f082011-04-12 05:54:46 +00001705 packet.SetFilePos(1); // Skip the 'A'
1706 bool success = true;
1707 while (success && packet.GetBytesLeft() > 0)
1708 {
1709 // Decode the decimal argument string length. This length is the
1710 // number of hex nibbles in the argument string value.
1711 const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1712 if (arg_len == UINT32_MAX)
1713 success = false;
1714 else
1715 {
1716 // Make sure the argument hex string length is followed by a comma
1717 if (packet.GetChar() != ',')
1718 success = false;
1719 else
1720 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001721 // Decode the argument index. We ignore this really because
Greg Clayton8b82f082011-04-12 05:54:46 +00001722 // who would really send down the arguments in a random order???
1723 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1724 if (arg_idx == UINT32_MAX)
1725 success = false;
1726 else
1727 {
1728 // Make sure the argument index is followed by a comma
1729 if (packet.GetChar() != ',')
1730 success = false;
1731 else
1732 {
1733 // Decode the argument string value from hex bytes
1734 // back into a UTF8 string and make sure the length
1735 // matches the one supplied in the packet
1736 std::string arg;
Todd Fialaaf245d12014-06-30 21:05:18 +00001737 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2))
Greg Clayton8b82f082011-04-12 05:54:46 +00001738 success = false;
1739 else
1740 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001741 // If there are any bytes left
Greg Clayton8b82f082011-04-12 05:54:46 +00001742 if (packet.GetBytesLeft())
1743 {
1744 if (packet.GetChar() != ',')
1745 success = false;
1746 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001747
Greg Clayton8b82f082011-04-12 05:54:46 +00001748 if (success)
1749 {
1750 if (arg_idx == 0)
1751 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
1752 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001753 if (log)
1754 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ());
1755 ++actual_arg_index;
Greg Clayton8b82f082011-04-12 05:54:46 +00001756 }
1757 }
1758 }
1759 }
1760 }
1761 }
1762 }
1763
1764 if (success)
1765 {
Todd Fiala9f377372014-01-27 20:44:50 +00001766 m_process_launch_error = LaunchProcess ();
Greg Clayton8b82f082011-04-12 05:54:46 +00001767 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1768 {
1769 return SendOKResponse ();
1770 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001771 else
1772 {
1773 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1774 if (log)
1775 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s",
1776 __FUNCTION__,
1777 m_process_launch_error.AsCString());
1778
1779 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001780 }
1781 return SendErrorResponse (8);
1782}
1783
Greg Clayton3dedae12013-12-06 21:45:27 +00001784GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001785GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
1786{
Greg Clayton8b82f082011-04-12 05:54:46 +00001787 StreamString response;
Todd Fialaaf245d12014-06-30 21:05:18 +00001788
1789 if (IsGdbServer ())
Greg Clayton8b82f082011-04-12 05:54:46 +00001790 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001791 // Fail if we don't have a current process.
1792 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1793 return SendErrorResponse (68);
1794
1795 // Make sure we set the current thread so g and p packets return
1796 // the data the gdb will expect.
1797 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1798 SetCurrentThreadID (tid);
1799
1800 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1801 if (!thread_sp)
1802 return SendErrorResponse (69);
1803
1804 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1805 }
1806 else
1807 {
1808 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here
1809 // should not be used. It is reporting process id instead of thread id. The
1810 // correct answer doesn't seem to make much sense for lldb-platform.
1811 // CONSIDER: flip to "unsupported".
1812 lldb::pid_t pid = m_process_launch_info.GetProcessID();
1813 response.Printf("QC%" PRIx64, pid);
1814
1815 // this should always be platform here
1816 assert (m_is_platform && "this code path should only be traversed for lldb-platform");
1817
1818 if (m_is_platform)
Greg Clayton8b82f082011-04-12 05:54:46 +00001819 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001820 // If we launch a process and this GDB server is acting as a platform,
1821 // then we need to clear the process launch state so we can start
1822 // launching another process. In order to launch a process a bunch or
1823 // packets need to be sent: environment packets, working directory,
1824 // disable ASLR, and many more settings. When we launch a process we
1825 // then need to know when to clear this information. Currently we are
1826 // selecting the 'qC' packet as that packet which seems to make the most
1827 // sense.
1828 if (pid != LLDB_INVALID_PROCESS_ID)
1829 {
1830 m_process_launch_info.Clear();
1831 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001832 }
1833 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001834 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00001835}
1836
1837bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00001838GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
1839{
1840 Mutex::Locker locker (m_spawned_pids_mutex);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001841 FreePortForProcess(pid);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001842 return m_spawned_pids.erase(pid) > 0;
1843}
1844bool
1845GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
1846 lldb::pid_t pid,
1847 bool exited,
1848 int signal, // Zero for no signal
1849 int status) // Exit value of process if signal is zero
1850{
1851 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1852 server->DebugserverProcessReaped (pid);
1853 return true;
1854}
1855
Todd Fiala3e92a2b2014-01-24 00:52:53 +00001856bool
1857GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
1858{
1859 // reap a process that we were debugging (but not debugserver)
1860 Mutex::Locker locker (m_spawned_pids_mutex);
1861 return m_spawned_pids.erase(pid) > 0;
1862}
1863
1864bool
1865GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
1866 lldb::pid_t pid,
1867 bool exited,
1868 int signal, // Zero for no signal
1869 int status) // Exit value of process if signal is zero
1870{
1871 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1872 server->DebuggedProcessReaped (pid);
1873 return true;
1874}
1875
Greg Clayton3dedae12013-12-06 21:45:27 +00001876GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001877GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
1878{
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001879#ifdef _WIN32
Deepak Panickal263fde02014-01-14 11:34:44 +00001880 return SendErrorResponse(9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001881#else
Todd Fiala015d8182014-07-22 23:41:36 +00001882 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1883
Greg Clayton8b82f082011-04-12 05:54:46 +00001884 // Spawn a local debugserver as a platform so we can then attach or launch
1885 // a process...
1886
1887 if (m_is_platform)
1888 {
Todd Fiala015d8182014-07-22 23:41:36 +00001889 if (log)
1890 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
1891
Greg Clayton8b82f082011-04-12 05:54:46 +00001892 // Sleep and wait a bit for debugserver to start to listen...
1893 ConnectionFileDescriptor file_conn;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001894 std::string hostname;
Sylvestre Ledrufaa63ce2013-09-28 15:57:37 +00001895 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001896 // with the TMPDIR environment variable
Greg Clayton29b8fc42013-11-21 01:44:58 +00001897 packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
1898 std::string name;
1899 std::string value;
1900 uint16_t port = UINT16_MAX;
1901 while (packet.GetNameColonValue(name, value))
Greg Clayton8b82f082011-04-12 05:54:46 +00001902 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001903 if (name.compare ("host") == 0)
1904 hostname.swap(value);
1905 else if (name.compare ("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00001906 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00001907 }
Greg Clayton29b8fc42013-11-21 01:44:58 +00001908 if (port == UINT16_MAX)
1909 port = GetNextAvailablePort();
1910
1911 // Spawn a new thread to accept the port that gets bound after
1912 // binding to port 0 (zero).
Greg Claytonfbb76342013-11-20 21:07:01 +00001913
Vince Harron1b5a74e2015-01-21 22:42:49 +00001914 // ignore the hostname send from the remote end, just use the ip address
1915 // that we're currently communicating with as the hostname
1916
Todd Fiala015d8182014-07-22 23:41:36 +00001917 // Spawn a debugserver and try to get the port it listens to.
1918 ProcessLaunchInfo debugserver_launch_info;
1919 if (hostname.empty())
1920 hostname = "127.0.0.1";
1921 if (log)
1922 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
1923
1924 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
1925
Vince Harron1b5a74e2015-01-21 22:42:49 +00001926 std::string platform_scheme;
1927 std::string platform_ip;
1928 int platform_port;
1929 std::string platform_path;
1930 bool ok = UriParser::Parse(GetConnection()->GetURI().c_str(), platform_scheme, platform_ip, platform_port, platform_path);
1931 assert(ok);
1932 Error error = StartDebugserverProcess (
1933 platform_ip.c_str(),
Todd Fiala015d8182014-07-22 23:41:36 +00001934 port,
1935 debugserver_launch_info,
1936 port);
1937
1938 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
1939
1940
1941 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1942 {
1943 Mutex::Locker locker (m_spawned_pids_mutex);
1944 m_spawned_pids.insert(debugserver_pid);
1945 if (port > 0)
1946 AssociatePortWithProcess(port, debugserver_pid);
1947 }
1948 else
1949 {
1950 if (port > 0)
1951 FreePort (port);
1952 }
1953
Greg Clayton29b8fc42013-11-21 01:44:58 +00001954 if (error.Success())
1955 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001956 if (log)
Todd Fiala015d8182014-07-22 23:41:36 +00001957 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001958
Todd Fiala015d8182014-07-22 23:41:36 +00001959 char response[256];
1960 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
1961 assert (response_len < (int)sizeof(response));
1962 PacketResult packet_result = SendPacketNoLock (response, response_len);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001963
Todd Fiala015d8182014-07-22 23:41:36 +00001964 if (packet_result != PacketResult::Success)
Greg Clayton29b8fc42013-11-21 01:44:58 +00001965 {
Todd Fiala015d8182014-07-22 23:41:36 +00001966 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1967 ::kill (debugserver_pid, SIGINT);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001968 }
Todd Fiala015d8182014-07-22 23:41:36 +00001969 return packet_result;
1970 }
1971 else
1972 {
1973 if (log)
1974 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ());
Greg Clayton8b82f082011-04-12 05:54:46 +00001975 }
1976 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001977 return SendErrorResponse (9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001978#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00001979}
1980
Todd Fiala403edc52014-01-23 22:05:44 +00001981bool
1982GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
1983{
1984 // make sure we know about this process
1985 {
1986 Mutex::Locker locker (m_spawned_pids_mutex);
1987 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1988 return false;
1989 }
1990
1991 // first try a SIGTERM (standard kill)
1992 Host::Kill (pid, SIGTERM);
1993
1994 // check if that worked
1995 for (size_t i=0; i<10; ++i)
1996 {
1997 {
1998 Mutex::Locker locker (m_spawned_pids_mutex);
1999 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2000 {
2001 // it is now killed
2002 return true;
2003 }
2004 }
2005 usleep (10000);
2006 }
2007
2008 // check one more time after the final usleep
2009 {
2010 Mutex::Locker locker (m_spawned_pids_mutex);
2011 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2012 return true;
2013 }
2014
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002015 // the launched process still lives. Now try killing it again,
Todd Fiala403edc52014-01-23 22:05:44 +00002016 // this time with an unblockable signal.
2017 Host::Kill (pid, SIGKILL);
2018
2019 for (size_t i=0; i<10; ++i)
2020 {
2021 {
2022 Mutex::Locker locker (m_spawned_pids_mutex);
2023 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2024 {
2025 // it is now killed
2026 return true;
2027 }
2028 }
2029 usleep (10000);
2030 }
2031
2032 // check one more time after the final usleep
2033 // Scope for locker
2034 {
2035 Mutex::Locker locker (m_spawned_pids_mutex);
2036 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2037 return true;
2038 }
2039
2040 // no luck - the process still lives
2041 return false;
2042}
2043
Greg Clayton3dedae12013-12-06 21:45:27 +00002044GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002045GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
2046{
Todd Fiala403edc52014-01-23 22:05:44 +00002047 packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002048
Todd Fiala403edc52014-01-23 22:05:44 +00002049 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
2050
2051 // verify that we know anything about this pid.
2052 // Scope for locker
Daniel Maleae0f8f572013-08-26 23:57:52 +00002053 {
Todd Fiala403edc52014-01-23 22:05:44 +00002054 Mutex::Locker locker (m_spawned_pids_mutex);
2055 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002056 {
Todd Fiala403edc52014-01-23 22:05:44 +00002057 // not a pid we know about
2058 return SendErrorResponse (10);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002059 }
2060 }
Todd Fiala403edc52014-01-23 22:05:44 +00002061
2062 // go ahead and attempt to kill the spawned process
2063 if (KillSpawnedProcess (pid))
2064 return SendOKResponse ();
2065 else
2066 return SendErrorResponse (11);
2067}
2068
2069GDBRemoteCommunication::PacketResult
2070GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
2071{
2072 // ignore for now if we're lldb_platform
2073 if (m_is_platform)
2074 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2075
2076 // shutdown all spawned processes
2077 std::set<lldb::pid_t> spawned_pids_copy;
2078
2079 // copy pids
2080 {
2081 Mutex::Locker locker (m_spawned_pids_mutex);
2082 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
2083 }
2084
2085 // nuke the spawned processes
2086 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
2087 {
2088 lldb::pid_t spawned_pid = *it;
2089 if (!KillSpawnedProcess (spawned_pid))
2090 {
2091 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
2092 }
2093 }
2094
Todd Fialaaf245d12014-06-30 21:05:18 +00002095 FlushInferiorOutput ();
2096
2097 // No OK response for kill packet.
2098 // return SendOKResponse ();
2099 return PacketResult::Success;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002100}
2101
Greg Clayton3dedae12013-12-06 21:45:27 +00002102GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002103GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
2104{
2105 if (m_process_launch_error.Success())
2106 return SendOKResponse();
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002107 StreamString response;
Greg Clayton8b82f082011-04-12 05:54:46 +00002108 response.PutChar('E');
2109 response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
Greg Clayton37a0a242012-04-11 00:24:49 +00002110 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00002111}
2112
Greg Clayton3dedae12013-12-06 21:45:27 +00002113GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002114GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet)
2115{
2116 packet.SetFilePos(::strlen ("QEnvironment:"));
2117 const uint32_t bytes_left = packet.GetBytesLeft();
2118 if (bytes_left > 0)
2119 {
2120 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
2121 return SendOKResponse ();
2122 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002123 return SendErrorResponse (12);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002124}
2125
Greg Clayton3dedae12013-12-06 21:45:27 +00002126GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002127GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
2128{
2129 packet.SetFilePos(::strlen ("QLaunchArch:"));
2130 const uint32_t bytes_left = packet.GetBytesLeft();
2131 if (bytes_left > 0)
2132 {
2133 const char* arch_triple = packet.Peek();
2134 ArchSpec arch_spec(arch_triple,NULL);
2135 m_process_launch_info.SetArchitecture(arch_spec);
2136 return SendOKResponse();
2137 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002138 return SendErrorResponse(13);
Greg Clayton8b82f082011-04-12 05:54:46 +00002139}
2140
Greg Clayton3dedae12013-12-06 21:45:27 +00002141GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002142GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
2143{
2144 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
2145 if (packet.GetU32(0))
2146 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
2147 else
2148 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
2149 return SendOKResponse ();
2150}
2151
Greg Clayton3dedae12013-12-06 21:45:27 +00002152GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002153GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
2154{
2155 packet.SetFilePos(::strlen ("QSetWorkingDir:"));
2156 std::string path;
2157 packet.GetHexByteString(path);
Greg Claytonfbb76342013-11-20 21:07:01 +00002158 if (m_is_platform)
2159 {
Colin Riley909bb7a2013-11-26 15:10:46 +00002160#ifdef _WIN32
2161 // Not implemented on Windows
2162 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
2163#else
Greg Claytonfbb76342013-11-20 21:07:01 +00002164 // If this packet is sent to a platform, then change the current working directory
2165 if (::chdir(path.c_str()) != 0)
2166 return SendErrorResponse(errno);
Colin Riley909bb7a2013-11-26 15:10:46 +00002167#endif
Greg Claytonfbb76342013-11-20 21:07:01 +00002168 }
2169 else
2170 {
2171 m_process_launch_info.SwapWorkingDirectory (path);
2172 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002173 return SendOKResponse ();
2174}
2175
Greg Clayton3dedae12013-12-06 21:45:27 +00002176GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002177GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
2178{
2179 StreamString response;
2180
2181 if (m_is_platform)
2182 {
2183 // If this packet is sent to a platform, then change the current working directory
2184 char cwd[PATH_MAX];
2185 if (getcwd(cwd, sizeof(cwd)) == NULL)
2186 {
2187 return SendErrorResponse(errno);
2188 }
2189 else
2190 {
2191 response.PutBytesAsRawHex8(cwd, strlen(cwd));
Greg Clayton3dedae12013-12-06 21:45:27 +00002192 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002193 }
2194 }
2195 else
2196 {
2197 const char *working_dir = m_process_launch_info.GetWorkingDirectory();
2198 if (working_dir && working_dir[0])
2199 {
2200 response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
Greg Clayton3dedae12013-12-06 21:45:27 +00002201 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002202 }
2203 else
2204 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002205 return SendErrorResponse(14);
Greg Claytonfbb76342013-11-20 21:07:01 +00002206 }
2207 }
2208}
2209
Greg Clayton3dedae12013-12-06 21:45:27 +00002210GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002211GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
2212{
2213 packet.SetFilePos(::strlen ("QSetSTDIN:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002214 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002215 std::string path;
2216 packet.GetHexByteString(path);
2217 const bool read = false;
2218 const bool write = true;
2219 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
2220 {
2221 m_process_launch_info.AppendFileAction(file_action);
2222 return SendOKResponse ();
2223 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002224 return SendErrorResponse (15);
Greg Clayton8b82f082011-04-12 05:54:46 +00002225}
2226
Greg Clayton3dedae12013-12-06 21:45:27 +00002227GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002228GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
2229{
2230 packet.SetFilePos(::strlen ("QSetSTDOUT:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002231 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002232 std::string path;
2233 packet.GetHexByteString(path);
2234 const bool read = true;
2235 const bool write = false;
2236 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
2237 {
2238 m_process_launch_info.AppendFileAction(file_action);
2239 return SendOKResponse ();
2240 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002241 return SendErrorResponse (16);
Greg Clayton8b82f082011-04-12 05:54:46 +00002242}
2243
Greg Clayton3dedae12013-12-06 21:45:27 +00002244GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002245GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
2246{
2247 packet.SetFilePos(::strlen ("QSetSTDERR:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002248 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002249 std::string path;
2250 packet.GetHexByteString(path);
2251 const bool read = true;
Greg Clayton9845a8d2012-03-06 04:01:04 +00002252 const bool write = false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002253 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
2254 {
2255 m_process_launch_info.AppendFileAction(file_action);
2256 return SendOKResponse ();
2257 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002258 return SendErrorResponse (17);
Greg Clayton8b82f082011-04-12 05:54:46 +00002259}
2260
Greg Clayton3dedae12013-12-06 21:45:27 +00002261GDBRemoteCommunication::PacketResult
Todd Fialaaf245d12014-06-30 21:05:18 +00002262GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet)
2263{
2264 if (!IsGdbServer ())
2265 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2266
2267 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2268 if (log)
2269 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2270
2271 // Ensure we have a native process.
2272 if (!m_debugged_process_sp)
2273 {
2274 if (log)
2275 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2276 return SendErrorResponse (0x36);
2277 }
2278
2279 // Pull out the signal number.
2280 packet.SetFilePos (::strlen ("C"));
2281 if (packet.GetBytesLeft () < 1)
2282 {
2283 // Shouldn't be using a C without a signal.
2284 return SendIllFormedResponse (packet, "C packet specified without signal.");
2285 }
2286 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2287 if (signo == std::numeric_limits<uint32_t>::max ())
2288 return SendIllFormedResponse (packet, "failed to parse signal number");
2289
2290 // Handle optional continue address.
2291 if (packet.GetBytesLeft () > 0)
2292 {
2293 // FIXME add continue at address support for $C{signo}[;{continue-address}].
2294 if (*packet.Peek () == ';')
2295 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2296 else
2297 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
2298 }
2299
2300 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
2301 Error error;
2302
2303 // We have two branches: what to do if a continue thread is specified (in which case we target
2304 // sending the signal to that thread), or when we don't have a continue thread set (in which
2305 // case we send a signal to the process).
2306
2307 // TODO discuss with Greg Clayton, make sure this makes sense.
2308
2309 lldb::tid_t signal_tid = GetContinueThreadID ();
2310 if (signal_tid != LLDB_INVALID_THREAD_ID)
2311 {
2312 // The resume action for the continue thread (or all threads if a continue thread is not set).
2313 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
2314
2315 // Add the action for the continue thread (or all threads when the continue thread isn't present).
2316 resume_actions.Append (action);
2317 }
2318 else
2319 {
2320 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
2321 error = m_debugged_process_sp->Signal (signo);
2322 if (error.Fail ())
2323 {
2324 if (log)
2325 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s",
2326 __FUNCTION__,
2327 m_debugged_process_sp->GetID (),
2328 error.AsCString ());
2329
2330 return SendErrorResponse (0x52);
2331 }
2332 }
2333
2334 // Resume the threads.
2335 error = m_debugged_process_sp->Resume (resume_actions);
2336 if (error.Fail ())
2337 {
2338 if (log)
2339 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s",
2340 __FUNCTION__,
2341 m_debugged_process_sp->GetID (),
2342 error.AsCString ());
2343
2344 return SendErrorResponse (0x38);
2345 }
2346
2347 // Don't send an "OK" packet; response is the stopped/exited message.
2348 return PacketResult::Success;
2349}
2350
2351GDBRemoteCommunication::PacketResult
2352GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment)
2353{
2354 if (!IsGdbServer ())
2355 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2356
2357 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2358 if (log)
2359 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2360
2361 // We reuse this method in vCont - don't double adjust the file position.
2362 if (!skip_file_pos_adjustment)
2363 packet.SetFilePos (::strlen ("c"));
2364
2365 // For now just support all continue.
2366 const bool has_continue_address = (packet.GetBytesLeft () > 0);
2367 if (has_continue_address)
2368 {
2369 if (log)
2370 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
2371 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2372 }
2373
2374 // Ensure we have a native process.
2375 if (!m_debugged_process_sp)
2376 {
2377 if (log)
2378 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2379 return SendErrorResponse (0x36);
2380 }
2381
2382 // Build the ResumeActionList
2383 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
2384
2385 Error error = m_debugged_process_sp->Resume (actions);
2386 if (error.Fail ())
2387 {
2388 if (log)
2389 {
2390 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s",
2391 __FUNCTION__,
2392 m_debugged_process_sp->GetID (),
2393 error.AsCString ());
2394 }
2395 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2396 }
2397
2398 if (log)
2399 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2400
2401 // No response required from continue.
2402 return PacketResult::Success;
2403}
2404
2405GDBRemoteCommunication::PacketResult
2406GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet)
2407{
2408 if (!IsGdbServer ())
2409 {
2410 // only llgs supports $vCont.
2411 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2412 }
2413
Todd Fialaaf245d12014-06-30 21:05:18 +00002414 StreamString response;
2415 response.Printf("vCont;c;C;s;S");
2416
2417 return SendPacketNoLock(response.GetData(), response.GetSize());
2418}
2419
2420GDBRemoteCommunication::PacketResult
2421GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet)
2422{
2423 if (!IsGdbServer ())
2424 {
2425 // only llgs supports $vCont
2426 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2427 }
2428
2429 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2430 if (log)
2431 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__);
2432
2433 packet.SetFilePos (::strlen ("vCont"));
2434
2435 // Check if this is all continue (no options or ";c").
2436 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0))
2437 {
2438 // Move the packet past the ";c".
2439 if (packet.GetBytesLeft ())
2440 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c"));
2441
2442 const bool skip_file_pos_adjustment = true;
2443 return Handle_c (packet, skip_file_pos_adjustment);
2444 }
2445 else if (::strcmp (packet.Peek (), ";s") == 0)
2446 {
2447 // Move past the ';', then do a simple 's'.
2448 packet.SetFilePos (packet.GetFilePos () + 1);
2449 return Handle_s (packet);
2450 }
2451
2452 // Ensure we have a native process.
2453 if (!m_debugged_process_sp)
2454 {
2455 if (log)
2456 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2457 return SendErrorResponse (0x36);
2458 }
2459
2460 ResumeActionList thread_actions;
2461
2462 while (packet.GetBytesLeft () && *packet.Peek () == ';')
2463 {
2464 // Skip the semi-colon.
2465 packet.GetChar ();
2466
2467 // Build up the thread action.
2468 ResumeAction thread_action;
2469 thread_action.tid = LLDB_INVALID_THREAD_ID;
2470 thread_action.state = eStateInvalid;
2471 thread_action.signal = 0;
2472
2473 const char action = packet.GetChar ();
2474 switch (action)
2475 {
2476 case 'C':
2477 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2478 if (thread_action.signal == 0)
2479 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
2480 // Fall through to next case...
2481
2482 case 'c':
2483 // Continue
2484 thread_action.state = eStateRunning;
2485 break;
2486
2487 case 'S':
2488 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2489 if (thread_action.signal == 0)
2490 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
2491 // Fall through to next case...
2492
2493 case 's':
2494 // Step
2495 thread_action.state = eStateStepping;
2496 break;
2497
2498 default:
2499 return SendIllFormedResponse (packet, "Unsupported vCont action");
2500 break;
2501 }
2502
2503 // Parse out optional :{thread-id} value.
2504 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
2505 {
2506 // Consume the separator.
2507 packet.GetChar ();
2508
2509 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2510 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
2511 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
2512 }
2513
2514 thread_actions.Append (thread_action);
2515 }
2516
2517 // If a default action for all other threads wasn't mentioned
2518 // then we should stop the threads.
2519 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0);
2520
2521 Error error = m_debugged_process_sp->Resume (thread_actions);
2522 if (error.Fail ())
2523 {
2524 if (log)
2525 {
2526 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s",
2527 __FUNCTION__,
2528 m_debugged_process_sp->GetID (),
2529 error.AsCString ());
2530 }
2531 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2532 }
2533
2534 if (log)
2535 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2536
2537 // No response required from vCont.
2538 return PacketResult::Success;
2539}
2540
2541GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00002542GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
2543{
2544 // Send response first before changing m_send_acks to we ack this packet
Greg Clayton3dedae12013-12-06 21:45:27 +00002545 PacketResult packet_result = SendOKResponse ();
Greg Clayton1cb64962011-03-24 04:28:38 +00002546 m_send_acks = false;
Greg Clayton3dedae12013-12-06 21:45:27 +00002547 return packet_result;
Greg Clayton1cb64962011-03-24 04:28:38 +00002548}
Daniel Maleae0f8f572013-08-26 23:57:52 +00002549
Greg Clayton3dedae12013-12-06 21:45:27 +00002550GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002551GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002552{
Greg Claytonfbb76342013-11-20 21:07:01 +00002553 packet.SetFilePos(::strlen("qPlatform_mkdir:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002554 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002555 if (packet.GetChar() == ',')
2556 {
2557 std::string path;
2558 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002559 Error error = FileSystem::MakeDirectory(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002560 if (error.Success())
2561 return SendPacketNoLock ("OK", 2);
2562 else
2563 return SendErrorResponse(error.GetError());
2564 }
2565 return SendErrorResponse(20);
Greg Claytonfbb76342013-11-20 21:07:01 +00002566}
2567
Greg Clayton3dedae12013-12-06 21:45:27 +00002568GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002569GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
2570{
2571 packet.SetFilePos(::strlen("qPlatform_chmod:"));
2572
2573 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002574 if (packet.GetChar() == ',')
2575 {
2576 std::string path;
2577 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002578 Error error = FileSystem::SetFilePermissions(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002579 if (error.Success())
2580 return SendPacketNoLock ("OK", 2);
2581 else
2582 return SendErrorResponse(error.GetError());
2583 }
2584 return SendErrorResponse(19);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002585}
2586
Greg Clayton3dedae12013-12-06 21:45:27 +00002587GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002588GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
2589{
2590 packet.SetFilePos(::strlen("vFile:open:"));
2591 std::string path;
2592 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002593 if (!path.empty())
2594 {
2595 if (packet.GetChar() == ',')
2596 {
2597 uint32_t flags = packet.GetHexMaxU32(false, 0);
2598 if (packet.GetChar() == ',')
2599 {
2600 mode_t mode = packet.GetHexMaxU32(false, 0600);
2601 Error error;
2602 int fd = ::open (path.c_str(), flags, mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002603 const int save_errno = fd == -1 ? errno : 0;
2604 StreamString response;
2605 response.PutChar('F');
2606 response.Printf("%i", fd);
2607 if (save_errno)
2608 response.Printf(",%i", save_errno);
2609 return SendPacketNoLock(response.GetData(), response.GetSize());
2610 }
2611 }
2612 }
2613 return SendErrorResponse(18);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002614}
2615
Greg Clayton3dedae12013-12-06 21:45:27 +00002616GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002617GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
2618{
2619 packet.SetFilePos(::strlen("vFile:close:"));
2620 int fd = packet.GetS32(-1);
2621 Error error;
2622 int err = -1;
2623 int save_errno = 0;
2624 if (fd >= 0)
2625 {
2626 err = close(fd);
2627 save_errno = err == -1 ? errno : 0;
2628 }
2629 else
2630 {
2631 save_errno = EINVAL;
2632 }
2633 StreamString response;
2634 response.PutChar('F');
2635 response.Printf("%i", err);
2636 if (save_errno)
2637 response.Printf(",%i", save_errno);
Greg Clayton2b98c562013-11-22 18:53:12 +00002638 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002639}
2640
Greg Clayton3dedae12013-12-06 21:45:27 +00002641GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002642GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
2643{
Virgile Belloae12a362013-08-27 16:21:49 +00002644#ifdef _WIN32
2645 // Not implemented on Windows
Greg Clayton2b98c562013-11-22 18:53:12 +00002646 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002647#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002648 StreamGDBRemote response;
2649 packet.SetFilePos(::strlen("vFile:pread:"));
2650 int fd = packet.GetS32(-1);
Greg Clayton2b98c562013-11-22 18:53:12 +00002651 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002652 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002653 uint64_t count = packet.GetU64(UINT64_MAX);
2654 if (packet.GetChar() == ',')
2655 {
2656 uint64_t offset = packet.GetU64(UINT32_MAX);
2657 if (count == UINT64_MAX)
2658 {
2659 response.Printf("F-1:%i", EINVAL);
2660 return SendPacketNoLock(response.GetData(), response.GetSize());
2661 }
2662
2663 std::string buffer(count, 0);
2664 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
2665 const int save_errno = bytes_read == -1 ? errno : 0;
2666 response.PutChar('F');
2667 response.Printf("%zi", bytes_read);
2668 if (save_errno)
2669 response.Printf(",%i", save_errno);
2670 else
2671 {
2672 response.PutChar(';');
2673 response.PutEscapedBytes(&buffer[0], bytes_read);
2674 }
2675 return SendPacketNoLock(response.GetData(), response.GetSize());
2676 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002677 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002678 return SendErrorResponse(21);
2679
Virgile Belloae12a362013-08-27 16:21:49 +00002680#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002681}
2682
Greg Clayton3dedae12013-12-06 21:45:27 +00002683GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002684GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
2685{
Virgile Belloae12a362013-08-27 16:21:49 +00002686#ifdef _WIN32
Greg Clayton2b98c562013-11-22 18:53:12 +00002687 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002688#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002689 packet.SetFilePos(::strlen("vFile:pwrite:"));
2690
2691 StreamGDBRemote response;
2692 response.PutChar('F');
2693
2694 int fd = packet.GetU32(UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002695 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002696 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002697 off_t offset = packet.GetU64(UINT32_MAX);
2698 if (packet.GetChar() == ',')
2699 {
2700 std::string buffer;
2701 if (packet.GetEscapedBinaryData(buffer))
2702 {
2703 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
2704 const int save_errno = bytes_written == -1 ? errno : 0;
2705 response.Printf("%zi", bytes_written);
2706 if (save_errno)
2707 response.Printf(",%i", save_errno);
2708 }
2709 else
2710 {
2711 response.Printf ("-1,%i", EINVAL);
2712 }
2713 return SendPacketNoLock(response.GetData(), response.GetSize());
2714 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002715 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002716 return SendErrorResponse(27);
Virgile Belloae12a362013-08-27 16:21:49 +00002717#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002718}
2719
Greg Clayton3dedae12013-12-06 21:45:27 +00002720GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002721GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet)
2722{
2723 packet.SetFilePos(::strlen("vFile:size:"));
2724 std::string path;
2725 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002726 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002727 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002728 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002729 StreamString response;
2730 response.PutChar('F');
2731 response.PutHex64(retcode);
2732 if (retcode == UINT64_MAX)
2733 {
2734 response.PutChar(',');
2735 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
2736 }
2737 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002738 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002739 return SendErrorResponse(22);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002740}
2741
Greg Clayton3dedae12013-12-06 21:45:27 +00002742GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002743GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
2744{
2745 packet.SetFilePos(::strlen("vFile:mode:"));
2746 std::string path;
2747 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002748 if (!path.empty())
2749 {
2750 Error error;
2751 const uint32_t mode = File::GetPermissions(path.c_str(), error);
2752 StreamString response;
2753 response.Printf("F%u", mode);
2754 if (mode == 0 || error.Fail())
2755 response.Printf(",%i", (int)error.GetError());
2756 return SendPacketNoLock(response.GetData(), response.GetSize());
2757 }
2758 return SendErrorResponse(23);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002759}
2760
Greg Clayton3dedae12013-12-06 21:45:27 +00002761GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002762GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
2763{
2764 packet.SetFilePos(::strlen("vFile:exists:"));
2765 std::string path;
2766 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002767 if (!path.empty())
2768 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002769 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002770 StreamString response;
2771 response.PutChar('F');
2772 response.PutChar(',');
2773 if (retcode)
2774 response.PutChar('1');
2775 else
2776 response.PutChar('0');
2777 return SendPacketNoLock(response.GetData(), response.GetSize());
2778 }
2779 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002780}
2781
Greg Clayton3dedae12013-12-06 21:45:27 +00002782GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002783GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002784{
Greg Claytonfbb76342013-11-20 21:07:01 +00002785 packet.SetFilePos(::strlen("vFile:symlink:"));
2786 std::string dst, src;
2787 packet.GetHexByteStringTerminatedBy(dst, ',');
2788 packet.GetChar(); // Skip ',' char
2789 packet.GetHexByteString(src);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002790 Error error = FileSystem::Symlink(src.c_str(), dst.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002791 StreamString response;
2792 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002793 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002794}
2795
Greg Clayton3dedae12013-12-06 21:45:27 +00002796GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002797GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
2798{
2799 packet.SetFilePos(::strlen("vFile:unlink:"));
2800 std::string path;
2801 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002802 Error error = FileSystem::Unlink(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002803 StreamString response;
2804 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002805 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002806}
2807
Greg Clayton3dedae12013-12-06 21:45:27 +00002808GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002809GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
2810{
2811 packet.SetFilePos(::strlen("qPlatform_shell:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002812 std::string path;
2813 std::string working_dir;
2814 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002815 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002816 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002817 if (packet.GetChar() == ',')
2818 {
2819 // FIXME: add timeout to qPlatform_shell packet
2820 // uint32_t timeout = packet.GetHexMaxU32(false, 32);
2821 uint32_t timeout = 10;
2822 if (packet.GetChar() == ',')
2823 packet.GetHexByteString(working_dir);
2824 int status, signo;
2825 std::string output;
2826 Error err = Host::RunShellCommand(path.c_str(),
2827 working_dir.empty() ? NULL : working_dir.c_str(),
2828 &status, &signo, &output, timeout);
2829 StreamGDBRemote response;
2830 if (err.Fail())
2831 {
2832 response.PutCString("F,");
2833 response.PutHex32(UINT32_MAX);
2834 }
2835 else
2836 {
2837 response.PutCString("F,");
2838 response.PutHex32(status);
2839 response.PutChar(',');
2840 response.PutHex32(signo);
2841 response.PutChar(',');
2842 response.PutEscapedBytes(output.c_str(), output.size());
2843 }
2844 return SendPacketNoLock(response.GetData(), response.GetSize());
2845 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002846 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002847 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002848}
2849
Todd Fialaaf245d12014-06-30 21:05:18 +00002850void
2851GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid)
2852{
2853 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code");
2854
2855 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2856 if (log)
2857 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
2858
2859 m_current_tid = tid;
2860 if (m_debugged_process_sp)
2861 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
2862}
2863
2864void
2865GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid)
2866{
2867 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code");
2868
2869 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2870 if (log)
2871 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
2872
2873 m_continue_tid = tid;
2874}
2875
2876GDBRemoteCommunication::PacketResult
2877GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet)
2878{
2879 // Handle the $? gdbremote command.
2880 if (!IsGdbServer ())
2881 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented");
2882
2883 // If no process, indicate error
2884 if (!m_debugged_process_sp)
2885 return SendErrorResponse (02);
2886
2887 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2888}
2889
2890GDBRemoteCommunication::PacketResult
2891GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
2892{
2893 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2894
2895 switch (process_state)
2896 {
2897 case eStateAttaching:
2898 case eStateLaunching:
2899 case eStateRunning:
2900 case eStateStepping:
2901 case eStateDetached:
2902 // NOTE: gdb protocol doc looks like it should return $OK
2903 // when everything is running (i.e. no stopped result).
2904 return PacketResult::Success; // Ignore
2905
2906 case eStateSuspended:
2907 case eStateStopped:
2908 case eStateCrashed:
2909 {
2910 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
2911 // Make sure we set the current thread so g and p packets return
2912 // the data the gdb will expect.
2913 SetCurrentThreadID (tid);
2914 return SendStopReplyPacketForThread (tid);
2915 }
2916
2917 case eStateInvalid:
2918 case eStateUnloaded:
2919 case eStateExited:
2920 if (flush_on_exit)
2921 FlushInferiorOutput ();
2922 return SendWResponse(m_debugged_process_sp.get());
2923
2924 default:
2925 if (log)
2926 {
2927 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s",
2928 __FUNCTION__,
2929 m_debugged_process_sp->GetID (),
2930 StateAsCString (process_state));
2931 }
2932 break;
2933 }
2934
2935 return SendErrorResponse (0);
2936}
2937
Greg Clayton3dedae12013-12-06 21:45:27 +00002938GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002939GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
2940{
Greg Clayton2b98c562013-11-22 18:53:12 +00002941 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002942}
2943
Greg Clayton3dedae12013-12-06 21:45:27 +00002944GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002945GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
2946{
Greg Clayton2b98c562013-11-22 18:53:12 +00002947 packet.SetFilePos(::strlen("vFile:MD5:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002948 std::string path;
2949 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002950 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002951 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002952 uint64_t a,b;
2953 StreamGDBRemote response;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002954 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false)
Greg Clayton2b98c562013-11-22 18:53:12 +00002955 {
2956 response.PutCString("F,");
2957 response.PutCString("x");
2958 }
2959 else
2960 {
2961 response.PutCString("F,");
2962 response.PutHex64(a);
2963 response.PutHex64(b);
2964 }
2965 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002966 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002967 return SendErrorResponse(25);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002968}
Greg Clayton2b98c562013-11-22 18:53:12 +00002969
Todd Fialaaf245d12014-06-30 21:05:18 +00002970GDBRemoteCommunication::PacketResult
2971GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
2972{
2973 // Ensure we're llgs.
2974 if (!IsGdbServer())
2975 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented");
2976
2977 // Fail if we don't have a current process.
2978 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2979 return SendErrorResponse (68);
2980
2981 // Ensure we have a thread.
2982 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
2983 if (!thread_sp)
2984 return SendErrorResponse (69);
2985
2986 // Get the register context for the first thread.
2987 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2988 if (!reg_context_sp)
2989 return SendErrorResponse (69);
2990
2991 // Parse out the register number from the request.
2992 packet.SetFilePos (strlen("qRegisterInfo"));
2993 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2994 if (reg_index == std::numeric_limits<uint32_t>::max ())
2995 return SendErrorResponse (69);
2996
2997 // Return the end of registers response if we've iterated one past the end of the register set.
Vince Harrond40ef992015-01-23 22:57:00 +00002998 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
Todd Fialaaf245d12014-06-30 21:05:18 +00002999 return SendErrorResponse (69);
3000
3001 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3002 if (!reg_info)
3003 return SendErrorResponse (69);
3004
3005 // Build the reginfos response.
3006 StreamGDBRemote response;
3007
3008 response.PutCString ("name:");
3009 response.PutCString (reg_info->name);
3010 response.PutChar (';');
3011
3012 if (reg_info->alt_name && reg_info->alt_name[0])
3013 {
3014 response.PutCString ("alt-name:");
3015 response.PutCString (reg_info->alt_name);
3016 response.PutChar (';');
3017 }
3018
3019 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
3020
3021 switch (reg_info->encoding)
3022 {
3023 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
3024 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
3025 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
3026 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
3027 default: break;
3028 }
3029
3030 switch (reg_info->format)
3031 {
3032 case eFormatBinary: response.PutCString ("format:binary;"); break;
3033 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
3034 case eFormatHex: response.PutCString ("format:hex;"); break;
3035 case eFormatFloat: response.PutCString ("format:float;"); break;
3036 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
3037 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
3038 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
3039 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
3040 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
3041 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
3042 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
3043 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
3044 default: break;
3045 };
3046
3047 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
3048 if (register_set_name)
3049 {
3050 response.PutCString ("set:");
3051 response.PutCString (register_set_name);
3052 response.PutChar (';');
3053 }
3054
3055 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
3056 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
3057
3058 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
3059 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3060
3061 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
3062 {
3063 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
3064 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
3065 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
3066 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
3067 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
3068 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
3069 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
3070 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
3071 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
3072 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
3073 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
3074 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
3075 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
3076 default: break;
3077 }
3078
3079 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
3080 {
3081 response.PutCString ("container-regs:");
3082 int i = 0;
3083 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3084 {
3085 if (i > 0)
3086 response.PutChar (',');
3087 response.Printf ("%" PRIx32, *reg_num);
3088 }
3089 response.PutChar (';');
3090 }
3091
3092 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
3093 {
3094 response.PutCString ("invalidate-regs:");
3095 int i = 0;
3096 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3097 {
3098 if (i > 0)
3099 response.PutChar (',');
3100 response.Printf ("%" PRIx32, *reg_num);
3101 }
3102 response.PutChar (';');
3103 }
3104
3105 return SendPacketNoLock(response.GetData(), response.GetSize());
3106}
3107
3108GDBRemoteCommunication::PacketResult
3109GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
3110{
3111 // Ensure we're llgs.
3112 if (!IsGdbServer())
3113 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented");
3114
Todd Fiala24189d42014-07-14 06:24:44 +00003115 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3116
Todd Fialaaf245d12014-06-30 21:05:18 +00003117 // Fail if we don't have a current process.
3118 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
Todd Fiala24189d42014-07-14 06:24:44 +00003119 {
3120 if (log)
3121 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
3122 return SendOKResponse ();
3123 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003124
3125 StreamGDBRemote response;
3126 response.PutChar ('m');
3127
Todd Fiala24189d42014-07-14 06:24:44 +00003128 if (log)
3129 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__);
3130
Todd Fialaaf245d12014-06-30 21:05:18 +00003131 NativeThreadProtocolSP thread_sp;
3132 uint32_t thread_index;
3133 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
3134 thread_sp;
3135 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
3136 {
Todd Fiala24189d42014-07-14 06:24:44 +00003137 if (log)
3138 log->Printf ("GDBRemoteCommunicationServer::%s() iterated thread %" PRIu32 "(%s, tid=0x%" PRIx64 ")", __FUNCTION__, thread_index, thread_sp ? "is not null" : "null", thread_sp ? thread_sp->GetID () : LLDB_INVALID_THREAD_ID);
Todd Fialaaf245d12014-06-30 21:05:18 +00003139 if (thread_index > 0)
3140 response.PutChar(',');
3141 response.Printf ("%" PRIx64, thread_sp->GetID ());
3142 }
3143
Todd Fiala24189d42014-07-14 06:24:44 +00003144 if (log)
3145 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__);
3146
Todd Fialaaf245d12014-06-30 21:05:18 +00003147 return SendPacketNoLock(response.GetData(), response.GetSize());
3148}
3149
3150GDBRemoteCommunication::PacketResult
3151GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
3152{
3153 // Ensure we're llgs.
3154 if (!IsGdbServer())
3155 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented");
3156
3157 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
3158 return SendPacketNoLock ("l", 1);
3159}
3160
3161GDBRemoteCommunication::PacketResult
3162GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet)
3163{
3164 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3165
3166 // Ensure we're llgs.
3167 if (!IsGdbServer())
3168 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented");
3169
3170 // Parse out the register number from the request.
3171 packet.SetFilePos (strlen("p"));
3172 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3173 if (reg_index == std::numeric_limits<uint32_t>::max ())
3174 {
3175 if (log)
3176 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3177 return SendErrorResponse (0x15);
3178 }
3179
3180 // Get the thread to use.
3181 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3182 if (!thread_sp)
3183 {
3184 if (log)
3185 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__);
3186 return SendErrorResponse (0x15);
3187 }
3188
3189 // Get the thread's register context.
3190 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3191 if (!reg_context_sp)
3192 {
3193 if (log)
3194 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
3195 return SendErrorResponse (0x15);
3196 }
3197
3198 // Return the end of registers response if we've iterated one past the end of the register set.
Vince Harrond40ef992015-01-23 22:57:00 +00003199 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
Todd Fialaaf245d12014-06-30 21:05:18 +00003200 {
3201 if (log)
Vince Harrond40ef992015-01-23 22:57:00 +00003202 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
Todd Fialaaf245d12014-06-30 21:05:18 +00003203 return SendErrorResponse (0x15);
3204 }
3205
3206 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3207 if (!reg_info)
3208 {
3209 if (log)
3210 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3211 return SendErrorResponse (0x15);
3212 }
3213
3214 // Build the reginfos response.
3215 StreamGDBRemote response;
3216
3217 // Retrieve the value
3218 RegisterValue reg_value;
3219 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
3220 if (error.Fail ())
3221 {
3222 if (log)
3223 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3224 return SendErrorResponse (0x15);
3225 }
3226
3227 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
3228 if (!data)
3229 {
3230 if (log)
3231 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
3232 return SendErrorResponse (0x15);
3233 }
3234
3235 // FIXME flip as needed to get data in big/little endian format for this host.
3236 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
3237 response.PutHex8 (data[i]);
3238
3239 return SendPacketNoLock (response.GetData (), response.GetSize ());
3240}
3241
3242GDBRemoteCommunication::PacketResult
3243GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet)
3244{
3245 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3246
3247 // Ensure we're llgs.
3248 if (!IsGdbServer())
3249 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented");
3250
3251 // Ensure there is more content.
3252 if (packet.GetBytesLeft () < 1)
3253 return SendIllFormedResponse (packet, "Empty P packet");
3254
3255 // Parse out the register number from the request.
3256 packet.SetFilePos (strlen("P"));
3257 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3258 if (reg_index == std::numeric_limits<uint32_t>::max ())
3259 {
3260 if (log)
3261 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3262 return SendErrorResponse (0x29);
3263 }
3264
3265 // Note debugserver would send an E30 here.
3266 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
3267 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
3268
3269 // Get process architecture.
3270 ArchSpec process_arch;
3271 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
3272 {
3273 if (log)
3274 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__);
3275 return SendErrorResponse (0x49);
3276 }
3277
3278 // Parse out the value.
3279 const uint64_t raw_value = packet.GetHexMaxU64 (process_arch.GetByteOrder () == lldb::eByteOrderLittle, std::numeric_limits<uint64_t>::max ());
3280
3281 // Get the thread to use.
3282 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3283 if (!thread_sp)
3284 {
3285 if (log)
3286 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__);
3287 return SendErrorResponse (0x28);
3288 }
3289
3290 // Get the thread's register context.
3291 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3292 if (!reg_context_sp)
3293 {
3294 if (log)
3295 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
3296 return SendErrorResponse (0x15);
3297 }
3298
3299 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3300 if (!reg_info)
3301 {
3302 if (log)
3303 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3304 return SendErrorResponse (0x48);
3305 }
3306
3307 // Return the end of registers response if we've iterated one past the end of the register set.
Vince Harrond40ef992015-01-23 22:57:00 +00003308 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
Todd Fialaaf245d12014-06-30 21:05:18 +00003309 {
3310 if (log)
Vince Harrond40ef992015-01-23 22:57:00 +00003311 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
Todd Fialaaf245d12014-06-30 21:05:18 +00003312 return SendErrorResponse (0x47);
3313 }
3314
3315
3316 // Build the reginfos response.
3317 StreamGDBRemote response;
3318
3319 // FIXME Could be suffixed with a thread: parameter.
3320 // That thread then needs to be fed back into the reg context retrieval above.
3321 Error error = reg_context_sp->WriteRegisterFromUnsigned (reg_info, raw_value);
3322 if (error.Fail ())
3323 {
3324 if (log)
3325 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3326 return SendErrorResponse (0x32);
3327 }
3328
3329 return SendOKResponse();
3330}
3331
3332GDBRemoteCommunicationServer::PacketResult
3333GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet)
3334{
3335 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3336
3337 // Ensure we're llgs.
3338 if (!IsGdbServer())
3339 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented");
3340
3341 // Fail if we don't have a current process.
3342 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3343 {
3344 if (log)
3345 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3346 return SendErrorResponse (0x15);
3347 }
3348
3349 // Parse out which variant of $H is requested.
3350 packet.SetFilePos (strlen("H"));
3351 if (packet.GetBytesLeft () < 1)
3352 {
3353 if (log)
3354 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__);
3355 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
3356 }
3357
3358 const char h_variant = packet.GetChar ();
3359 switch (h_variant)
3360 {
3361 case 'g':
3362 break;
3363
3364 case 'c':
3365 break;
3366
3367 default:
3368 if (log)
3369 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
3370 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3371 }
3372
3373 // Parse out the thread number.
3374 // FIXME return a parse success/fail value. All values are valid here.
3375 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
3376
3377 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
3378 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
3379 {
3380 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
3381 if (!thread_sp)
3382 {
3383 if (log)
3384 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
3385 return SendErrorResponse (0x15);
3386 }
3387 }
3388
3389 // Now switch the given thread type.
3390 switch (h_variant)
3391 {
3392 case 'g':
3393 SetCurrentThreadID (tid);
3394 break;
3395
3396 case 'c':
3397 SetContinueThreadID (tid);
3398 break;
3399
3400 default:
3401 assert (false && "unsupported $H variant - shouldn't get here");
3402 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3403 }
3404
3405 return SendOKResponse();
3406}
3407
3408GDBRemoteCommunicationServer::PacketResult
3409GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet)
3410{
3411 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3412
3413 // Ensure we're llgs.
3414 if (!IsGdbServer())
3415 {
3416 // Only supported on llgs
3417 return SendUnimplementedResponse ("");
3418 }
3419
3420 // Fail if we don't have a current process.
3421 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3422 {
3423 if (log)
3424 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3425 return SendErrorResponse (0x15);
3426 }
3427
Todd Fiala511e5cd2014-09-11 23:29:14 +00003428 // Interrupt the process.
3429 Error error = m_debugged_process_sp->Interrupt ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003430 if (error.Fail ())
3431 {
3432 if (log)
3433 {
3434 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s",
3435 __FUNCTION__,
3436 m_debugged_process_sp->GetID (),
3437 error.AsCString ());
3438 }
3439 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
3440 }
3441
3442 if (log)
3443 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
3444
3445 // No response required from stop all.
3446 return PacketResult::Success;
3447}
3448
3449GDBRemoteCommunicationServer::PacketResult
3450GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet)
3451{
3452 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3453
3454 // Ensure we're llgs.
3455 if (!IsGdbServer())
3456 {
3457 // Only supported on llgs
3458 return SendUnimplementedResponse ("");
3459 }
3460
3461 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3462 {
3463 if (log)
3464 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3465 return SendErrorResponse (0x15);
3466 }
3467
3468 // Parse out the memory address.
3469 packet.SetFilePos (strlen("m"));
3470 if (packet.GetBytesLeft() < 1)
3471 return SendIllFormedResponse(packet, "Too short m packet");
3472
3473 // Read the address. Punting on validation.
3474 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3475 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3476
3477 // Validate comma.
3478 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3479 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
3480
3481 // Get # bytes to read.
3482 if (packet.GetBytesLeft() < 1)
3483 return SendIllFormedResponse(packet, "Length missing in m packet");
3484
3485 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3486 if (byte_count == 0)
3487 {
3488 if (log)
3489 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__);
3490 return PacketResult::Success;
3491 }
3492
3493 // Allocate the response buffer.
3494 std::string buf(byte_count, '\0');
3495 if (buf.empty())
3496 return SendErrorResponse (0x78);
3497
3498
3499 // Retrieve the process memory.
3500 lldb::addr_t bytes_read = 0;
3501 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
3502 if (error.Fail ())
3503 {
3504 if (log)
3505 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
3506 return SendErrorResponse (0x08);
3507 }
3508
3509 if (bytes_read == 0)
3510 {
3511 if (log)
3512 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": read %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, bytes_read, byte_count);
3513 return SendErrorResponse (0x08);
3514 }
3515
3516 StreamGDBRemote response;
3517 for (lldb::addr_t i = 0; i < bytes_read; ++i)
3518 response.PutHex8(buf[i]);
3519
3520 return SendPacketNoLock(response.GetData(), response.GetSize());
3521}
3522
3523GDBRemoteCommunication::PacketResult
3524GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet)
3525{
3526 packet.SetFilePos(::strlen ("QSetDetachOnError:"));
3527 if (packet.GetU32(0))
3528 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError);
3529 else
3530 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError);
3531 return SendOKResponse ();
3532}
3533
3534GDBRemoteCommunicationServer::PacketResult
3535GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet)
3536{
3537 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3538
3539 // Ensure we're llgs.
3540 if (!IsGdbServer())
3541 {
3542 // Only supported on llgs
3543 return SendUnimplementedResponse ("");
3544 }
3545
3546 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3547 {
3548 if (log)
3549 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3550 return SendErrorResponse (0x15);
3551 }
3552
3553 // Parse out the memory address.
3554 packet.SetFilePos (strlen("M"));
3555 if (packet.GetBytesLeft() < 1)
3556 return SendIllFormedResponse(packet, "Too short M packet");
3557
3558 // Read the address. Punting on validation.
3559 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3560 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
3561
3562 // Validate comma.
3563 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3564 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
3565
3566 // Get # bytes to read.
3567 if (packet.GetBytesLeft() < 1)
3568 return SendIllFormedResponse(packet, "Length missing in M packet");
3569
3570 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3571 if (byte_count == 0)
3572 {
3573 if (log)
3574 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__);
3575 return PacketResult::Success;
3576 }
3577
3578 // Validate colon.
3579 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
3580 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
3581
3582 // Allocate the conversion buffer.
3583 std::vector<uint8_t> buf(byte_count, 0);
3584 if (buf.empty())
3585 return SendErrorResponse (0x78);
3586
3587 // Convert the hex memory write contents to bytes.
3588 StreamGDBRemote response;
3589 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
3590 if (convert_count != byte_count)
3591 {
3592 if (log)
3593 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": asked to write %" PRIu64 " bytes, but only found %" PRIu64 " to convert.", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, byte_count, convert_count);
3594 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
3595 }
3596
3597 // Write the process memory.
3598 lldb::addr_t bytes_written = 0;
3599 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
3600 if (error.Fail ())
3601 {
3602 if (log)
3603 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
3604 return SendErrorResponse (0x09);
3605 }
3606
3607 if (bytes_written == 0)
3608 {
3609 if (log)
3610 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": wrote %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, bytes_written, byte_count);
3611 return SendErrorResponse (0x09);
3612 }
3613
3614 return SendOKResponse ();
3615}
3616
3617GDBRemoteCommunicationServer::PacketResult
3618GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
3619{
3620 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3621
3622 // We don't support if we're not llgs.
3623 if (!IsGdbServer())
3624 return SendUnimplementedResponse ("");
3625
3626 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
3627 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
3628 // client only asks this when a process is being debugged.
3629
3630 // Ensure we have a process running; otherwise, we can't figure this out
3631 // since we won't have a NativeProcessProtocol.
3632 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3633 {
3634 if (log)
3635 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3636 return SendErrorResponse (0x15);
3637 }
3638
3639 // Test if we can get any region back when asking for the region around NULL.
3640 MemoryRegionInfo region_info;
3641 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
3642 if (error.Fail ())
3643 {
3644 // We don't support memory region info collection for this NativeProcessProtocol.
3645 return SendUnimplementedResponse ("");
3646 }
3647
3648 return SendOKResponse();
3649}
3650
3651GDBRemoteCommunicationServer::PacketResult
3652GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
3653{
3654 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3655
3656 // We don't support if we're not llgs.
3657 if (!IsGdbServer())
3658 return SendUnimplementedResponse ("");
3659
3660 // Ensure we have a process.
3661 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3662 {
3663 if (log)
3664 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3665 return SendErrorResponse (0x15);
3666 }
3667
3668 // Parse out the memory address.
3669 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
3670 if (packet.GetBytesLeft() < 1)
3671 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
3672
3673 // Read the address. Punting on validation.
3674 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3675
3676 StreamGDBRemote response;
3677
3678 // Get the memory region info for the target address.
3679 MemoryRegionInfo region_info;
3680 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
3681 if (error.Fail ())
3682 {
3683 // Return the error message.
3684
3685 response.PutCString ("error:");
3686 response.PutCStringAsRawHex8 (error.AsCString ());
3687 response.PutChar (';');
3688 }
3689 else
3690 {
3691 // Range start and size.
3692 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
3693
3694 // Permissions.
3695 if (region_info.GetReadable () ||
3696 region_info.GetWritable () ||
3697 region_info.GetExecutable ())
3698 {
3699 // Write permissions info.
3700 response.PutCString ("permissions:");
3701
3702 if (region_info.GetReadable ())
3703 response.PutChar ('r');
3704 if (region_info.GetWritable ())
3705 response.PutChar('w');
3706 if (region_info.GetExecutable())
3707 response.PutChar ('x');
3708
3709 response.PutChar (';');
3710 }
3711 }
3712
3713 return SendPacketNoLock(response.GetData(), response.GetSize());
3714}
3715
3716GDBRemoteCommunicationServer::PacketResult
3717GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet)
3718{
3719 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3720
3721 // We don't support if we're not llgs.
3722 if (!IsGdbServer())
3723 return SendUnimplementedResponse ("");
3724
3725 // Ensure we have a process.
3726 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3727 {
3728 if (log)
3729 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3730 return SendErrorResponse (0x15);
3731 }
3732
3733 // Parse out software or hardware breakpoint requested.
3734 packet.SetFilePos (strlen("Z"));
3735 if (packet.GetBytesLeft() < 1)
3736 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
3737
3738 bool want_breakpoint = true;
3739 bool want_hardware = false;
3740
3741 const char breakpoint_type_char = packet.GetChar ();
3742 switch (breakpoint_type_char)
3743 {
3744 case '0': want_hardware = false; want_breakpoint = true; break;
3745 case '1': want_hardware = true; want_breakpoint = true; break;
3746 case '2': want_breakpoint = false; break;
3747 case '3': want_breakpoint = false; break;
3748 default:
3749 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
3750
3751 }
3752
3753 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3754 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type");
3755
3756 // FIXME implement watchpoint support.
3757 if (!want_breakpoint)
3758 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3759
3760 // Parse out the breakpoint address.
3761 if (packet.GetBytesLeft() < 1)
3762 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
3763 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3764
3765 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3766 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
3767
3768 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3769 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3770 if (kind == std::numeric_limits<uint32_t>::max ())
3771 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument");
3772
3773 if (want_breakpoint)
3774 {
3775 // Try to set the breakpoint.
3776 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware);
3777 if (error.Success ())
3778 return SendOKResponse ();
3779 else
3780 {
3781 if (log)
3782 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3783 return SendErrorResponse (0x09);
3784 }
3785 }
3786
3787 // FIXME fix up after watchpoints are handled.
3788 return SendUnimplementedResponse ("");
3789}
3790
3791GDBRemoteCommunicationServer::PacketResult
3792GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet)
3793{
3794 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3795
3796 // We don't support if we're not llgs.
3797 if (!IsGdbServer())
3798 return SendUnimplementedResponse ("");
3799
3800 // Ensure we have a process.
3801 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3802 {
3803 if (log)
3804 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3805 return SendErrorResponse (0x15);
3806 }
3807
3808 // Parse out software or hardware breakpoint requested.
Todd Fiala75f47c32014-10-11 21:42:09 +00003809 packet.SetFilePos (strlen("z"));
Todd Fialaaf245d12014-06-30 21:05:18 +00003810 if (packet.GetBytesLeft() < 1)
3811 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
3812
3813 bool want_breakpoint = true;
3814
3815 const char breakpoint_type_char = packet.GetChar ();
3816 switch (breakpoint_type_char)
3817 {
3818 case '0': want_breakpoint = true; break;
3819 case '1': want_breakpoint = true; break;
3820 case '2': want_breakpoint = false; break;
3821 case '3': want_breakpoint = false; break;
3822 default:
3823 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
3824
3825 }
3826
3827 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3828 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type");
3829
3830 // FIXME implement watchpoint support.
3831 if (!want_breakpoint)
3832 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3833
3834 // Parse out the breakpoint address.
3835 if (packet.GetBytesLeft() < 1)
3836 return SendIllFormedResponse(packet, "Too short z packet, missing address");
3837 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3838
3839 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3840 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
3841
3842 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3843 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3844 if (kind == std::numeric_limits<uint32_t>::max ())
3845 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument");
3846
3847 if (want_breakpoint)
3848 {
Todd Fiala75f47c32014-10-11 21:42:09 +00003849 // Try to clear the breakpoint.
Todd Fialaaf245d12014-06-30 21:05:18 +00003850 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr);
3851 if (error.Success ())
3852 return SendOKResponse ();
3853 else
3854 {
3855 if (log)
3856 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3857 return SendErrorResponse (0x09);
3858 }
3859 }
3860
3861 // FIXME fix up after watchpoints are handled.
3862 return SendUnimplementedResponse ("");
3863}
3864
3865GDBRemoteCommunicationServer::PacketResult
3866GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet)
3867{
3868 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
3869
3870 // We don't support if we're not llgs.
3871 if (!IsGdbServer())
3872 return SendUnimplementedResponse ("");
3873
3874 // Ensure we have a process.
3875 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3876 {
3877 if (log)
3878 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3879 return SendErrorResponse (0x32);
3880 }
3881
3882 // We first try to use a continue thread id. If any one or any all set, use the current thread.
3883 // Bail out if we don't have a thread id.
3884 lldb::tid_t tid = GetContinueThreadID ();
3885 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3886 tid = GetCurrentThreadID ();
3887 if (tid == LLDB_INVALID_THREAD_ID)
3888 return SendErrorResponse (0x33);
3889
3890 // Double check that we have such a thread.
3891 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3892 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
3893 if (!thread_sp || thread_sp->GetID () != tid)
3894 return SendErrorResponse (0x33);
3895
3896 // Create the step action for the given thread.
3897 lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
3898
3899 // Setup the actions list.
3900 lldb_private::ResumeActionList actions;
3901 actions.Append (action);
3902
3903 // All other threads stop while we're single stepping a thread.
3904 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3905 Error error = m_debugged_process_sp->Resume (actions);
3906 if (error.Fail ())
3907 {
3908 if (log)
3909 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
3910 return SendErrorResponse(0x49);
3911 }
3912
3913 // No response here - the stop or exit will come from the resulting action.
3914 return PacketResult::Success;
3915}
3916
3917GDBRemoteCommunicationServer::PacketResult
3918GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet)
3919{
3920 StreamGDBRemote response;
3921
3922 // Features common to lldb-platform and llgs.
3923 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less
3924 response.Printf ("PacketSize=%x", max_packet_size);
3925
3926 response.PutCString (";QStartNoAckMode+");
3927 response.PutCString (";QThreadSuffixSupported+");
3928 response.PutCString (";QListThreadsInStopReply+");
3929#if defined(__linux__)
3930 response.PutCString (";qXfer:auxv:read+");
3931#endif
3932
3933 return SendPacketNoLock(response.GetData(), response.GetSize());
3934}
3935
3936GDBRemoteCommunicationServer::PacketResult
3937GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet)
3938{
3939 m_thread_suffix_supported = true;
3940 return SendOKResponse();
3941}
3942
3943GDBRemoteCommunicationServer::PacketResult
3944GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet)
3945{
3946 m_list_threads_in_stop_reply = true;
3947 return SendOKResponse();
3948}
3949
3950GDBRemoteCommunicationServer::PacketResult
3951GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
3952{
3953 // We don't support if we're not llgs.
3954 if (!IsGdbServer())
3955 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
3956
3957 // *BSD impls should be able to do this too.
3958#if defined(__linux__)
3959 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3960
3961 // Parse out the offset.
3962 packet.SetFilePos (strlen("qXfer:auxv:read::"));
3963 if (packet.GetBytesLeft () < 1)
3964 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3965
3966 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3967 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
3968 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3969
3970 // Parse out comma.
3971 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
3972 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
3973
3974 // Parse out the length.
3975 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3976 if (auxv_length == std::numeric_limits<uint64_t>::max ())
3977 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
3978
3979 // Grab the auxv data if we need it.
3980 if (!m_active_auxv_buffer_sp)
3981 {
3982 // Make sure we have a valid process.
3983 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3984 {
3985 if (log)
3986 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3987 return SendErrorResponse (0x10);
3988 }
3989
3990 // Grab the auxv data.
3991 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
3992 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
3993 {
3994 // Hmm, no auxv data, call that an error.
3995 if (log)
3996 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__);
3997 m_active_auxv_buffer_sp.reset ();
3998 return SendErrorResponse (0x11);
3999 }
4000 }
4001
4002 // FIXME find out if/how I lock the stream here.
4003
4004 StreamGDBRemote response;
4005 bool done_with_buffer = false;
4006
4007 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
4008 {
4009 // We have nothing left to send. Mark the buffer as complete.
4010 response.PutChar ('l');
4011 done_with_buffer = true;
4012 }
4013 else
4014 {
4015 // Figure out how many bytes are available starting at the given offset.
4016 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
4017
4018 // Figure out how many bytes we're going to read.
4019 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
4020
4021 // Mark the response type according to whether we're reading the remainder of the auxv data.
4022 if (bytes_to_read >= bytes_remaining)
4023 {
4024 // There will be nothing left to read after this
4025 response.PutChar ('l');
4026 done_with_buffer = true;
4027 }
4028 else
4029 {
4030 // There will still be bytes to read after this request.
4031 response.PutChar ('m');
4032 }
4033
4034 // Now write the data in encoded binary form.
4035 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
4036 }
4037
4038 if (done_with_buffer)
4039 m_active_auxv_buffer_sp.reset ();
4040
4041 return SendPacketNoLock(response.GetData(), response.GetSize());
4042#else
4043 return SendUnimplementedResponse ("not implemented on this platform");
4044#endif
4045}
4046
4047GDBRemoteCommunicationServer::PacketResult
4048GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
4049{
4050 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4051
4052 // We don't support if we're not llgs.
4053 if (!IsGdbServer())
4054 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4055
4056 // Move past packet name.
4057 packet.SetFilePos (strlen ("QSaveRegisterState"));
4058
4059 // Get the thread to use.
4060 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4061 if (!thread_sp)
4062 {
4063 if (m_thread_suffix_supported)
4064 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
4065 else
4066 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4067 }
4068
4069 // Grab the register context for the thread.
4070 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4071 if (!reg_context_sp)
4072 {
4073 if (log)
4074 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
4075 return SendErrorResponse (0x15);
4076 }
4077
4078 // Save registers to a buffer.
4079 DataBufferSP register_data_sp;
4080 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
4081 if (error.Fail ())
4082 {
4083 if (log)
4084 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4085 return SendErrorResponse (0x75);
4086 }
4087
4088 // Allocate a new save id.
4089 const uint32_t save_id = GetNextSavedRegistersID ();
4090 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
4091
4092 // Save the register data buffer under the save id.
4093 {
4094 Mutex::Locker locker (m_saved_registers_mutex);
4095 m_saved_registers_map[save_id] = register_data_sp;
4096 }
4097
4098 // Write the response.
4099 StreamGDBRemote response;
4100 response.Printf ("%" PRIu32, save_id);
4101 return SendPacketNoLock(response.GetData(), response.GetSize());
4102}
4103
4104GDBRemoteCommunicationServer::PacketResult
4105GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
4106{
4107 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4108
4109 // We don't support if we're not llgs.
4110 if (!IsGdbServer())
4111 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4112
4113 // Parse out save id.
4114 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
4115 if (packet.GetBytesLeft () < 1)
4116 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
4117
4118 const uint32_t save_id = packet.GetU32 (0);
4119 if (save_id == 0)
4120 {
4121 if (log)
4122 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
4123 return SendErrorResponse (0x76);
4124 }
4125
4126 // Get the thread to use.
4127 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4128 if (!thread_sp)
4129 {
4130 if (m_thread_suffix_supported)
4131 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
4132 else
4133 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4134 }
4135
4136 // Grab the register context for the thread.
4137 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4138 if (!reg_context_sp)
4139 {
4140 if (log)
4141 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
4142 return SendErrorResponse (0x15);
4143 }
4144
4145 // Retrieve register state buffer, then remove from the list.
4146 DataBufferSP register_data_sp;
4147 {
4148 Mutex::Locker locker (m_saved_registers_mutex);
4149
4150 // Find the register set buffer for the given save id.
4151 auto it = m_saved_registers_map.find (save_id);
4152 if (it == m_saved_registers_map.end ())
4153 {
4154 if (log)
4155 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " does not have a register set save buffer for id %" PRIu32, __FUNCTION__, m_debugged_process_sp->GetID (), save_id);
4156 return SendErrorResponse (0x77);
4157 }
4158 register_data_sp = it->second;
4159
4160 // Remove it from the map.
4161 m_saved_registers_map.erase (it);
4162 }
4163
4164 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
4165 if (error.Fail ())
4166 {
4167 if (log)
4168 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4169 return SendErrorResponse (0x77);
4170 }
4171
4172 return SendOKResponse();
4173}
4174
Todd Fiala7306cf32014-07-29 22:30:01 +00004175GDBRemoteCommunicationServer::PacketResult
4176GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet)
4177{
4178 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4179
4180 // We don't support if we're not llgs.
4181 if (!IsGdbServer())
4182 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4183
4184 // Consume the ';' after vAttach.
4185 packet.SetFilePos (strlen ("vAttach"));
4186 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
4187 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
4188
4189 // Grab the PID to which we will attach (assume hex encoding).
4190 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4191 if (pid == LLDB_INVALID_PROCESS_ID)
4192 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
4193
4194 // Attempt to attach.
4195 if (log)
4196 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
4197
4198 Error error = AttachToProcess (pid);
4199
4200 if (error.Fail ())
4201 {
4202 if (log)
4203 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
4204 return SendErrorResponse (0x01);
4205 }
4206
4207 // Notify we attached by sending a stop packet.
4208 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
Oleksiy Vyalov859e4b52014-12-10 01:27:28 +00004209}
Todd Fiala7306cf32014-07-29 22:30:01 +00004210
Oleksiy Vyalov859e4b52014-12-10 01:27:28 +00004211GDBRemoteCommunicationServer::PacketResult
4212GDBRemoteCommunicationServer::Handle_D (StringExtractorGDBRemote &packet)
4213{
4214 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
4215
4216 // We don't support if we're not llgs.
4217 if (!IsGdbServer())
4218 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4219
4220 // Scope for mutex locker.
4221 Mutex::Locker locker (m_spawned_pids_mutex);
4222
4223 // Fail if we don't have a current process.
4224 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
4225 {
4226 if (log)
4227 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
4228 return SendErrorResponse (0x15);
4229 }
4230
4231 if (m_spawned_pids.find(m_debugged_process_sp->GetID ()) == m_spawned_pids.end())
4232 {
4233 if (log)
4234 log->Printf ("GDBRemoteCommunicationServer::%s failed to find PID %" PRIu64 " in spawned pids list",
4235 __FUNCTION__, m_debugged_process_sp->GetID ());
4236 return SendErrorResponse (0x1);
4237 }
4238
4239 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
4240
4241 // Consume the ';' after D.
4242 packet.SetFilePos (1);
4243 if (packet.GetBytesLeft ())
4244 {
4245 if (packet.GetChar () != ';')
4246 return SendIllFormedResponse (packet, "D missing expected ';'");
4247
4248 // Grab the PID from which we will detach (assume hex encoding).
4249 pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4250 if (pid == LLDB_INVALID_PROCESS_ID)
4251 return SendIllFormedResponse (packet, "D failed to parse the process id");
4252 }
4253
4254 if (pid != LLDB_INVALID_PROCESS_ID &&
4255 m_debugged_process_sp->GetID () != pid)
4256 {
4257 return SendIllFormedResponse (packet, "Invalid pid");
4258 }
4259
4260 if (m_stdio_communication.IsConnected ())
4261 {
4262 m_stdio_communication.StopReadThread ();
4263 }
4264
4265 const Error error = m_debugged_process_sp->Detach ();
4266 if (error.Fail ())
4267 {
4268 if (log)
4269 log->Printf ("GDBRemoteCommunicationServer::%s failed to detach from pid %" PRIu64 ": %s\n",
4270 __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4271 return SendErrorResponse (0x01);
4272 }
4273
4274 m_spawned_pids.erase (m_debugged_process_sp->GetID ());
4275 return SendOKResponse ();
Todd Fiala7306cf32014-07-29 22:30:01 +00004276}
4277
Todd Fiala1109ed42014-09-10 21:28:38 +00004278GDBRemoteCommunicationServer::PacketResult
4279GDBRemoteCommunicationServer::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
4280{
4281 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4282
4283 // We don't support if we're not llgs.
4284 if (!IsGdbServer())
4285 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4286
4287 packet.SetFilePos (strlen("qThreadStopInfo"));
4288 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
4289 if (tid == LLDB_INVALID_THREAD_ID)
4290 {
4291 if (log)
4292 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
4293 return SendErrorResponse (0x15);
4294 }
4295 return SendStopReplyPacketForThread (tid);
4296}
4297
Todd Fialaaf245d12014-06-30 21:05:18 +00004298void
4299GDBRemoteCommunicationServer::FlushInferiorOutput ()
4300{
4301 // If we're not monitoring an inferior's terminal, ignore this.
4302 if (!m_stdio_communication.IsConnected())
4303 return;
4304
4305 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
4306 if (log)
4307 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
4308
4309 // FIXME implement a timeout on the join.
4310 m_stdio_communication.JoinReadThread();
4311}
4312
4313void
4314GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection ()
4315{
4316 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4317
4318 // Tell the stdio connection to shut down.
4319 if (m_stdio_communication.IsConnected())
4320 {
4321 auto connection = m_stdio_communication.GetConnection();
4322 if (connection)
4323 {
4324 Error error;
4325 connection->Disconnect (&error);
4326
4327 if (error.Success ())
4328 {
4329 if (log)
4330 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
4331 }
4332 else
4333 {
4334 if (log)
4335 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
4336 }
4337 }
4338 }
4339}
4340
4341
4342lldb_private::NativeThreadProtocolSP
4343GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
4344{
4345 NativeThreadProtocolSP thread_sp;
4346
4347 // We have no thread if we don't have a process.
4348 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4349 return thread_sp;
4350
4351 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
4352 // Use the current thread in that case.
4353 if (!m_thread_suffix_supported)
4354 {
4355 const lldb::tid_t current_tid = GetCurrentThreadID ();
4356 if (current_tid == LLDB_INVALID_THREAD_ID)
4357 return thread_sp;
4358 else if (current_tid == 0)
4359 {
4360 // Pick a thread.
4361 return m_debugged_process_sp->GetThreadAtIndex (0);
4362 }
4363 else
4364 return m_debugged_process_sp->GetThreadByID (current_tid);
4365 }
4366
4367 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4368
4369 // Parse out the ';'.
4370 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
4371 {
4372 if (log)
4373 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4374 return thread_sp;
4375 }
4376
4377 if (!packet.GetBytesLeft ())
4378 return thread_sp;
4379
4380 // Parse out thread: portion.
4381 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
4382 {
4383 if (log)
4384 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4385 return thread_sp;
4386 }
4387 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
4388 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4389 if (tid != 0)
4390 return m_debugged_process_sp->GetThreadByID (tid);
4391
4392 return thread_sp;
4393}
4394
4395lldb::tid_t
4396GDBRemoteCommunicationServer::GetCurrentThreadID () const
4397{
4398 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
4399 {
4400 // Use whatever the debug process says is the current thread id
4401 // since the protocol either didn't specify or specified we want
4402 // any/all threads marked as the current thread.
4403 if (!m_debugged_process_sp)
4404 return LLDB_INVALID_THREAD_ID;
4405 return m_debugged_process_sp->GetCurrentThreadID ();
4406 }
4407 // Use the specific current thread id set by the gdb remote protocol.
4408 return m_current_tid;
4409}
4410
4411uint32_t
4412GDBRemoteCommunicationServer::GetNextSavedRegistersID ()
4413{
4414 Mutex::Locker locker (m_saved_registers_mutex);
4415 return m_next_saved_registers_id++;
4416}
4417
Todd Fialaa9882ce2014-08-28 15:46:54 +00004418void
4419GDBRemoteCommunicationServer::ClearProcessSpecificData ()
4420{
4421 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
4422 if (log)
4423 log->Printf ("GDBRemoteCommunicationServer::%s()", __FUNCTION__);
4424
4425 // Clear any auxv cached data.
4426 // *BSD impls should be able to do this too.
4427#if defined(__linux__)
4428 if (log)
4429 log->Printf ("GDBRemoteCommunicationServer::%s clearing auxv buffer (previously %s)",
4430 __FUNCTION__,
4431 m_active_auxv_buffer_sp ? "was set" : "was not set");
4432 m_active_auxv_buffer_sp.reset ();
4433#endif
4434}