blob: b20a8aba87a94cc3af49c53bf1080a11504ebc37 [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"
26#include "lldb/Core/ConnectionFileDescriptor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000027#include "lldb/Core/Debugger.h"
Greg Clayton576d8832011-03-22 04:00:09 +000028#include "lldb/Core/Log.h"
29#include "lldb/Core/State.h"
30#include "lldb/Core/StreamString.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"
Greg Clayton576d8832011-03-22 04:00:09 +000037#include "lldb/Host/TimeValue.h"
Zachary Turner696b5282014-08-14 16:01:25 +000038#include "lldb/Target/FileAction.h"
Todd Fialab8b49ec2014-01-28 00:34:23 +000039#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000040#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Target/NativeRegisterContext.h"
Todd Fiala24189d42014-07-14 06:24:44 +000042#include "Host/common/NativeProcessProtocol.h"
43#include "Host/common/NativeThreadProtocol.h"
Greg Clayton576d8832011-03-22 04:00:09 +000044
45// Project includes
46#include "Utility/StringExtractorGDBRemote.h"
47#include "ProcessGDBRemote.h"
48#include "ProcessGDBRemoteLog.h"
49
50using namespace lldb;
51using namespace lldb_private;
52
53//----------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +000054// GDBRemote Errors
55//----------------------------------------------------------------------
56
57namespace
58{
59 enum GDBRemoteServerError
60 {
61 // Set to the first unused error number in literal form below
62 eErrorFirst = 29,
63 eErrorNoProcess = eErrorFirst,
64 eErrorResume,
65 eErrorExitStatus
66 };
67}
68
69//----------------------------------------------------------------------
Greg Clayton576d8832011-03-22 04:00:09 +000070// GDBRemoteCommunicationServer constructor
71//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000072GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform) :
73 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
Todd Fialab8b49ec2014-01-28 00:34:23 +000074 m_platform_sp (Platform::GetDefaultPlatform ()),
Greg Clayton8b82f082011-04-12 05:54:46 +000075 m_async_thread (LLDB_INVALID_HOST_THREAD),
76 m_process_launch_info (),
77 m_process_launch_error (),
Daniel Maleae0f8f572013-08-26 23:57:52 +000078 m_spawned_pids (),
79 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton8b82f082011-04-12 05:54:46 +000080 m_proc_infos (),
81 m_proc_infos_index (0),
Greg Clayton2b98c562013-11-22 18:53:12 +000082 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +000083 m_port_offset(0),
84 m_current_tid (LLDB_INVALID_THREAD_ID),
85 m_continue_tid (LLDB_INVALID_THREAD_ID),
86 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
87 m_debugged_process_sp (),
88 m_debugger_sp (),
89 m_stdio_communication ("process.stdio"),
90 m_exit_now (false),
91 m_inferior_prev_state (StateType::eStateInvalid),
92 m_thread_suffix_supported (false),
93 m_list_threads_in_stop_reply (false),
94 m_active_auxv_buffer_sp (),
95 m_saved_registers_mutex (),
96 m_saved_registers_map (),
97 m_next_saved_registers_id (1)
Greg Clayton576d8832011-03-22 04:00:09 +000098{
Todd Fialaaf245d12014-06-30 21:05:18 +000099 assert(is_platform && "must be lldb-platform if debugger is not specified");
Greg Clayton576d8832011-03-22 04:00:09 +0000100}
101
Todd Fialab8b49ec2014-01-28 00:34:23 +0000102GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform,
Todd Fialaaf245d12014-06-30 21:05:18 +0000103 const lldb::PlatformSP& platform_sp,
104 lldb::DebuggerSP &debugger_sp) :
Todd Fialab8b49ec2014-01-28 00:34:23 +0000105 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
106 m_platform_sp (platform_sp),
107 m_async_thread (LLDB_INVALID_HOST_THREAD),
108 m_process_launch_info (),
109 m_process_launch_error (),
110 m_spawned_pids (),
111 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
112 m_proc_infos (),
113 m_proc_infos_index (0),
114 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000115 m_port_offset(0),
116 m_current_tid (LLDB_INVALID_THREAD_ID),
117 m_continue_tid (LLDB_INVALID_THREAD_ID),
118 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
119 m_debugged_process_sp (),
120 m_debugger_sp (debugger_sp),
121 m_stdio_communication ("process.stdio"),
122 m_exit_now (false),
123 m_inferior_prev_state (StateType::eStateInvalid),
124 m_thread_suffix_supported (false),
125 m_list_threads_in_stop_reply (false),
126 m_active_auxv_buffer_sp (),
127 m_saved_registers_mutex (),
128 m_saved_registers_map (),
129 m_next_saved_registers_id (1)
Todd Fialab8b49ec2014-01-28 00:34:23 +0000130{
131 assert(platform_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000132 assert((is_platform || debugger_sp) && "must specify non-NULL debugger_sp when lldb-gdbserver");
Todd Fialab8b49ec2014-01-28 00:34:23 +0000133}
134
Greg Clayton576d8832011-03-22 04:00:09 +0000135//----------------------------------------------------------------------
136// Destructor
137//----------------------------------------------------------------------
138GDBRemoteCommunicationServer::~GDBRemoteCommunicationServer()
139{
140}
141
Todd Fialaaf245d12014-06-30 21:05:18 +0000142GDBRemoteCommunication::PacketResult
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000143GDBRemoteCommunicationServer::GetPacketAndSendResponse (uint32_t timeout_usec,
Greg Clayton1cb64962011-03-24 04:28:38 +0000144 Error &error,
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000145 bool &interrupt,
Greg Claytond314e812011-03-23 00:09:55 +0000146 bool &quit)
Greg Clayton576d8832011-03-22 04:00:09 +0000147{
148 StringExtractorGDBRemote packet;
Todd Fialaaf245d12014-06-30 21:05:18 +0000149
Greg Clayton3dedae12013-12-06 21:45:27 +0000150 PacketResult packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
151 if (packet_result == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000152 {
153 const StringExtractorGDBRemote::ServerPacketType packet_type = packet.GetServerPacketType ();
154 switch (packet_type)
155 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000156 case StringExtractorGDBRemote::eServerPacketType_nack:
157 case StringExtractorGDBRemote::eServerPacketType_ack:
158 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000159
Greg Clayton3dedae12013-12-06 21:45:27 +0000160 case StringExtractorGDBRemote::eServerPacketType_invalid:
161 error.SetErrorString("invalid packet");
162 quit = true;
163 break;
Greg Claytond314e812011-03-23 00:09:55 +0000164
Greg Clayton3dedae12013-12-06 21:45:27 +0000165 default:
166 case StringExtractorGDBRemote::eServerPacketType_unimplemented:
167 packet_result = SendUnimplementedResponse (packet.GetStringRef().c_str());
168 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000169
Greg Clayton3dedae12013-12-06 21:45:27 +0000170 case StringExtractorGDBRemote::eServerPacketType_A:
171 packet_result = Handle_A (packet);
172 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000173
Greg Clayton3dedae12013-12-06 21:45:27 +0000174 case StringExtractorGDBRemote::eServerPacketType_qfProcessInfo:
175 packet_result = Handle_qfProcessInfo (packet);
176 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000177
Greg Clayton3dedae12013-12-06 21:45:27 +0000178 case StringExtractorGDBRemote::eServerPacketType_qsProcessInfo:
179 packet_result = Handle_qsProcessInfo (packet);
180 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000181
Greg Clayton3dedae12013-12-06 21:45:27 +0000182 case StringExtractorGDBRemote::eServerPacketType_qC:
183 packet_result = Handle_qC (packet);
184 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000185
Greg Clayton3dedae12013-12-06 21:45:27 +0000186 case StringExtractorGDBRemote::eServerPacketType_qHostInfo:
187 packet_result = Handle_qHostInfo (packet);
188 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000189
Greg Clayton3dedae12013-12-06 21:45:27 +0000190 case StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer:
191 packet_result = Handle_qLaunchGDBServer (packet);
192 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000193
Greg Clayton3dedae12013-12-06 21:45:27 +0000194 case StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess:
195 packet_result = Handle_qKillSpawnedProcess (packet);
196 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000197
Todd Fiala403edc52014-01-23 22:05:44 +0000198 case StringExtractorGDBRemote::eServerPacketType_k:
199 packet_result = Handle_k (packet);
Todd Fialaaf245d12014-06-30 21:05:18 +0000200 quit = true;
Todd Fiala403edc52014-01-23 22:05:44 +0000201 break;
202
Greg Clayton3dedae12013-12-06 21:45:27 +0000203 case StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess:
204 packet_result = Handle_qLaunchSuccess (packet);
205 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000206
Greg Clayton3dedae12013-12-06 21:45:27 +0000207 case StringExtractorGDBRemote::eServerPacketType_qGroupName:
208 packet_result = Handle_qGroupName (packet);
209 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000210
Todd Fialaaf245d12014-06-30 21:05:18 +0000211 case StringExtractorGDBRemote::eServerPacketType_qProcessInfo:
212 packet_result = Handle_qProcessInfo (packet);
213 break;
214
Greg Clayton3dedae12013-12-06 21:45:27 +0000215 case StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID:
216 packet_result = Handle_qProcessInfoPID (packet);
217 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000218
Greg Clayton3dedae12013-12-06 21:45:27 +0000219 case StringExtractorGDBRemote::eServerPacketType_qSpeedTest:
220 packet_result = Handle_qSpeedTest (packet);
221 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000222
Greg Clayton3dedae12013-12-06 21:45:27 +0000223 case StringExtractorGDBRemote::eServerPacketType_qUserName:
224 packet_result = Handle_qUserName (packet);
225 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000226
Greg Clayton3dedae12013-12-06 21:45:27 +0000227 case StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir:
228 packet_result = Handle_qGetWorkingDir(packet);
229 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000230
Greg Clayton3dedae12013-12-06 21:45:27 +0000231 case StringExtractorGDBRemote::eServerPacketType_QEnvironment:
232 packet_result = Handle_QEnvironment (packet);
233 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000234
Greg Clayton3dedae12013-12-06 21:45:27 +0000235 case StringExtractorGDBRemote::eServerPacketType_QLaunchArch:
236 packet_result = Handle_QLaunchArch (packet);
237 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000238
Greg Clayton3dedae12013-12-06 21:45:27 +0000239 case StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR:
240 packet_result = Handle_QSetDisableASLR (packet);
241 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000242
Jim Ingham106d0282014-06-25 02:32:56 +0000243 case StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError:
244 packet_result = Handle_QSetDetachOnError (packet);
245 break;
246
Greg Clayton3dedae12013-12-06 21:45:27 +0000247 case StringExtractorGDBRemote::eServerPacketType_QSetSTDIN:
248 packet_result = Handle_QSetSTDIN (packet);
249 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000250
Greg Clayton3dedae12013-12-06 21:45:27 +0000251 case StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT:
252 packet_result = Handle_QSetSTDOUT (packet);
253 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000254
Greg Clayton3dedae12013-12-06 21:45:27 +0000255 case StringExtractorGDBRemote::eServerPacketType_QSetSTDERR:
256 packet_result = Handle_QSetSTDERR (packet);
257 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000258
Greg Clayton3dedae12013-12-06 21:45:27 +0000259 case StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir:
260 packet_result = Handle_QSetWorkingDir (packet);
261 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000262
Greg Clayton3dedae12013-12-06 21:45:27 +0000263 case StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode:
264 packet_result = Handle_QStartNoAckMode (packet);
265 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000266
Greg Clayton3dedae12013-12-06 21:45:27 +0000267 case StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir:
268 packet_result = Handle_qPlatform_mkdir (packet);
269 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000270
Greg Clayton3dedae12013-12-06 21:45:27 +0000271 case StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod:
272 packet_result = Handle_qPlatform_chmod (packet);
273 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000274
Greg Clayton3dedae12013-12-06 21:45:27 +0000275 case StringExtractorGDBRemote::eServerPacketType_qPlatform_shell:
276 packet_result = Handle_qPlatform_shell (packet);
277 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000278
Todd Fialaaf245d12014-06-30 21:05:18 +0000279 case StringExtractorGDBRemote::eServerPacketType_C:
280 packet_result = Handle_C (packet);
281 break;
282
283 case StringExtractorGDBRemote::eServerPacketType_c:
284 packet_result = Handle_c (packet);
285 break;
286
287 case StringExtractorGDBRemote::eServerPacketType_vCont:
288 packet_result = Handle_vCont (packet);
289 break;
290
291 case StringExtractorGDBRemote::eServerPacketType_vCont_actions:
292 packet_result = Handle_vCont_actions (packet);
293 break;
294
295 case StringExtractorGDBRemote::eServerPacketType_stop_reason: // ?
296 packet_result = Handle_stop_reason (packet);
297 break;
298
Greg Clayton3dedae12013-12-06 21:45:27 +0000299 case StringExtractorGDBRemote::eServerPacketType_vFile_open:
300 packet_result = Handle_vFile_Open (packet);
301 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000302
Greg Clayton3dedae12013-12-06 21:45:27 +0000303 case StringExtractorGDBRemote::eServerPacketType_vFile_close:
304 packet_result = Handle_vFile_Close (packet);
305 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000306
Greg Clayton3dedae12013-12-06 21:45:27 +0000307 case StringExtractorGDBRemote::eServerPacketType_vFile_pread:
308 packet_result = Handle_vFile_pRead (packet);
309 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000310
Greg Clayton3dedae12013-12-06 21:45:27 +0000311 case StringExtractorGDBRemote::eServerPacketType_vFile_pwrite:
312 packet_result = Handle_vFile_pWrite (packet);
313 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000314
Greg Clayton3dedae12013-12-06 21:45:27 +0000315 case StringExtractorGDBRemote::eServerPacketType_vFile_size:
316 packet_result = Handle_vFile_Size (packet);
317 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000318
Greg Clayton3dedae12013-12-06 21:45:27 +0000319 case StringExtractorGDBRemote::eServerPacketType_vFile_mode:
320 packet_result = Handle_vFile_Mode (packet);
321 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000322
Greg Clayton3dedae12013-12-06 21:45:27 +0000323 case StringExtractorGDBRemote::eServerPacketType_vFile_exists:
324 packet_result = Handle_vFile_Exists (packet);
325 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000326
Greg Clayton3dedae12013-12-06 21:45:27 +0000327 case StringExtractorGDBRemote::eServerPacketType_vFile_stat:
328 packet_result = Handle_vFile_Stat (packet);
329 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000330
Greg Clayton3dedae12013-12-06 21:45:27 +0000331 case StringExtractorGDBRemote::eServerPacketType_vFile_md5:
332 packet_result = Handle_vFile_MD5 (packet);
333 break;
334
335 case StringExtractorGDBRemote::eServerPacketType_vFile_symlink:
336 packet_result = Handle_vFile_symlink (packet);
337 break;
338
339 case StringExtractorGDBRemote::eServerPacketType_vFile_unlink:
340 packet_result = Handle_vFile_unlink (packet);
341 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000342
343 case StringExtractorGDBRemote::eServerPacketType_qRegisterInfo:
344 packet_result = Handle_qRegisterInfo (packet);
345 break;
346
347 case StringExtractorGDBRemote::eServerPacketType_qfThreadInfo:
348 packet_result = Handle_qfThreadInfo (packet);
349 break;
350
351 case StringExtractorGDBRemote::eServerPacketType_qsThreadInfo:
352 packet_result = Handle_qsThreadInfo (packet);
353 break;
354
355 case StringExtractorGDBRemote::eServerPacketType_p:
356 packet_result = Handle_p (packet);
357 break;
358
359 case StringExtractorGDBRemote::eServerPacketType_P:
360 packet_result = Handle_P (packet);
361 break;
362
363 case StringExtractorGDBRemote::eServerPacketType_H:
364 packet_result = Handle_H (packet);
365 break;
366
367 case StringExtractorGDBRemote::eServerPacketType_m:
368 packet_result = Handle_m (packet);
369 break;
370
371 case StringExtractorGDBRemote::eServerPacketType_M:
372 packet_result = Handle_M (packet);
373 break;
374
375 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported:
376 packet_result = Handle_qMemoryRegionInfoSupported (packet);
377 break;
378
379 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo:
380 packet_result = Handle_qMemoryRegionInfo (packet);
381 break;
382
383 case StringExtractorGDBRemote::eServerPacketType_interrupt:
384 if (IsGdbServer ())
385 packet_result = Handle_interrupt (packet);
386 else
387 {
388 error.SetErrorString("interrupt received");
389 interrupt = true;
390 }
391 break;
392
393 case StringExtractorGDBRemote::eServerPacketType_Z:
394 packet_result = Handle_Z (packet);
395 break;
396
397 case StringExtractorGDBRemote::eServerPacketType_z:
398 packet_result = Handle_z (packet);
399 break;
400
401 case StringExtractorGDBRemote::eServerPacketType_s:
402 packet_result = Handle_s (packet);
403 break;
404
405 case StringExtractorGDBRemote::eServerPacketType_qSupported:
406 packet_result = Handle_qSupported (packet);
407 break;
408
409 case StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported:
410 packet_result = Handle_QThreadSuffixSupported (packet);
411 break;
412
413 case StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply:
414 packet_result = Handle_QListThreadsInStopReply (packet);
415 break;
416
417 case StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read:
418 packet_result = Handle_qXfer_auxv_read (packet);
419 break;
420
421 case StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState:
422 packet_result = Handle_QSaveRegisterState (packet);
423 break;
424
425 case StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState:
426 packet_result = Handle_QRestoreRegisterState (packet);
427 break;
Todd Fiala7306cf32014-07-29 22:30:01 +0000428
429 case StringExtractorGDBRemote::eServerPacketType_vAttach:
430 packet_result = Handle_vAttach (packet);
431 break;
Todd Fiala1109ed42014-09-10 21:28:38 +0000432
433 case StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo:
434 packet_result = Handle_qThreadStopInfo (packet);
435 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000436 }
Greg Clayton576d8832011-03-22 04:00:09 +0000437 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000438 else
439 {
440 if (!IsConnected())
Greg Clayton3dedae12013-12-06 21:45:27 +0000441 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000442 error.SetErrorString("lost connection");
Greg Clayton3dedae12013-12-06 21:45:27 +0000443 quit = true;
444 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000445 else
Greg Clayton3dedae12013-12-06 21:45:27 +0000446 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000447 error.SetErrorString("timeout");
Greg Clayton3dedae12013-12-06 21:45:27 +0000448 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000449 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000450
451 // Check if anything occurred that would force us to want to exit.
452 if (m_exit_now)
453 quit = true;
454
455 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000456}
457
Todd Fiala403edc52014-01-23 22:05:44 +0000458lldb_private::Error
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000459GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc)
Todd Fiala403edc52014-01-23 22:05:44 +0000460{
461 if ((argc < 1) || !args || !args[0] || !args[0][0])
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000462 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
Todd Fiala403edc52014-01-23 22:05:44 +0000463
Todd Fiala403edc52014-01-23 22:05:44 +0000464 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000465 return lldb_private::Error ();
466}
467
468lldb_private::Error
469GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags)
470{
Todd Fiala403edc52014-01-23 22:05:44 +0000471 m_process_launch_info.GetFlags ().Set (launch_flags);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000472 return lldb_private::Error ();
473}
474
475lldb_private::Error
476GDBRemoteCommunicationServer::LaunchProcess ()
477{
Todd Fialaaf245d12014-06-30 21:05:18 +0000478 // FIXME This looks an awful lot like we could override this in
479 // derived classes, one for lldb-platform, the other for lldb-gdbserver.
480 if (IsGdbServer ())
Todd Fiala87bac592014-09-18 21:02:03 +0000481 return LaunchProcessForDebugging ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000482 else
483 return LaunchPlatformProcess ();
484}
485
486lldb_private::Error
Todd Fiala87bac592014-09-18 21:02:03 +0000487GDBRemoteCommunicationServer::LaunchProcessForDebugging ()
Todd Fialaaf245d12014-06-30 21:05:18 +0000488{
489 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
490
491 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
492 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
493
494 lldb_private::Error error;
495 {
496 Mutex::Locker locker (m_debugged_process_mutex);
497 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
498 error = m_platform_sp->LaunchNativeProcess (
499 m_process_launch_info,
500 *this,
501 m_debugged_process_sp);
502 }
503
504 if (!error.Success ())
505 {
506 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
507 return error;
508 }
509
510 // Setup stdout/stderr mapping from inferior.
511 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
512 if (terminal_fd >= 0)
513 {
514 if (log)
515 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
516 error = SetSTDIOFileDescriptor (terminal_fd);
517 if (error.Fail ())
518 return error;
519 }
520 else
521 {
522 if (log)
523 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
524 }
525
526 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
527
528 // Add to list of spawned processes.
529 lldb::pid_t pid;
530 if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
531 {
532 // add to spawned pids
Todd Fiala87bac592014-09-18 21:02:03 +0000533 Mutex::Locker locker (m_spawned_pids_mutex);
534 // On an lldb-gdbserver, we would expect there to be only one.
535 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
536 m_spawned_pids.insert (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000537 }
538
539 return error;
540}
541
542lldb_private::Error
543GDBRemoteCommunicationServer::LaunchPlatformProcess ()
544{
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000545 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
546 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
547
548 // specify the process monitor if not already set. This should
549 // generally be what happens since we need to reap started
550 // processes.
551 if (!m_process_launch_info.GetMonitorProcessCallback ())
552 m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false);
Todd Fiala403edc52014-01-23 22:05:44 +0000553
Todd Fialab8b49ec2014-01-28 00:34:23 +0000554 lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
Todd Fiala403edc52014-01-23 22:05:44 +0000555 if (!error.Success ())
556 {
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000557 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
Todd Fiala403edc52014-01-23 22:05:44 +0000558 return error;
559 }
560
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000561 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 +0000562
563 // add to list of spawned processes. On an lldb-gdbserver, we
564 // would expect there to be only one.
565 lldb::pid_t pid;
566 if ( (pid = m_process_launch_info.GetProcessID()) != LLDB_INVALID_PROCESS_ID )
567 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000568 // add to spawned pids
569 {
570 Mutex::Locker locker (m_spawned_pids_mutex);
571 m_spawned_pids.insert(pid);
572 }
Todd Fiala403edc52014-01-23 22:05:44 +0000573 }
574
575 return error;
576}
577
Todd Fialaaf245d12014-06-30 21:05:18 +0000578lldb_private::Error
579GDBRemoteCommunicationServer::AttachToProcess (lldb::pid_t pid)
580{
581 Error error;
582
583 if (!IsGdbServer ())
584 {
585 error.SetErrorString("cannot AttachToProcess () unless process is lldb-gdbserver");
586 return error;
587 }
588
589 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
590 if (log)
591 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64, __FUNCTION__, pid);
592
593 // Scope for mutex locker.
594 {
595 // Before we try to attach, make sure we aren't already monitoring something else.
596 Mutex::Locker locker (m_spawned_pids_mutex);
597 if (!m_spawned_pids.empty ())
598 {
599 error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
600 return error;
601 }
602
603 // Try to attach.
604 error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp);
605 if (!error.Success ())
606 {
607 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
608 return error;
609 }
610
611 // Setup stdout/stderr mapping from inferior.
612 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
613 if (terminal_fd >= 0)
614 {
615 if (log)
616 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
617 error = SetSTDIOFileDescriptor (terminal_fd);
618 if (error.Fail ())
619 return error;
620 }
621 else
622 {
623 if (log)
624 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
625 }
626
627 printf ("Attached to process %" PRIu64 "...\n", pid);
628
629 // Add to list of spawned processes.
630 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
631 m_spawned_pids.insert (pid);
632
633 return error;
634 }
635}
636
637void
638GDBRemoteCommunicationServer::InitializeDelegate (lldb_private::NativeProcessProtocol *process)
639{
640 assert (process && "process cannot be NULL");
641 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
642 if (log)
643 {
644 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
645 __FUNCTION__,
646 process->GetID (),
647 StateAsCString (process->GetState ()));
648 }
649}
650
651GDBRemoteCommunication::PacketResult
652GDBRemoteCommunicationServer::SendWResponse (lldb_private::NativeProcessProtocol *process)
653{
654 assert (process && "process cannot be NULL");
655 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
656
657 // send W notification
658 ExitType exit_type = ExitType::eExitTypeInvalid;
659 int return_code = 0;
660 std::string exit_description;
661
662 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
663 if (!got_exit_info)
664 {
665 if (log)
666 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
667
668 StreamGDBRemote response;
669 response.PutChar ('E');
670 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
671 return SendPacketNoLock(response.GetData(), response.GetSize());
672 }
673 else
674 {
675 if (log)
676 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 ());
677
678 StreamGDBRemote response;
679
680 char return_type_code;
681 switch (exit_type)
682 {
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000683 case ExitType::eExitTypeExit:
684 return_type_code = 'W';
685 break;
686 case ExitType::eExitTypeSignal:
687 return_type_code = 'X';
688 break;
689 case ExitType::eExitTypeStop:
690 return_type_code = 'S';
691 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000692 case ExitType::eExitTypeInvalid:
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000693 return_type_code = 'E';
694 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000695 }
696 response.PutChar (return_type_code);
697
698 // POSIX exit status limited to unsigned 8 bits.
699 response.PutHex8 (return_code);
700
701 return SendPacketNoLock(response.GetData(), response.GetSize());
702 }
703}
704
705static void
706AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
707{
708 int64_t i;
709 if (swap)
710 {
711 for (i = buf_size-1; i >= 0; i--)
712 response.PutHex8 (buf[i]);
713 }
714 else
715 {
716 for (i = 0; i < buf_size; i++)
717 response.PutHex8 (buf[i]);
718 }
719}
720
721static void
722WriteRegisterValueInHexFixedWidth (StreamString &response,
723 NativeRegisterContextSP &reg_ctx_sp,
724 const RegisterInfo &reg_info,
725 const RegisterValue *reg_value_p)
726{
727 RegisterValue reg_value;
728 if (!reg_value_p)
729 {
730 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
731 if (error.Success ())
732 reg_value_p = &reg_value;
733 // else log.
734 }
735
736 if (reg_value_p)
737 {
738 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
739 }
740 else
741 {
742 // Zero-out any unreadable values.
743 if (reg_info.byte_size > 0)
744 {
745 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
746 AppendHexValue (response, zeros.data(), zeros.size(), false);
747 }
748 }
749}
750
751// WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
752
753
754static void
755WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response,
756 NativeRegisterContextSP &reg_ctx_sp,
757 const RegisterInfo &reg_info,
758 const RegisterValue &reg_value)
759{
760 // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
761 // gdb register number, and VVVVVVVV is the correct number of hex bytes
762 // as ASCII for the register value.
763 if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM)
764 return;
765
766 response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]);
767 WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, &reg_value);
768 response.PutChar (';');
769}
770
771
772GDBRemoteCommunication::PacketResult
773GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid)
774{
775 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
776
777 // Ensure we're llgs.
778 if (!IsGdbServer ())
779 {
780 // Only supported on llgs
781 return SendUnimplementedResponse ("");
782 }
783
784 // Ensure we have a debugged process.
785 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
786 return SendErrorResponse (50);
787
788 if (log)
789 log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
790 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
791
792 // Ensure we can get info on the given thread.
793 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
794 if (!thread_sp)
795 return SendErrorResponse (51);
796
797 // Grab the reason this thread stopped.
798 struct ThreadStopInfo tid_stop_info;
799 if (!thread_sp->GetStopReason (tid_stop_info))
800 return SendErrorResponse (52);
801
802 const bool did_exec = tid_stop_info.reason == eStopReasonExec;
803 // FIXME implement register handling for exec'd inferiors.
804 // if (did_exec)
805 // {
806 // const bool force = true;
807 // InitializeRegisters(force);
808 // }
809
810 StreamString response;
811 // Output the T packet with the thread
812 response.PutChar ('T');
813 int signum = tid_stop_info.details.signal.signo;
814 if (log)
815 {
816 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
817 __FUNCTION__,
818 m_debugged_process_sp->GetID (),
819 tid,
820 signum,
821 tid_stop_info.reason,
822 tid_stop_info.details.exception.type);
823 }
824
825 switch (tid_stop_info.reason)
826 {
827 case eStopReasonSignal:
828 case eStopReasonException:
829 signum = thread_sp->TranslateStopInfoToGdbSignal (tid_stop_info);
830 break;
831 default:
832 signum = 0;
833 if (log)
834 {
835 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " has stop reason %d, using signo = 0 in stop reply response",
836 __FUNCTION__,
837 m_debugged_process_sp->GetID (),
838 tid,
839 tid_stop_info.reason);
840 }
841 break;
842 }
843
844 // Print the signal number.
845 response.PutHex8 (signum & 0xff);
846
847 // Include the tid.
848 response.Printf ("thread:%" PRIx64 ";", tid);
849
850 // Include the thread name if there is one.
Todd Fiala7206c6d2014-09-12 22:51:49 +0000851 const std::string thread_name = thread_sp->GetName ();
852 if (!thread_name.empty ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000853 {
Todd Fiala7206c6d2014-09-12 22:51:49 +0000854 size_t thread_name_len = thread_name.length ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000855
Todd Fiala7206c6d2014-09-12 22:51:49 +0000856 if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
Todd Fialaaf245d12014-06-30 21:05:18 +0000857 {
858 response.PutCString ("name:");
Todd Fiala7206c6d2014-09-12 22:51:49 +0000859 response.PutCString (thread_name.c_str ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000860 }
861 else
862 {
863 // The thread name contains special chars, send as hex bytes.
864 response.PutCString ("hexname:");
Todd Fiala7206c6d2014-09-12 22:51:49 +0000865 response.PutCStringAsRawHex8 (thread_name.c_str ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000866 }
867 response.PutChar (';');
868 }
869
870 // FIXME look for analog
871 // thread_identifier_info_data_t thread_ident_info;
872 // if (DNBThreadGetIdentifierInfo (pid, tid, &thread_ident_info))
873 // {
874 // if (thread_ident_info.dispatch_qaddr != 0)
875 // ostrm << std::hex << "qaddr:" << thread_ident_info.dispatch_qaddr << ';';
876 // }
877
878 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
879 // will send all thread IDs back in the "threads" key whose value is
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000880 // a list of hex thread IDs separated by commas:
Todd Fialaaf245d12014-06-30 21:05:18 +0000881 // "threads:10a,10b,10c;"
882 // This will save the debugger from having to send a pair of qfThreadInfo
883 // and qsThreadInfo packets, but it also might take a lot of room in the
884 // stop reply packet, so it must be enabled only on systems where there
885 // are no limits on packet lengths.
886 if (m_list_threads_in_stop_reply)
887 {
888 response.PutCString ("threads:");
889
890 uint32_t thread_index = 0;
891 NativeThreadProtocolSP listed_thread_sp;
892 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))
893 {
894 if (thread_index > 0)
895 response.PutChar (',');
896 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
897 }
898 response.PutChar (';');
899 }
900
901 //
902 // Expedite registers.
903 //
904
905 // Grab the register context.
906 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
907 if (reg_ctx_sp)
908 {
909 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
910 const RegisterSet *reg_set_p;
911 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
912 {
913 if (log)
914 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);
915
916 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
917 {
918 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
919 if (reg_info_p == nullptr)
920 {
921 if (log)
922 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);
923 }
924 else if (reg_info_p->value_regs == nullptr)
925 {
926 // Only expediate registers that are not contained in other registers.
927 RegisterValue reg_value;
928 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
929 if (error.Success ())
930 WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
931 else
932 {
933 if (log)
934 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 ());
935
936 }
937 }
938 }
939 }
940 }
941
942 if (did_exec)
943 {
944 response.PutCString ("reason:exec;");
945 }
946 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
947 {
948 response.PutCString ("metype:");
949 response.PutHex64 (tid_stop_info.details.exception.type);
950 response.PutCString (";mecount:");
951 response.PutHex32 (tid_stop_info.details.exception.data_count);
952 response.PutChar (';');
953
954 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
955 {
956 response.PutCString ("medata:");
957 response.PutHex64 (tid_stop_info.details.exception.data[i]);
958 response.PutChar (';');
959 }
960 }
961
962 return SendPacketNoLock (response.GetData(), response.GetSize());
963}
964
965void
966GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
967{
968 assert (process && "process cannot be NULL");
969
970 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
971 if (log)
972 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
973
974 // Send the exit result, and don't flush output.
975 // Note: flushing output here would join the inferior stdio reflection thread, which
976 // would gunk up the waitpid monitor thread that is calling this.
977 PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
978 if (result != PacketResult::Success)
979 {
980 if (log)
981 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
982 }
983
984 // Remove the process from the list of spawned pids.
985 {
986 Mutex::Locker locker (m_spawned_pids_mutex);
987 if (m_spawned_pids.erase (process->GetID ()) < 1)
988 {
989 if (log)
990 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
991
992 }
993 }
994
995 // FIXME can't do this yet - since process state propagation is currently
996 // synchronous, it is running off the NativeProcessProtocol's innards and
997 // will tear down the NPP while it still has code to execute.
998#if 0
999 // Clear the NativeProcessProtocol pointer.
1000 {
1001 Mutex::Locker locker (m_debugged_process_mutex);
1002 m_debugged_process_sp.reset();
1003 }
1004#endif
1005
1006 // Close the pipe to the inferior terminal i/o if we launched it
1007 // and set one up. Otherwise, 'k' and its flush of stdio could
1008 // end up waiting on a thread join that will never end. Consider
1009 // adding a timeout to the connection thread join call so we
1010 // can avoid that scenario altogether.
1011 MaybeCloseInferiorTerminalConnection ();
1012
1013 // We are ready to exit the debug monitor.
1014 m_exit_now = true;
1015}
1016
1017void
1018GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
1019{
1020 assert (process && "process cannot be NULL");
1021
1022 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1023 if (log)
1024 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1025
1026 // Send the stop reason unless this is the stop after the
1027 // launch or attach.
1028 switch (m_inferior_prev_state)
1029 {
1030 case eStateLaunching:
1031 case eStateAttaching:
1032 // Don't send anything per debugserver behavior.
1033 break;
1034 default:
1035 // In all other cases, send the stop reason.
1036 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
1037 if (result != PacketResult::Success)
1038 {
1039 if (log)
1040 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1041 }
1042 break;
1043 }
1044}
1045
1046void
1047GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
1048{
1049 assert (process && "process cannot be NULL");
1050 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1051 if (log)
1052 {
1053 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
1054 __FUNCTION__,
1055 process->GetID (),
1056 StateAsCString (state));
1057 }
1058
1059 switch (state)
1060 {
1061 case StateType::eStateExited:
1062 HandleInferiorState_Exited (process);
1063 break;
1064
1065 case StateType::eStateStopped:
1066 HandleInferiorState_Stopped (process);
1067 break;
1068
1069 default:
1070 if (log)
1071 {
1072 log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
1073 __FUNCTION__,
1074 process->GetID (),
1075 StateAsCString (state));
1076 }
1077 break;
1078 }
1079
1080 // Remember the previous state reported to us.
1081 m_inferior_prev_state = state;
1082}
1083
Todd Fialaa9882ce2014-08-28 15:46:54 +00001084void
1085GDBRemoteCommunicationServer::DidExec (NativeProcessProtocol *process)
1086{
1087 ClearProcessSpecificData ();
1088}
1089
Todd Fialaaf245d12014-06-30 21:05:18 +00001090GDBRemoteCommunication::PacketResult
1091GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len)
1092{
1093 if ((buffer == nullptr) || (len == 0))
1094 {
1095 // Nothing to send.
1096 return PacketResult::Success;
1097 }
1098
1099 StreamString response;
1100 response.PutChar ('O');
1101 response.PutBytesAsRawHex8 (buffer, len);
1102
1103 return SendPacketNoLock (response.GetData (), response.GetSize ());
1104}
1105
1106lldb_private::Error
1107GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd)
1108{
1109 Error error;
1110
1111 // Set up the Read Thread for reading/handling process I/O
1112 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
1113 if (!conn_up)
1114 {
1115 error.SetErrorString ("failed to create ConnectionFileDescriptor");
1116 return error;
1117 }
1118
1119 m_stdio_communication.SetConnection (conn_up.release());
1120 if (!m_stdio_communication.IsConnected ())
1121 {
1122 error.SetErrorString ("failed to set connection for inferior I/O communication");
1123 return error;
1124 }
1125
1126 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1127 m_stdio_communication.StartReadThread();
1128
1129 return error;
1130}
1131
1132void
1133GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1134{
1135 GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton);
1136 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
1137}
1138
Greg Clayton3dedae12013-12-06 21:45:27 +00001139GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001140GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
Greg Clayton576d8832011-03-22 04:00:09 +00001141{
Greg Clayton32e0a752011-03-30 18:16:51 +00001142 // TODO: Log the packet we aren't handling...
Greg Clayton37a0a242012-04-11 00:24:49 +00001143 return SendPacketNoLock ("", 0);
Greg Clayton576d8832011-03-22 04:00:09 +00001144}
1145
Todd Fialaaf245d12014-06-30 21:05:18 +00001146
Greg Clayton3dedae12013-12-06 21:45:27 +00001147GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001148GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
1149{
1150 char packet[16];
1151 int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
Andy Gibbsa297a972013-06-19 19:04:53 +00001152 assert (packet_len < (int)sizeof(packet));
Greg Clayton37a0a242012-04-11 00:24:49 +00001153 return SendPacketNoLock (packet, packet_len);
Greg Clayton32e0a752011-03-30 18:16:51 +00001154}
1155
Todd Fialaaf245d12014-06-30 21:05:18 +00001156GDBRemoteCommunication::PacketResult
1157GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message)
1158{
1159 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
1160 if (log)
1161 log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : "");
1162 return SendErrorResponse (0x03);
1163}
Greg Clayton32e0a752011-03-30 18:16:51 +00001164
Greg Clayton3dedae12013-12-06 21:45:27 +00001165GDBRemoteCommunication::PacketResult
Greg Clayton1cb64962011-03-24 04:28:38 +00001166GDBRemoteCommunicationServer::SendOKResponse ()
1167{
Greg Clayton37a0a242012-04-11 00:24:49 +00001168 return SendPacketNoLock ("OK", 2);
Greg Clayton1cb64962011-03-24 04:28:38 +00001169}
1170
1171bool
1172GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
1173{
Greg Clayton3dedae12013-12-06 21:45:27 +00001174 return GetAck() == PacketResult::Success;
Greg Clayton1cb64962011-03-24 04:28:38 +00001175}
Greg Clayton576d8832011-03-22 04:00:09 +00001176
Greg Clayton3dedae12013-12-06 21:45:27 +00001177GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001178GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
Greg Clayton576d8832011-03-22 04:00:09 +00001179{
1180 StreamString response;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001181
Greg Clayton576d8832011-03-22 04:00:09 +00001182 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
1183
Zachary Turner13b18262014-08-20 16:42:51 +00001184 ArchSpec host_arch(HostInfo::GetArchitecture());
Greg Clayton576d8832011-03-22 04:00:09 +00001185 const llvm::Triple &host_triple = host_arch.GetTriple();
Greg Clayton1cb64962011-03-24 04:28:38 +00001186 response.PutCString("triple:");
Greg Clayton44272a42014-09-18 00:18:32 +00001187 response.PutCStringAsRawHex8(host_triple.getTriple().c_str());
Greg Clayton1cb64962011-03-24 04:28:38 +00001188 response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001189
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001190 const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
1191 if (distribution_id)
1192 {
1193 response.PutCString("distribution_id:");
1194 response.PutCStringAsRawHex8(distribution_id);
1195 response.PutCString(";");
1196 }
1197
Todd Fialaaf245d12014-06-30 21:05:18 +00001198 // Only send out MachO info when lldb-platform/llgs is running on a MachO host.
1199#if defined(__APPLE__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001200 uint32_t cpu = host_arch.GetMachOCPUType();
1201 uint32_t sub = host_arch.GetMachOCPUSubType();
1202 if (cpu != LLDB_INVALID_CPUTYPE)
1203 response.Printf ("cputype:%u;", cpu);
1204 if (sub != LLDB_INVALID_CPUTYPE)
1205 response.Printf ("cpusubtype:%u;", sub);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001206
Enrico Granata1c5431a2012-07-13 23:55:22 +00001207 if (cpu == ArchSpec::kCore_arm_any)
Enrico Granataf04a2192012-07-13 23:18:48 +00001208 response.Printf("watchpoint_exceptions_received:before;"); // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
1209 else
1210 response.Printf("watchpoint_exceptions_received:after;");
Todd Fialaaf245d12014-06-30 21:05:18 +00001211#else
1212 response.Printf("watchpoint_exceptions_received:after;");
1213#endif
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001214
Greg Clayton576d8832011-03-22 04:00:09 +00001215 switch (lldb::endian::InlHostByteOrder())
1216 {
1217 case eByteOrderBig: response.PutCString ("endian:big;"); break;
1218 case eByteOrderLittle: response.PutCString ("endian:little;"); break;
1219 case eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1220 default: response.PutCString ("endian:unknown;"); break;
1221 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001222
Greg Clayton1cb64962011-03-24 04:28:38 +00001223 uint32_t major = UINT32_MAX;
1224 uint32_t minor = UINT32_MAX;
1225 uint32_t update = UINT32_MAX;
Zachary Turner97a14e62014-08-19 17:18:29 +00001226 if (HostInfo::GetOSVersion(major, minor, update))
Greg Clayton1cb64962011-03-24 04:28:38 +00001227 {
1228 if (major != UINT32_MAX)
1229 {
1230 response.Printf("os_version:%u", major);
1231 if (minor != UINT32_MAX)
1232 {
1233 response.Printf(".%u", minor);
1234 if (update != UINT32_MAX)
1235 response.Printf(".%u", update);
1236 }
1237 response.PutChar(';');
1238 }
1239 }
1240
1241 std::string s;
Zachary Turner97a14e62014-08-19 17:18:29 +00001242#if !defined(__linux__)
1243 if (HostInfo::GetOSBuildString(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001244 {
1245 response.PutCString ("os_build:");
1246 response.PutCStringAsRawHex8(s.c_str());
1247 response.PutChar(';');
1248 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001249 if (HostInfo::GetOSKernelDescription(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001250 {
1251 response.PutCString ("os_kernel:");
1252 response.PutCStringAsRawHex8(s.c_str());
1253 response.PutChar(';');
1254 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001255#endif
1256
Greg Clayton2b98c562013-11-22 18:53:12 +00001257#if defined(__APPLE__)
1258
Todd Fiala013434e2014-07-09 01:29:05 +00001259#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001260 // For iOS devices, we are connected through a USB Mux so we never pretend
1261 // to actually have a hostname as far as the remote lldb that is connecting
1262 // to this lldb-platform is concerned
1263 response.PutCString ("hostname:");
Greg Clayton16810922014-02-27 19:38:18 +00001264 response.PutCStringAsRawHex8("127.0.0.1");
Greg Clayton2b98c562013-11-22 18:53:12 +00001265 response.PutChar(';');
Todd Fiala013434e2014-07-09 01:29:05 +00001266#else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001267 if (HostInfo::GetHostname(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001268 {
1269 response.PutCString ("hostname:");
1270 response.PutCStringAsRawHex8(s.c_str());
1271 response.PutChar(';');
1272 }
Todd Fiala013434e2014-07-09 01:29:05 +00001273#endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001274
1275#else // #if defined(__APPLE__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001276 if (HostInfo::GetHostname(s))
Greg Clayton2b98c562013-11-22 18:53:12 +00001277 {
1278 response.PutCString ("hostname:");
1279 response.PutCStringAsRawHex8(s.c_str());
1280 response.PutChar(';');
1281 }
1282#endif // #if defined(__APPLE__)
1283
Greg Clayton3dedae12013-12-06 21:45:27 +00001284 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001285}
Greg Clayton1cb64962011-03-24 04:28:38 +00001286
Greg Clayton32e0a752011-03-30 18:16:51 +00001287static void
Greg Clayton8b82f082011-04-12 05:54:46 +00001288CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
Greg Clayton32e0a752011-03-30 18:16:51 +00001289{
Daniel Malead01b2952012-11-29 21:49:15 +00001290 response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
Greg Clayton32e0a752011-03-30 18:16:51 +00001291 proc_info.GetProcessID(),
1292 proc_info.GetParentProcessID(),
Greg Clayton8b82f082011-04-12 05:54:46 +00001293 proc_info.GetUserID(),
1294 proc_info.GetGroupID(),
Greg Clayton32e0a752011-03-30 18:16:51 +00001295 proc_info.GetEffectiveUserID(),
1296 proc_info.GetEffectiveGroupID());
1297 response.PutCString ("name:");
1298 response.PutCStringAsRawHex8(proc_info.GetName());
1299 response.PutChar(';');
1300 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1301 if (proc_arch.IsValid())
1302 {
1303 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1304 response.PutCString("triple:");
Greg Clayton44272a42014-09-18 00:18:32 +00001305 response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001306 response.PutChar(';');
1307 }
1308}
Greg Clayton1cb64962011-03-24 04:28:38 +00001309
Todd Fialaaf245d12014-06-30 21:05:18 +00001310static void
1311CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response)
1312{
1313 response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1314 proc_info.GetProcessID(),
1315 proc_info.GetParentProcessID(),
1316 proc_info.GetUserID(),
1317 proc_info.GetGroupID(),
1318 proc_info.GetEffectiveUserID(),
1319 proc_info.GetEffectiveGroupID());
1320
1321 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1322 if (proc_arch.IsValid())
1323 {
Todd Fialac540dd02014-08-26 18:21:02 +00001324 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1325#if defined(__APPLE__)
1326 // We'll send cputype/cpusubtype.
Todd Fialaaf245d12014-06-30 21:05:18 +00001327 const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1328 if (cpu_type != 0)
1329 response.Printf ("cputype:%" PRIx32 ";", cpu_type);
1330
1331 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1332 if (cpu_subtype != 0)
1333 response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype);
Todd Fialac540dd02014-08-26 18:21:02 +00001334
Todd Fialaaf245d12014-06-30 21:05:18 +00001335
Todd Fialaaf245d12014-06-30 21:05:18 +00001336 const std::string vendor = proc_triple.getVendorName ();
1337 if (!vendor.empty ())
1338 response.Printf ("vendor:%s;", vendor.c_str ());
Todd Fialac540dd02014-08-26 18:21:02 +00001339#else
1340 // We'll send the triple.
Greg Clayton44272a42014-09-18 00:18:32 +00001341 response.PutCString("triple:");
1342 response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1343 response.PutChar(';');
1344
Todd Fialac540dd02014-08-26 18:21:02 +00001345#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001346 std::string ostype = proc_triple.getOSName ();
1347 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1348 if (proc_triple.getVendor () == llvm::Triple::Apple)
1349 {
1350 switch (proc_triple.getArch ())
1351 {
1352 case llvm::Triple::arm:
Todd Fialad8eaa172014-07-23 14:37:35 +00001353 case llvm::Triple::aarch64:
Todd Fialaaf245d12014-06-30 21:05:18 +00001354 ostype = "ios";
1355 break;
1356 default:
1357 // No change.
1358 break;
1359 }
1360 }
1361 response.Printf ("ostype:%s;", ostype.c_str ());
1362
1363
1364 switch (proc_arch.GetByteOrder ())
1365 {
1366 case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break;
1367 case lldb::eByteOrderBig: response.PutCString ("endian:big;"); break;
1368 case lldb::eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1369 default:
1370 // Nothing.
1371 break;
1372 }
1373
1374 if (proc_triple.isArch64Bit ())
1375 response.PutCString ("ptrsize:8;");
1376 else if (proc_triple.isArch32Bit ())
1377 response.PutCString ("ptrsize:4;");
1378 else if (proc_triple.isArch16Bit ())
1379 response.PutCString ("ptrsize:2;");
1380 }
1381
1382}
1383
1384
1385GDBRemoteCommunication::PacketResult
1386GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1387{
1388 // Only the gdb server handles this.
1389 if (!IsGdbServer ())
1390 return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
1391
1392 // Fail if we don't have a current process.
1393 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1394 return SendErrorResponse (68);
1395
1396 ProcessInstanceInfo proc_info;
1397 if (Host::GetProcessInfo (m_debugged_process_sp->GetID (), proc_info))
1398 {
1399 StreamString response;
1400 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1401 return SendPacketNoLock (response.GetData (), response.GetSize ());
1402 }
1403
1404 return SendErrorResponse (1);
1405}
1406
Greg Clayton3dedae12013-12-06 21:45:27 +00001407GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001408GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
Greg Clayton1cb64962011-03-24 04:28:38 +00001409{
Greg Clayton32e0a752011-03-30 18:16:51 +00001410 // Packet format: "qProcessInfoPID:%i" where %i is the pid
Greg Clayton8b82f082011-04-12 05:54:46 +00001411 packet.SetFilePos(::strlen ("qProcessInfoPID:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001412 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
1413 if (pid != LLDB_INVALID_PROCESS_ID)
1414 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001415 ProcessInstanceInfo proc_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001416 if (Host::GetProcessInfo(pid, proc_info))
1417 {
1418 StreamString response;
1419 CreateProcessInfoResponse (proc_info, response);
Greg Clayton37a0a242012-04-11 00:24:49 +00001420 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001421 }
1422 }
1423 return SendErrorResponse (1);
1424}
1425
Greg Clayton3dedae12013-12-06 21:45:27 +00001426GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001427GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
1428{
1429 m_proc_infos_index = 0;
1430 m_proc_infos.Clear();
1431
Greg Clayton8b82f082011-04-12 05:54:46 +00001432 ProcessInstanceInfoMatch match_info;
1433 packet.SetFilePos(::strlen ("qfProcessInfo"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001434 if (packet.GetChar() == ':')
1435 {
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001436
Greg Clayton32e0a752011-03-30 18:16:51 +00001437 std::string key;
1438 std::string value;
1439 while (packet.GetNameColonValue(key, value))
1440 {
1441 bool success = true;
1442 if (key.compare("name") == 0)
1443 {
1444 StringExtractor extractor;
1445 extractor.GetStringRef().swap(value);
1446 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001447 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001448 }
1449 else if (key.compare("name_match") == 0)
1450 {
1451 if (value.compare("equals") == 0)
1452 {
1453 match_info.SetNameMatchType (eNameMatchEquals);
1454 }
1455 else if (value.compare("starts_with") == 0)
1456 {
1457 match_info.SetNameMatchType (eNameMatchStartsWith);
1458 }
1459 else if (value.compare("ends_with") == 0)
1460 {
1461 match_info.SetNameMatchType (eNameMatchEndsWith);
1462 }
1463 else if (value.compare("contains") == 0)
1464 {
1465 match_info.SetNameMatchType (eNameMatchContains);
1466 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001467 else if (value.compare("regex") == 0)
Greg Clayton32e0a752011-03-30 18:16:51 +00001468 {
1469 match_info.SetNameMatchType (eNameMatchRegularExpression);
1470 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001471 else
Greg Clayton32e0a752011-03-30 18:16:51 +00001472 {
1473 success = false;
1474 }
1475 }
1476 else if (key.compare("pid") == 0)
1477 {
1478 match_info.GetProcessInfo().SetProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1479 }
1480 else if (key.compare("parent_pid") == 0)
1481 {
1482 match_info.GetProcessInfo().SetParentProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1483 }
1484 else if (key.compare("uid") == 0)
1485 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001486 match_info.GetProcessInfo().SetUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001487 }
1488 else if (key.compare("gid") == 0)
1489 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001490 match_info.GetProcessInfo().SetGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001491 }
1492 else if (key.compare("euid") == 0)
1493 {
1494 match_info.GetProcessInfo().SetEffectiveUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1495 }
1496 else if (key.compare("egid") == 0)
1497 {
1498 match_info.GetProcessInfo().SetEffectiveGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1499 }
1500 else if (key.compare("all_users") == 0)
1501 {
1502 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
1503 }
1504 else if (key.compare("triple") == 0)
1505 {
Greg Claytoneb0103f2011-04-07 22:46:35 +00001506 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
Greg Clayton32e0a752011-03-30 18:16:51 +00001507 }
1508 else
1509 {
1510 success = false;
1511 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001512
Greg Clayton32e0a752011-03-30 18:16:51 +00001513 if (!success)
1514 return SendErrorResponse (2);
1515 }
1516 }
1517
1518 if (Host::FindProcesses (match_info, m_proc_infos))
1519 {
1520 // We found something, return the first item by calling the get
1521 // subsequent process info packet handler...
1522 return Handle_qsProcessInfo (packet);
1523 }
1524 return SendErrorResponse (3);
1525}
1526
Greg Clayton3dedae12013-12-06 21:45:27 +00001527GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001528GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
1529{
1530 if (m_proc_infos_index < m_proc_infos.GetSize())
1531 {
1532 StreamString response;
1533 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
1534 ++m_proc_infos_index;
Greg Clayton37a0a242012-04-11 00:24:49 +00001535 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001536 }
1537 return SendErrorResponse (4);
1538}
1539
Greg Clayton3dedae12013-12-06 21:45:27 +00001540GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001541GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
1542{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001543#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001544 // Packet format: "qUserName:%i" where %i is the uid
Greg Clayton8b82f082011-04-12 05:54:46 +00001545 packet.SetFilePos(::strlen ("qUserName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001546 uint32_t uid = packet.GetU32 (UINT32_MAX);
1547 if (uid != UINT32_MAX)
1548 {
1549 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001550 if (HostInfo::LookupUserName(uid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001551 {
1552 StreamString response;
1553 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001554 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001555 }
1556 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001557#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001558 return SendErrorResponse (5);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001559
Greg Clayton32e0a752011-03-30 18:16:51 +00001560}
1561
Greg Clayton3dedae12013-12-06 21:45:27 +00001562GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001563GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
1564{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001565#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001566 // Packet format: "qGroupName:%i" where %i is the gid
Greg Clayton8b82f082011-04-12 05:54:46 +00001567 packet.SetFilePos(::strlen ("qGroupName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001568 uint32_t gid = packet.GetU32 (UINT32_MAX);
1569 if (gid != UINT32_MAX)
1570 {
1571 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001572 if (HostInfo::LookupGroupName(gid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001573 {
1574 StreamString response;
1575 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001576 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001577 }
1578 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001579#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001580 return SendErrorResponse (6);
1581}
1582
Greg Clayton3dedae12013-12-06 21:45:27 +00001583GDBRemoteCommunication::PacketResult
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001584GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
1585{
Greg Clayton8b82f082011-04-12 05:54:46 +00001586 packet.SetFilePos(::strlen ("qSpeedTest:"));
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001587
1588 std::string key;
1589 std::string value;
1590 bool success = packet.GetNameColonValue(key, value);
1591 if (success && key.compare("response_size") == 0)
1592 {
1593 uint32_t response_size = Args::StringToUInt32(value.c_str(), 0, 0, &success);
1594 if (success)
1595 {
1596 if (response_size == 0)
1597 return SendOKResponse();
1598 StreamString response;
1599 uint32_t bytes_left = response_size;
1600 response.PutCString("data:");
1601 while (bytes_left > 0)
1602 {
1603 if (bytes_left >= 26)
1604 {
1605 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1606 bytes_left -= 26;
1607 }
1608 else
1609 {
1610 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1611 bytes_left = 0;
1612 }
1613 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001614 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001615 }
1616 }
1617 return SendErrorResponse (7);
1618}
Greg Clayton8b82f082011-04-12 05:54:46 +00001619
Greg Clayton8b82f082011-04-12 05:54:46 +00001620//
1621//static bool
1622//WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
1623//{
1624// const int time_delta_usecs = 100000;
1625// const int num_retries = timeout_in_seconds/time_delta_usecs;
1626// for (int i=0; i<num_retries; i++)
1627// {
1628// struct proc_bsdinfo bsd_info;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001629// int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
1630// (uint64_t) 0,
1631// &bsd_info,
Greg Clayton8b82f082011-04-12 05:54:46 +00001632// PROC_PIDTBSDINFO_SIZE);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001633//
Greg Clayton8b82f082011-04-12 05:54:46 +00001634// switch (error)
1635// {
1636// case EINVAL:
1637// case ENOTSUP:
1638// case ESRCH:
1639// case EPERM:
1640// return false;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001641//
Greg Clayton8b82f082011-04-12 05:54:46 +00001642// default:
1643// break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001644//
Greg Clayton8b82f082011-04-12 05:54:46 +00001645// case 0:
1646// if (bsd_info.pbi_status == SSTOP)
1647// return true;
1648// }
1649// ::usleep (time_delta_usecs);
1650// }
1651// return false;
1652//}
1653
Greg Clayton3dedae12013-12-06 21:45:27 +00001654GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001655GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
1656{
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001657 // The 'A' packet is the most over designed packet ever here with
1658 // redundant argument indexes, redundant argument lengths and needed hex
1659 // encoded argument string values. Really all that is needed is a comma
Greg Clayton8b82f082011-04-12 05:54:46 +00001660 // separated hex encoded argument value list, but we will stay true to the
1661 // documented version of the 'A' packet here...
1662
Todd Fialaaf245d12014-06-30 21:05:18 +00001663 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1664 int actual_arg_index = 0;
1665
Greg Clayton8b82f082011-04-12 05:54:46 +00001666 packet.SetFilePos(1); // Skip the 'A'
1667 bool success = true;
1668 while (success && packet.GetBytesLeft() > 0)
1669 {
1670 // Decode the decimal argument string length. This length is the
1671 // number of hex nibbles in the argument string value.
1672 const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1673 if (arg_len == UINT32_MAX)
1674 success = false;
1675 else
1676 {
1677 // Make sure the argument hex string length is followed by a comma
1678 if (packet.GetChar() != ',')
1679 success = false;
1680 else
1681 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001682 // Decode the argument index. We ignore this really because
Greg Clayton8b82f082011-04-12 05:54:46 +00001683 // who would really send down the arguments in a random order???
1684 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1685 if (arg_idx == UINT32_MAX)
1686 success = false;
1687 else
1688 {
1689 // Make sure the argument index is followed by a comma
1690 if (packet.GetChar() != ',')
1691 success = false;
1692 else
1693 {
1694 // Decode the argument string value from hex bytes
1695 // back into a UTF8 string and make sure the length
1696 // matches the one supplied in the packet
1697 std::string arg;
Todd Fialaaf245d12014-06-30 21:05:18 +00001698 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2))
Greg Clayton8b82f082011-04-12 05:54:46 +00001699 success = false;
1700 else
1701 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001702 // If there are any bytes left
Greg Clayton8b82f082011-04-12 05:54:46 +00001703 if (packet.GetBytesLeft())
1704 {
1705 if (packet.GetChar() != ',')
1706 success = false;
1707 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001708
Greg Clayton8b82f082011-04-12 05:54:46 +00001709 if (success)
1710 {
1711 if (arg_idx == 0)
1712 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
1713 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001714 if (log)
1715 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ());
1716 ++actual_arg_index;
Greg Clayton8b82f082011-04-12 05:54:46 +00001717 }
1718 }
1719 }
1720 }
1721 }
1722 }
1723 }
1724
1725 if (success)
1726 {
Todd Fiala9f377372014-01-27 20:44:50 +00001727 m_process_launch_error = LaunchProcess ();
Greg Clayton8b82f082011-04-12 05:54:46 +00001728 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1729 {
1730 return SendOKResponse ();
1731 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001732 else
1733 {
1734 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1735 if (log)
1736 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s",
1737 __FUNCTION__,
1738 m_process_launch_error.AsCString());
1739
1740 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001741 }
1742 return SendErrorResponse (8);
1743}
1744
Greg Clayton3dedae12013-12-06 21:45:27 +00001745GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001746GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
1747{
Greg Clayton8b82f082011-04-12 05:54:46 +00001748 StreamString response;
Todd Fialaaf245d12014-06-30 21:05:18 +00001749
1750 if (IsGdbServer ())
Greg Clayton8b82f082011-04-12 05:54:46 +00001751 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001752 // Fail if we don't have a current process.
1753 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1754 return SendErrorResponse (68);
1755
1756 // Make sure we set the current thread so g and p packets return
1757 // the data the gdb will expect.
1758 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1759 SetCurrentThreadID (tid);
1760
1761 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1762 if (!thread_sp)
1763 return SendErrorResponse (69);
1764
1765 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1766 }
1767 else
1768 {
1769 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here
1770 // should not be used. It is reporting process id instead of thread id. The
1771 // correct answer doesn't seem to make much sense for lldb-platform.
1772 // CONSIDER: flip to "unsupported".
1773 lldb::pid_t pid = m_process_launch_info.GetProcessID();
1774 response.Printf("QC%" PRIx64, pid);
1775
1776 // this should always be platform here
1777 assert (m_is_platform && "this code path should only be traversed for lldb-platform");
1778
1779 if (m_is_platform)
Greg Clayton8b82f082011-04-12 05:54:46 +00001780 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001781 // If we launch a process and this GDB server is acting as a platform,
1782 // then we need to clear the process launch state so we can start
1783 // launching another process. In order to launch a process a bunch or
1784 // packets need to be sent: environment packets, working directory,
1785 // disable ASLR, and many more settings. When we launch a process we
1786 // then need to know when to clear this information. Currently we are
1787 // selecting the 'qC' packet as that packet which seems to make the most
1788 // sense.
1789 if (pid != LLDB_INVALID_PROCESS_ID)
1790 {
1791 m_process_launch_info.Clear();
1792 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001793 }
1794 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001795 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00001796}
1797
1798bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00001799GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
1800{
1801 Mutex::Locker locker (m_spawned_pids_mutex);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001802 FreePortForProcess(pid);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001803 return m_spawned_pids.erase(pid) > 0;
1804}
1805bool
1806GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
1807 lldb::pid_t pid,
1808 bool exited,
1809 int signal, // Zero for no signal
1810 int status) // Exit value of process if signal is zero
1811{
1812 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1813 server->DebugserverProcessReaped (pid);
1814 return true;
1815}
1816
Todd Fiala3e92a2b2014-01-24 00:52:53 +00001817bool
1818GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
1819{
1820 // reap a process that we were debugging (but not debugserver)
1821 Mutex::Locker locker (m_spawned_pids_mutex);
1822 return m_spawned_pids.erase(pid) > 0;
1823}
1824
1825bool
1826GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
1827 lldb::pid_t pid,
1828 bool exited,
1829 int signal, // Zero for no signal
1830 int status) // Exit value of process if signal is zero
1831{
1832 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1833 server->DebuggedProcessReaped (pid);
1834 return true;
1835}
1836
Greg Clayton3dedae12013-12-06 21:45:27 +00001837GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001838GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
1839{
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001840#ifdef _WIN32
Deepak Panickal263fde02014-01-14 11:34:44 +00001841 return SendErrorResponse(9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001842#else
Todd Fiala015d8182014-07-22 23:41:36 +00001843 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1844
Greg Clayton8b82f082011-04-12 05:54:46 +00001845 // Spawn a local debugserver as a platform so we can then attach or launch
1846 // a process...
1847
1848 if (m_is_platform)
1849 {
Todd Fiala015d8182014-07-22 23:41:36 +00001850 if (log)
1851 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
1852
Greg Clayton8b82f082011-04-12 05:54:46 +00001853 // Sleep and wait a bit for debugserver to start to listen...
1854 ConnectionFileDescriptor file_conn;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001855 std::string hostname;
Sylvestre Ledrufaa63ce2013-09-28 15:57:37 +00001856 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001857 // with the TMPDIR environment variable
Greg Clayton29b8fc42013-11-21 01:44:58 +00001858 packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
1859 std::string name;
1860 std::string value;
1861 uint16_t port = UINT16_MAX;
1862 while (packet.GetNameColonValue(name, value))
Greg Clayton8b82f082011-04-12 05:54:46 +00001863 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001864 if (name.compare ("host") == 0)
1865 hostname.swap(value);
1866 else if (name.compare ("port") == 0)
1867 port = Args::StringToUInt32(value.c_str(), 0, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00001868 }
Greg Clayton29b8fc42013-11-21 01:44:58 +00001869 if (port == UINT16_MAX)
1870 port = GetNextAvailablePort();
1871
1872 // Spawn a new thread to accept the port that gets bound after
1873 // binding to port 0 (zero).
Greg Claytonfbb76342013-11-20 21:07:01 +00001874
Todd Fiala015d8182014-07-22 23:41:36 +00001875 // Spawn a debugserver and try to get the port it listens to.
1876 ProcessLaunchInfo debugserver_launch_info;
1877 if (hostname.empty())
1878 hostname = "127.0.0.1";
1879 if (log)
1880 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
1881
1882 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
1883
1884 Error error = StartDebugserverProcess (hostname.empty() ? NULL : hostname.c_str(),
1885 port,
1886 debugserver_launch_info,
1887 port);
1888
1889 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
1890
1891
1892 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1893 {
1894 Mutex::Locker locker (m_spawned_pids_mutex);
1895 m_spawned_pids.insert(debugserver_pid);
1896 if (port > 0)
1897 AssociatePortWithProcess(port, debugserver_pid);
1898 }
1899 else
1900 {
1901 if (port > 0)
1902 FreePort (port);
1903 }
1904
Greg Clayton29b8fc42013-11-21 01:44:58 +00001905 if (error.Success())
1906 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001907 if (log)
Todd Fiala015d8182014-07-22 23:41:36 +00001908 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001909
Todd Fiala015d8182014-07-22 23:41:36 +00001910 char response[256];
1911 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
1912 assert (response_len < (int)sizeof(response));
1913 PacketResult packet_result = SendPacketNoLock (response, response_len);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001914
Todd Fiala015d8182014-07-22 23:41:36 +00001915 if (packet_result != PacketResult::Success)
Greg Clayton29b8fc42013-11-21 01:44:58 +00001916 {
Todd Fiala015d8182014-07-22 23:41:36 +00001917 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1918 ::kill (debugserver_pid, SIGINT);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001919 }
Todd Fiala015d8182014-07-22 23:41:36 +00001920 return packet_result;
1921 }
1922 else
1923 {
1924 if (log)
1925 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ());
Greg Clayton8b82f082011-04-12 05:54:46 +00001926 }
1927 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001928 return SendErrorResponse (9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001929#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00001930}
1931
Todd Fiala403edc52014-01-23 22:05:44 +00001932bool
1933GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
1934{
1935 // make sure we know about this process
1936 {
1937 Mutex::Locker locker (m_spawned_pids_mutex);
1938 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1939 return false;
1940 }
1941
1942 // first try a SIGTERM (standard kill)
1943 Host::Kill (pid, SIGTERM);
1944
1945 // check if that worked
1946 for (size_t i=0; i<10; ++i)
1947 {
1948 {
1949 Mutex::Locker locker (m_spawned_pids_mutex);
1950 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1951 {
1952 // it is now killed
1953 return true;
1954 }
1955 }
1956 usleep (10000);
1957 }
1958
1959 // check one more time after the final usleep
1960 {
1961 Mutex::Locker locker (m_spawned_pids_mutex);
1962 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1963 return true;
1964 }
1965
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001966 // the launched process still lives. Now try killing it again,
Todd Fiala403edc52014-01-23 22:05:44 +00001967 // this time with an unblockable signal.
1968 Host::Kill (pid, SIGKILL);
1969
1970 for (size_t i=0; i<10; ++i)
1971 {
1972 {
1973 Mutex::Locker locker (m_spawned_pids_mutex);
1974 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1975 {
1976 // it is now killed
1977 return true;
1978 }
1979 }
1980 usleep (10000);
1981 }
1982
1983 // check one more time after the final usleep
1984 // Scope for locker
1985 {
1986 Mutex::Locker locker (m_spawned_pids_mutex);
1987 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1988 return true;
1989 }
1990
1991 // no luck - the process still lives
1992 return false;
1993}
1994
Greg Clayton3dedae12013-12-06 21:45:27 +00001995GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00001996GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
1997{
Todd Fiala403edc52014-01-23 22:05:44 +00001998 packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001999
Todd Fiala403edc52014-01-23 22:05:44 +00002000 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
2001
2002 // verify that we know anything about this pid.
2003 // Scope for locker
Daniel Maleae0f8f572013-08-26 23:57:52 +00002004 {
Todd Fiala403edc52014-01-23 22:05:44 +00002005 Mutex::Locker locker (m_spawned_pids_mutex);
2006 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002007 {
Todd Fiala403edc52014-01-23 22:05:44 +00002008 // not a pid we know about
2009 return SendErrorResponse (10);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002010 }
2011 }
Todd Fiala403edc52014-01-23 22:05:44 +00002012
2013 // go ahead and attempt to kill the spawned process
2014 if (KillSpawnedProcess (pid))
2015 return SendOKResponse ();
2016 else
2017 return SendErrorResponse (11);
2018}
2019
2020GDBRemoteCommunication::PacketResult
2021GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
2022{
2023 // ignore for now if we're lldb_platform
2024 if (m_is_platform)
2025 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2026
2027 // shutdown all spawned processes
2028 std::set<lldb::pid_t> spawned_pids_copy;
2029
2030 // copy pids
2031 {
2032 Mutex::Locker locker (m_spawned_pids_mutex);
2033 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
2034 }
2035
2036 // nuke the spawned processes
2037 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
2038 {
2039 lldb::pid_t spawned_pid = *it;
2040 if (!KillSpawnedProcess (spawned_pid))
2041 {
2042 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
2043 }
2044 }
2045
Todd Fialaaf245d12014-06-30 21:05:18 +00002046 FlushInferiorOutput ();
2047
2048 // No OK response for kill packet.
2049 // return SendOKResponse ();
2050 return PacketResult::Success;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002051}
2052
Greg Clayton3dedae12013-12-06 21:45:27 +00002053GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002054GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
2055{
2056 if (m_process_launch_error.Success())
2057 return SendOKResponse();
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002058 StreamString response;
Greg Clayton8b82f082011-04-12 05:54:46 +00002059 response.PutChar('E');
2060 response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
Greg Clayton37a0a242012-04-11 00:24:49 +00002061 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00002062}
2063
Greg Clayton3dedae12013-12-06 21:45:27 +00002064GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002065GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet)
2066{
2067 packet.SetFilePos(::strlen ("QEnvironment:"));
2068 const uint32_t bytes_left = packet.GetBytesLeft();
2069 if (bytes_left > 0)
2070 {
2071 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
2072 return SendOKResponse ();
2073 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002074 return SendErrorResponse (12);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002075}
2076
Greg Clayton3dedae12013-12-06 21:45:27 +00002077GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002078GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
2079{
2080 packet.SetFilePos(::strlen ("QLaunchArch:"));
2081 const uint32_t bytes_left = packet.GetBytesLeft();
2082 if (bytes_left > 0)
2083 {
2084 const char* arch_triple = packet.Peek();
2085 ArchSpec arch_spec(arch_triple,NULL);
2086 m_process_launch_info.SetArchitecture(arch_spec);
2087 return SendOKResponse();
2088 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002089 return SendErrorResponse(13);
Greg Clayton8b82f082011-04-12 05:54:46 +00002090}
2091
Greg Clayton3dedae12013-12-06 21:45:27 +00002092GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002093GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
2094{
2095 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
2096 if (packet.GetU32(0))
2097 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
2098 else
2099 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
2100 return SendOKResponse ();
2101}
2102
Greg Clayton3dedae12013-12-06 21:45:27 +00002103GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002104GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
2105{
2106 packet.SetFilePos(::strlen ("QSetWorkingDir:"));
2107 std::string path;
2108 packet.GetHexByteString(path);
Greg Claytonfbb76342013-11-20 21:07:01 +00002109 if (m_is_platform)
2110 {
Colin Riley909bb7a2013-11-26 15:10:46 +00002111#ifdef _WIN32
2112 // Not implemented on Windows
2113 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
2114#else
Greg Claytonfbb76342013-11-20 21:07:01 +00002115 // If this packet is sent to a platform, then change the current working directory
2116 if (::chdir(path.c_str()) != 0)
2117 return SendErrorResponse(errno);
Colin Riley909bb7a2013-11-26 15:10:46 +00002118#endif
Greg Claytonfbb76342013-11-20 21:07:01 +00002119 }
2120 else
2121 {
2122 m_process_launch_info.SwapWorkingDirectory (path);
2123 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002124 return SendOKResponse ();
2125}
2126
Greg Clayton3dedae12013-12-06 21:45:27 +00002127GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002128GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
2129{
2130 StreamString response;
2131
2132 if (m_is_platform)
2133 {
2134 // If this packet is sent to a platform, then change the current working directory
2135 char cwd[PATH_MAX];
2136 if (getcwd(cwd, sizeof(cwd)) == NULL)
2137 {
2138 return SendErrorResponse(errno);
2139 }
2140 else
2141 {
2142 response.PutBytesAsRawHex8(cwd, strlen(cwd));
Greg Clayton3dedae12013-12-06 21:45:27 +00002143 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002144 }
2145 }
2146 else
2147 {
2148 const char *working_dir = m_process_launch_info.GetWorkingDirectory();
2149 if (working_dir && working_dir[0])
2150 {
2151 response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
Greg Clayton3dedae12013-12-06 21:45:27 +00002152 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002153 }
2154 else
2155 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002156 return SendErrorResponse(14);
Greg Claytonfbb76342013-11-20 21:07:01 +00002157 }
2158 }
2159}
2160
Greg Clayton3dedae12013-12-06 21:45:27 +00002161GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002162GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
2163{
2164 packet.SetFilePos(::strlen ("QSetSTDIN:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002165 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002166 std::string path;
2167 packet.GetHexByteString(path);
2168 const bool read = false;
2169 const bool write = true;
2170 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
2171 {
2172 m_process_launch_info.AppendFileAction(file_action);
2173 return SendOKResponse ();
2174 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002175 return SendErrorResponse (15);
Greg Clayton8b82f082011-04-12 05:54:46 +00002176}
2177
Greg Clayton3dedae12013-12-06 21:45:27 +00002178GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002179GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
2180{
2181 packet.SetFilePos(::strlen ("QSetSTDOUT:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002182 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002183 std::string path;
2184 packet.GetHexByteString(path);
2185 const bool read = true;
2186 const bool write = false;
2187 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
2188 {
2189 m_process_launch_info.AppendFileAction(file_action);
2190 return SendOKResponse ();
2191 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002192 return SendErrorResponse (16);
Greg Clayton8b82f082011-04-12 05:54:46 +00002193}
2194
Greg Clayton3dedae12013-12-06 21:45:27 +00002195GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002196GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
2197{
2198 packet.SetFilePos(::strlen ("QSetSTDERR:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002199 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002200 std::string path;
2201 packet.GetHexByteString(path);
2202 const bool read = true;
Greg Clayton9845a8d2012-03-06 04:01:04 +00002203 const bool write = false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002204 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
2205 {
2206 m_process_launch_info.AppendFileAction(file_action);
2207 return SendOKResponse ();
2208 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002209 return SendErrorResponse (17);
Greg Clayton8b82f082011-04-12 05:54:46 +00002210}
2211
Greg Clayton3dedae12013-12-06 21:45:27 +00002212GDBRemoteCommunication::PacketResult
Todd Fialaaf245d12014-06-30 21:05:18 +00002213GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet)
2214{
2215 if (!IsGdbServer ())
2216 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2217
2218 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2219 if (log)
2220 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2221
2222 // Ensure we have a native process.
2223 if (!m_debugged_process_sp)
2224 {
2225 if (log)
2226 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2227 return SendErrorResponse (0x36);
2228 }
2229
2230 // Pull out the signal number.
2231 packet.SetFilePos (::strlen ("C"));
2232 if (packet.GetBytesLeft () < 1)
2233 {
2234 // Shouldn't be using a C without a signal.
2235 return SendIllFormedResponse (packet, "C packet specified without signal.");
2236 }
2237 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2238 if (signo == std::numeric_limits<uint32_t>::max ())
2239 return SendIllFormedResponse (packet, "failed to parse signal number");
2240
2241 // Handle optional continue address.
2242 if (packet.GetBytesLeft () > 0)
2243 {
2244 // FIXME add continue at address support for $C{signo}[;{continue-address}].
2245 if (*packet.Peek () == ';')
2246 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2247 else
2248 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
2249 }
2250
2251 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
2252 Error error;
2253
2254 // We have two branches: what to do if a continue thread is specified (in which case we target
2255 // sending the signal to that thread), or when we don't have a continue thread set (in which
2256 // case we send a signal to the process).
2257
2258 // TODO discuss with Greg Clayton, make sure this makes sense.
2259
2260 lldb::tid_t signal_tid = GetContinueThreadID ();
2261 if (signal_tid != LLDB_INVALID_THREAD_ID)
2262 {
2263 // The resume action for the continue thread (or all threads if a continue thread is not set).
2264 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
2265
2266 // Add the action for the continue thread (or all threads when the continue thread isn't present).
2267 resume_actions.Append (action);
2268 }
2269 else
2270 {
2271 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
2272 error = m_debugged_process_sp->Signal (signo);
2273 if (error.Fail ())
2274 {
2275 if (log)
2276 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s",
2277 __FUNCTION__,
2278 m_debugged_process_sp->GetID (),
2279 error.AsCString ());
2280
2281 return SendErrorResponse (0x52);
2282 }
2283 }
2284
2285 // Resume the threads.
2286 error = m_debugged_process_sp->Resume (resume_actions);
2287 if (error.Fail ())
2288 {
2289 if (log)
2290 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s",
2291 __FUNCTION__,
2292 m_debugged_process_sp->GetID (),
2293 error.AsCString ());
2294
2295 return SendErrorResponse (0x38);
2296 }
2297
2298 // Don't send an "OK" packet; response is the stopped/exited message.
2299 return PacketResult::Success;
2300}
2301
2302GDBRemoteCommunication::PacketResult
2303GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment)
2304{
2305 if (!IsGdbServer ())
2306 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2307
2308 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2309 if (log)
2310 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2311
2312 // We reuse this method in vCont - don't double adjust the file position.
2313 if (!skip_file_pos_adjustment)
2314 packet.SetFilePos (::strlen ("c"));
2315
2316 // For now just support all continue.
2317 const bool has_continue_address = (packet.GetBytesLeft () > 0);
2318 if (has_continue_address)
2319 {
2320 if (log)
2321 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
2322 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2323 }
2324
2325 // Ensure we have a native process.
2326 if (!m_debugged_process_sp)
2327 {
2328 if (log)
2329 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2330 return SendErrorResponse (0x36);
2331 }
2332
2333 // Build the ResumeActionList
2334 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
2335
2336 Error error = m_debugged_process_sp->Resume (actions);
2337 if (error.Fail ())
2338 {
2339 if (log)
2340 {
2341 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s",
2342 __FUNCTION__,
2343 m_debugged_process_sp->GetID (),
2344 error.AsCString ());
2345 }
2346 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2347 }
2348
2349 if (log)
2350 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2351
2352 // No response required from continue.
2353 return PacketResult::Success;
2354}
2355
2356GDBRemoteCommunication::PacketResult
2357GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet)
2358{
2359 if (!IsGdbServer ())
2360 {
2361 // only llgs supports $vCont.
2362 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2363 }
2364
Todd Fialaaf245d12014-06-30 21:05:18 +00002365 StreamString response;
2366 response.Printf("vCont;c;C;s;S");
2367
2368 return SendPacketNoLock(response.GetData(), response.GetSize());
2369}
2370
2371GDBRemoteCommunication::PacketResult
2372GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet)
2373{
2374 if (!IsGdbServer ())
2375 {
2376 // only llgs supports $vCont
2377 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2378 }
2379
2380 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2381 if (log)
2382 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__);
2383
2384 packet.SetFilePos (::strlen ("vCont"));
2385
2386 // Check if this is all continue (no options or ";c").
2387 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0))
2388 {
2389 // Move the packet past the ";c".
2390 if (packet.GetBytesLeft ())
2391 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c"));
2392
2393 const bool skip_file_pos_adjustment = true;
2394 return Handle_c (packet, skip_file_pos_adjustment);
2395 }
2396 else if (::strcmp (packet.Peek (), ";s") == 0)
2397 {
2398 // Move past the ';', then do a simple 's'.
2399 packet.SetFilePos (packet.GetFilePos () + 1);
2400 return Handle_s (packet);
2401 }
2402
2403 // Ensure we have a native process.
2404 if (!m_debugged_process_sp)
2405 {
2406 if (log)
2407 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2408 return SendErrorResponse (0x36);
2409 }
2410
2411 ResumeActionList thread_actions;
2412
2413 while (packet.GetBytesLeft () && *packet.Peek () == ';')
2414 {
2415 // Skip the semi-colon.
2416 packet.GetChar ();
2417
2418 // Build up the thread action.
2419 ResumeAction thread_action;
2420 thread_action.tid = LLDB_INVALID_THREAD_ID;
2421 thread_action.state = eStateInvalid;
2422 thread_action.signal = 0;
2423
2424 const char action = packet.GetChar ();
2425 switch (action)
2426 {
2427 case 'C':
2428 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2429 if (thread_action.signal == 0)
2430 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
2431 // Fall through to next case...
2432
2433 case 'c':
2434 // Continue
2435 thread_action.state = eStateRunning;
2436 break;
2437
2438 case 'S':
2439 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2440 if (thread_action.signal == 0)
2441 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
2442 // Fall through to next case...
2443
2444 case 's':
2445 // Step
2446 thread_action.state = eStateStepping;
2447 break;
2448
2449 default:
2450 return SendIllFormedResponse (packet, "Unsupported vCont action");
2451 break;
2452 }
2453
2454 // Parse out optional :{thread-id} value.
2455 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
2456 {
2457 // Consume the separator.
2458 packet.GetChar ();
2459
2460 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2461 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
2462 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
2463 }
2464
2465 thread_actions.Append (thread_action);
2466 }
2467
2468 // If a default action for all other threads wasn't mentioned
2469 // then we should stop the threads.
2470 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0);
2471
2472 Error error = m_debugged_process_sp->Resume (thread_actions);
2473 if (error.Fail ())
2474 {
2475 if (log)
2476 {
2477 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s",
2478 __FUNCTION__,
2479 m_debugged_process_sp->GetID (),
2480 error.AsCString ());
2481 }
2482 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2483 }
2484
2485 if (log)
2486 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2487
2488 // No response required from vCont.
2489 return PacketResult::Success;
2490}
2491
2492GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00002493GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
2494{
2495 // Send response first before changing m_send_acks to we ack this packet
Greg Clayton3dedae12013-12-06 21:45:27 +00002496 PacketResult packet_result = SendOKResponse ();
Greg Clayton1cb64962011-03-24 04:28:38 +00002497 m_send_acks = false;
Greg Clayton3dedae12013-12-06 21:45:27 +00002498 return packet_result;
Greg Clayton1cb64962011-03-24 04:28:38 +00002499}
Daniel Maleae0f8f572013-08-26 23:57:52 +00002500
Greg Clayton3dedae12013-12-06 21:45:27 +00002501GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002502GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002503{
Greg Claytonfbb76342013-11-20 21:07:01 +00002504 packet.SetFilePos(::strlen("qPlatform_mkdir:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002505 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002506 if (packet.GetChar() == ',')
2507 {
2508 std::string path;
2509 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002510 Error error = FileSystem::MakeDirectory(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002511 if (error.Success())
2512 return SendPacketNoLock ("OK", 2);
2513 else
2514 return SendErrorResponse(error.GetError());
2515 }
2516 return SendErrorResponse(20);
Greg Claytonfbb76342013-11-20 21:07:01 +00002517}
2518
Greg Clayton3dedae12013-12-06 21:45:27 +00002519GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002520GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
2521{
2522 packet.SetFilePos(::strlen("qPlatform_chmod:"));
2523
2524 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002525 if (packet.GetChar() == ',')
2526 {
2527 std::string path;
2528 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002529 Error error = FileSystem::SetFilePermissions(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002530 if (error.Success())
2531 return SendPacketNoLock ("OK", 2);
2532 else
2533 return SendErrorResponse(error.GetError());
2534 }
2535 return SendErrorResponse(19);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002536}
2537
Greg Clayton3dedae12013-12-06 21:45:27 +00002538GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002539GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
2540{
2541 packet.SetFilePos(::strlen("vFile:open:"));
2542 std::string path;
2543 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002544 if (!path.empty())
2545 {
2546 if (packet.GetChar() == ',')
2547 {
2548 uint32_t flags = packet.GetHexMaxU32(false, 0);
2549 if (packet.GetChar() == ',')
2550 {
2551 mode_t mode = packet.GetHexMaxU32(false, 0600);
2552 Error error;
2553 int fd = ::open (path.c_str(), flags, mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002554 const int save_errno = fd == -1 ? errno : 0;
2555 StreamString response;
2556 response.PutChar('F');
2557 response.Printf("%i", fd);
2558 if (save_errno)
2559 response.Printf(",%i", save_errno);
2560 return SendPacketNoLock(response.GetData(), response.GetSize());
2561 }
2562 }
2563 }
2564 return SendErrorResponse(18);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002565}
2566
Greg Clayton3dedae12013-12-06 21:45:27 +00002567GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002568GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
2569{
2570 packet.SetFilePos(::strlen("vFile:close:"));
2571 int fd = packet.GetS32(-1);
2572 Error error;
2573 int err = -1;
2574 int save_errno = 0;
2575 if (fd >= 0)
2576 {
2577 err = close(fd);
2578 save_errno = err == -1 ? errno : 0;
2579 }
2580 else
2581 {
2582 save_errno = EINVAL;
2583 }
2584 StreamString response;
2585 response.PutChar('F');
2586 response.Printf("%i", err);
2587 if (save_errno)
2588 response.Printf(",%i", save_errno);
Greg Clayton2b98c562013-11-22 18:53:12 +00002589 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002590}
2591
Greg Clayton3dedae12013-12-06 21:45:27 +00002592GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002593GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
2594{
Virgile Belloae12a362013-08-27 16:21:49 +00002595#ifdef _WIN32
2596 // Not implemented on Windows
Greg Clayton2b98c562013-11-22 18:53:12 +00002597 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002598#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002599 StreamGDBRemote response;
2600 packet.SetFilePos(::strlen("vFile:pread:"));
2601 int fd = packet.GetS32(-1);
Greg Clayton2b98c562013-11-22 18:53:12 +00002602 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002603 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002604 uint64_t count = packet.GetU64(UINT64_MAX);
2605 if (packet.GetChar() == ',')
2606 {
2607 uint64_t offset = packet.GetU64(UINT32_MAX);
2608 if (count == UINT64_MAX)
2609 {
2610 response.Printf("F-1:%i", EINVAL);
2611 return SendPacketNoLock(response.GetData(), response.GetSize());
2612 }
2613
2614 std::string buffer(count, 0);
2615 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
2616 const int save_errno = bytes_read == -1 ? errno : 0;
2617 response.PutChar('F');
2618 response.Printf("%zi", bytes_read);
2619 if (save_errno)
2620 response.Printf(",%i", save_errno);
2621 else
2622 {
2623 response.PutChar(';');
2624 response.PutEscapedBytes(&buffer[0], bytes_read);
2625 }
2626 return SendPacketNoLock(response.GetData(), response.GetSize());
2627 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002628 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002629 return SendErrorResponse(21);
2630
Virgile Belloae12a362013-08-27 16:21:49 +00002631#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002632}
2633
Greg Clayton3dedae12013-12-06 21:45:27 +00002634GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002635GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
2636{
Virgile Belloae12a362013-08-27 16:21:49 +00002637#ifdef _WIN32
Greg Clayton2b98c562013-11-22 18:53:12 +00002638 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002639#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002640 packet.SetFilePos(::strlen("vFile:pwrite:"));
2641
2642 StreamGDBRemote response;
2643 response.PutChar('F');
2644
2645 int fd = packet.GetU32(UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002646 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002647 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002648 off_t offset = packet.GetU64(UINT32_MAX);
2649 if (packet.GetChar() == ',')
2650 {
2651 std::string buffer;
2652 if (packet.GetEscapedBinaryData(buffer))
2653 {
2654 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
2655 const int save_errno = bytes_written == -1 ? errno : 0;
2656 response.Printf("%zi", bytes_written);
2657 if (save_errno)
2658 response.Printf(",%i", save_errno);
2659 }
2660 else
2661 {
2662 response.Printf ("-1,%i", EINVAL);
2663 }
2664 return SendPacketNoLock(response.GetData(), response.GetSize());
2665 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002666 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002667 return SendErrorResponse(27);
Virgile Belloae12a362013-08-27 16:21:49 +00002668#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002669}
2670
Greg Clayton3dedae12013-12-06 21:45:27 +00002671GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002672GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet)
2673{
2674 packet.SetFilePos(::strlen("vFile:size:"));
2675 std::string path;
2676 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002677 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002678 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002679 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002680 StreamString response;
2681 response.PutChar('F');
2682 response.PutHex64(retcode);
2683 if (retcode == UINT64_MAX)
2684 {
2685 response.PutChar(',');
2686 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
2687 }
2688 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002689 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002690 return SendErrorResponse(22);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002691}
2692
Greg Clayton3dedae12013-12-06 21:45:27 +00002693GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002694GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
2695{
2696 packet.SetFilePos(::strlen("vFile:mode:"));
2697 std::string path;
2698 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002699 if (!path.empty())
2700 {
2701 Error error;
2702 const uint32_t mode = File::GetPermissions(path.c_str(), error);
2703 StreamString response;
2704 response.Printf("F%u", mode);
2705 if (mode == 0 || error.Fail())
2706 response.Printf(",%i", (int)error.GetError());
2707 return SendPacketNoLock(response.GetData(), response.GetSize());
2708 }
2709 return SendErrorResponse(23);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002710}
2711
Greg Clayton3dedae12013-12-06 21:45:27 +00002712GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002713GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
2714{
2715 packet.SetFilePos(::strlen("vFile:exists:"));
2716 std::string path;
2717 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002718 if (!path.empty())
2719 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002720 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002721 StreamString response;
2722 response.PutChar('F');
2723 response.PutChar(',');
2724 if (retcode)
2725 response.PutChar('1');
2726 else
2727 response.PutChar('0');
2728 return SendPacketNoLock(response.GetData(), response.GetSize());
2729 }
2730 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002731}
2732
Greg Clayton3dedae12013-12-06 21:45:27 +00002733GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002734GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002735{
Greg Claytonfbb76342013-11-20 21:07:01 +00002736 packet.SetFilePos(::strlen("vFile:symlink:"));
2737 std::string dst, src;
2738 packet.GetHexByteStringTerminatedBy(dst, ',');
2739 packet.GetChar(); // Skip ',' char
2740 packet.GetHexByteString(src);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002741 Error error = FileSystem::Symlink(src.c_str(), dst.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002742 StreamString response;
2743 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002744 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002745}
2746
Greg Clayton3dedae12013-12-06 21:45:27 +00002747GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002748GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
2749{
2750 packet.SetFilePos(::strlen("vFile:unlink:"));
2751 std::string path;
2752 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002753 Error error = FileSystem::Unlink(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002754 StreamString response;
2755 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002756 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002757}
2758
Greg Clayton3dedae12013-12-06 21:45:27 +00002759GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002760GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
2761{
2762 packet.SetFilePos(::strlen("qPlatform_shell:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002763 std::string path;
2764 std::string working_dir;
2765 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002766 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002767 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002768 if (packet.GetChar() == ',')
2769 {
2770 // FIXME: add timeout to qPlatform_shell packet
2771 // uint32_t timeout = packet.GetHexMaxU32(false, 32);
2772 uint32_t timeout = 10;
2773 if (packet.GetChar() == ',')
2774 packet.GetHexByteString(working_dir);
2775 int status, signo;
2776 std::string output;
2777 Error err = Host::RunShellCommand(path.c_str(),
2778 working_dir.empty() ? NULL : working_dir.c_str(),
2779 &status, &signo, &output, timeout);
2780 StreamGDBRemote response;
2781 if (err.Fail())
2782 {
2783 response.PutCString("F,");
2784 response.PutHex32(UINT32_MAX);
2785 }
2786 else
2787 {
2788 response.PutCString("F,");
2789 response.PutHex32(status);
2790 response.PutChar(',');
2791 response.PutHex32(signo);
2792 response.PutChar(',');
2793 response.PutEscapedBytes(output.c_str(), output.size());
2794 }
2795 return SendPacketNoLock(response.GetData(), response.GetSize());
2796 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002797 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002798 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002799}
2800
Todd Fialaaf245d12014-06-30 21:05:18 +00002801void
2802GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid)
2803{
2804 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code");
2805
2806 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2807 if (log)
2808 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
2809
2810 m_current_tid = tid;
2811 if (m_debugged_process_sp)
2812 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
2813}
2814
2815void
2816GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid)
2817{
2818 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code");
2819
2820 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2821 if (log)
2822 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
2823
2824 m_continue_tid = tid;
2825}
2826
2827GDBRemoteCommunication::PacketResult
2828GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet)
2829{
2830 // Handle the $? gdbremote command.
2831 if (!IsGdbServer ())
2832 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented");
2833
2834 // If no process, indicate error
2835 if (!m_debugged_process_sp)
2836 return SendErrorResponse (02);
2837
2838 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2839}
2840
2841GDBRemoteCommunication::PacketResult
2842GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
2843{
2844 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2845
2846 switch (process_state)
2847 {
2848 case eStateAttaching:
2849 case eStateLaunching:
2850 case eStateRunning:
2851 case eStateStepping:
2852 case eStateDetached:
2853 // NOTE: gdb protocol doc looks like it should return $OK
2854 // when everything is running (i.e. no stopped result).
2855 return PacketResult::Success; // Ignore
2856
2857 case eStateSuspended:
2858 case eStateStopped:
2859 case eStateCrashed:
2860 {
2861 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
2862 // Make sure we set the current thread so g and p packets return
2863 // the data the gdb will expect.
2864 SetCurrentThreadID (tid);
2865 return SendStopReplyPacketForThread (tid);
2866 }
2867
2868 case eStateInvalid:
2869 case eStateUnloaded:
2870 case eStateExited:
2871 if (flush_on_exit)
2872 FlushInferiorOutput ();
2873 return SendWResponse(m_debugged_process_sp.get());
2874
2875 default:
2876 if (log)
2877 {
2878 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s",
2879 __FUNCTION__,
2880 m_debugged_process_sp->GetID (),
2881 StateAsCString (process_state));
2882 }
2883 break;
2884 }
2885
2886 return SendErrorResponse (0);
2887}
2888
Greg Clayton3dedae12013-12-06 21:45:27 +00002889GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002890GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
2891{
Greg Clayton2b98c562013-11-22 18:53:12 +00002892 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002893}
2894
Greg Clayton3dedae12013-12-06 21:45:27 +00002895GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002896GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
2897{
Greg Clayton2b98c562013-11-22 18:53:12 +00002898 packet.SetFilePos(::strlen("vFile:MD5:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002899 std::string path;
2900 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002901 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002902 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002903 uint64_t a,b;
2904 StreamGDBRemote response;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002905 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false)
Greg Clayton2b98c562013-11-22 18:53:12 +00002906 {
2907 response.PutCString("F,");
2908 response.PutCString("x");
2909 }
2910 else
2911 {
2912 response.PutCString("F,");
2913 response.PutHex64(a);
2914 response.PutHex64(b);
2915 }
2916 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002917 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002918 return SendErrorResponse(25);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002919}
Greg Clayton2b98c562013-11-22 18:53:12 +00002920
Todd Fialaaf245d12014-06-30 21:05:18 +00002921GDBRemoteCommunication::PacketResult
2922GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
2923{
2924 // Ensure we're llgs.
2925 if (!IsGdbServer())
2926 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented");
2927
2928 // Fail if we don't have a current process.
2929 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2930 return SendErrorResponse (68);
2931
2932 // Ensure we have a thread.
2933 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
2934 if (!thread_sp)
2935 return SendErrorResponse (69);
2936
2937 // Get the register context for the first thread.
2938 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2939 if (!reg_context_sp)
2940 return SendErrorResponse (69);
2941
2942 // Parse out the register number from the request.
2943 packet.SetFilePos (strlen("qRegisterInfo"));
2944 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2945 if (reg_index == std::numeric_limits<uint32_t>::max ())
2946 return SendErrorResponse (69);
2947
2948 // Return the end of registers response if we've iterated one past the end of the register set.
2949 if (reg_index >= reg_context_sp->GetRegisterCount ())
2950 return SendErrorResponse (69);
2951
2952 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2953 if (!reg_info)
2954 return SendErrorResponse (69);
2955
2956 // Build the reginfos response.
2957 StreamGDBRemote response;
2958
2959 response.PutCString ("name:");
2960 response.PutCString (reg_info->name);
2961 response.PutChar (';');
2962
2963 if (reg_info->alt_name && reg_info->alt_name[0])
2964 {
2965 response.PutCString ("alt-name:");
2966 response.PutCString (reg_info->alt_name);
2967 response.PutChar (';');
2968 }
2969
2970 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
2971
2972 switch (reg_info->encoding)
2973 {
2974 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
2975 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
2976 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
2977 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
2978 default: break;
2979 }
2980
2981 switch (reg_info->format)
2982 {
2983 case eFormatBinary: response.PutCString ("format:binary;"); break;
2984 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
2985 case eFormatHex: response.PutCString ("format:hex;"); break;
2986 case eFormatFloat: response.PutCString ("format:float;"); break;
2987 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
2988 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
2989 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
2990 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
2991 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
2992 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
2993 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
2994 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
2995 default: break;
2996 };
2997
2998 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
2999 if (register_set_name)
3000 {
3001 response.PutCString ("set:");
3002 response.PutCString (register_set_name);
3003 response.PutChar (';');
3004 }
3005
3006 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
3007 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
3008
3009 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
3010 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3011
3012 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
3013 {
3014 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
3015 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
3016 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
3017 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
3018 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
3019 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
3020 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
3021 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
3022 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
3023 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
3024 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
3025 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
3026 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
3027 default: break;
3028 }
3029
3030 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
3031 {
3032 response.PutCString ("container-regs:");
3033 int i = 0;
3034 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3035 {
3036 if (i > 0)
3037 response.PutChar (',');
3038 response.Printf ("%" PRIx32, *reg_num);
3039 }
3040 response.PutChar (';');
3041 }
3042
3043 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
3044 {
3045 response.PutCString ("invalidate-regs:");
3046 int i = 0;
3047 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3048 {
3049 if (i > 0)
3050 response.PutChar (',');
3051 response.Printf ("%" PRIx32, *reg_num);
3052 }
3053 response.PutChar (';');
3054 }
3055
3056 return SendPacketNoLock(response.GetData(), response.GetSize());
3057}
3058
3059GDBRemoteCommunication::PacketResult
3060GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
3061{
3062 // Ensure we're llgs.
3063 if (!IsGdbServer())
3064 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented");
3065
Todd Fiala24189d42014-07-14 06:24:44 +00003066 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3067
Todd Fialaaf245d12014-06-30 21:05:18 +00003068 // Fail if we don't have a current process.
3069 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
Todd Fiala24189d42014-07-14 06:24:44 +00003070 {
3071 if (log)
3072 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
3073 return SendOKResponse ();
3074 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003075
3076 StreamGDBRemote response;
3077 response.PutChar ('m');
3078
Todd Fiala24189d42014-07-14 06:24:44 +00003079 if (log)
3080 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__);
3081
Todd Fialaaf245d12014-06-30 21:05:18 +00003082 NativeThreadProtocolSP thread_sp;
3083 uint32_t thread_index;
3084 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
3085 thread_sp;
3086 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
3087 {
Todd Fiala24189d42014-07-14 06:24:44 +00003088 if (log)
3089 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 +00003090 if (thread_index > 0)
3091 response.PutChar(',');
3092 response.Printf ("%" PRIx64, thread_sp->GetID ());
3093 }
3094
Todd Fiala24189d42014-07-14 06:24:44 +00003095 if (log)
3096 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__);
3097
Todd Fialaaf245d12014-06-30 21:05:18 +00003098 return SendPacketNoLock(response.GetData(), response.GetSize());
3099}
3100
3101GDBRemoteCommunication::PacketResult
3102GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
3103{
3104 // Ensure we're llgs.
3105 if (!IsGdbServer())
3106 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented");
3107
3108 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
3109 return SendPacketNoLock ("l", 1);
3110}
3111
3112GDBRemoteCommunication::PacketResult
3113GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet)
3114{
3115 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3116
3117 // Ensure we're llgs.
3118 if (!IsGdbServer())
3119 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented");
3120
3121 // Parse out the register number from the request.
3122 packet.SetFilePos (strlen("p"));
3123 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3124 if (reg_index == std::numeric_limits<uint32_t>::max ())
3125 {
3126 if (log)
3127 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3128 return SendErrorResponse (0x15);
3129 }
3130
3131 // Get the thread to use.
3132 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3133 if (!thread_sp)
3134 {
3135 if (log)
3136 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__);
3137 return SendErrorResponse (0x15);
3138 }
3139
3140 // Get the thread's register context.
3141 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3142 if (!reg_context_sp)
3143 {
3144 if (log)
3145 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 ());
3146 return SendErrorResponse (0x15);
3147 }
3148
3149 // Return the end of registers response if we've iterated one past the end of the register set.
3150 if (reg_index >= reg_context_sp->GetRegisterCount ())
3151 {
3152 if (log)
3153 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3154 return SendErrorResponse (0x15);
3155 }
3156
3157 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3158 if (!reg_info)
3159 {
3160 if (log)
3161 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3162 return SendErrorResponse (0x15);
3163 }
3164
3165 // Build the reginfos response.
3166 StreamGDBRemote response;
3167
3168 // Retrieve the value
3169 RegisterValue reg_value;
3170 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
3171 if (error.Fail ())
3172 {
3173 if (log)
3174 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3175 return SendErrorResponse (0x15);
3176 }
3177
3178 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
3179 if (!data)
3180 {
3181 if (log)
3182 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
3183 return SendErrorResponse (0x15);
3184 }
3185
3186 // FIXME flip as needed to get data in big/little endian format for this host.
3187 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
3188 response.PutHex8 (data[i]);
3189
3190 return SendPacketNoLock (response.GetData (), response.GetSize ());
3191}
3192
3193GDBRemoteCommunication::PacketResult
3194GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet)
3195{
3196 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3197
3198 // Ensure we're llgs.
3199 if (!IsGdbServer())
3200 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented");
3201
3202 // Ensure there is more content.
3203 if (packet.GetBytesLeft () < 1)
3204 return SendIllFormedResponse (packet, "Empty P packet");
3205
3206 // Parse out the register number from the request.
3207 packet.SetFilePos (strlen("P"));
3208 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3209 if (reg_index == std::numeric_limits<uint32_t>::max ())
3210 {
3211 if (log)
3212 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3213 return SendErrorResponse (0x29);
3214 }
3215
3216 // Note debugserver would send an E30 here.
3217 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
3218 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
3219
3220 // Get process architecture.
3221 ArchSpec process_arch;
3222 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
3223 {
3224 if (log)
3225 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__);
3226 return SendErrorResponse (0x49);
3227 }
3228
3229 // Parse out the value.
3230 const uint64_t raw_value = packet.GetHexMaxU64 (process_arch.GetByteOrder () == lldb::eByteOrderLittle, std::numeric_limits<uint64_t>::max ());
3231
3232 // Get the thread to use.
3233 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3234 if (!thread_sp)
3235 {
3236 if (log)
3237 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__);
3238 return SendErrorResponse (0x28);
3239 }
3240
3241 // Get the thread's register context.
3242 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3243 if (!reg_context_sp)
3244 {
3245 if (log)
3246 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 ());
3247 return SendErrorResponse (0x15);
3248 }
3249
3250 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3251 if (!reg_info)
3252 {
3253 if (log)
3254 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3255 return SendErrorResponse (0x48);
3256 }
3257
3258 // Return the end of registers response if we've iterated one past the end of the register set.
3259 if (reg_index >= reg_context_sp->GetRegisterCount ())
3260 {
3261 if (log)
3262 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3263 return SendErrorResponse (0x47);
3264 }
3265
3266
3267 // Build the reginfos response.
3268 StreamGDBRemote response;
3269
3270 // FIXME Could be suffixed with a thread: parameter.
3271 // That thread then needs to be fed back into the reg context retrieval above.
3272 Error error = reg_context_sp->WriteRegisterFromUnsigned (reg_info, raw_value);
3273 if (error.Fail ())
3274 {
3275 if (log)
3276 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3277 return SendErrorResponse (0x32);
3278 }
3279
3280 return SendOKResponse();
3281}
3282
3283GDBRemoteCommunicationServer::PacketResult
3284GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet)
3285{
3286 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3287
3288 // Ensure we're llgs.
3289 if (!IsGdbServer())
3290 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented");
3291
3292 // Fail if we don't have a current process.
3293 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3294 {
3295 if (log)
3296 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3297 return SendErrorResponse (0x15);
3298 }
3299
3300 // Parse out which variant of $H is requested.
3301 packet.SetFilePos (strlen("H"));
3302 if (packet.GetBytesLeft () < 1)
3303 {
3304 if (log)
3305 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__);
3306 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
3307 }
3308
3309 const char h_variant = packet.GetChar ();
3310 switch (h_variant)
3311 {
3312 case 'g':
3313 break;
3314
3315 case 'c':
3316 break;
3317
3318 default:
3319 if (log)
3320 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
3321 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3322 }
3323
3324 // Parse out the thread number.
3325 // FIXME return a parse success/fail value. All values are valid here.
3326 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
3327
3328 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
3329 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
3330 {
3331 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
3332 if (!thread_sp)
3333 {
3334 if (log)
3335 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
3336 return SendErrorResponse (0x15);
3337 }
3338 }
3339
3340 // Now switch the given thread type.
3341 switch (h_variant)
3342 {
3343 case 'g':
3344 SetCurrentThreadID (tid);
3345 break;
3346
3347 case 'c':
3348 SetContinueThreadID (tid);
3349 break;
3350
3351 default:
3352 assert (false && "unsupported $H variant - shouldn't get here");
3353 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3354 }
3355
3356 return SendOKResponse();
3357}
3358
3359GDBRemoteCommunicationServer::PacketResult
3360GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet)
3361{
3362 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3363
3364 // Ensure we're llgs.
3365 if (!IsGdbServer())
3366 {
3367 // Only supported on llgs
3368 return SendUnimplementedResponse ("");
3369 }
3370
3371 // Fail if we don't have a current process.
3372 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3373 {
3374 if (log)
3375 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3376 return SendErrorResponse (0x15);
3377 }
3378
Todd Fiala511e5cd2014-09-11 23:29:14 +00003379 // Interrupt the process.
3380 Error error = m_debugged_process_sp->Interrupt ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003381 if (error.Fail ())
3382 {
3383 if (log)
3384 {
3385 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s",
3386 __FUNCTION__,
3387 m_debugged_process_sp->GetID (),
3388 error.AsCString ());
3389 }
3390 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
3391 }
3392
3393 if (log)
3394 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
3395
3396 // No response required from stop all.
3397 return PacketResult::Success;
3398}
3399
3400GDBRemoteCommunicationServer::PacketResult
3401GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet)
3402{
3403 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3404
3405 // Ensure we're llgs.
3406 if (!IsGdbServer())
3407 {
3408 // Only supported on llgs
3409 return SendUnimplementedResponse ("");
3410 }
3411
3412 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3413 {
3414 if (log)
3415 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3416 return SendErrorResponse (0x15);
3417 }
3418
3419 // Parse out the memory address.
3420 packet.SetFilePos (strlen("m"));
3421 if (packet.GetBytesLeft() < 1)
3422 return SendIllFormedResponse(packet, "Too short m packet");
3423
3424 // Read the address. Punting on validation.
3425 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3426 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3427
3428 // Validate comma.
3429 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3430 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
3431
3432 // Get # bytes to read.
3433 if (packet.GetBytesLeft() < 1)
3434 return SendIllFormedResponse(packet, "Length missing in m packet");
3435
3436 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3437 if (byte_count == 0)
3438 {
3439 if (log)
3440 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__);
3441 return PacketResult::Success;
3442 }
3443
3444 // Allocate the response buffer.
3445 std::string buf(byte_count, '\0');
3446 if (buf.empty())
3447 return SendErrorResponse (0x78);
3448
3449
3450 // Retrieve the process memory.
3451 lldb::addr_t bytes_read = 0;
3452 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
3453 if (error.Fail ())
3454 {
3455 if (log)
3456 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
3457 return SendErrorResponse (0x08);
3458 }
3459
3460 if (bytes_read == 0)
3461 {
3462 if (log)
3463 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);
3464 return SendErrorResponse (0x08);
3465 }
3466
3467 StreamGDBRemote response;
3468 for (lldb::addr_t i = 0; i < bytes_read; ++i)
3469 response.PutHex8(buf[i]);
3470
3471 return SendPacketNoLock(response.GetData(), response.GetSize());
3472}
3473
3474GDBRemoteCommunication::PacketResult
3475GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet)
3476{
3477 packet.SetFilePos(::strlen ("QSetDetachOnError:"));
3478 if (packet.GetU32(0))
3479 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError);
3480 else
3481 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError);
3482 return SendOKResponse ();
3483}
3484
3485GDBRemoteCommunicationServer::PacketResult
3486GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet)
3487{
3488 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3489
3490 // Ensure we're llgs.
3491 if (!IsGdbServer())
3492 {
3493 // Only supported on llgs
3494 return SendUnimplementedResponse ("");
3495 }
3496
3497 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3498 {
3499 if (log)
3500 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3501 return SendErrorResponse (0x15);
3502 }
3503
3504 // Parse out the memory address.
3505 packet.SetFilePos (strlen("M"));
3506 if (packet.GetBytesLeft() < 1)
3507 return SendIllFormedResponse(packet, "Too short M packet");
3508
3509 // Read the address. Punting on validation.
3510 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3511 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
3512
3513 // Validate comma.
3514 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3515 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
3516
3517 // Get # bytes to read.
3518 if (packet.GetBytesLeft() < 1)
3519 return SendIllFormedResponse(packet, "Length missing in M packet");
3520
3521 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3522 if (byte_count == 0)
3523 {
3524 if (log)
3525 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__);
3526 return PacketResult::Success;
3527 }
3528
3529 // Validate colon.
3530 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
3531 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
3532
3533 // Allocate the conversion buffer.
3534 std::vector<uint8_t> buf(byte_count, 0);
3535 if (buf.empty())
3536 return SendErrorResponse (0x78);
3537
3538 // Convert the hex memory write contents to bytes.
3539 StreamGDBRemote response;
3540 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
3541 if (convert_count != byte_count)
3542 {
3543 if (log)
3544 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);
3545 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
3546 }
3547
3548 // Write the process memory.
3549 lldb::addr_t bytes_written = 0;
3550 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
3551 if (error.Fail ())
3552 {
3553 if (log)
3554 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
3555 return SendErrorResponse (0x09);
3556 }
3557
3558 if (bytes_written == 0)
3559 {
3560 if (log)
3561 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);
3562 return SendErrorResponse (0x09);
3563 }
3564
3565 return SendOKResponse ();
3566}
3567
3568GDBRemoteCommunicationServer::PacketResult
3569GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
3570{
3571 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3572
3573 // We don't support if we're not llgs.
3574 if (!IsGdbServer())
3575 return SendUnimplementedResponse ("");
3576
3577 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
3578 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
3579 // client only asks this when a process is being debugged.
3580
3581 // Ensure we have a process running; otherwise, we can't figure this out
3582 // since we won't have a NativeProcessProtocol.
3583 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3584 {
3585 if (log)
3586 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3587 return SendErrorResponse (0x15);
3588 }
3589
3590 // Test if we can get any region back when asking for the region around NULL.
3591 MemoryRegionInfo region_info;
3592 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
3593 if (error.Fail ())
3594 {
3595 // We don't support memory region info collection for this NativeProcessProtocol.
3596 return SendUnimplementedResponse ("");
3597 }
3598
3599 return SendOKResponse();
3600}
3601
3602GDBRemoteCommunicationServer::PacketResult
3603GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
3604{
3605 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3606
3607 // We don't support if we're not llgs.
3608 if (!IsGdbServer())
3609 return SendUnimplementedResponse ("");
3610
3611 // Ensure we have a process.
3612 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3613 {
3614 if (log)
3615 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3616 return SendErrorResponse (0x15);
3617 }
3618
3619 // Parse out the memory address.
3620 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
3621 if (packet.GetBytesLeft() < 1)
3622 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
3623
3624 // Read the address. Punting on validation.
3625 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3626
3627 StreamGDBRemote response;
3628
3629 // Get the memory region info for the target address.
3630 MemoryRegionInfo region_info;
3631 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
3632 if (error.Fail ())
3633 {
3634 // Return the error message.
3635
3636 response.PutCString ("error:");
3637 response.PutCStringAsRawHex8 (error.AsCString ());
3638 response.PutChar (';');
3639 }
3640 else
3641 {
3642 // Range start and size.
3643 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
3644
3645 // Permissions.
3646 if (region_info.GetReadable () ||
3647 region_info.GetWritable () ||
3648 region_info.GetExecutable ())
3649 {
3650 // Write permissions info.
3651 response.PutCString ("permissions:");
3652
3653 if (region_info.GetReadable ())
3654 response.PutChar ('r');
3655 if (region_info.GetWritable ())
3656 response.PutChar('w');
3657 if (region_info.GetExecutable())
3658 response.PutChar ('x');
3659
3660 response.PutChar (';');
3661 }
3662 }
3663
3664 return SendPacketNoLock(response.GetData(), response.GetSize());
3665}
3666
3667GDBRemoteCommunicationServer::PacketResult
3668GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet)
3669{
3670 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3671
3672 // We don't support if we're not llgs.
3673 if (!IsGdbServer())
3674 return SendUnimplementedResponse ("");
3675
3676 // Ensure we have a process.
3677 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3678 {
3679 if (log)
3680 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3681 return SendErrorResponse (0x15);
3682 }
3683
3684 // Parse out software or hardware breakpoint requested.
3685 packet.SetFilePos (strlen("Z"));
3686 if (packet.GetBytesLeft() < 1)
3687 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
3688
3689 bool want_breakpoint = true;
3690 bool want_hardware = false;
3691
3692 const char breakpoint_type_char = packet.GetChar ();
3693 switch (breakpoint_type_char)
3694 {
3695 case '0': want_hardware = false; want_breakpoint = true; break;
3696 case '1': want_hardware = true; want_breakpoint = true; break;
3697 case '2': want_breakpoint = false; break;
3698 case '3': want_breakpoint = false; break;
3699 default:
3700 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
3701
3702 }
3703
3704 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3705 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type");
3706
3707 // FIXME implement watchpoint support.
3708 if (!want_breakpoint)
3709 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3710
3711 // Parse out the breakpoint address.
3712 if (packet.GetBytesLeft() < 1)
3713 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
3714 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3715
3716 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3717 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
3718
3719 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3720 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3721 if (kind == std::numeric_limits<uint32_t>::max ())
3722 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument");
3723
3724 if (want_breakpoint)
3725 {
3726 // Try to set the breakpoint.
3727 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware);
3728 if (error.Success ())
3729 return SendOKResponse ();
3730 else
3731 {
3732 if (log)
3733 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3734 return SendErrorResponse (0x09);
3735 }
3736 }
3737
3738 // FIXME fix up after watchpoints are handled.
3739 return SendUnimplementedResponse ("");
3740}
3741
3742GDBRemoteCommunicationServer::PacketResult
3743GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet)
3744{
3745 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3746
3747 // We don't support if we're not llgs.
3748 if (!IsGdbServer())
3749 return SendUnimplementedResponse ("");
3750
3751 // Ensure we have a process.
3752 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3753 {
3754 if (log)
3755 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3756 return SendErrorResponse (0x15);
3757 }
3758
3759 // Parse out software or hardware breakpoint requested.
3760 packet.SetFilePos (strlen("Z"));
3761 if (packet.GetBytesLeft() < 1)
3762 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
3763
3764 bool want_breakpoint = true;
3765
3766 const char breakpoint_type_char = packet.GetChar ();
3767 switch (breakpoint_type_char)
3768 {
3769 case '0': want_breakpoint = true; break;
3770 case '1': want_breakpoint = true; break;
3771 case '2': want_breakpoint = false; break;
3772 case '3': want_breakpoint = false; break;
3773 default:
3774 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
3775
3776 }
3777
3778 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3779 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type");
3780
3781 // FIXME implement watchpoint support.
3782 if (!want_breakpoint)
3783 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3784
3785 // Parse out the breakpoint address.
3786 if (packet.GetBytesLeft() < 1)
3787 return SendIllFormedResponse(packet, "Too short z packet, missing address");
3788 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3789
3790 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3791 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
3792
3793 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3794 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3795 if (kind == std::numeric_limits<uint32_t>::max ())
3796 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument");
3797
3798 if (want_breakpoint)
3799 {
3800 // Try to set the breakpoint.
3801 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr);
3802 if (error.Success ())
3803 return SendOKResponse ();
3804 else
3805 {
3806 if (log)
3807 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3808 return SendErrorResponse (0x09);
3809 }
3810 }
3811
3812 // FIXME fix up after watchpoints are handled.
3813 return SendUnimplementedResponse ("");
3814}
3815
3816GDBRemoteCommunicationServer::PacketResult
3817GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet)
3818{
3819 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
3820
3821 // We don't support if we're not llgs.
3822 if (!IsGdbServer())
3823 return SendUnimplementedResponse ("");
3824
3825 // Ensure we have a process.
3826 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3827 {
3828 if (log)
3829 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3830 return SendErrorResponse (0x32);
3831 }
3832
3833 // We first try to use a continue thread id. If any one or any all set, use the current thread.
3834 // Bail out if we don't have a thread id.
3835 lldb::tid_t tid = GetContinueThreadID ();
3836 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3837 tid = GetCurrentThreadID ();
3838 if (tid == LLDB_INVALID_THREAD_ID)
3839 return SendErrorResponse (0x33);
3840
3841 // Double check that we have such a thread.
3842 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3843 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
3844 if (!thread_sp || thread_sp->GetID () != tid)
3845 return SendErrorResponse (0x33);
3846
3847 // Create the step action for the given thread.
3848 lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
3849
3850 // Setup the actions list.
3851 lldb_private::ResumeActionList actions;
3852 actions.Append (action);
3853
3854 // All other threads stop while we're single stepping a thread.
3855 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3856 Error error = m_debugged_process_sp->Resume (actions);
3857 if (error.Fail ())
3858 {
3859 if (log)
3860 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
3861 return SendErrorResponse(0x49);
3862 }
3863
3864 // No response here - the stop or exit will come from the resulting action.
3865 return PacketResult::Success;
3866}
3867
3868GDBRemoteCommunicationServer::PacketResult
3869GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet)
3870{
3871 StreamGDBRemote response;
3872
3873 // Features common to lldb-platform and llgs.
3874 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less
3875 response.Printf ("PacketSize=%x", max_packet_size);
3876
3877 response.PutCString (";QStartNoAckMode+");
3878 response.PutCString (";QThreadSuffixSupported+");
3879 response.PutCString (";QListThreadsInStopReply+");
3880#if defined(__linux__)
3881 response.PutCString (";qXfer:auxv:read+");
3882#endif
3883
3884 return SendPacketNoLock(response.GetData(), response.GetSize());
3885}
3886
3887GDBRemoteCommunicationServer::PacketResult
3888GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet)
3889{
3890 m_thread_suffix_supported = true;
3891 return SendOKResponse();
3892}
3893
3894GDBRemoteCommunicationServer::PacketResult
3895GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet)
3896{
3897 m_list_threads_in_stop_reply = true;
3898 return SendOKResponse();
3899}
3900
3901GDBRemoteCommunicationServer::PacketResult
3902GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
3903{
3904 // We don't support if we're not llgs.
3905 if (!IsGdbServer())
3906 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
3907
3908 // *BSD impls should be able to do this too.
3909#if defined(__linux__)
3910 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3911
3912 // Parse out the offset.
3913 packet.SetFilePos (strlen("qXfer:auxv:read::"));
3914 if (packet.GetBytesLeft () < 1)
3915 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3916
3917 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3918 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
3919 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3920
3921 // Parse out comma.
3922 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
3923 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
3924
3925 // Parse out the length.
3926 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3927 if (auxv_length == std::numeric_limits<uint64_t>::max ())
3928 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
3929
3930 // Grab the auxv data if we need it.
3931 if (!m_active_auxv_buffer_sp)
3932 {
3933 // Make sure we have a valid process.
3934 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3935 {
3936 if (log)
3937 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3938 return SendErrorResponse (0x10);
3939 }
3940
3941 // Grab the auxv data.
3942 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
3943 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
3944 {
3945 // Hmm, no auxv data, call that an error.
3946 if (log)
3947 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__);
3948 m_active_auxv_buffer_sp.reset ();
3949 return SendErrorResponse (0x11);
3950 }
3951 }
3952
3953 // FIXME find out if/how I lock the stream here.
3954
3955 StreamGDBRemote response;
3956 bool done_with_buffer = false;
3957
3958 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
3959 {
3960 // We have nothing left to send. Mark the buffer as complete.
3961 response.PutChar ('l');
3962 done_with_buffer = true;
3963 }
3964 else
3965 {
3966 // Figure out how many bytes are available starting at the given offset.
3967 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
3968
3969 // Figure out how many bytes we're going to read.
3970 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
3971
3972 // Mark the response type according to whether we're reading the remainder of the auxv data.
3973 if (bytes_to_read >= bytes_remaining)
3974 {
3975 // There will be nothing left to read after this
3976 response.PutChar ('l');
3977 done_with_buffer = true;
3978 }
3979 else
3980 {
3981 // There will still be bytes to read after this request.
3982 response.PutChar ('m');
3983 }
3984
3985 // Now write the data in encoded binary form.
3986 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
3987 }
3988
3989 if (done_with_buffer)
3990 m_active_auxv_buffer_sp.reset ();
3991
3992 return SendPacketNoLock(response.GetData(), response.GetSize());
3993#else
3994 return SendUnimplementedResponse ("not implemented on this platform");
3995#endif
3996}
3997
3998GDBRemoteCommunicationServer::PacketResult
3999GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
4000{
4001 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4002
4003 // We don't support if we're not llgs.
4004 if (!IsGdbServer())
4005 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4006
4007 // Move past packet name.
4008 packet.SetFilePos (strlen ("QSaveRegisterState"));
4009
4010 // Get the thread to use.
4011 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4012 if (!thread_sp)
4013 {
4014 if (m_thread_suffix_supported)
4015 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
4016 else
4017 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4018 }
4019
4020 // Grab the register context for the thread.
4021 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4022 if (!reg_context_sp)
4023 {
4024 if (log)
4025 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 ());
4026 return SendErrorResponse (0x15);
4027 }
4028
4029 // Save registers to a buffer.
4030 DataBufferSP register_data_sp;
4031 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
4032 if (error.Fail ())
4033 {
4034 if (log)
4035 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4036 return SendErrorResponse (0x75);
4037 }
4038
4039 // Allocate a new save id.
4040 const uint32_t save_id = GetNextSavedRegistersID ();
4041 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
4042
4043 // Save the register data buffer under the save id.
4044 {
4045 Mutex::Locker locker (m_saved_registers_mutex);
4046 m_saved_registers_map[save_id] = register_data_sp;
4047 }
4048
4049 // Write the response.
4050 StreamGDBRemote response;
4051 response.Printf ("%" PRIu32, save_id);
4052 return SendPacketNoLock(response.GetData(), response.GetSize());
4053}
4054
4055GDBRemoteCommunicationServer::PacketResult
4056GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
4057{
4058 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4059
4060 // We don't support if we're not llgs.
4061 if (!IsGdbServer())
4062 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4063
4064 // Parse out save id.
4065 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
4066 if (packet.GetBytesLeft () < 1)
4067 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
4068
4069 const uint32_t save_id = packet.GetU32 (0);
4070 if (save_id == 0)
4071 {
4072 if (log)
4073 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
4074 return SendErrorResponse (0x76);
4075 }
4076
4077 // Get the thread to use.
4078 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4079 if (!thread_sp)
4080 {
4081 if (m_thread_suffix_supported)
4082 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
4083 else
4084 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4085 }
4086
4087 // Grab the register context for the thread.
4088 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4089 if (!reg_context_sp)
4090 {
4091 if (log)
4092 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 ());
4093 return SendErrorResponse (0x15);
4094 }
4095
4096 // Retrieve register state buffer, then remove from the list.
4097 DataBufferSP register_data_sp;
4098 {
4099 Mutex::Locker locker (m_saved_registers_mutex);
4100
4101 // Find the register set buffer for the given save id.
4102 auto it = m_saved_registers_map.find (save_id);
4103 if (it == m_saved_registers_map.end ())
4104 {
4105 if (log)
4106 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);
4107 return SendErrorResponse (0x77);
4108 }
4109 register_data_sp = it->second;
4110
4111 // Remove it from the map.
4112 m_saved_registers_map.erase (it);
4113 }
4114
4115 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
4116 if (error.Fail ())
4117 {
4118 if (log)
4119 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4120 return SendErrorResponse (0x77);
4121 }
4122
4123 return SendOKResponse();
4124}
4125
Todd Fiala7306cf32014-07-29 22:30:01 +00004126GDBRemoteCommunicationServer::PacketResult
4127GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet)
4128{
4129 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4130
4131 // We don't support if we're not llgs.
4132 if (!IsGdbServer())
4133 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4134
4135 // Consume the ';' after vAttach.
4136 packet.SetFilePos (strlen ("vAttach"));
4137 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
4138 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
4139
4140 // Grab the PID to which we will attach (assume hex encoding).
4141 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4142 if (pid == LLDB_INVALID_PROCESS_ID)
4143 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
4144
4145 // Attempt to attach.
4146 if (log)
4147 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
4148
4149 Error error = AttachToProcess (pid);
4150
4151 if (error.Fail ())
4152 {
4153 if (log)
4154 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
4155 return SendErrorResponse (0x01);
4156 }
4157
4158 // Notify we attached by sending a stop packet.
4159 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
4160
4161 return PacketResult::Success;
4162}
4163
Todd Fiala1109ed42014-09-10 21:28:38 +00004164GDBRemoteCommunicationServer::PacketResult
4165GDBRemoteCommunicationServer::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
4166{
4167 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4168
4169 // We don't support if we're not llgs.
4170 if (!IsGdbServer())
4171 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4172
4173 packet.SetFilePos (strlen("qThreadStopInfo"));
4174 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
4175 if (tid == LLDB_INVALID_THREAD_ID)
4176 {
4177 if (log)
4178 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
4179 return SendErrorResponse (0x15);
4180 }
4181 return SendStopReplyPacketForThread (tid);
4182}
4183
Todd Fialaaf245d12014-06-30 21:05:18 +00004184void
4185GDBRemoteCommunicationServer::FlushInferiorOutput ()
4186{
4187 // If we're not monitoring an inferior's terminal, ignore this.
4188 if (!m_stdio_communication.IsConnected())
4189 return;
4190
4191 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
4192 if (log)
4193 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
4194
4195 // FIXME implement a timeout on the join.
4196 m_stdio_communication.JoinReadThread();
4197}
4198
4199void
4200GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection ()
4201{
4202 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4203
4204 // Tell the stdio connection to shut down.
4205 if (m_stdio_communication.IsConnected())
4206 {
4207 auto connection = m_stdio_communication.GetConnection();
4208 if (connection)
4209 {
4210 Error error;
4211 connection->Disconnect (&error);
4212
4213 if (error.Success ())
4214 {
4215 if (log)
4216 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
4217 }
4218 else
4219 {
4220 if (log)
4221 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
4222 }
4223 }
4224 }
4225}
4226
4227
4228lldb_private::NativeThreadProtocolSP
4229GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
4230{
4231 NativeThreadProtocolSP thread_sp;
4232
4233 // We have no thread if we don't have a process.
4234 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4235 return thread_sp;
4236
4237 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
4238 // Use the current thread in that case.
4239 if (!m_thread_suffix_supported)
4240 {
4241 const lldb::tid_t current_tid = GetCurrentThreadID ();
4242 if (current_tid == LLDB_INVALID_THREAD_ID)
4243 return thread_sp;
4244 else if (current_tid == 0)
4245 {
4246 // Pick a thread.
4247 return m_debugged_process_sp->GetThreadAtIndex (0);
4248 }
4249 else
4250 return m_debugged_process_sp->GetThreadByID (current_tid);
4251 }
4252
4253 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4254
4255 // Parse out the ';'.
4256 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
4257 {
4258 if (log)
4259 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4260 return thread_sp;
4261 }
4262
4263 if (!packet.GetBytesLeft ())
4264 return thread_sp;
4265
4266 // Parse out thread: portion.
4267 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
4268 {
4269 if (log)
4270 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4271 return thread_sp;
4272 }
4273 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
4274 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4275 if (tid != 0)
4276 return m_debugged_process_sp->GetThreadByID (tid);
4277
4278 return thread_sp;
4279}
4280
4281lldb::tid_t
4282GDBRemoteCommunicationServer::GetCurrentThreadID () const
4283{
4284 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
4285 {
4286 // Use whatever the debug process says is the current thread id
4287 // since the protocol either didn't specify or specified we want
4288 // any/all threads marked as the current thread.
4289 if (!m_debugged_process_sp)
4290 return LLDB_INVALID_THREAD_ID;
4291 return m_debugged_process_sp->GetCurrentThreadID ();
4292 }
4293 // Use the specific current thread id set by the gdb remote protocol.
4294 return m_current_tid;
4295}
4296
4297uint32_t
4298GDBRemoteCommunicationServer::GetNextSavedRegistersID ()
4299{
4300 Mutex::Locker locker (m_saved_registers_mutex);
4301 return m_next_saved_registers_id++;
4302}
4303
Todd Fialaa9882ce2014-08-28 15:46:54 +00004304void
4305GDBRemoteCommunicationServer::ClearProcessSpecificData ()
4306{
4307 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
4308 if (log)
4309 log->Printf ("GDBRemoteCommunicationServer::%s()", __FUNCTION__);
4310
4311 // Clear any auxv cached data.
4312 // *BSD impls should be able to do this too.
4313#if defined(__linux__)
4314 if (log)
4315 log->Printf ("GDBRemoteCommunicationServer::%s clearing auxv buffer (previously %s)",
4316 __FUNCTION__,
4317 m_active_auxv_buffer_sp ? "was set" : "was not set");
4318 m_active_auxv_buffer_sp.reset ();
4319#endif
4320}