blob: dc99a990c5f56be20c2245c3693a6e03b5265655 [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;
Greg Clayton576d8832011-03-22 04:00:09 +0000432 }
Greg Clayton576d8832011-03-22 04:00:09 +0000433 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000434 else
435 {
436 if (!IsConnected())
Greg Clayton3dedae12013-12-06 21:45:27 +0000437 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000438 error.SetErrorString("lost connection");
Greg Clayton3dedae12013-12-06 21:45:27 +0000439 quit = true;
440 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000441 else
Greg Clayton3dedae12013-12-06 21:45:27 +0000442 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000443 error.SetErrorString("timeout");
Greg Clayton3dedae12013-12-06 21:45:27 +0000444 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000445 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000446
447 // Check if anything occurred that would force us to want to exit.
448 if (m_exit_now)
449 quit = true;
450
451 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000452}
453
Todd Fiala403edc52014-01-23 22:05:44 +0000454lldb_private::Error
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000455GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc)
Todd Fiala403edc52014-01-23 22:05:44 +0000456{
457 if ((argc < 1) || !args || !args[0] || !args[0][0])
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000458 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
Todd Fiala403edc52014-01-23 22:05:44 +0000459
Todd Fiala403edc52014-01-23 22:05:44 +0000460 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000461 return lldb_private::Error ();
462}
463
464lldb_private::Error
465GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags)
466{
Todd Fiala403edc52014-01-23 22:05:44 +0000467 m_process_launch_info.GetFlags ().Set (launch_flags);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000468 return lldb_private::Error ();
469}
470
471lldb_private::Error
472GDBRemoteCommunicationServer::LaunchProcess ()
473{
Todd Fialaaf245d12014-06-30 21:05:18 +0000474 // FIXME This looks an awful lot like we could override this in
475 // derived classes, one for lldb-platform, the other for lldb-gdbserver.
476 if (IsGdbServer ())
477 return LaunchDebugServerProcess ();
478 else
479 return LaunchPlatformProcess ();
480}
481
482lldb_private::Error
483GDBRemoteCommunicationServer::LaunchDebugServerProcess ()
484{
485 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
486
487 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
488 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
489
490 lldb_private::Error error;
491 {
492 Mutex::Locker locker (m_debugged_process_mutex);
493 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
494 error = m_platform_sp->LaunchNativeProcess (
495 m_process_launch_info,
496 *this,
497 m_debugged_process_sp);
498 }
499
500 if (!error.Success ())
501 {
502 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
503 return error;
504 }
505
506 // Setup stdout/stderr mapping from inferior.
507 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
508 if (terminal_fd >= 0)
509 {
510 if (log)
511 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
512 error = SetSTDIOFileDescriptor (terminal_fd);
513 if (error.Fail ())
514 return error;
515 }
516 else
517 {
518 if (log)
519 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
520 }
521
522 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
523
524 // Add to list of spawned processes.
525 lldb::pid_t pid;
526 if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
527 {
528 // add to spawned pids
529 {
530 Mutex::Locker locker (m_spawned_pids_mutex);
531 // On an lldb-gdbserver, we would expect there to be only one.
532 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
533 m_spawned_pids.insert (pid);
534 }
535 }
536
537 if (error.Success ())
538 {
539 if (log)
540 log->Printf ("GDBRemoteCommunicationServer::%s beginning check to wait for launched application to hit first stop", __FUNCTION__);
541
542 int iteration = 0;
543 // Wait for the process to hit its first stop state.
544 while (!StateIsStoppedState (m_debugged_process_sp->GetState (), false))
545 {
546 if (log)
547 log->Printf ("GDBRemoteCommunicationServer::%s waiting for launched process to hit first stop (%d)...", __FUNCTION__, iteration++);
548
Todd Fiala2850b1b2014-06-30 23:51:35 +0000549 // FIXME use a finer granularity.
550 std::this_thread::sleep_for(std::chrono::seconds(1));
Todd Fialaaf245d12014-06-30 21:05:18 +0000551 }
552
553 if (log)
554 log->Printf ("GDBRemoteCommunicationServer::%s launched application has hit first stop", __FUNCTION__);
555
556 }
557
558 return error;
559}
560
561lldb_private::Error
562GDBRemoteCommunicationServer::LaunchPlatformProcess ()
563{
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000564 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
565 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
566
567 // specify the process monitor if not already set. This should
568 // generally be what happens since we need to reap started
569 // processes.
570 if (!m_process_launch_info.GetMonitorProcessCallback ())
571 m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false);
Todd Fiala403edc52014-01-23 22:05:44 +0000572
Todd Fialab8b49ec2014-01-28 00:34:23 +0000573 lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
Todd Fiala403edc52014-01-23 22:05:44 +0000574 if (!error.Success ())
575 {
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000576 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
Todd Fiala403edc52014-01-23 22:05:44 +0000577 return error;
578 }
579
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000580 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 +0000581
582 // add to list of spawned processes. On an lldb-gdbserver, we
583 // would expect there to be only one.
584 lldb::pid_t pid;
585 if ( (pid = m_process_launch_info.GetProcessID()) != LLDB_INVALID_PROCESS_ID )
586 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000587 // add to spawned pids
588 {
589 Mutex::Locker locker (m_spawned_pids_mutex);
590 m_spawned_pids.insert(pid);
591 }
Todd Fiala403edc52014-01-23 22:05:44 +0000592 }
593
594 return error;
595}
596
Todd Fialaaf245d12014-06-30 21:05:18 +0000597lldb_private::Error
598GDBRemoteCommunicationServer::AttachToProcess (lldb::pid_t pid)
599{
600 Error error;
601
602 if (!IsGdbServer ())
603 {
604 error.SetErrorString("cannot AttachToProcess () unless process is lldb-gdbserver");
605 return error;
606 }
607
608 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
609 if (log)
610 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64, __FUNCTION__, pid);
611
612 // Scope for mutex locker.
613 {
614 // Before we try to attach, make sure we aren't already monitoring something else.
615 Mutex::Locker locker (m_spawned_pids_mutex);
616 if (!m_spawned_pids.empty ())
617 {
618 error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
619 return error;
620 }
621
622 // Try to attach.
623 error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp);
624 if (!error.Success ())
625 {
626 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
627 return error;
628 }
629
630 // Setup stdout/stderr mapping from inferior.
631 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
632 if (terminal_fd >= 0)
633 {
634 if (log)
635 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
636 error = SetSTDIOFileDescriptor (terminal_fd);
637 if (error.Fail ())
638 return error;
639 }
640 else
641 {
642 if (log)
643 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
644 }
645
646 printf ("Attached to process %" PRIu64 "...\n", pid);
647
648 // Add to list of spawned processes.
649 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
650 m_spawned_pids.insert (pid);
651
652 return error;
653 }
654}
655
656void
657GDBRemoteCommunicationServer::InitializeDelegate (lldb_private::NativeProcessProtocol *process)
658{
659 assert (process && "process cannot be NULL");
660 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
661 if (log)
662 {
663 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
664 __FUNCTION__,
665 process->GetID (),
666 StateAsCString (process->GetState ()));
667 }
668}
669
670GDBRemoteCommunication::PacketResult
671GDBRemoteCommunicationServer::SendWResponse (lldb_private::NativeProcessProtocol *process)
672{
673 assert (process && "process cannot be NULL");
674 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
675
676 // send W notification
677 ExitType exit_type = ExitType::eExitTypeInvalid;
678 int return_code = 0;
679 std::string exit_description;
680
681 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
682 if (!got_exit_info)
683 {
684 if (log)
685 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
686
687 StreamGDBRemote response;
688 response.PutChar ('E');
689 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
690 return SendPacketNoLock(response.GetData(), response.GetSize());
691 }
692 else
693 {
694 if (log)
695 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 ());
696
697 StreamGDBRemote response;
698
699 char return_type_code;
700 switch (exit_type)
701 {
702 case ExitType::eExitTypeExit: return_type_code = 'W'; break;
703 case ExitType::eExitTypeSignal: return_type_code = 'X'; break;
704 case ExitType::eExitTypeStop: return_type_code = 'S'; break;
705
706 case ExitType::eExitTypeInvalid:
707 default: return_type_code = 'E'; break;
708 }
709 response.PutChar (return_type_code);
710
711 // POSIX exit status limited to unsigned 8 bits.
712 response.PutHex8 (return_code);
713
714 return SendPacketNoLock(response.GetData(), response.GetSize());
715 }
716}
717
718static void
719AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
720{
721 int64_t i;
722 if (swap)
723 {
724 for (i = buf_size-1; i >= 0; i--)
725 response.PutHex8 (buf[i]);
726 }
727 else
728 {
729 for (i = 0; i < buf_size; i++)
730 response.PutHex8 (buf[i]);
731 }
732}
733
734static void
735WriteRegisterValueInHexFixedWidth (StreamString &response,
736 NativeRegisterContextSP &reg_ctx_sp,
737 const RegisterInfo &reg_info,
738 const RegisterValue *reg_value_p)
739{
740 RegisterValue reg_value;
741 if (!reg_value_p)
742 {
743 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
744 if (error.Success ())
745 reg_value_p = &reg_value;
746 // else log.
747 }
748
749 if (reg_value_p)
750 {
751 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
752 }
753 else
754 {
755 // Zero-out any unreadable values.
756 if (reg_info.byte_size > 0)
757 {
758 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
759 AppendHexValue (response, zeros.data(), zeros.size(), false);
760 }
761 }
762}
763
764// WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
765
766
767static void
768WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response,
769 NativeRegisterContextSP &reg_ctx_sp,
770 const RegisterInfo &reg_info,
771 const RegisterValue &reg_value)
772{
773 // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
774 // gdb register number, and VVVVVVVV is the correct number of hex bytes
775 // as ASCII for the register value.
776 if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM)
777 return;
778
779 response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]);
780 WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, &reg_value);
781 response.PutChar (';');
782}
783
784
785GDBRemoteCommunication::PacketResult
786GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid)
787{
788 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
789
790 // Ensure we're llgs.
791 if (!IsGdbServer ())
792 {
793 // Only supported on llgs
794 return SendUnimplementedResponse ("");
795 }
796
797 // Ensure we have a debugged process.
798 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
799 return SendErrorResponse (50);
800
801 if (log)
802 log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
803 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
804
805 // Ensure we can get info on the given thread.
806 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
807 if (!thread_sp)
808 return SendErrorResponse (51);
809
810 // Grab the reason this thread stopped.
811 struct ThreadStopInfo tid_stop_info;
812 if (!thread_sp->GetStopReason (tid_stop_info))
813 return SendErrorResponse (52);
814
815 const bool did_exec = tid_stop_info.reason == eStopReasonExec;
816 // FIXME implement register handling for exec'd inferiors.
817 // if (did_exec)
818 // {
819 // const bool force = true;
820 // InitializeRegisters(force);
821 // }
822
823 StreamString response;
824 // Output the T packet with the thread
825 response.PutChar ('T');
826 int signum = tid_stop_info.details.signal.signo;
827 if (log)
828 {
829 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
830 __FUNCTION__,
831 m_debugged_process_sp->GetID (),
832 tid,
833 signum,
834 tid_stop_info.reason,
835 tid_stop_info.details.exception.type);
836 }
837
838 switch (tid_stop_info.reason)
839 {
840 case eStopReasonSignal:
841 case eStopReasonException:
842 signum = thread_sp->TranslateStopInfoToGdbSignal (tid_stop_info);
843 break;
844 default:
845 signum = 0;
846 if (log)
847 {
848 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " has stop reason %d, using signo = 0 in stop reply response",
849 __FUNCTION__,
850 m_debugged_process_sp->GetID (),
851 tid,
852 tid_stop_info.reason);
853 }
854 break;
855 }
856
857 // Print the signal number.
858 response.PutHex8 (signum & 0xff);
859
860 // Include the tid.
861 response.Printf ("thread:%" PRIx64 ";", tid);
862
863 // Include the thread name if there is one.
864 const char *thread_name = thread_sp->GetName ();
865 if (thread_name && thread_name[0])
866 {
867 size_t thread_name_len = strlen(thread_name);
868
869 if (::strcspn (thread_name, "$#+-;:") == thread_name_len)
870 {
871 response.PutCString ("name:");
872 response.PutCString (thread_name);
873 }
874 else
875 {
876 // The thread name contains special chars, send as hex bytes.
877 response.PutCString ("hexname:");
878 response.PutCStringAsRawHex8 (thread_name);
879 }
880 response.PutChar (';');
881 }
882
883 // FIXME look for analog
884 // thread_identifier_info_data_t thread_ident_info;
885 // if (DNBThreadGetIdentifierInfo (pid, tid, &thread_ident_info))
886 // {
887 // if (thread_ident_info.dispatch_qaddr != 0)
888 // ostrm << std::hex << "qaddr:" << thread_ident_info.dispatch_qaddr << ';';
889 // }
890
891 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
892 // will send all thread IDs back in the "threads" key whose value is
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000893 // a list of hex thread IDs separated by commas:
Todd Fialaaf245d12014-06-30 21:05:18 +0000894 // "threads:10a,10b,10c;"
895 // This will save the debugger from having to send a pair of qfThreadInfo
896 // and qsThreadInfo packets, but it also might take a lot of room in the
897 // stop reply packet, so it must be enabled only on systems where there
898 // are no limits on packet lengths.
899 if (m_list_threads_in_stop_reply)
900 {
901 response.PutCString ("threads:");
902
903 uint32_t thread_index = 0;
904 NativeThreadProtocolSP listed_thread_sp;
905 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))
906 {
907 if (thread_index > 0)
908 response.PutChar (',');
909 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
910 }
911 response.PutChar (';');
912 }
913
914 //
915 // Expedite registers.
916 //
917
918 // Grab the register context.
919 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
920 if (reg_ctx_sp)
921 {
922 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
923 const RegisterSet *reg_set_p;
924 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
925 {
926 if (log)
927 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);
928
929 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
930 {
931 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
932 if (reg_info_p == nullptr)
933 {
934 if (log)
935 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);
936 }
937 else if (reg_info_p->value_regs == nullptr)
938 {
939 // Only expediate registers that are not contained in other registers.
940 RegisterValue reg_value;
941 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
942 if (error.Success ())
943 WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
944 else
945 {
946 if (log)
947 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 ());
948
949 }
950 }
951 }
952 }
953 }
954
955 if (did_exec)
956 {
957 response.PutCString ("reason:exec;");
958 }
959 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
960 {
961 response.PutCString ("metype:");
962 response.PutHex64 (tid_stop_info.details.exception.type);
963 response.PutCString (";mecount:");
964 response.PutHex32 (tid_stop_info.details.exception.data_count);
965 response.PutChar (';');
966
967 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
968 {
969 response.PutCString ("medata:");
970 response.PutHex64 (tid_stop_info.details.exception.data[i]);
971 response.PutChar (';');
972 }
973 }
974
975 return SendPacketNoLock (response.GetData(), response.GetSize());
976}
977
978void
979GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
980{
981 assert (process && "process cannot be NULL");
982
983 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
984 if (log)
985 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
986
987 // Send the exit result, and don't flush output.
988 // Note: flushing output here would join the inferior stdio reflection thread, which
989 // would gunk up the waitpid monitor thread that is calling this.
990 PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
991 if (result != PacketResult::Success)
992 {
993 if (log)
994 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
995 }
996
997 // Remove the process from the list of spawned pids.
998 {
999 Mutex::Locker locker (m_spawned_pids_mutex);
1000 if (m_spawned_pids.erase (process->GetID ()) < 1)
1001 {
1002 if (log)
1003 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
1004
1005 }
1006 }
1007
1008 // FIXME can't do this yet - since process state propagation is currently
1009 // synchronous, it is running off the NativeProcessProtocol's innards and
1010 // will tear down the NPP while it still has code to execute.
1011#if 0
1012 // Clear the NativeProcessProtocol pointer.
1013 {
1014 Mutex::Locker locker (m_debugged_process_mutex);
1015 m_debugged_process_sp.reset();
1016 }
1017#endif
1018
1019 // Close the pipe to the inferior terminal i/o if we launched it
1020 // and set one up. Otherwise, 'k' and its flush of stdio could
1021 // end up waiting on a thread join that will never end. Consider
1022 // adding a timeout to the connection thread join call so we
1023 // can avoid that scenario altogether.
1024 MaybeCloseInferiorTerminalConnection ();
1025
1026 // We are ready to exit the debug monitor.
1027 m_exit_now = true;
1028}
1029
1030void
1031GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
1032{
1033 assert (process && "process cannot be NULL");
1034
1035 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1036 if (log)
1037 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1038
1039 // Send the stop reason unless this is the stop after the
1040 // launch or attach.
1041 switch (m_inferior_prev_state)
1042 {
1043 case eStateLaunching:
1044 case eStateAttaching:
1045 // Don't send anything per debugserver behavior.
1046 break;
1047 default:
1048 // In all other cases, send the stop reason.
1049 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
1050 if (result != PacketResult::Success)
1051 {
1052 if (log)
1053 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1054 }
1055 break;
1056 }
1057}
1058
1059void
1060GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
1061{
1062 assert (process && "process cannot be NULL");
1063 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1064 if (log)
1065 {
1066 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
1067 __FUNCTION__,
1068 process->GetID (),
1069 StateAsCString (state));
1070 }
1071
1072 switch (state)
1073 {
1074 case StateType::eStateExited:
1075 HandleInferiorState_Exited (process);
1076 break;
1077
1078 case StateType::eStateStopped:
1079 HandleInferiorState_Stopped (process);
1080 break;
1081
1082 default:
1083 if (log)
1084 {
1085 log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
1086 __FUNCTION__,
1087 process->GetID (),
1088 StateAsCString (state));
1089 }
1090 break;
1091 }
1092
1093 // Remember the previous state reported to us.
1094 m_inferior_prev_state = state;
1095}
1096
1097GDBRemoteCommunication::PacketResult
1098GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len)
1099{
1100 if ((buffer == nullptr) || (len == 0))
1101 {
1102 // Nothing to send.
1103 return PacketResult::Success;
1104 }
1105
1106 StreamString response;
1107 response.PutChar ('O');
1108 response.PutBytesAsRawHex8 (buffer, len);
1109
1110 return SendPacketNoLock (response.GetData (), response.GetSize ());
1111}
1112
1113lldb_private::Error
1114GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd)
1115{
1116 Error error;
1117
1118 // Set up the Read Thread for reading/handling process I/O
1119 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
1120 if (!conn_up)
1121 {
1122 error.SetErrorString ("failed to create ConnectionFileDescriptor");
1123 return error;
1124 }
1125
1126 m_stdio_communication.SetConnection (conn_up.release());
1127 if (!m_stdio_communication.IsConnected ())
1128 {
1129 error.SetErrorString ("failed to set connection for inferior I/O communication");
1130 return error;
1131 }
1132
1133 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1134 m_stdio_communication.StartReadThread();
1135
1136 return error;
1137}
1138
1139void
1140GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1141{
1142 GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton);
1143 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
1144}
1145
Greg Clayton3dedae12013-12-06 21:45:27 +00001146GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001147GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
Greg Clayton576d8832011-03-22 04:00:09 +00001148{
Greg Clayton32e0a752011-03-30 18:16:51 +00001149 // TODO: Log the packet we aren't handling...
Greg Clayton37a0a242012-04-11 00:24:49 +00001150 return SendPacketNoLock ("", 0);
Greg Clayton576d8832011-03-22 04:00:09 +00001151}
1152
Todd Fialaaf245d12014-06-30 21:05:18 +00001153
Greg Clayton3dedae12013-12-06 21:45:27 +00001154GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001155GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
1156{
1157 char packet[16];
1158 int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
Andy Gibbsa297a972013-06-19 19:04:53 +00001159 assert (packet_len < (int)sizeof(packet));
Greg Clayton37a0a242012-04-11 00:24:49 +00001160 return SendPacketNoLock (packet, packet_len);
Greg Clayton32e0a752011-03-30 18:16:51 +00001161}
1162
Todd Fialaaf245d12014-06-30 21:05:18 +00001163GDBRemoteCommunication::PacketResult
1164GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message)
1165{
1166 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
1167 if (log)
1168 log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : "");
1169 return SendErrorResponse (0x03);
1170}
Greg Clayton32e0a752011-03-30 18:16:51 +00001171
Greg Clayton3dedae12013-12-06 21:45:27 +00001172GDBRemoteCommunication::PacketResult
Greg Clayton1cb64962011-03-24 04:28:38 +00001173GDBRemoteCommunicationServer::SendOKResponse ()
1174{
Greg Clayton37a0a242012-04-11 00:24:49 +00001175 return SendPacketNoLock ("OK", 2);
Greg Clayton1cb64962011-03-24 04:28:38 +00001176}
1177
1178bool
1179GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
1180{
Greg Clayton3dedae12013-12-06 21:45:27 +00001181 return GetAck() == PacketResult::Success;
Greg Clayton1cb64962011-03-24 04:28:38 +00001182}
Greg Clayton576d8832011-03-22 04:00:09 +00001183
Greg Clayton3dedae12013-12-06 21:45:27 +00001184GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001185GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
Greg Clayton576d8832011-03-22 04:00:09 +00001186{
1187 StreamString response;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001188
Greg Clayton576d8832011-03-22 04:00:09 +00001189 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
1190
Zachary Turner13b18262014-08-20 16:42:51 +00001191 ArchSpec host_arch(HostInfo::GetArchitecture());
Greg Clayton576d8832011-03-22 04:00:09 +00001192 const llvm::Triple &host_triple = host_arch.GetTriple();
Greg Clayton1cb64962011-03-24 04:28:38 +00001193 response.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00001194 response.PutCString(host_triple.getTriple().c_str());
Greg Clayton1cb64962011-03-24 04:28:38 +00001195 response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001196
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001197 const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
1198 if (distribution_id)
1199 {
1200 response.PutCString("distribution_id:");
1201 response.PutCStringAsRawHex8(distribution_id);
1202 response.PutCString(";");
1203 }
1204
Todd Fialaaf245d12014-06-30 21:05:18 +00001205 // Only send out MachO info when lldb-platform/llgs is running on a MachO host.
1206#if defined(__APPLE__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001207 uint32_t cpu = host_arch.GetMachOCPUType();
1208 uint32_t sub = host_arch.GetMachOCPUSubType();
1209 if (cpu != LLDB_INVALID_CPUTYPE)
1210 response.Printf ("cputype:%u;", cpu);
1211 if (sub != LLDB_INVALID_CPUTYPE)
1212 response.Printf ("cpusubtype:%u;", sub);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001213
Enrico Granata1c5431a2012-07-13 23:55:22 +00001214 if (cpu == ArchSpec::kCore_arm_any)
Enrico Granataf04a2192012-07-13 23:18:48 +00001215 response.Printf("watchpoint_exceptions_received:before;"); // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
1216 else
1217 response.Printf("watchpoint_exceptions_received:after;");
Todd Fialaaf245d12014-06-30 21:05:18 +00001218#else
1219 response.Printf("watchpoint_exceptions_received:after;");
1220#endif
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001221
Greg Clayton576d8832011-03-22 04:00:09 +00001222 switch (lldb::endian::InlHostByteOrder())
1223 {
1224 case eByteOrderBig: response.PutCString ("endian:big;"); break;
1225 case eByteOrderLittle: response.PutCString ("endian:little;"); break;
1226 case eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1227 default: response.PutCString ("endian:unknown;"); break;
1228 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001229
Greg Clayton1cb64962011-03-24 04:28:38 +00001230 uint32_t major = UINT32_MAX;
1231 uint32_t minor = UINT32_MAX;
1232 uint32_t update = UINT32_MAX;
Zachary Turner97a14e62014-08-19 17:18:29 +00001233 if (HostInfo::GetOSVersion(major, minor, update))
Greg Clayton1cb64962011-03-24 04:28:38 +00001234 {
1235 if (major != UINT32_MAX)
1236 {
1237 response.Printf("os_version:%u", major);
1238 if (minor != UINT32_MAX)
1239 {
1240 response.Printf(".%u", minor);
1241 if (update != UINT32_MAX)
1242 response.Printf(".%u", update);
1243 }
1244 response.PutChar(';');
1245 }
1246 }
1247
1248 std::string s;
Zachary Turner97a14e62014-08-19 17:18:29 +00001249#if !defined(__linux__)
1250 if (HostInfo::GetOSBuildString(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001251 {
1252 response.PutCString ("os_build:");
1253 response.PutCStringAsRawHex8(s.c_str());
1254 response.PutChar(';');
1255 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001256 if (HostInfo::GetOSKernelDescription(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001257 {
1258 response.PutCString ("os_kernel:");
1259 response.PutCStringAsRawHex8(s.c_str());
1260 response.PutChar(';');
1261 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001262#endif
1263
Greg Clayton2b98c562013-11-22 18:53:12 +00001264#if defined(__APPLE__)
1265
Todd Fiala013434e2014-07-09 01:29:05 +00001266#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001267 // For iOS devices, we are connected through a USB Mux so we never pretend
1268 // to actually have a hostname as far as the remote lldb that is connecting
1269 // to this lldb-platform is concerned
1270 response.PutCString ("hostname:");
Greg Clayton16810922014-02-27 19:38:18 +00001271 response.PutCStringAsRawHex8("127.0.0.1");
Greg Clayton2b98c562013-11-22 18:53:12 +00001272 response.PutChar(';');
Todd Fiala013434e2014-07-09 01:29:05 +00001273#else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001274 if (HostInfo::GetHostname(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001275 {
1276 response.PutCString ("hostname:");
1277 response.PutCStringAsRawHex8(s.c_str());
1278 response.PutChar(';');
1279 }
Todd Fiala013434e2014-07-09 01:29:05 +00001280#endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001281
1282#else // #if defined(__APPLE__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001283 if (HostInfo::GetHostname(s))
Greg Clayton2b98c562013-11-22 18:53:12 +00001284 {
1285 response.PutCString ("hostname:");
1286 response.PutCStringAsRawHex8(s.c_str());
1287 response.PutChar(';');
1288 }
1289#endif // #if defined(__APPLE__)
1290
Greg Clayton3dedae12013-12-06 21:45:27 +00001291 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001292}
Greg Clayton1cb64962011-03-24 04:28:38 +00001293
Greg Clayton32e0a752011-03-30 18:16:51 +00001294static void
Greg Clayton8b82f082011-04-12 05:54:46 +00001295CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
Greg Clayton32e0a752011-03-30 18:16:51 +00001296{
Daniel Malead01b2952012-11-29 21:49:15 +00001297 response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
Greg Clayton32e0a752011-03-30 18:16:51 +00001298 proc_info.GetProcessID(),
1299 proc_info.GetParentProcessID(),
Greg Clayton8b82f082011-04-12 05:54:46 +00001300 proc_info.GetUserID(),
1301 proc_info.GetGroupID(),
Greg Clayton32e0a752011-03-30 18:16:51 +00001302 proc_info.GetEffectiveUserID(),
1303 proc_info.GetEffectiveGroupID());
1304 response.PutCString ("name:");
1305 response.PutCStringAsRawHex8(proc_info.GetName());
1306 response.PutChar(';');
1307 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1308 if (proc_arch.IsValid())
1309 {
1310 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1311 response.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00001312 response.PutCString(proc_triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001313 response.PutChar(';');
1314 }
1315}
Greg Clayton1cb64962011-03-24 04:28:38 +00001316
Todd Fialaaf245d12014-06-30 21:05:18 +00001317static void
1318CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response)
1319{
1320 response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1321 proc_info.GetProcessID(),
1322 proc_info.GetParentProcessID(),
1323 proc_info.GetUserID(),
1324 proc_info.GetGroupID(),
1325 proc_info.GetEffectiveUserID(),
1326 proc_info.GetEffectiveGroupID());
1327
1328 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1329 if (proc_arch.IsValid())
1330 {
1331 const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1332 if (cpu_type != 0)
1333 response.Printf ("cputype:%" PRIx32 ";", cpu_type);
1334
1335 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1336 if (cpu_subtype != 0)
1337 response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype);
1338
1339 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1340 const std::string vendor = proc_triple.getVendorName ();
1341 if (!vendor.empty ())
1342 response.Printf ("vendor:%s;", vendor.c_str ());
1343
1344 std::string ostype = proc_triple.getOSName ();
1345 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1346 if (proc_triple.getVendor () == llvm::Triple::Apple)
1347 {
1348 switch (proc_triple.getArch ())
1349 {
1350 case llvm::Triple::arm:
Todd Fialad8eaa172014-07-23 14:37:35 +00001351 case llvm::Triple::aarch64:
Todd Fialaaf245d12014-06-30 21:05:18 +00001352 ostype = "ios";
1353 break;
1354 default:
1355 // No change.
1356 break;
1357 }
1358 }
1359 response.Printf ("ostype:%s;", ostype.c_str ());
1360
1361
1362 switch (proc_arch.GetByteOrder ())
1363 {
1364 case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break;
1365 case lldb::eByteOrderBig: response.PutCString ("endian:big;"); break;
1366 case lldb::eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1367 default:
1368 // Nothing.
1369 break;
1370 }
1371
1372 if (proc_triple.isArch64Bit ())
1373 response.PutCString ("ptrsize:8;");
1374 else if (proc_triple.isArch32Bit ())
1375 response.PutCString ("ptrsize:4;");
1376 else if (proc_triple.isArch16Bit ())
1377 response.PutCString ("ptrsize:2;");
1378 }
1379
1380}
1381
1382
1383GDBRemoteCommunication::PacketResult
1384GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1385{
1386 // Only the gdb server handles this.
1387 if (!IsGdbServer ())
1388 return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
1389
1390 // Fail if we don't have a current process.
1391 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1392 return SendErrorResponse (68);
1393
1394 ProcessInstanceInfo proc_info;
1395 if (Host::GetProcessInfo (m_debugged_process_sp->GetID (), proc_info))
1396 {
1397 StreamString response;
1398 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1399 return SendPacketNoLock (response.GetData (), response.GetSize ());
1400 }
1401
1402 return SendErrorResponse (1);
1403}
1404
Greg Clayton3dedae12013-12-06 21:45:27 +00001405GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001406GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
Greg Clayton1cb64962011-03-24 04:28:38 +00001407{
Greg Clayton32e0a752011-03-30 18:16:51 +00001408 // Packet format: "qProcessInfoPID:%i" where %i is the pid
Greg Clayton8b82f082011-04-12 05:54:46 +00001409 packet.SetFilePos(::strlen ("qProcessInfoPID:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001410 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
1411 if (pid != LLDB_INVALID_PROCESS_ID)
1412 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001413 ProcessInstanceInfo proc_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001414 if (Host::GetProcessInfo(pid, proc_info))
1415 {
1416 StreamString response;
1417 CreateProcessInfoResponse (proc_info, response);
Greg Clayton37a0a242012-04-11 00:24:49 +00001418 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001419 }
1420 }
1421 return SendErrorResponse (1);
1422}
1423
Greg Clayton3dedae12013-12-06 21:45:27 +00001424GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001425GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
1426{
1427 m_proc_infos_index = 0;
1428 m_proc_infos.Clear();
1429
Greg Clayton8b82f082011-04-12 05:54:46 +00001430 ProcessInstanceInfoMatch match_info;
1431 packet.SetFilePos(::strlen ("qfProcessInfo"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001432 if (packet.GetChar() == ':')
1433 {
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001434
Greg Clayton32e0a752011-03-30 18:16:51 +00001435 std::string key;
1436 std::string value;
1437 while (packet.GetNameColonValue(key, value))
1438 {
1439 bool success = true;
1440 if (key.compare("name") == 0)
1441 {
1442 StringExtractor extractor;
1443 extractor.GetStringRef().swap(value);
1444 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001445 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001446 }
1447 else if (key.compare("name_match") == 0)
1448 {
1449 if (value.compare("equals") == 0)
1450 {
1451 match_info.SetNameMatchType (eNameMatchEquals);
1452 }
1453 else if (value.compare("starts_with") == 0)
1454 {
1455 match_info.SetNameMatchType (eNameMatchStartsWith);
1456 }
1457 else if (value.compare("ends_with") == 0)
1458 {
1459 match_info.SetNameMatchType (eNameMatchEndsWith);
1460 }
1461 else if (value.compare("contains") == 0)
1462 {
1463 match_info.SetNameMatchType (eNameMatchContains);
1464 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001465 else if (value.compare("regex") == 0)
Greg Clayton32e0a752011-03-30 18:16:51 +00001466 {
1467 match_info.SetNameMatchType (eNameMatchRegularExpression);
1468 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001469 else
Greg Clayton32e0a752011-03-30 18:16:51 +00001470 {
1471 success = false;
1472 }
1473 }
1474 else if (key.compare("pid") == 0)
1475 {
1476 match_info.GetProcessInfo().SetProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1477 }
1478 else if (key.compare("parent_pid") == 0)
1479 {
1480 match_info.GetProcessInfo().SetParentProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1481 }
1482 else if (key.compare("uid") == 0)
1483 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001484 match_info.GetProcessInfo().SetUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001485 }
1486 else if (key.compare("gid") == 0)
1487 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001488 match_info.GetProcessInfo().SetGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001489 }
1490 else if (key.compare("euid") == 0)
1491 {
1492 match_info.GetProcessInfo().SetEffectiveUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1493 }
1494 else if (key.compare("egid") == 0)
1495 {
1496 match_info.GetProcessInfo().SetEffectiveGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1497 }
1498 else if (key.compare("all_users") == 0)
1499 {
1500 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
1501 }
1502 else if (key.compare("triple") == 0)
1503 {
Greg Claytoneb0103f2011-04-07 22:46:35 +00001504 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
Greg Clayton32e0a752011-03-30 18:16:51 +00001505 }
1506 else
1507 {
1508 success = false;
1509 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001510
Greg Clayton32e0a752011-03-30 18:16:51 +00001511 if (!success)
1512 return SendErrorResponse (2);
1513 }
1514 }
1515
1516 if (Host::FindProcesses (match_info, m_proc_infos))
1517 {
1518 // We found something, return the first item by calling the get
1519 // subsequent process info packet handler...
1520 return Handle_qsProcessInfo (packet);
1521 }
1522 return SendErrorResponse (3);
1523}
1524
Greg Clayton3dedae12013-12-06 21:45:27 +00001525GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001526GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
1527{
1528 if (m_proc_infos_index < m_proc_infos.GetSize())
1529 {
1530 StreamString response;
1531 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
1532 ++m_proc_infos_index;
Greg Clayton37a0a242012-04-11 00:24:49 +00001533 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001534 }
1535 return SendErrorResponse (4);
1536}
1537
Greg Clayton3dedae12013-12-06 21:45:27 +00001538GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001539GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
1540{
1541 // Packet format: "qUserName:%i" where %i is the uid
Greg Clayton8b82f082011-04-12 05:54:46 +00001542 packet.SetFilePos(::strlen ("qUserName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001543 uint32_t uid = packet.GetU32 (UINT32_MAX);
1544 if (uid != UINT32_MAX)
1545 {
1546 std::string name;
1547 if (Host::GetUserName (uid, name))
1548 {
1549 StreamString response;
1550 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001551 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001552 }
1553 }
1554 return SendErrorResponse (5);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001555
Greg Clayton32e0a752011-03-30 18:16:51 +00001556}
1557
Greg Clayton3dedae12013-12-06 21:45:27 +00001558GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001559GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
1560{
1561 // Packet format: "qGroupName:%i" where %i is the gid
Greg Clayton8b82f082011-04-12 05:54:46 +00001562 packet.SetFilePos(::strlen ("qGroupName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001563 uint32_t gid = packet.GetU32 (UINT32_MAX);
1564 if (gid != UINT32_MAX)
1565 {
1566 std::string name;
1567 if (Host::GetGroupName (gid, name))
1568 {
1569 StreamString response;
1570 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001571 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001572 }
1573 }
1574 return SendErrorResponse (6);
1575}
1576
Greg Clayton3dedae12013-12-06 21:45:27 +00001577GDBRemoteCommunication::PacketResult
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001578GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
1579{
Greg Clayton8b82f082011-04-12 05:54:46 +00001580 packet.SetFilePos(::strlen ("qSpeedTest:"));
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001581
1582 std::string key;
1583 std::string value;
1584 bool success = packet.GetNameColonValue(key, value);
1585 if (success && key.compare("response_size") == 0)
1586 {
1587 uint32_t response_size = Args::StringToUInt32(value.c_str(), 0, 0, &success);
1588 if (success)
1589 {
1590 if (response_size == 0)
1591 return SendOKResponse();
1592 StreamString response;
1593 uint32_t bytes_left = response_size;
1594 response.PutCString("data:");
1595 while (bytes_left > 0)
1596 {
1597 if (bytes_left >= 26)
1598 {
1599 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1600 bytes_left -= 26;
1601 }
1602 else
1603 {
1604 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1605 bytes_left = 0;
1606 }
1607 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001608 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001609 }
1610 }
1611 return SendErrorResponse (7);
1612}
Greg Clayton8b82f082011-04-12 05:54:46 +00001613
Greg Clayton8b82f082011-04-12 05:54:46 +00001614//
1615//static bool
1616//WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
1617//{
1618// const int time_delta_usecs = 100000;
1619// const int num_retries = timeout_in_seconds/time_delta_usecs;
1620// for (int i=0; i<num_retries; i++)
1621// {
1622// struct proc_bsdinfo bsd_info;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001623// int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
1624// (uint64_t) 0,
1625// &bsd_info,
Greg Clayton8b82f082011-04-12 05:54:46 +00001626// PROC_PIDTBSDINFO_SIZE);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001627//
Greg Clayton8b82f082011-04-12 05:54:46 +00001628// switch (error)
1629// {
1630// case EINVAL:
1631// case ENOTSUP:
1632// case ESRCH:
1633// case EPERM:
1634// return false;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001635//
Greg Clayton8b82f082011-04-12 05:54:46 +00001636// default:
1637// break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001638//
Greg Clayton8b82f082011-04-12 05:54:46 +00001639// case 0:
1640// if (bsd_info.pbi_status == SSTOP)
1641// return true;
1642// }
1643// ::usleep (time_delta_usecs);
1644// }
1645// return false;
1646//}
1647
Greg Clayton3dedae12013-12-06 21:45:27 +00001648GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001649GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
1650{
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001651 // The 'A' packet is the most over designed packet ever here with
1652 // redundant argument indexes, redundant argument lengths and needed hex
1653 // encoded argument string values. Really all that is needed is a comma
Greg Clayton8b82f082011-04-12 05:54:46 +00001654 // separated hex encoded argument value list, but we will stay true to the
1655 // documented version of the 'A' packet here...
1656
Todd Fialaaf245d12014-06-30 21:05:18 +00001657 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1658 int actual_arg_index = 0;
1659
Greg Clayton8b82f082011-04-12 05:54:46 +00001660 packet.SetFilePos(1); // Skip the 'A'
1661 bool success = true;
1662 while (success && packet.GetBytesLeft() > 0)
1663 {
1664 // Decode the decimal argument string length. This length is the
1665 // number of hex nibbles in the argument string value.
1666 const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1667 if (arg_len == UINT32_MAX)
1668 success = false;
1669 else
1670 {
1671 // Make sure the argument hex string length is followed by a comma
1672 if (packet.GetChar() != ',')
1673 success = false;
1674 else
1675 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001676 // Decode the argument index. We ignore this really because
Greg Clayton8b82f082011-04-12 05:54:46 +00001677 // who would really send down the arguments in a random order???
1678 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1679 if (arg_idx == UINT32_MAX)
1680 success = false;
1681 else
1682 {
1683 // Make sure the argument index is followed by a comma
1684 if (packet.GetChar() != ',')
1685 success = false;
1686 else
1687 {
1688 // Decode the argument string value from hex bytes
1689 // back into a UTF8 string and make sure the length
1690 // matches the one supplied in the packet
1691 std::string arg;
Todd Fialaaf245d12014-06-30 21:05:18 +00001692 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2))
Greg Clayton8b82f082011-04-12 05:54:46 +00001693 success = false;
1694 else
1695 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001696 // If there are any bytes left
Greg Clayton8b82f082011-04-12 05:54:46 +00001697 if (packet.GetBytesLeft())
1698 {
1699 if (packet.GetChar() != ',')
1700 success = false;
1701 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001702
Greg Clayton8b82f082011-04-12 05:54:46 +00001703 if (success)
1704 {
1705 if (arg_idx == 0)
1706 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
1707 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001708 if (log)
1709 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ());
1710 ++actual_arg_index;
Greg Clayton8b82f082011-04-12 05:54:46 +00001711 }
1712 }
1713 }
1714 }
1715 }
1716 }
1717 }
1718
1719 if (success)
1720 {
Todd Fiala9f377372014-01-27 20:44:50 +00001721 m_process_launch_error = LaunchProcess ();
Greg Clayton8b82f082011-04-12 05:54:46 +00001722 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1723 {
1724 return SendOKResponse ();
1725 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001726 else
1727 {
1728 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1729 if (log)
1730 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s",
1731 __FUNCTION__,
1732 m_process_launch_error.AsCString());
1733
1734 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001735 }
1736 return SendErrorResponse (8);
1737}
1738
Greg Clayton3dedae12013-12-06 21:45:27 +00001739GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001740GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
1741{
Greg Clayton8b82f082011-04-12 05:54:46 +00001742 StreamString response;
Todd Fialaaf245d12014-06-30 21:05:18 +00001743
1744 if (IsGdbServer ())
Greg Clayton8b82f082011-04-12 05:54:46 +00001745 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001746 // Fail if we don't have a current process.
1747 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1748 return SendErrorResponse (68);
1749
1750 // Make sure we set the current thread so g and p packets return
1751 // the data the gdb will expect.
1752 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1753 SetCurrentThreadID (tid);
1754
1755 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1756 if (!thread_sp)
1757 return SendErrorResponse (69);
1758
1759 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1760 }
1761 else
1762 {
1763 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here
1764 // should not be used. It is reporting process id instead of thread id. The
1765 // correct answer doesn't seem to make much sense for lldb-platform.
1766 // CONSIDER: flip to "unsupported".
1767 lldb::pid_t pid = m_process_launch_info.GetProcessID();
1768 response.Printf("QC%" PRIx64, pid);
1769
1770 // this should always be platform here
1771 assert (m_is_platform && "this code path should only be traversed for lldb-platform");
1772
1773 if (m_is_platform)
Greg Clayton8b82f082011-04-12 05:54:46 +00001774 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001775 // If we launch a process and this GDB server is acting as a platform,
1776 // then we need to clear the process launch state so we can start
1777 // launching another process. In order to launch a process a bunch or
1778 // packets need to be sent: environment packets, working directory,
1779 // disable ASLR, and many more settings. When we launch a process we
1780 // then need to know when to clear this information. Currently we are
1781 // selecting the 'qC' packet as that packet which seems to make the most
1782 // sense.
1783 if (pid != LLDB_INVALID_PROCESS_ID)
1784 {
1785 m_process_launch_info.Clear();
1786 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001787 }
1788 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001789 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00001790}
1791
1792bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00001793GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
1794{
1795 Mutex::Locker locker (m_spawned_pids_mutex);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001796 FreePortForProcess(pid);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001797 return m_spawned_pids.erase(pid) > 0;
1798}
1799bool
1800GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
1801 lldb::pid_t pid,
1802 bool exited,
1803 int signal, // Zero for no signal
1804 int status) // Exit value of process if signal is zero
1805{
1806 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1807 server->DebugserverProcessReaped (pid);
1808 return true;
1809}
1810
Todd Fiala3e92a2b2014-01-24 00:52:53 +00001811bool
1812GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
1813{
1814 // reap a process that we were debugging (but not debugserver)
1815 Mutex::Locker locker (m_spawned_pids_mutex);
1816 return m_spawned_pids.erase(pid) > 0;
1817}
1818
1819bool
1820GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
1821 lldb::pid_t pid,
1822 bool exited,
1823 int signal, // Zero for no signal
1824 int status) // Exit value of process if signal is zero
1825{
1826 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1827 server->DebuggedProcessReaped (pid);
1828 return true;
1829}
1830
Greg Clayton3dedae12013-12-06 21:45:27 +00001831GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001832GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
1833{
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001834#ifdef _WIN32
Deepak Panickal263fde02014-01-14 11:34:44 +00001835 return SendErrorResponse(9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001836#else
Todd Fiala015d8182014-07-22 23:41:36 +00001837 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1838
Greg Clayton8b82f082011-04-12 05:54:46 +00001839 // Spawn a local debugserver as a platform so we can then attach or launch
1840 // a process...
1841
1842 if (m_is_platform)
1843 {
Todd Fiala015d8182014-07-22 23:41:36 +00001844 if (log)
1845 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
1846
Greg Clayton8b82f082011-04-12 05:54:46 +00001847 // Sleep and wait a bit for debugserver to start to listen...
1848 ConnectionFileDescriptor file_conn;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001849 std::string hostname;
Sylvestre Ledrufaa63ce2013-09-28 15:57:37 +00001850 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001851 // with the TMPDIR environment variable
Greg Clayton29b8fc42013-11-21 01:44:58 +00001852 packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
1853 std::string name;
1854 std::string value;
1855 uint16_t port = UINT16_MAX;
1856 while (packet.GetNameColonValue(name, value))
Greg Clayton8b82f082011-04-12 05:54:46 +00001857 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001858 if (name.compare ("host") == 0)
1859 hostname.swap(value);
1860 else if (name.compare ("port") == 0)
1861 port = Args::StringToUInt32(value.c_str(), 0, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00001862 }
Greg Clayton29b8fc42013-11-21 01:44:58 +00001863 if (port == UINT16_MAX)
1864 port = GetNextAvailablePort();
1865
1866 // Spawn a new thread to accept the port that gets bound after
1867 // binding to port 0 (zero).
Greg Claytonfbb76342013-11-20 21:07:01 +00001868
Todd Fiala015d8182014-07-22 23:41:36 +00001869 // Spawn a debugserver and try to get the port it listens to.
1870 ProcessLaunchInfo debugserver_launch_info;
1871 if (hostname.empty())
1872 hostname = "127.0.0.1";
1873 if (log)
1874 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
1875
1876 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
1877
1878 Error error = StartDebugserverProcess (hostname.empty() ? NULL : hostname.c_str(),
1879 port,
1880 debugserver_launch_info,
1881 port);
1882
1883 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
1884
1885
1886 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1887 {
1888 Mutex::Locker locker (m_spawned_pids_mutex);
1889 m_spawned_pids.insert(debugserver_pid);
1890 if (port > 0)
1891 AssociatePortWithProcess(port, debugserver_pid);
1892 }
1893 else
1894 {
1895 if (port > 0)
1896 FreePort (port);
1897 }
1898
Greg Clayton29b8fc42013-11-21 01:44:58 +00001899 if (error.Success())
1900 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001901 if (log)
Todd Fiala015d8182014-07-22 23:41:36 +00001902 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001903
Todd Fiala015d8182014-07-22 23:41:36 +00001904 char response[256];
1905 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
1906 assert (response_len < (int)sizeof(response));
1907 PacketResult packet_result = SendPacketNoLock (response, response_len);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001908
Todd Fiala015d8182014-07-22 23:41:36 +00001909 if (packet_result != PacketResult::Success)
Greg Clayton29b8fc42013-11-21 01:44:58 +00001910 {
Todd Fiala015d8182014-07-22 23:41:36 +00001911 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1912 ::kill (debugserver_pid, SIGINT);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001913 }
Todd Fiala015d8182014-07-22 23:41:36 +00001914 return packet_result;
1915 }
1916 else
1917 {
1918 if (log)
1919 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ());
Greg Clayton8b82f082011-04-12 05:54:46 +00001920 }
1921 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001922 return SendErrorResponse (9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001923#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00001924}
1925
Todd Fiala403edc52014-01-23 22:05:44 +00001926bool
1927GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
1928{
1929 // make sure we know about this process
1930 {
1931 Mutex::Locker locker (m_spawned_pids_mutex);
1932 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1933 return false;
1934 }
1935
1936 // first try a SIGTERM (standard kill)
1937 Host::Kill (pid, SIGTERM);
1938
1939 // check if that worked
1940 for (size_t i=0; i<10; ++i)
1941 {
1942 {
1943 Mutex::Locker locker (m_spawned_pids_mutex);
1944 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1945 {
1946 // it is now killed
1947 return true;
1948 }
1949 }
1950 usleep (10000);
1951 }
1952
1953 // check one more time after the final usleep
1954 {
1955 Mutex::Locker locker (m_spawned_pids_mutex);
1956 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1957 return true;
1958 }
1959
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001960 // the launched process still lives. Now try killing it again,
Todd Fiala403edc52014-01-23 22:05:44 +00001961 // this time with an unblockable signal.
1962 Host::Kill (pid, SIGKILL);
1963
1964 for (size_t i=0; i<10; ++i)
1965 {
1966 {
1967 Mutex::Locker locker (m_spawned_pids_mutex);
1968 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1969 {
1970 // it is now killed
1971 return true;
1972 }
1973 }
1974 usleep (10000);
1975 }
1976
1977 // check one more time after the final usleep
1978 // Scope for locker
1979 {
1980 Mutex::Locker locker (m_spawned_pids_mutex);
1981 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1982 return true;
1983 }
1984
1985 // no luck - the process still lives
1986 return false;
1987}
1988
Greg Clayton3dedae12013-12-06 21:45:27 +00001989GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00001990GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
1991{
Todd Fiala403edc52014-01-23 22:05:44 +00001992 packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001993
Todd Fiala403edc52014-01-23 22:05:44 +00001994 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
1995
1996 // verify that we know anything about this pid.
1997 // Scope for locker
Daniel Maleae0f8f572013-08-26 23:57:52 +00001998 {
Todd Fiala403edc52014-01-23 22:05:44 +00001999 Mutex::Locker locker (m_spawned_pids_mutex);
2000 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002001 {
Todd Fiala403edc52014-01-23 22:05:44 +00002002 // not a pid we know about
2003 return SendErrorResponse (10);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002004 }
2005 }
Todd Fiala403edc52014-01-23 22:05:44 +00002006
2007 // go ahead and attempt to kill the spawned process
2008 if (KillSpawnedProcess (pid))
2009 return SendOKResponse ();
2010 else
2011 return SendErrorResponse (11);
2012}
2013
2014GDBRemoteCommunication::PacketResult
2015GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
2016{
2017 // ignore for now if we're lldb_platform
2018 if (m_is_platform)
2019 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2020
2021 // shutdown all spawned processes
2022 std::set<lldb::pid_t> spawned_pids_copy;
2023
2024 // copy pids
2025 {
2026 Mutex::Locker locker (m_spawned_pids_mutex);
2027 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
2028 }
2029
2030 // nuke the spawned processes
2031 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
2032 {
2033 lldb::pid_t spawned_pid = *it;
2034 if (!KillSpawnedProcess (spawned_pid))
2035 {
2036 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
2037 }
2038 }
2039
Todd Fialaaf245d12014-06-30 21:05:18 +00002040 FlushInferiorOutput ();
2041
2042 // No OK response for kill packet.
2043 // return SendOKResponse ();
2044 return PacketResult::Success;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002045}
2046
Greg Clayton3dedae12013-12-06 21:45:27 +00002047GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002048GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
2049{
2050 if (m_process_launch_error.Success())
2051 return SendOKResponse();
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002052 StreamString response;
Greg Clayton8b82f082011-04-12 05:54:46 +00002053 response.PutChar('E');
2054 response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
Greg Clayton37a0a242012-04-11 00:24:49 +00002055 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00002056}
2057
Greg Clayton3dedae12013-12-06 21:45:27 +00002058GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002059GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet)
2060{
2061 packet.SetFilePos(::strlen ("QEnvironment:"));
2062 const uint32_t bytes_left = packet.GetBytesLeft();
2063 if (bytes_left > 0)
2064 {
2065 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
2066 return SendOKResponse ();
2067 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002068 return SendErrorResponse (12);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002069}
2070
Greg Clayton3dedae12013-12-06 21:45:27 +00002071GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002072GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
2073{
2074 packet.SetFilePos(::strlen ("QLaunchArch:"));
2075 const uint32_t bytes_left = packet.GetBytesLeft();
2076 if (bytes_left > 0)
2077 {
2078 const char* arch_triple = packet.Peek();
2079 ArchSpec arch_spec(arch_triple,NULL);
2080 m_process_launch_info.SetArchitecture(arch_spec);
2081 return SendOKResponse();
2082 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002083 return SendErrorResponse(13);
Greg Clayton8b82f082011-04-12 05:54:46 +00002084}
2085
Greg Clayton3dedae12013-12-06 21:45:27 +00002086GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002087GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
2088{
2089 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
2090 if (packet.GetU32(0))
2091 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
2092 else
2093 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
2094 return SendOKResponse ();
2095}
2096
Greg Clayton3dedae12013-12-06 21:45:27 +00002097GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002098GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
2099{
2100 packet.SetFilePos(::strlen ("QSetWorkingDir:"));
2101 std::string path;
2102 packet.GetHexByteString(path);
Greg Claytonfbb76342013-11-20 21:07:01 +00002103 if (m_is_platform)
2104 {
Colin Riley909bb7a2013-11-26 15:10:46 +00002105#ifdef _WIN32
2106 // Not implemented on Windows
2107 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
2108#else
Greg Claytonfbb76342013-11-20 21:07:01 +00002109 // If this packet is sent to a platform, then change the current working directory
2110 if (::chdir(path.c_str()) != 0)
2111 return SendErrorResponse(errno);
Colin Riley909bb7a2013-11-26 15:10:46 +00002112#endif
Greg Claytonfbb76342013-11-20 21:07:01 +00002113 }
2114 else
2115 {
2116 m_process_launch_info.SwapWorkingDirectory (path);
2117 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002118 return SendOKResponse ();
2119}
2120
Greg Clayton3dedae12013-12-06 21:45:27 +00002121GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002122GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
2123{
2124 StreamString response;
2125
2126 if (m_is_platform)
2127 {
2128 // If this packet is sent to a platform, then change the current working directory
2129 char cwd[PATH_MAX];
2130 if (getcwd(cwd, sizeof(cwd)) == NULL)
2131 {
2132 return SendErrorResponse(errno);
2133 }
2134 else
2135 {
2136 response.PutBytesAsRawHex8(cwd, strlen(cwd));
Greg Clayton3dedae12013-12-06 21:45:27 +00002137 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002138 }
2139 }
2140 else
2141 {
2142 const char *working_dir = m_process_launch_info.GetWorkingDirectory();
2143 if (working_dir && working_dir[0])
2144 {
2145 response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
Greg Clayton3dedae12013-12-06 21:45:27 +00002146 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002147 }
2148 else
2149 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002150 return SendErrorResponse(14);
Greg Claytonfbb76342013-11-20 21:07:01 +00002151 }
2152 }
2153}
2154
Greg Clayton3dedae12013-12-06 21:45:27 +00002155GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002156GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
2157{
2158 packet.SetFilePos(::strlen ("QSetSTDIN:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002159 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002160 std::string path;
2161 packet.GetHexByteString(path);
2162 const bool read = false;
2163 const bool write = true;
2164 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
2165 {
2166 m_process_launch_info.AppendFileAction(file_action);
2167 return SendOKResponse ();
2168 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002169 return SendErrorResponse (15);
Greg Clayton8b82f082011-04-12 05:54:46 +00002170}
2171
Greg Clayton3dedae12013-12-06 21:45:27 +00002172GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002173GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
2174{
2175 packet.SetFilePos(::strlen ("QSetSTDOUT:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002176 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002177 std::string path;
2178 packet.GetHexByteString(path);
2179 const bool read = true;
2180 const bool write = false;
2181 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
2182 {
2183 m_process_launch_info.AppendFileAction(file_action);
2184 return SendOKResponse ();
2185 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002186 return SendErrorResponse (16);
Greg Clayton8b82f082011-04-12 05:54:46 +00002187}
2188
Greg Clayton3dedae12013-12-06 21:45:27 +00002189GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002190GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
2191{
2192 packet.SetFilePos(::strlen ("QSetSTDERR:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002193 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002194 std::string path;
2195 packet.GetHexByteString(path);
2196 const bool read = true;
Greg Clayton9845a8d2012-03-06 04:01:04 +00002197 const bool write = false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002198 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
2199 {
2200 m_process_launch_info.AppendFileAction(file_action);
2201 return SendOKResponse ();
2202 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002203 return SendErrorResponse (17);
Greg Clayton8b82f082011-04-12 05:54:46 +00002204}
2205
Greg Clayton3dedae12013-12-06 21:45:27 +00002206GDBRemoteCommunication::PacketResult
Todd Fialaaf245d12014-06-30 21:05:18 +00002207GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet)
2208{
2209 if (!IsGdbServer ())
2210 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2211
2212 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2213 if (log)
2214 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2215
2216 // Ensure we have a native process.
2217 if (!m_debugged_process_sp)
2218 {
2219 if (log)
2220 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2221 return SendErrorResponse (0x36);
2222 }
2223
2224 // Pull out the signal number.
2225 packet.SetFilePos (::strlen ("C"));
2226 if (packet.GetBytesLeft () < 1)
2227 {
2228 // Shouldn't be using a C without a signal.
2229 return SendIllFormedResponse (packet, "C packet specified without signal.");
2230 }
2231 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2232 if (signo == std::numeric_limits<uint32_t>::max ())
2233 return SendIllFormedResponse (packet, "failed to parse signal number");
2234
2235 // Handle optional continue address.
2236 if (packet.GetBytesLeft () > 0)
2237 {
2238 // FIXME add continue at address support for $C{signo}[;{continue-address}].
2239 if (*packet.Peek () == ';')
2240 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2241 else
2242 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
2243 }
2244
2245 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
2246 Error error;
2247
2248 // We have two branches: what to do if a continue thread is specified (in which case we target
2249 // sending the signal to that thread), or when we don't have a continue thread set (in which
2250 // case we send a signal to the process).
2251
2252 // TODO discuss with Greg Clayton, make sure this makes sense.
2253
2254 lldb::tid_t signal_tid = GetContinueThreadID ();
2255 if (signal_tid != LLDB_INVALID_THREAD_ID)
2256 {
2257 // The resume action for the continue thread (or all threads if a continue thread is not set).
2258 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
2259
2260 // Add the action for the continue thread (or all threads when the continue thread isn't present).
2261 resume_actions.Append (action);
2262 }
2263 else
2264 {
2265 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
2266 error = m_debugged_process_sp->Signal (signo);
2267 if (error.Fail ())
2268 {
2269 if (log)
2270 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s",
2271 __FUNCTION__,
2272 m_debugged_process_sp->GetID (),
2273 error.AsCString ());
2274
2275 return SendErrorResponse (0x52);
2276 }
2277 }
2278
2279 // Resume the threads.
2280 error = m_debugged_process_sp->Resume (resume_actions);
2281 if (error.Fail ())
2282 {
2283 if (log)
2284 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s",
2285 __FUNCTION__,
2286 m_debugged_process_sp->GetID (),
2287 error.AsCString ());
2288
2289 return SendErrorResponse (0x38);
2290 }
2291
2292 // Don't send an "OK" packet; response is the stopped/exited message.
2293 return PacketResult::Success;
2294}
2295
2296GDBRemoteCommunication::PacketResult
2297GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment)
2298{
2299 if (!IsGdbServer ())
2300 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2301
2302 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2303 if (log)
2304 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2305
2306 // We reuse this method in vCont - don't double adjust the file position.
2307 if (!skip_file_pos_adjustment)
2308 packet.SetFilePos (::strlen ("c"));
2309
2310 // For now just support all continue.
2311 const bool has_continue_address = (packet.GetBytesLeft () > 0);
2312 if (has_continue_address)
2313 {
2314 if (log)
2315 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
2316 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2317 }
2318
2319 // Ensure we have a native process.
2320 if (!m_debugged_process_sp)
2321 {
2322 if (log)
2323 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2324 return SendErrorResponse (0x36);
2325 }
2326
2327 // Build the ResumeActionList
2328 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
2329
2330 Error error = m_debugged_process_sp->Resume (actions);
2331 if (error.Fail ())
2332 {
2333 if (log)
2334 {
2335 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s",
2336 __FUNCTION__,
2337 m_debugged_process_sp->GetID (),
2338 error.AsCString ());
2339 }
2340 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2341 }
2342
2343 if (log)
2344 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2345
2346 // No response required from continue.
2347 return PacketResult::Success;
2348}
2349
2350GDBRemoteCommunication::PacketResult
2351GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet)
2352{
2353 if (!IsGdbServer ())
2354 {
2355 // only llgs supports $vCont.
2356 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2357 }
2358
2359 // We handle $vCont messages for c.
2360 // TODO add C, s and S.
2361 StreamString response;
2362 response.Printf("vCont;c;C;s;S");
2363
2364 return SendPacketNoLock(response.GetData(), response.GetSize());
2365}
2366
2367GDBRemoteCommunication::PacketResult
2368GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet)
2369{
2370 if (!IsGdbServer ())
2371 {
2372 // only llgs supports $vCont
2373 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2374 }
2375
2376 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2377 if (log)
2378 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__);
2379
2380 packet.SetFilePos (::strlen ("vCont"));
2381
2382 // Check if this is all continue (no options or ";c").
2383 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0))
2384 {
2385 // Move the packet past the ";c".
2386 if (packet.GetBytesLeft ())
2387 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c"));
2388
2389 const bool skip_file_pos_adjustment = true;
2390 return Handle_c (packet, skip_file_pos_adjustment);
2391 }
2392 else if (::strcmp (packet.Peek (), ";s") == 0)
2393 {
2394 // Move past the ';', then do a simple 's'.
2395 packet.SetFilePos (packet.GetFilePos () + 1);
2396 return Handle_s (packet);
2397 }
2398
2399 // Ensure we have a native process.
2400 if (!m_debugged_process_sp)
2401 {
2402 if (log)
2403 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2404 return SendErrorResponse (0x36);
2405 }
2406
2407 ResumeActionList thread_actions;
2408
2409 while (packet.GetBytesLeft () && *packet.Peek () == ';')
2410 {
2411 // Skip the semi-colon.
2412 packet.GetChar ();
2413
2414 // Build up the thread action.
2415 ResumeAction thread_action;
2416 thread_action.tid = LLDB_INVALID_THREAD_ID;
2417 thread_action.state = eStateInvalid;
2418 thread_action.signal = 0;
2419
2420 const char action = packet.GetChar ();
2421 switch (action)
2422 {
2423 case 'C':
2424 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2425 if (thread_action.signal == 0)
2426 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
2427 // Fall through to next case...
2428
2429 case 'c':
2430 // Continue
2431 thread_action.state = eStateRunning;
2432 break;
2433
2434 case 'S':
2435 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2436 if (thread_action.signal == 0)
2437 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
2438 // Fall through to next case...
2439
2440 case 's':
2441 // Step
2442 thread_action.state = eStateStepping;
2443 break;
2444
2445 default:
2446 return SendIllFormedResponse (packet, "Unsupported vCont action");
2447 break;
2448 }
2449
2450 // Parse out optional :{thread-id} value.
2451 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
2452 {
2453 // Consume the separator.
2454 packet.GetChar ();
2455
2456 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2457 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
2458 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
2459 }
2460
2461 thread_actions.Append (thread_action);
2462 }
2463
2464 // If a default action for all other threads wasn't mentioned
2465 // then we should stop the threads.
2466 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0);
2467
2468 Error error = m_debugged_process_sp->Resume (thread_actions);
2469 if (error.Fail ())
2470 {
2471 if (log)
2472 {
2473 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s",
2474 __FUNCTION__,
2475 m_debugged_process_sp->GetID (),
2476 error.AsCString ());
2477 }
2478 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2479 }
2480
2481 if (log)
2482 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2483
2484 // No response required from vCont.
2485 return PacketResult::Success;
2486}
2487
2488GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00002489GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
2490{
2491 // Send response first before changing m_send_acks to we ack this packet
Greg Clayton3dedae12013-12-06 21:45:27 +00002492 PacketResult packet_result = SendOKResponse ();
Greg Clayton1cb64962011-03-24 04:28:38 +00002493 m_send_acks = false;
Greg Clayton3dedae12013-12-06 21:45:27 +00002494 return packet_result;
Greg Clayton1cb64962011-03-24 04:28:38 +00002495}
Daniel Maleae0f8f572013-08-26 23:57:52 +00002496
Greg Clayton3dedae12013-12-06 21:45:27 +00002497GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002498GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002499{
Greg Claytonfbb76342013-11-20 21:07:01 +00002500 packet.SetFilePos(::strlen("qPlatform_mkdir:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002501 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002502 if (packet.GetChar() == ',')
2503 {
2504 std::string path;
2505 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002506 Error error = FileSystem::MakeDirectory(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002507 if (error.Success())
2508 return SendPacketNoLock ("OK", 2);
2509 else
2510 return SendErrorResponse(error.GetError());
2511 }
2512 return SendErrorResponse(20);
Greg Claytonfbb76342013-11-20 21:07:01 +00002513}
2514
Greg Clayton3dedae12013-12-06 21:45:27 +00002515GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002516GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
2517{
2518 packet.SetFilePos(::strlen("qPlatform_chmod:"));
2519
2520 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002521 if (packet.GetChar() == ',')
2522 {
2523 std::string path;
2524 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002525 Error error = FileSystem::SetFilePermissions(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002526 if (error.Success())
2527 return SendPacketNoLock ("OK", 2);
2528 else
2529 return SendErrorResponse(error.GetError());
2530 }
2531 return SendErrorResponse(19);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002532}
2533
Greg Clayton3dedae12013-12-06 21:45:27 +00002534GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002535GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
2536{
2537 packet.SetFilePos(::strlen("vFile:open:"));
2538 std::string path;
2539 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002540 if (!path.empty())
2541 {
2542 if (packet.GetChar() == ',')
2543 {
2544 uint32_t flags = packet.GetHexMaxU32(false, 0);
2545 if (packet.GetChar() == ',')
2546 {
2547 mode_t mode = packet.GetHexMaxU32(false, 0600);
2548 Error error;
2549 int fd = ::open (path.c_str(), flags, mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002550 const int save_errno = fd == -1 ? errno : 0;
2551 StreamString response;
2552 response.PutChar('F');
2553 response.Printf("%i", fd);
2554 if (save_errno)
2555 response.Printf(",%i", save_errno);
2556 return SendPacketNoLock(response.GetData(), response.GetSize());
2557 }
2558 }
2559 }
2560 return SendErrorResponse(18);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002561}
2562
Greg Clayton3dedae12013-12-06 21:45:27 +00002563GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002564GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
2565{
2566 packet.SetFilePos(::strlen("vFile:close:"));
2567 int fd = packet.GetS32(-1);
2568 Error error;
2569 int err = -1;
2570 int save_errno = 0;
2571 if (fd >= 0)
2572 {
2573 err = close(fd);
2574 save_errno = err == -1 ? errno : 0;
2575 }
2576 else
2577 {
2578 save_errno = EINVAL;
2579 }
2580 StreamString response;
2581 response.PutChar('F');
2582 response.Printf("%i", err);
2583 if (save_errno)
2584 response.Printf(",%i", save_errno);
Greg Clayton2b98c562013-11-22 18:53:12 +00002585 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002586}
2587
Greg Clayton3dedae12013-12-06 21:45:27 +00002588GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002589GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
2590{
Virgile Belloae12a362013-08-27 16:21:49 +00002591#ifdef _WIN32
2592 // Not implemented on Windows
Greg Clayton2b98c562013-11-22 18:53:12 +00002593 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002594#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002595 StreamGDBRemote response;
2596 packet.SetFilePos(::strlen("vFile:pread:"));
2597 int fd = packet.GetS32(-1);
Greg Clayton2b98c562013-11-22 18:53:12 +00002598 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002599 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002600 uint64_t count = packet.GetU64(UINT64_MAX);
2601 if (packet.GetChar() == ',')
2602 {
2603 uint64_t offset = packet.GetU64(UINT32_MAX);
2604 if (count == UINT64_MAX)
2605 {
2606 response.Printf("F-1:%i", EINVAL);
2607 return SendPacketNoLock(response.GetData(), response.GetSize());
2608 }
2609
2610 std::string buffer(count, 0);
2611 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
2612 const int save_errno = bytes_read == -1 ? errno : 0;
2613 response.PutChar('F');
2614 response.Printf("%zi", bytes_read);
2615 if (save_errno)
2616 response.Printf(",%i", save_errno);
2617 else
2618 {
2619 response.PutChar(';');
2620 response.PutEscapedBytes(&buffer[0], bytes_read);
2621 }
2622 return SendPacketNoLock(response.GetData(), response.GetSize());
2623 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002624 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002625 return SendErrorResponse(21);
2626
Virgile Belloae12a362013-08-27 16:21:49 +00002627#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002628}
2629
Greg Clayton3dedae12013-12-06 21:45:27 +00002630GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002631GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
2632{
Virgile Belloae12a362013-08-27 16:21:49 +00002633#ifdef _WIN32
Greg Clayton2b98c562013-11-22 18:53:12 +00002634 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002635#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002636 packet.SetFilePos(::strlen("vFile:pwrite:"));
2637
2638 StreamGDBRemote response;
2639 response.PutChar('F');
2640
2641 int fd = packet.GetU32(UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002642 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002643 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002644 off_t offset = packet.GetU64(UINT32_MAX);
2645 if (packet.GetChar() == ',')
2646 {
2647 std::string buffer;
2648 if (packet.GetEscapedBinaryData(buffer))
2649 {
2650 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
2651 const int save_errno = bytes_written == -1 ? errno : 0;
2652 response.Printf("%zi", bytes_written);
2653 if (save_errno)
2654 response.Printf(",%i", save_errno);
2655 }
2656 else
2657 {
2658 response.Printf ("-1,%i", EINVAL);
2659 }
2660 return SendPacketNoLock(response.GetData(), response.GetSize());
2661 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002662 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002663 return SendErrorResponse(27);
Virgile Belloae12a362013-08-27 16:21:49 +00002664#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002665}
2666
Greg Clayton3dedae12013-12-06 21:45:27 +00002667GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002668GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet)
2669{
2670 packet.SetFilePos(::strlen("vFile:size:"));
2671 std::string path;
2672 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002673 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002674 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002675 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002676 StreamString response;
2677 response.PutChar('F');
2678 response.PutHex64(retcode);
2679 if (retcode == UINT64_MAX)
2680 {
2681 response.PutChar(',');
2682 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
2683 }
2684 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002685 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002686 return SendErrorResponse(22);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002687}
2688
Greg Clayton3dedae12013-12-06 21:45:27 +00002689GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002690GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
2691{
2692 packet.SetFilePos(::strlen("vFile:mode:"));
2693 std::string path;
2694 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002695 if (!path.empty())
2696 {
2697 Error error;
2698 const uint32_t mode = File::GetPermissions(path.c_str(), error);
2699 StreamString response;
2700 response.Printf("F%u", mode);
2701 if (mode == 0 || error.Fail())
2702 response.Printf(",%i", (int)error.GetError());
2703 return SendPacketNoLock(response.GetData(), response.GetSize());
2704 }
2705 return SendErrorResponse(23);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002706}
2707
Greg Clayton3dedae12013-12-06 21:45:27 +00002708GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002709GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
2710{
2711 packet.SetFilePos(::strlen("vFile:exists:"));
2712 std::string path;
2713 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002714 if (!path.empty())
2715 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002716 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002717 StreamString response;
2718 response.PutChar('F');
2719 response.PutChar(',');
2720 if (retcode)
2721 response.PutChar('1');
2722 else
2723 response.PutChar('0');
2724 return SendPacketNoLock(response.GetData(), response.GetSize());
2725 }
2726 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002727}
2728
Greg Clayton3dedae12013-12-06 21:45:27 +00002729GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002730GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002731{
Greg Claytonfbb76342013-11-20 21:07:01 +00002732 packet.SetFilePos(::strlen("vFile:symlink:"));
2733 std::string dst, src;
2734 packet.GetHexByteStringTerminatedBy(dst, ',');
2735 packet.GetChar(); // Skip ',' char
2736 packet.GetHexByteString(src);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002737 Error error = FileSystem::Symlink(src.c_str(), dst.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002738 StreamString response;
2739 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002740 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002741}
2742
Greg Clayton3dedae12013-12-06 21:45:27 +00002743GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002744GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
2745{
2746 packet.SetFilePos(::strlen("vFile:unlink:"));
2747 std::string path;
2748 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002749 Error error = FileSystem::Unlink(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002750 StreamString response;
2751 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002752 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002753}
2754
Greg Clayton3dedae12013-12-06 21:45:27 +00002755GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002756GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
2757{
2758 packet.SetFilePos(::strlen("qPlatform_shell:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002759 std::string path;
2760 std::string working_dir;
2761 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002762 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002763 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002764 if (packet.GetChar() == ',')
2765 {
2766 // FIXME: add timeout to qPlatform_shell packet
2767 // uint32_t timeout = packet.GetHexMaxU32(false, 32);
2768 uint32_t timeout = 10;
2769 if (packet.GetChar() == ',')
2770 packet.GetHexByteString(working_dir);
2771 int status, signo;
2772 std::string output;
2773 Error err = Host::RunShellCommand(path.c_str(),
2774 working_dir.empty() ? NULL : working_dir.c_str(),
2775 &status, &signo, &output, timeout);
2776 StreamGDBRemote response;
2777 if (err.Fail())
2778 {
2779 response.PutCString("F,");
2780 response.PutHex32(UINT32_MAX);
2781 }
2782 else
2783 {
2784 response.PutCString("F,");
2785 response.PutHex32(status);
2786 response.PutChar(',');
2787 response.PutHex32(signo);
2788 response.PutChar(',');
2789 response.PutEscapedBytes(output.c_str(), output.size());
2790 }
2791 return SendPacketNoLock(response.GetData(), response.GetSize());
2792 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002793 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002794 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002795}
2796
Todd Fialaaf245d12014-06-30 21:05:18 +00002797void
2798GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid)
2799{
2800 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code");
2801
2802 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2803 if (log)
2804 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
2805
2806 m_current_tid = tid;
2807 if (m_debugged_process_sp)
2808 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
2809}
2810
2811void
2812GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid)
2813{
2814 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code");
2815
2816 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2817 if (log)
2818 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
2819
2820 m_continue_tid = tid;
2821}
2822
2823GDBRemoteCommunication::PacketResult
2824GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet)
2825{
2826 // Handle the $? gdbremote command.
2827 if (!IsGdbServer ())
2828 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented");
2829
2830 // If no process, indicate error
2831 if (!m_debugged_process_sp)
2832 return SendErrorResponse (02);
2833
2834 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2835}
2836
2837GDBRemoteCommunication::PacketResult
2838GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
2839{
2840 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2841
2842 switch (process_state)
2843 {
2844 case eStateAttaching:
2845 case eStateLaunching:
2846 case eStateRunning:
2847 case eStateStepping:
2848 case eStateDetached:
2849 // NOTE: gdb protocol doc looks like it should return $OK
2850 // when everything is running (i.e. no stopped result).
2851 return PacketResult::Success; // Ignore
2852
2853 case eStateSuspended:
2854 case eStateStopped:
2855 case eStateCrashed:
2856 {
2857 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
2858 // Make sure we set the current thread so g and p packets return
2859 // the data the gdb will expect.
2860 SetCurrentThreadID (tid);
2861 return SendStopReplyPacketForThread (tid);
2862 }
2863
2864 case eStateInvalid:
2865 case eStateUnloaded:
2866 case eStateExited:
2867 if (flush_on_exit)
2868 FlushInferiorOutput ();
2869 return SendWResponse(m_debugged_process_sp.get());
2870
2871 default:
2872 if (log)
2873 {
2874 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s",
2875 __FUNCTION__,
2876 m_debugged_process_sp->GetID (),
2877 StateAsCString (process_state));
2878 }
2879 break;
2880 }
2881
2882 return SendErrorResponse (0);
2883}
2884
Greg Clayton3dedae12013-12-06 21:45:27 +00002885GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002886GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
2887{
Greg Clayton2b98c562013-11-22 18:53:12 +00002888 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002889}
2890
Greg Clayton3dedae12013-12-06 21:45:27 +00002891GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002892GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
2893{
Greg Clayton2b98c562013-11-22 18:53:12 +00002894 packet.SetFilePos(::strlen("vFile:MD5:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002895 std::string path;
2896 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002897 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002898 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002899 uint64_t a,b;
2900 StreamGDBRemote response;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002901 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false)
Greg Clayton2b98c562013-11-22 18:53:12 +00002902 {
2903 response.PutCString("F,");
2904 response.PutCString("x");
2905 }
2906 else
2907 {
2908 response.PutCString("F,");
2909 response.PutHex64(a);
2910 response.PutHex64(b);
2911 }
2912 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002913 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002914 return SendErrorResponse(25);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002915}
Greg Clayton2b98c562013-11-22 18:53:12 +00002916
Todd Fialaaf245d12014-06-30 21:05:18 +00002917GDBRemoteCommunication::PacketResult
2918GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
2919{
2920 // Ensure we're llgs.
2921 if (!IsGdbServer())
2922 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented");
2923
2924 // Fail if we don't have a current process.
2925 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2926 return SendErrorResponse (68);
2927
2928 // Ensure we have a thread.
2929 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
2930 if (!thread_sp)
2931 return SendErrorResponse (69);
2932
2933 // Get the register context for the first thread.
2934 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2935 if (!reg_context_sp)
2936 return SendErrorResponse (69);
2937
2938 // Parse out the register number from the request.
2939 packet.SetFilePos (strlen("qRegisterInfo"));
2940 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2941 if (reg_index == std::numeric_limits<uint32_t>::max ())
2942 return SendErrorResponse (69);
2943
2944 // Return the end of registers response if we've iterated one past the end of the register set.
2945 if (reg_index >= reg_context_sp->GetRegisterCount ())
2946 return SendErrorResponse (69);
2947
2948 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2949 if (!reg_info)
2950 return SendErrorResponse (69);
2951
2952 // Build the reginfos response.
2953 StreamGDBRemote response;
2954
2955 response.PutCString ("name:");
2956 response.PutCString (reg_info->name);
2957 response.PutChar (';');
2958
2959 if (reg_info->alt_name && reg_info->alt_name[0])
2960 {
2961 response.PutCString ("alt-name:");
2962 response.PutCString (reg_info->alt_name);
2963 response.PutChar (';');
2964 }
2965
2966 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
2967
2968 switch (reg_info->encoding)
2969 {
2970 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
2971 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
2972 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
2973 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
2974 default: break;
2975 }
2976
2977 switch (reg_info->format)
2978 {
2979 case eFormatBinary: response.PutCString ("format:binary;"); break;
2980 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
2981 case eFormatHex: response.PutCString ("format:hex;"); break;
2982 case eFormatFloat: response.PutCString ("format:float;"); break;
2983 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
2984 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
2985 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
2986 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
2987 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
2988 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
2989 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
2990 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
2991 default: break;
2992 };
2993
2994 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
2995 if (register_set_name)
2996 {
2997 response.PutCString ("set:");
2998 response.PutCString (register_set_name);
2999 response.PutChar (';');
3000 }
3001
3002 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
3003 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
3004
3005 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
3006 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3007
3008 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
3009 {
3010 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
3011 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
3012 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
3013 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
3014 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
3015 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
3016 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
3017 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
3018 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
3019 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
3020 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
3021 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
3022 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
3023 default: break;
3024 }
3025
3026 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
3027 {
3028 response.PutCString ("container-regs:");
3029 int i = 0;
3030 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3031 {
3032 if (i > 0)
3033 response.PutChar (',');
3034 response.Printf ("%" PRIx32, *reg_num);
3035 }
3036 response.PutChar (';');
3037 }
3038
3039 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
3040 {
3041 response.PutCString ("invalidate-regs:");
3042 int i = 0;
3043 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3044 {
3045 if (i > 0)
3046 response.PutChar (',');
3047 response.Printf ("%" PRIx32, *reg_num);
3048 }
3049 response.PutChar (';');
3050 }
3051
3052 return SendPacketNoLock(response.GetData(), response.GetSize());
3053}
3054
3055GDBRemoteCommunication::PacketResult
3056GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
3057{
3058 // Ensure we're llgs.
3059 if (!IsGdbServer())
3060 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented");
3061
Todd Fiala24189d42014-07-14 06:24:44 +00003062 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3063
Todd Fialaaf245d12014-06-30 21:05:18 +00003064 // Fail if we don't have a current process.
3065 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
Todd Fiala24189d42014-07-14 06:24:44 +00003066 {
3067 if (log)
3068 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
3069 return SendOKResponse ();
3070 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003071
3072 StreamGDBRemote response;
3073 response.PutChar ('m');
3074
Todd Fiala24189d42014-07-14 06:24:44 +00003075 if (log)
3076 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__);
3077
Todd Fialaaf245d12014-06-30 21:05:18 +00003078 NativeThreadProtocolSP thread_sp;
3079 uint32_t thread_index;
3080 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
3081 thread_sp;
3082 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
3083 {
Todd Fiala24189d42014-07-14 06:24:44 +00003084 if (log)
3085 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 +00003086 if (thread_index > 0)
3087 response.PutChar(',');
3088 response.Printf ("%" PRIx64, thread_sp->GetID ());
3089 }
3090
Todd Fiala24189d42014-07-14 06:24:44 +00003091 if (log)
3092 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__);
3093
Todd Fialaaf245d12014-06-30 21:05:18 +00003094 return SendPacketNoLock(response.GetData(), response.GetSize());
3095}
3096
3097GDBRemoteCommunication::PacketResult
3098GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
3099{
3100 // Ensure we're llgs.
3101 if (!IsGdbServer())
3102 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented");
3103
3104 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
3105 return SendPacketNoLock ("l", 1);
3106}
3107
3108GDBRemoteCommunication::PacketResult
3109GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet)
3110{
3111 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3112
3113 // Ensure we're llgs.
3114 if (!IsGdbServer())
3115 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented");
3116
3117 // Parse out the register number from the request.
3118 packet.SetFilePos (strlen("p"));
3119 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3120 if (reg_index == std::numeric_limits<uint32_t>::max ())
3121 {
3122 if (log)
3123 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3124 return SendErrorResponse (0x15);
3125 }
3126
3127 // Get the thread to use.
3128 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3129 if (!thread_sp)
3130 {
3131 if (log)
3132 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__);
3133 return SendErrorResponse (0x15);
3134 }
3135
3136 // Get the thread's register context.
3137 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3138 if (!reg_context_sp)
3139 {
3140 if (log)
3141 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 ());
3142 return SendErrorResponse (0x15);
3143 }
3144
3145 // Return the end of registers response if we've iterated one past the end of the register set.
3146 if (reg_index >= reg_context_sp->GetRegisterCount ())
3147 {
3148 if (log)
3149 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3150 return SendErrorResponse (0x15);
3151 }
3152
3153 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3154 if (!reg_info)
3155 {
3156 if (log)
3157 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3158 return SendErrorResponse (0x15);
3159 }
3160
3161 // Build the reginfos response.
3162 StreamGDBRemote response;
3163
3164 // Retrieve the value
3165 RegisterValue reg_value;
3166 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
3167 if (error.Fail ())
3168 {
3169 if (log)
3170 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3171 return SendErrorResponse (0x15);
3172 }
3173
3174 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
3175 if (!data)
3176 {
3177 if (log)
3178 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
3179 return SendErrorResponse (0x15);
3180 }
3181
3182 // FIXME flip as needed to get data in big/little endian format for this host.
3183 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
3184 response.PutHex8 (data[i]);
3185
3186 return SendPacketNoLock (response.GetData (), response.GetSize ());
3187}
3188
3189GDBRemoteCommunication::PacketResult
3190GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet)
3191{
3192 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3193
3194 // Ensure we're llgs.
3195 if (!IsGdbServer())
3196 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented");
3197
3198 // Ensure there is more content.
3199 if (packet.GetBytesLeft () < 1)
3200 return SendIllFormedResponse (packet, "Empty P packet");
3201
3202 // Parse out the register number from the request.
3203 packet.SetFilePos (strlen("P"));
3204 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3205 if (reg_index == std::numeric_limits<uint32_t>::max ())
3206 {
3207 if (log)
3208 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3209 return SendErrorResponse (0x29);
3210 }
3211
3212 // Note debugserver would send an E30 here.
3213 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
3214 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
3215
3216 // Get process architecture.
3217 ArchSpec process_arch;
3218 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
3219 {
3220 if (log)
3221 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__);
3222 return SendErrorResponse (0x49);
3223 }
3224
3225 // Parse out the value.
3226 const uint64_t raw_value = packet.GetHexMaxU64 (process_arch.GetByteOrder () == lldb::eByteOrderLittle, std::numeric_limits<uint64_t>::max ());
3227
3228 // Get the thread to use.
3229 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3230 if (!thread_sp)
3231 {
3232 if (log)
3233 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__);
3234 return SendErrorResponse (0x28);
3235 }
3236
3237 // Get the thread's register context.
3238 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3239 if (!reg_context_sp)
3240 {
3241 if (log)
3242 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 ());
3243 return SendErrorResponse (0x15);
3244 }
3245
3246 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3247 if (!reg_info)
3248 {
3249 if (log)
3250 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3251 return SendErrorResponse (0x48);
3252 }
3253
3254 // Return the end of registers response if we've iterated one past the end of the register set.
3255 if (reg_index >= reg_context_sp->GetRegisterCount ())
3256 {
3257 if (log)
3258 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3259 return SendErrorResponse (0x47);
3260 }
3261
3262
3263 // Build the reginfos response.
3264 StreamGDBRemote response;
3265
3266 // FIXME Could be suffixed with a thread: parameter.
3267 // That thread then needs to be fed back into the reg context retrieval above.
3268 Error error = reg_context_sp->WriteRegisterFromUnsigned (reg_info, raw_value);
3269 if (error.Fail ())
3270 {
3271 if (log)
3272 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3273 return SendErrorResponse (0x32);
3274 }
3275
3276 return SendOKResponse();
3277}
3278
3279GDBRemoteCommunicationServer::PacketResult
3280GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet)
3281{
3282 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3283
3284 // Ensure we're llgs.
3285 if (!IsGdbServer())
3286 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented");
3287
3288 // Fail if we don't have a current process.
3289 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3290 {
3291 if (log)
3292 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3293 return SendErrorResponse (0x15);
3294 }
3295
3296 // Parse out which variant of $H is requested.
3297 packet.SetFilePos (strlen("H"));
3298 if (packet.GetBytesLeft () < 1)
3299 {
3300 if (log)
3301 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__);
3302 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
3303 }
3304
3305 const char h_variant = packet.GetChar ();
3306 switch (h_variant)
3307 {
3308 case 'g':
3309 break;
3310
3311 case 'c':
3312 break;
3313
3314 default:
3315 if (log)
3316 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
3317 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3318 }
3319
3320 // Parse out the thread number.
3321 // FIXME return a parse success/fail value. All values are valid here.
3322 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
3323
3324 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
3325 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
3326 {
3327 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
3328 if (!thread_sp)
3329 {
3330 if (log)
3331 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
3332 return SendErrorResponse (0x15);
3333 }
3334 }
3335
3336 // Now switch the given thread type.
3337 switch (h_variant)
3338 {
3339 case 'g':
3340 SetCurrentThreadID (tid);
3341 break;
3342
3343 case 'c':
3344 SetContinueThreadID (tid);
3345 break;
3346
3347 default:
3348 assert (false && "unsupported $H variant - shouldn't get here");
3349 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3350 }
3351
3352 return SendOKResponse();
3353}
3354
3355GDBRemoteCommunicationServer::PacketResult
3356GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet)
3357{
3358 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3359
3360 // Ensure we're llgs.
3361 if (!IsGdbServer())
3362 {
3363 // Only supported on llgs
3364 return SendUnimplementedResponse ("");
3365 }
3366
3367 // Fail if we don't have a current process.
3368 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3369 {
3370 if (log)
3371 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3372 return SendErrorResponse (0x15);
3373 }
3374
3375 // Build the ResumeActionList - stop everything.
3376 lldb_private::ResumeActionList actions (StateType::eStateStopped, 0);
3377
3378 Error error = m_debugged_process_sp->Resume (actions);
3379 if (error.Fail ())
3380 {
3381 if (log)
3382 {
3383 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s",
3384 __FUNCTION__,
3385 m_debugged_process_sp->GetID (),
3386 error.AsCString ());
3387 }
3388 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
3389 }
3390
3391 if (log)
3392 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
3393
3394 // No response required from stop all.
3395 return PacketResult::Success;
3396}
3397
3398GDBRemoteCommunicationServer::PacketResult
3399GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet)
3400{
3401 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3402
3403 // Ensure we're llgs.
3404 if (!IsGdbServer())
3405 {
3406 // Only supported on llgs
3407 return SendUnimplementedResponse ("");
3408 }
3409
3410 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3411 {
3412 if (log)
3413 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3414 return SendErrorResponse (0x15);
3415 }
3416
3417 // Parse out the memory address.
3418 packet.SetFilePos (strlen("m"));
3419 if (packet.GetBytesLeft() < 1)
3420 return SendIllFormedResponse(packet, "Too short m packet");
3421
3422 // Read the address. Punting on validation.
3423 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3424 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3425
3426 // Validate comma.
3427 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3428 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
3429
3430 // Get # bytes to read.
3431 if (packet.GetBytesLeft() < 1)
3432 return SendIllFormedResponse(packet, "Length missing in m packet");
3433
3434 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3435 if (byte_count == 0)
3436 {
3437 if (log)
3438 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__);
3439 return PacketResult::Success;
3440 }
3441
3442 // Allocate the response buffer.
3443 std::string buf(byte_count, '\0');
3444 if (buf.empty())
3445 return SendErrorResponse (0x78);
3446
3447
3448 // Retrieve the process memory.
3449 lldb::addr_t bytes_read = 0;
3450 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
3451 if (error.Fail ())
3452 {
3453 if (log)
3454 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
3455 return SendErrorResponse (0x08);
3456 }
3457
3458 if (bytes_read == 0)
3459 {
3460 if (log)
3461 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);
3462 return SendErrorResponse (0x08);
3463 }
3464
3465 StreamGDBRemote response;
3466 for (lldb::addr_t i = 0; i < bytes_read; ++i)
3467 response.PutHex8(buf[i]);
3468
3469 return SendPacketNoLock(response.GetData(), response.GetSize());
3470}
3471
3472GDBRemoteCommunication::PacketResult
3473GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet)
3474{
3475 packet.SetFilePos(::strlen ("QSetDetachOnError:"));
3476 if (packet.GetU32(0))
3477 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError);
3478 else
3479 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError);
3480 return SendOKResponse ();
3481}
3482
3483GDBRemoteCommunicationServer::PacketResult
3484GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet)
3485{
3486 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3487
3488 // Ensure we're llgs.
3489 if (!IsGdbServer())
3490 {
3491 // Only supported on llgs
3492 return SendUnimplementedResponse ("");
3493 }
3494
3495 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3496 {
3497 if (log)
3498 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3499 return SendErrorResponse (0x15);
3500 }
3501
3502 // Parse out the memory address.
3503 packet.SetFilePos (strlen("M"));
3504 if (packet.GetBytesLeft() < 1)
3505 return SendIllFormedResponse(packet, "Too short M packet");
3506
3507 // Read the address. Punting on validation.
3508 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3509 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
3510
3511 // Validate comma.
3512 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3513 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
3514
3515 // Get # bytes to read.
3516 if (packet.GetBytesLeft() < 1)
3517 return SendIllFormedResponse(packet, "Length missing in M packet");
3518
3519 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3520 if (byte_count == 0)
3521 {
3522 if (log)
3523 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__);
3524 return PacketResult::Success;
3525 }
3526
3527 // Validate colon.
3528 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
3529 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
3530
3531 // Allocate the conversion buffer.
3532 std::vector<uint8_t> buf(byte_count, 0);
3533 if (buf.empty())
3534 return SendErrorResponse (0x78);
3535
3536 // Convert the hex memory write contents to bytes.
3537 StreamGDBRemote response;
3538 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
3539 if (convert_count != byte_count)
3540 {
3541 if (log)
3542 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);
3543 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
3544 }
3545
3546 // Write the process memory.
3547 lldb::addr_t bytes_written = 0;
3548 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
3549 if (error.Fail ())
3550 {
3551 if (log)
3552 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
3553 return SendErrorResponse (0x09);
3554 }
3555
3556 if (bytes_written == 0)
3557 {
3558 if (log)
3559 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);
3560 return SendErrorResponse (0x09);
3561 }
3562
3563 return SendOKResponse ();
3564}
3565
3566GDBRemoteCommunicationServer::PacketResult
3567GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
3568{
3569 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3570
3571 // We don't support if we're not llgs.
3572 if (!IsGdbServer())
3573 return SendUnimplementedResponse ("");
3574
3575 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
3576 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
3577 // client only asks this when a process is being debugged.
3578
3579 // Ensure we have a process running; otherwise, we can't figure this out
3580 // since we won't have a NativeProcessProtocol.
3581 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3582 {
3583 if (log)
3584 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3585 return SendErrorResponse (0x15);
3586 }
3587
3588 // Test if we can get any region back when asking for the region around NULL.
3589 MemoryRegionInfo region_info;
3590 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
3591 if (error.Fail ())
3592 {
3593 // We don't support memory region info collection for this NativeProcessProtocol.
3594 return SendUnimplementedResponse ("");
3595 }
3596
3597 return SendOKResponse();
3598}
3599
3600GDBRemoteCommunicationServer::PacketResult
3601GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
3602{
3603 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3604
3605 // We don't support if we're not llgs.
3606 if (!IsGdbServer())
3607 return SendUnimplementedResponse ("");
3608
3609 // Ensure we have a process.
3610 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3611 {
3612 if (log)
3613 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3614 return SendErrorResponse (0x15);
3615 }
3616
3617 // Parse out the memory address.
3618 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
3619 if (packet.GetBytesLeft() < 1)
3620 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
3621
3622 // Read the address. Punting on validation.
3623 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3624
3625 StreamGDBRemote response;
3626
3627 // Get the memory region info for the target address.
3628 MemoryRegionInfo region_info;
3629 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
3630 if (error.Fail ())
3631 {
3632 // Return the error message.
3633
3634 response.PutCString ("error:");
3635 response.PutCStringAsRawHex8 (error.AsCString ());
3636 response.PutChar (';');
3637 }
3638 else
3639 {
3640 // Range start and size.
3641 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
3642
3643 // Permissions.
3644 if (region_info.GetReadable () ||
3645 region_info.GetWritable () ||
3646 region_info.GetExecutable ())
3647 {
3648 // Write permissions info.
3649 response.PutCString ("permissions:");
3650
3651 if (region_info.GetReadable ())
3652 response.PutChar ('r');
3653 if (region_info.GetWritable ())
3654 response.PutChar('w');
3655 if (region_info.GetExecutable())
3656 response.PutChar ('x');
3657
3658 response.PutChar (';');
3659 }
3660 }
3661
3662 return SendPacketNoLock(response.GetData(), response.GetSize());
3663}
3664
3665GDBRemoteCommunicationServer::PacketResult
3666GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet)
3667{
3668 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3669
3670 // We don't support if we're not llgs.
3671 if (!IsGdbServer())
3672 return SendUnimplementedResponse ("");
3673
3674 // Ensure we have a process.
3675 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3676 {
3677 if (log)
3678 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3679 return SendErrorResponse (0x15);
3680 }
3681
3682 // Parse out software or hardware breakpoint requested.
3683 packet.SetFilePos (strlen("Z"));
3684 if (packet.GetBytesLeft() < 1)
3685 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
3686
3687 bool want_breakpoint = true;
3688 bool want_hardware = false;
3689
3690 const char breakpoint_type_char = packet.GetChar ();
3691 switch (breakpoint_type_char)
3692 {
3693 case '0': want_hardware = false; want_breakpoint = true; break;
3694 case '1': want_hardware = true; want_breakpoint = true; break;
3695 case '2': want_breakpoint = false; break;
3696 case '3': want_breakpoint = false; break;
3697 default:
3698 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
3699
3700 }
3701
3702 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3703 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type");
3704
3705 // FIXME implement watchpoint support.
3706 if (!want_breakpoint)
3707 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3708
3709 // Parse out the breakpoint address.
3710 if (packet.GetBytesLeft() < 1)
3711 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
3712 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3713
3714 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3715 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
3716
3717 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3718 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3719 if (kind == std::numeric_limits<uint32_t>::max ())
3720 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument");
3721
3722 if (want_breakpoint)
3723 {
3724 // Try to set the breakpoint.
3725 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware);
3726 if (error.Success ())
3727 return SendOKResponse ();
3728 else
3729 {
3730 if (log)
3731 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3732 return SendErrorResponse (0x09);
3733 }
3734 }
3735
3736 // FIXME fix up after watchpoints are handled.
3737 return SendUnimplementedResponse ("");
3738}
3739
3740GDBRemoteCommunicationServer::PacketResult
3741GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet)
3742{
3743 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3744
3745 // We don't support if we're not llgs.
3746 if (!IsGdbServer())
3747 return SendUnimplementedResponse ("");
3748
3749 // Ensure we have a process.
3750 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3751 {
3752 if (log)
3753 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3754 return SendErrorResponse (0x15);
3755 }
3756
3757 // Parse out software or hardware breakpoint requested.
3758 packet.SetFilePos (strlen("Z"));
3759 if (packet.GetBytesLeft() < 1)
3760 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
3761
3762 bool want_breakpoint = true;
3763
3764 const char breakpoint_type_char = packet.GetChar ();
3765 switch (breakpoint_type_char)
3766 {
3767 case '0': want_breakpoint = true; break;
3768 case '1': want_breakpoint = true; break;
3769 case '2': want_breakpoint = false; break;
3770 case '3': want_breakpoint = false; break;
3771 default:
3772 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
3773
3774 }
3775
3776 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3777 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type");
3778
3779 // FIXME implement watchpoint support.
3780 if (!want_breakpoint)
3781 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3782
3783 // Parse out the breakpoint address.
3784 if (packet.GetBytesLeft() < 1)
3785 return SendIllFormedResponse(packet, "Too short z packet, missing address");
3786 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3787
3788 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3789 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
3790
3791 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3792 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3793 if (kind == std::numeric_limits<uint32_t>::max ())
3794 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument");
3795
3796 if (want_breakpoint)
3797 {
3798 // Try to set the breakpoint.
3799 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr);
3800 if (error.Success ())
3801 return SendOKResponse ();
3802 else
3803 {
3804 if (log)
3805 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3806 return SendErrorResponse (0x09);
3807 }
3808 }
3809
3810 // FIXME fix up after watchpoints are handled.
3811 return SendUnimplementedResponse ("");
3812}
3813
3814GDBRemoteCommunicationServer::PacketResult
3815GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet)
3816{
3817 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
3818
3819 // We don't support if we're not llgs.
3820 if (!IsGdbServer())
3821 return SendUnimplementedResponse ("");
3822
3823 // Ensure we have a process.
3824 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3825 {
3826 if (log)
3827 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3828 return SendErrorResponse (0x32);
3829 }
3830
3831 // We first try to use a continue thread id. If any one or any all set, use the current thread.
3832 // Bail out if we don't have a thread id.
3833 lldb::tid_t tid = GetContinueThreadID ();
3834 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3835 tid = GetCurrentThreadID ();
3836 if (tid == LLDB_INVALID_THREAD_ID)
3837 return SendErrorResponse (0x33);
3838
3839 // Double check that we have such a thread.
3840 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3841 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
3842 if (!thread_sp || thread_sp->GetID () != tid)
3843 return SendErrorResponse (0x33);
3844
3845 // Create the step action for the given thread.
3846 lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
3847
3848 // Setup the actions list.
3849 lldb_private::ResumeActionList actions;
3850 actions.Append (action);
3851
3852 // All other threads stop while we're single stepping a thread.
3853 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3854 Error error = m_debugged_process_sp->Resume (actions);
3855 if (error.Fail ())
3856 {
3857 if (log)
3858 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
3859 return SendErrorResponse(0x49);
3860 }
3861
3862 // No response here - the stop or exit will come from the resulting action.
3863 return PacketResult::Success;
3864}
3865
3866GDBRemoteCommunicationServer::PacketResult
3867GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet)
3868{
3869 StreamGDBRemote response;
3870
3871 // Features common to lldb-platform and llgs.
3872 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less
3873 response.Printf ("PacketSize=%x", max_packet_size);
3874
3875 response.PutCString (";QStartNoAckMode+");
3876 response.PutCString (";QThreadSuffixSupported+");
3877 response.PutCString (";QListThreadsInStopReply+");
3878#if defined(__linux__)
3879 response.PutCString (";qXfer:auxv:read+");
3880#endif
3881
3882 return SendPacketNoLock(response.GetData(), response.GetSize());
3883}
3884
3885GDBRemoteCommunicationServer::PacketResult
3886GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet)
3887{
3888 m_thread_suffix_supported = true;
3889 return SendOKResponse();
3890}
3891
3892GDBRemoteCommunicationServer::PacketResult
3893GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet)
3894{
3895 m_list_threads_in_stop_reply = true;
3896 return SendOKResponse();
3897}
3898
3899GDBRemoteCommunicationServer::PacketResult
3900GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
3901{
3902 // We don't support if we're not llgs.
3903 if (!IsGdbServer())
3904 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
3905
3906 // *BSD impls should be able to do this too.
3907#if defined(__linux__)
3908 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3909
3910 // Parse out the offset.
3911 packet.SetFilePos (strlen("qXfer:auxv:read::"));
3912 if (packet.GetBytesLeft () < 1)
3913 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3914
3915 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3916 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
3917 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3918
3919 // Parse out comma.
3920 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
3921 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
3922
3923 // Parse out the length.
3924 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3925 if (auxv_length == std::numeric_limits<uint64_t>::max ())
3926 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
3927
3928 // Grab the auxv data if we need it.
3929 if (!m_active_auxv_buffer_sp)
3930 {
3931 // Make sure we have a valid process.
3932 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3933 {
3934 if (log)
3935 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3936 return SendErrorResponse (0x10);
3937 }
3938
3939 // Grab the auxv data.
3940 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
3941 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
3942 {
3943 // Hmm, no auxv data, call that an error.
3944 if (log)
3945 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__);
3946 m_active_auxv_buffer_sp.reset ();
3947 return SendErrorResponse (0x11);
3948 }
3949 }
3950
3951 // FIXME find out if/how I lock the stream here.
3952
3953 StreamGDBRemote response;
3954 bool done_with_buffer = false;
3955
3956 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
3957 {
3958 // We have nothing left to send. Mark the buffer as complete.
3959 response.PutChar ('l');
3960 done_with_buffer = true;
3961 }
3962 else
3963 {
3964 // Figure out how many bytes are available starting at the given offset.
3965 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
3966
3967 // Figure out how many bytes we're going to read.
3968 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
3969
3970 // Mark the response type according to whether we're reading the remainder of the auxv data.
3971 if (bytes_to_read >= bytes_remaining)
3972 {
3973 // There will be nothing left to read after this
3974 response.PutChar ('l');
3975 done_with_buffer = true;
3976 }
3977 else
3978 {
3979 // There will still be bytes to read after this request.
3980 response.PutChar ('m');
3981 }
3982
3983 // Now write the data in encoded binary form.
3984 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
3985 }
3986
3987 if (done_with_buffer)
3988 m_active_auxv_buffer_sp.reset ();
3989
3990 return SendPacketNoLock(response.GetData(), response.GetSize());
3991#else
3992 return SendUnimplementedResponse ("not implemented on this platform");
3993#endif
3994}
3995
3996GDBRemoteCommunicationServer::PacketResult
3997GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
3998{
3999 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4000
4001 // We don't support if we're not llgs.
4002 if (!IsGdbServer())
4003 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4004
4005 // Move past packet name.
4006 packet.SetFilePos (strlen ("QSaveRegisterState"));
4007
4008 // Get the thread to use.
4009 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4010 if (!thread_sp)
4011 {
4012 if (m_thread_suffix_supported)
4013 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
4014 else
4015 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4016 }
4017
4018 // Grab the register context for the thread.
4019 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4020 if (!reg_context_sp)
4021 {
4022 if (log)
4023 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 ());
4024 return SendErrorResponse (0x15);
4025 }
4026
4027 // Save registers to a buffer.
4028 DataBufferSP register_data_sp;
4029 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
4030 if (error.Fail ())
4031 {
4032 if (log)
4033 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4034 return SendErrorResponse (0x75);
4035 }
4036
4037 // Allocate a new save id.
4038 const uint32_t save_id = GetNextSavedRegistersID ();
4039 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
4040
4041 // Save the register data buffer under the save id.
4042 {
4043 Mutex::Locker locker (m_saved_registers_mutex);
4044 m_saved_registers_map[save_id] = register_data_sp;
4045 }
4046
4047 // Write the response.
4048 StreamGDBRemote response;
4049 response.Printf ("%" PRIu32, save_id);
4050 return SendPacketNoLock(response.GetData(), response.GetSize());
4051}
4052
4053GDBRemoteCommunicationServer::PacketResult
4054GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
4055{
4056 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4057
4058 // We don't support if we're not llgs.
4059 if (!IsGdbServer())
4060 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4061
4062 // Parse out save id.
4063 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
4064 if (packet.GetBytesLeft () < 1)
4065 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
4066
4067 const uint32_t save_id = packet.GetU32 (0);
4068 if (save_id == 0)
4069 {
4070 if (log)
4071 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
4072 return SendErrorResponse (0x76);
4073 }
4074
4075 // Get the thread to use.
4076 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4077 if (!thread_sp)
4078 {
4079 if (m_thread_suffix_supported)
4080 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
4081 else
4082 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4083 }
4084
4085 // Grab the register context for the thread.
4086 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4087 if (!reg_context_sp)
4088 {
4089 if (log)
4090 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 ());
4091 return SendErrorResponse (0x15);
4092 }
4093
4094 // Retrieve register state buffer, then remove from the list.
4095 DataBufferSP register_data_sp;
4096 {
4097 Mutex::Locker locker (m_saved_registers_mutex);
4098
4099 // Find the register set buffer for the given save id.
4100 auto it = m_saved_registers_map.find (save_id);
4101 if (it == m_saved_registers_map.end ())
4102 {
4103 if (log)
4104 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);
4105 return SendErrorResponse (0x77);
4106 }
4107 register_data_sp = it->second;
4108
4109 // Remove it from the map.
4110 m_saved_registers_map.erase (it);
4111 }
4112
4113 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
4114 if (error.Fail ())
4115 {
4116 if (log)
4117 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4118 return SendErrorResponse (0x77);
4119 }
4120
4121 return SendOKResponse();
4122}
4123
Todd Fiala7306cf32014-07-29 22:30:01 +00004124GDBRemoteCommunicationServer::PacketResult
4125GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet)
4126{
4127 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4128
4129 // We don't support if we're not llgs.
4130 if (!IsGdbServer())
4131 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4132
4133 // Consume the ';' after vAttach.
4134 packet.SetFilePos (strlen ("vAttach"));
4135 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
4136 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
4137
4138 // Grab the PID to which we will attach (assume hex encoding).
4139 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4140 if (pid == LLDB_INVALID_PROCESS_ID)
4141 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
4142
4143 // Attempt to attach.
4144 if (log)
4145 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
4146
4147 Error error = AttachToProcess (pid);
4148
4149 if (error.Fail ())
4150 {
4151 if (log)
4152 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
4153 return SendErrorResponse (0x01);
4154 }
4155
4156 // Notify we attached by sending a stop packet.
4157 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
4158
4159 return PacketResult::Success;
4160}
4161
Todd Fialaaf245d12014-06-30 21:05:18 +00004162void
4163GDBRemoteCommunicationServer::FlushInferiorOutput ()
4164{
4165 // If we're not monitoring an inferior's terminal, ignore this.
4166 if (!m_stdio_communication.IsConnected())
4167 return;
4168
4169 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
4170 if (log)
4171 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
4172
4173 // FIXME implement a timeout on the join.
4174 m_stdio_communication.JoinReadThread();
4175}
4176
4177void
4178GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection ()
4179{
4180 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4181
4182 // Tell the stdio connection to shut down.
4183 if (m_stdio_communication.IsConnected())
4184 {
4185 auto connection = m_stdio_communication.GetConnection();
4186 if (connection)
4187 {
4188 Error error;
4189 connection->Disconnect (&error);
4190
4191 if (error.Success ())
4192 {
4193 if (log)
4194 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
4195 }
4196 else
4197 {
4198 if (log)
4199 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
4200 }
4201 }
4202 }
4203}
4204
4205
4206lldb_private::NativeThreadProtocolSP
4207GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
4208{
4209 NativeThreadProtocolSP thread_sp;
4210
4211 // We have no thread if we don't have a process.
4212 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4213 return thread_sp;
4214
4215 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
4216 // Use the current thread in that case.
4217 if (!m_thread_suffix_supported)
4218 {
4219 const lldb::tid_t current_tid = GetCurrentThreadID ();
4220 if (current_tid == LLDB_INVALID_THREAD_ID)
4221 return thread_sp;
4222 else if (current_tid == 0)
4223 {
4224 // Pick a thread.
4225 return m_debugged_process_sp->GetThreadAtIndex (0);
4226 }
4227 else
4228 return m_debugged_process_sp->GetThreadByID (current_tid);
4229 }
4230
4231 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4232
4233 // Parse out the ';'.
4234 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
4235 {
4236 if (log)
4237 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4238 return thread_sp;
4239 }
4240
4241 if (!packet.GetBytesLeft ())
4242 return thread_sp;
4243
4244 // Parse out thread: portion.
4245 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
4246 {
4247 if (log)
4248 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4249 return thread_sp;
4250 }
4251 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
4252 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4253 if (tid != 0)
4254 return m_debugged_process_sp->GetThreadByID (tid);
4255
4256 return thread_sp;
4257}
4258
4259lldb::tid_t
4260GDBRemoteCommunicationServer::GetCurrentThreadID () const
4261{
4262 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
4263 {
4264 // Use whatever the debug process says is the current thread id
4265 // since the protocol either didn't specify or specified we want
4266 // any/all threads marked as the current thread.
4267 if (!m_debugged_process_sp)
4268 return LLDB_INVALID_THREAD_ID;
4269 return m_debugged_process_sp->GetCurrentThreadID ();
4270 }
4271 // Use the specific current thread id set by the gdb remote protocol.
4272 return m_current_tid;
4273}
4274
4275uint32_t
4276GDBRemoteCommunicationServer::GetNextSavedRegistersID ()
4277{
4278 Mutex::Locker locker (m_saved_registers_mutex);
4279 return m_next_saved_registers_id++;
4280}
4281