blob: 99e0fc634df0303210fb93310222d5a492276060 [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 {
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000702 case ExitType::eExitTypeExit:
703 return_type_code = 'W';
704 break;
705 case ExitType::eExitTypeSignal:
706 return_type_code = 'X';
707 break;
708 case ExitType::eExitTypeStop:
709 return_type_code = 'S';
710 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000711 case ExitType::eExitTypeInvalid:
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000712 return_type_code = 'E';
713 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000714 }
715 response.PutChar (return_type_code);
716
717 // POSIX exit status limited to unsigned 8 bits.
718 response.PutHex8 (return_code);
719
720 return SendPacketNoLock(response.GetData(), response.GetSize());
721 }
722}
723
724static void
725AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
726{
727 int64_t i;
728 if (swap)
729 {
730 for (i = buf_size-1; i >= 0; i--)
731 response.PutHex8 (buf[i]);
732 }
733 else
734 {
735 for (i = 0; i < buf_size; i++)
736 response.PutHex8 (buf[i]);
737 }
738}
739
740static void
741WriteRegisterValueInHexFixedWidth (StreamString &response,
742 NativeRegisterContextSP &reg_ctx_sp,
743 const RegisterInfo &reg_info,
744 const RegisterValue *reg_value_p)
745{
746 RegisterValue reg_value;
747 if (!reg_value_p)
748 {
749 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
750 if (error.Success ())
751 reg_value_p = &reg_value;
752 // else log.
753 }
754
755 if (reg_value_p)
756 {
757 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
758 }
759 else
760 {
761 // Zero-out any unreadable values.
762 if (reg_info.byte_size > 0)
763 {
764 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
765 AppendHexValue (response, zeros.data(), zeros.size(), false);
766 }
767 }
768}
769
770// WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
771
772
773static void
774WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response,
775 NativeRegisterContextSP &reg_ctx_sp,
776 const RegisterInfo &reg_info,
777 const RegisterValue &reg_value)
778{
779 // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
780 // gdb register number, and VVVVVVVV is the correct number of hex bytes
781 // as ASCII for the register value.
782 if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM)
783 return;
784
785 response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]);
786 WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, &reg_value);
787 response.PutChar (';');
788}
789
790
791GDBRemoteCommunication::PacketResult
792GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid)
793{
794 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
795
796 // Ensure we're llgs.
797 if (!IsGdbServer ())
798 {
799 // Only supported on llgs
800 return SendUnimplementedResponse ("");
801 }
802
803 // Ensure we have a debugged process.
804 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
805 return SendErrorResponse (50);
806
807 if (log)
808 log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
809 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
810
811 // Ensure we can get info on the given thread.
812 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
813 if (!thread_sp)
814 return SendErrorResponse (51);
815
816 // Grab the reason this thread stopped.
817 struct ThreadStopInfo tid_stop_info;
818 if (!thread_sp->GetStopReason (tid_stop_info))
819 return SendErrorResponse (52);
820
821 const bool did_exec = tid_stop_info.reason == eStopReasonExec;
822 // FIXME implement register handling for exec'd inferiors.
823 // if (did_exec)
824 // {
825 // const bool force = true;
826 // InitializeRegisters(force);
827 // }
828
829 StreamString response;
830 // Output the T packet with the thread
831 response.PutChar ('T');
832 int signum = tid_stop_info.details.signal.signo;
833 if (log)
834 {
835 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
836 __FUNCTION__,
837 m_debugged_process_sp->GetID (),
838 tid,
839 signum,
840 tid_stop_info.reason,
841 tid_stop_info.details.exception.type);
842 }
843
844 switch (tid_stop_info.reason)
845 {
846 case eStopReasonSignal:
847 case eStopReasonException:
848 signum = thread_sp->TranslateStopInfoToGdbSignal (tid_stop_info);
849 break;
850 default:
851 signum = 0;
852 if (log)
853 {
854 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " has stop reason %d, using signo = 0 in stop reply response",
855 __FUNCTION__,
856 m_debugged_process_sp->GetID (),
857 tid,
858 tid_stop_info.reason);
859 }
860 break;
861 }
862
863 // Print the signal number.
864 response.PutHex8 (signum & 0xff);
865
866 // Include the tid.
867 response.Printf ("thread:%" PRIx64 ";", tid);
868
869 // Include the thread name if there is one.
870 const char *thread_name = thread_sp->GetName ();
871 if (thread_name && thread_name[0])
872 {
873 size_t thread_name_len = strlen(thread_name);
874
875 if (::strcspn (thread_name, "$#+-;:") == thread_name_len)
876 {
877 response.PutCString ("name:");
878 response.PutCString (thread_name);
879 }
880 else
881 {
882 // The thread name contains special chars, send as hex bytes.
883 response.PutCString ("hexname:");
884 response.PutCStringAsRawHex8 (thread_name);
885 }
886 response.PutChar (';');
887 }
888
889 // FIXME look for analog
890 // thread_identifier_info_data_t thread_ident_info;
891 // if (DNBThreadGetIdentifierInfo (pid, tid, &thread_ident_info))
892 // {
893 // if (thread_ident_info.dispatch_qaddr != 0)
894 // ostrm << std::hex << "qaddr:" << thread_ident_info.dispatch_qaddr << ';';
895 // }
896
897 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
898 // will send all thread IDs back in the "threads" key whose value is
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000899 // a list of hex thread IDs separated by commas:
Todd Fialaaf245d12014-06-30 21:05:18 +0000900 // "threads:10a,10b,10c;"
901 // This will save the debugger from having to send a pair of qfThreadInfo
902 // and qsThreadInfo packets, but it also might take a lot of room in the
903 // stop reply packet, so it must be enabled only on systems where there
904 // are no limits on packet lengths.
905 if (m_list_threads_in_stop_reply)
906 {
907 response.PutCString ("threads:");
908
909 uint32_t thread_index = 0;
910 NativeThreadProtocolSP listed_thread_sp;
911 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))
912 {
913 if (thread_index > 0)
914 response.PutChar (',');
915 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
916 }
917 response.PutChar (';');
918 }
919
920 //
921 // Expedite registers.
922 //
923
924 // Grab the register context.
925 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
926 if (reg_ctx_sp)
927 {
928 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
929 const RegisterSet *reg_set_p;
930 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
931 {
932 if (log)
933 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);
934
935 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
936 {
937 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
938 if (reg_info_p == nullptr)
939 {
940 if (log)
941 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);
942 }
943 else if (reg_info_p->value_regs == nullptr)
944 {
945 // Only expediate registers that are not contained in other registers.
946 RegisterValue reg_value;
947 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
948 if (error.Success ())
949 WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
950 else
951 {
952 if (log)
953 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 ());
954
955 }
956 }
957 }
958 }
959 }
960
961 if (did_exec)
962 {
963 response.PutCString ("reason:exec;");
964 }
965 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
966 {
967 response.PutCString ("metype:");
968 response.PutHex64 (tid_stop_info.details.exception.type);
969 response.PutCString (";mecount:");
970 response.PutHex32 (tid_stop_info.details.exception.data_count);
971 response.PutChar (';');
972
973 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
974 {
975 response.PutCString ("medata:");
976 response.PutHex64 (tid_stop_info.details.exception.data[i]);
977 response.PutChar (';');
978 }
979 }
980
981 return SendPacketNoLock (response.GetData(), response.GetSize());
982}
983
984void
985GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
986{
987 assert (process && "process cannot be NULL");
988
989 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
990 if (log)
991 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
992
993 // Send the exit result, and don't flush output.
994 // Note: flushing output here would join the inferior stdio reflection thread, which
995 // would gunk up the waitpid monitor thread that is calling this.
996 PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
997 if (result != PacketResult::Success)
998 {
999 if (log)
1000 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1001 }
1002
1003 // Remove the process from the list of spawned pids.
1004 {
1005 Mutex::Locker locker (m_spawned_pids_mutex);
1006 if (m_spawned_pids.erase (process->GetID ()) < 1)
1007 {
1008 if (log)
1009 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
1010
1011 }
1012 }
1013
1014 // FIXME can't do this yet - since process state propagation is currently
1015 // synchronous, it is running off the NativeProcessProtocol's innards and
1016 // will tear down the NPP while it still has code to execute.
1017#if 0
1018 // Clear the NativeProcessProtocol pointer.
1019 {
1020 Mutex::Locker locker (m_debugged_process_mutex);
1021 m_debugged_process_sp.reset();
1022 }
1023#endif
1024
1025 // Close the pipe to the inferior terminal i/o if we launched it
1026 // and set one up. Otherwise, 'k' and its flush of stdio could
1027 // end up waiting on a thread join that will never end. Consider
1028 // adding a timeout to the connection thread join call so we
1029 // can avoid that scenario altogether.
1030 MaybeCloseInferiorTerminalConnection ();
1031
1032 // We are ready to exit the debug monitor.
1033 m_exit_now = true;
1034}
1035
1036void
1037GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
1038{
1039 assert (process && "process cannot be NULL");
1040
1041 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1042 if (log)
1043 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1044
1045 // Send the stop reason unless this is the stop after the
1046 // launch or attach.
1047 switch (m_inferior_prev_state)
1048 {
1049 case eStateLaunching:
1050 case eStateAttaching:
1051 // Don't send anything per debugserver behavior.
1052 break;
1053 default:
1054 // In all other cases, send the stop reason.
1055 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
1056 if (result != PacketResult::Success)
1057 {
1058 if (log)
1059 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1060 }
1061 break;
1062 }
1063}
1064
1065void
1066GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
1067{
1068 assert (process && "process cannot be NULL");
1069 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1070 if (log)
1071 {
1072 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
1073 __FUNCTION__,
1074 process->GetID (),
1075 StateAsCString (state));
1076 }
1077
1078 switch (state)
1079 {
1080 case StateType::eStateExited:
1081 HandleInferiorState_Exited (process);
1082 break;
1083
1084 case StateType::eStateStopped:
1085 HandleInferiorState_Stopped (process);
1086 break;
1087
1088 default:
1089 if (log)
1090 {
1091 log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
1092 __FUNCTION__,
1093 process->GetID (),
1094 StateAsCString (state));
1095 }
1096 break;
1097 }
1098
1099 // Remember the previous state reported to us.
1100 m_inferior_prev_state = state;
1101}
1102
Todd Fialaa9882ce2014-08-28 15:46:54 +00001103void
1104GDBRemoteCommunicationServer::DidExec (NativeProcessProtocol *process)
1105{
1106 ClearProcessSpecificData ();
1107}
1108
Todd Fialaaf245d12014-06-30 21:05:18 +00001109GDBRemoteCommunication::PacketResult
1110GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len)
1111{
1112 if ((buffer == nullptr) || (len == 0))
1113 {
1114 // Nothing to send.
1115 return PacketResult::Success;
1116 }
1117
1118 StreamString response;
1119 response.PutChar ('O');
1120 response.PutBytesAsRawHex8 (buffer, len);
1121
1122 return SendPacketNoLock (response.GetData (), response.GetSize ());
1123}
1124
1125lldb_private::Error
1126GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd)
1127{
1128 Error error;
1129
1130 // Set up the Read Thread for reading/handling process I/O
1131 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
1132 if (!conn_up)
1133 {
1134 error.SetErrorString ("failed to create ConnectionFileDescriptor");
1135 return error;
1136 }
1137
1138 m_stdio_communication.SetConnection (conn_up.release());
1139 if (!m_stdio_communication.IsConnected ())
1140 {
1141 error.SetErrorString ("failed to set connection for inferior I/O communication");
1142 return error;
1143 }
1144
1145 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1146 m_stdio_communication.StartReadThread();
1147
1148 return error;
1149}
1150
1151void
1152GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1153{
1154 GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton);
1155 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
1156}
1157
Greg Clayton3dedae12013-12-06 21:45:27 +00001158GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001159GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
Greg Clayton576d8832011-03-22 04:00:09 +00001160{
Greg Clayton32e0a752011-03-30 18:16:51 +00001161 // TODO: Log the packet we aren't handling...
Greg Clayton37a0a242012-04-11 00:24:49 +00001162 return SendPacketNoLock ("", 0);
Greg Clayton576d8832011-03-22 04:00:09 +00001163}
1164
Todd Fialaaf245d12014-06-30 21:05:18 +00001165
Greg Clayton3dedae12013-12-06 21:45:27 +00001166GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001167GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
1168{
1169 char packet[16];
1170 int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
Andy Gibbsa297a972013-06-19 19:04:53 +00001171 assert (packet_len < (int)sizeof(packet));
Greg Clayton37a0a242012-04-11 00:24:49 +00001172 return SendPacketNoLock (packet, packet_len);
Greg Clayton32e0a752011-03-30 18:16:51 +00001173}
1174
Todd Fialaaf245d12014-06-30 21:05:18 +00001175GDBRemoteCommunication::PacketResult
1176GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message)
1177{
1178 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
1179 if (log)
1180 log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : "");
1181 return SendErrorResponse (0x03);
1182}
Greg Clayton32e0a752011-03-30 18:16:51 +00001183
Greg Clayton3dedae12013-12-06 21:45:27 +00001184GDBRemoteCommunication::PacketResult
Greg Clayton1cb64962011-03-24 04:28:38 +00001185GDBRemoteCommunicationServer::SendOKResponse ()
1186{
Greg Clayton37a0a242012-04-11 00:24:49 +00001187 return SendPacketNoLock ("OK", 2);
Greg Clayton1cb64962011-03-24 04:28:38 +00001188}
1189
1190bool
1191GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
1192{
Greg Clayton3dedae12013-12-06 21:45:27 +00001193 return GetAck() == PacketResult::Success;
Greg Clayton1cb64962011-03-24 04:28:38 +00001194}
Greg Clayton576d8832011-03-22 04:00:09 +00001195
Greg Clayton3dedae12013-12-06 21:45:27 +00001196GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001197GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
Greg Clayton576d8832011-03-22 04:00:09 +00001198{
1199 StreamString response;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001200
Greg Clayton576d8832011-03-22 04:00:09 +00001201 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
1202
Zachary Turner13b18262014-08-20 16:42:51 +00001203 ArchSpec host_arch(HostInfo::GetArchitecture());
Greg Clayton576d8832011-03-22 04:00:09 +00001204 const llvm::Triple &host_triple = host_arch.GetTriple();
Greg Clayton1cb64962011-03-24 04:28:38 +00001205 response.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00001206 response.PutCString(host_triple.getTriple().c_str());
Greg Clayton1cb64962011-03-24 04:28:38 +00001207 response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001208
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001209 const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
1210 if (distribution_id)
1211 {
1212 response.PutCString("distribution_id:");
1213 response.PutCStringAsRawHex8(distribution_id);
1214 response.PutCString(";");
1215 }
1216
Todd Fialaaf245d12014-06-30 21:05:18 +00001217 // Only send out MachO info when lldb-platform/llgs is running on a MachO host.
1218#if defined(__APPLE__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001219 uint32_t cpu = host_arch.GetMachOCPUType();
1220 uint32_t sub = host_arch.GetMachOCPUSubType();
1221 if (cpu != LLDB_INVALID_CPUTYPE)
1222 response.Printf ("cputype:%u;", cpu);
1223 if (sub != LLDB_INVALID_CPUTYPE)
1224 response.Printf ("cpusubtype:%u;", sub);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001225
Enrico Granata1c5431a2012-07-13 23:55:22 +00001226 if (cpu == ArchSpec::kCore_arm_any)
Enrico Granataf04a2192012-07-13 23:18:48 +00001227 response.Printf("watchpoint_exceptions_received:before;"); // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
1228 else
1229 response.Printf("watchpoint_exceptions_received:after;");
Todd Fialaaf245d12014-06-30 21:05:18 +00001230#else
1231 response.Printf("watchpoint_exceptions_received:after;");
1232#endif
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001233
Greg Clayton576d8832011-03-22 04:00:09 +00001234 switch (lldb::endian::InlHostByteOrder())
1235 {
1236 case eByteOrderBig: response.PutCString ("endian:big;"); break;
1237 case eByteOrderLittle: response.PutCString ("endian:little;"); break;
1238 case eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1239 default: response.PutCString ("endian:unknown;"); break;
1240 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001241
Greg Clayton1cb64962011-03-24 04:28:38 +00001242 uint32_t major = UINT32_MAX;
1243 uint32_t minor = UINT32_MAX;
1244 uint32_t update = UINT32_MAX;
Zachary Turner97a14e62014-08-19 17:18:29 +00001245 if (HostInfo::GetOSVersion(major, minor, update))
Greg Clayton1cb64962011-03-24 04:28:38 +00001246 {
1247 if (major != UINT32_MAX)
1248 {
1249 response.Printf("os_version:%u", major);
1250 if (minor != UINT32_MAX)
1251 {
1252 response.Printf(".%u", minor);
1253 if (update != UINT32_MAX)
1254 response.Printf(".%u", update);
1255 }
1256 response.PutChar(';');
1257 }
1258 }
1259
1260 std::string s;
Zachary Turner97a14e62014-08-19 17:18:29 +00001261#if !defined(__linux__)
1262 if (HostInfo::GetOSBuildString(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001263 {
1264 response.PutCString ("os_build:");
1265 response.PutCStringAsRawHex8(s.c_str());
1266 response.PutChar(';');
1267 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001268 if (HostInfo::GetOSKernelDescription(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001269 {
1270 response.PutCString ("os_kernel:");
1271 response.PutCStringAsRawHex8(s.c_str());
1272 response.PutChar(';');
1273 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001274#endif
1275
Greg Clayton2b98c562013-11-22 18:53:12 +00001276#if defined(__APPLE__)
1277
Todd Fiala013434e2014-07-09 01:29:05 +00001278#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001279 // For iOS devices, we are connected through a USB Mux so we never pretend
1280 // to actually have a hostname as far as the remote lldb that is connecting
1281 // to this lldb-platform is concerned
1282 response.PutCString ("hostname:");
Greg Clayton16810922014-02-27 19:38:18 +00001283 response.PutCStringAsRawHex8("127.0.0.1");
Greg Clayton2b98c562013-11-22 18:53:12 +00001284 response.PutChar(';');
Todd Fiala013434e2014-07-09 01:29:05 +00001285#else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001286 if (HostInfo::GetHostname(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001287 {
1288 response.PutCString ("hostname:");
1289 response.PutCStringAsRawHex8(s.c_str());
1290 response.PutChar(';');
1291 }
Todd Fiala013434e2014-07-09 01:29:05 +00001292#endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001293
1294#else // #if defined(__APPLE__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001295 if (HostInfo::GetHostname(s))
Greg Clayton2b98c562013-11-22 18:53:12 +00001296 {
1297 response.PutCString ("hostname:");
1298 response.PutCStringAsRawHex8(s.c_str());
1299 response.PutChar(';');
1300 }
1301#endif // #if defined(__APPLE__)
1302
Greg Clayton3dedae12013-12-06 21:45:27 +00001303 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001304}
Greg Clayton1cb64962011-03-24 04:28:38 +00001305
Greg Clayton32e0a752011-03-30 18:16:51 +00001306static void
Greg Clayton8b82f082011-04-12 05:54:46 +00001307CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
Greg Clayton32e0a752011-03-30 18:16:51 +00001308{
Daniel Malead01b2952012-11-29 21:49:15 +00001309 response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
Greg Clayton32e0a752011-03-30 18:16:51 +00001310 proc_info.GetProcessID(),
1311 proc_info.GetParentProcessID(),
Greg Clayton8b82f082011-04-12 05:54:46 +00001312 proc_info.GetUserID(),
1313 proc_info.GetGroupID(),
Greg Clayton32e0a752011-03-30 18:16:51 +00001314 proc_info.GetEffectiveUserID(),
1315 proc_info.GetEffectiveGroupID());
1316 response.PutCString ("name:");
1317 response.PutCStringAsRawHex8(proc_info.GetName());
1318 response.PutChar(';');
1319 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1320 if (proc_arch.IsValid())
1321 {
1322 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1323 response.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00001324 response.PutCString(proc_triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001325 response.PutChar(';');
1326 }
1327}
Greg Clayton1cb64962011-03-24 04:28:38 +00001328
Todd Fialaaf245d12014-06-30 21:05:18 +00001329static void
1330CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response)
1331{
1332 response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1333 proc_info.GetProcessID(),
1334 proc_info.GetParentProcessID(),
1335 proc_info.GetUserID(),
1336 proc_info.GetGroupID(),
1337 proc_info.GetEffectiveUserID(),
1338 proc_info.GetEffectiveGroupID());
1339
1340 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1341 if (proc_arch.IsValid())
1342 {
Todd Fialac540dd02014-08-26 18:21:02 +00001343 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1344#if defined(__APPLE__)
1345 // We'll send cputype/cpusubtype.
Todd Fialaaf245d12014-06-30 21:05:18 +00001346 const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1347 if (cpu_type != 0)
1348 response.Printf ("cputype:%" PRIx32 ";", cpu_type);
1349
1350 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1351 if (cpu_subtype != 0)
1352 response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype);
Todd Fialac540dd02014-08-26 18:21:02 +00001353
Todd Fialaaf245d12014-06-30 21:05:18 +00001354
Todd Fialaaf245d12014-06-30 21:05:18 +00001355 const std::string vendor = proc_triple.getVendorName ();
1356 if (!vendor.empty ())
1357 response.Printf ("vendor:%s;", vendor.c_str ());
Todd Fialac540dd02014-08-26 18:21:02 +00001358#else
1359 // We'll send the triple.
1360 response.Printf ("triple:%s;", proc_triple.getTriple().c_str ());
1361#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001362 std::string ostype = proc_triple.getOSName ();
1363 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1364 if (proc_triple.getVendor () == llvm::Triple::Apple)
1365 {
1366 switch (proc_triple.getArch ())
1367 {
1368 case llvm::Triple::arm:
Todd Fialad8eaa172014-07-23 14:37:35 +00001369 case llvm::Triple::aarch64:
Todd Fialaaf245d12014-06-30 21:05:18 +00001370 ostype = "ios";
1371 break;
1372 default:
1373 // No change.
1374 break;
1375 }
1376 }
1377 response.Printf ("ostype:%s;", ostype.c_str ());
1378
1379
1380 switch (proc_arch.GetByteOrder ())
1381 {
1382 case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break;
1383 case lldb::eByteOrderBig: response.PutCString ("endian:big;"); break;
1384 case lldb::eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1385 default:
1386 // Nothing.
1387 break;
1388 }
1389
1390 if (proc_triple.isArch64Bit ())
1391 response.PutCString ("ptrsize:8;");
1392 else if (proc_triple.isArch32Bit ())
1393 response.PutCString ("ptrsize:4;");
1394 else if (proc_triple.isArch16Bit ())
1395 response.PutCString ("ptrsize:2;");
1396 }
1397
1398}
1399
1400
1401GDBRemoteCommunication::PacketResult
1402GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1403{
1404 // Only the gdb server handles this.
1405 if (!IsGdbServer ())
1406 return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
1407
1408 // Fail if we don't have a current process.
1409 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1410 return SendErrorResponse (68);
1411
1412 ProcessInstanceInfo proc_info;
1413 if (Host::GetProcessInfo (m_debugged_process_sp->GetID (), proc_info))
1414 {
1415 StreamString response;
1416 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1417 return SendPacketNoLock (response.GetData (), response.GetSize ());
1418 }
1419
1420 return SendErrorResponse (1);
1421}
1422
Greg Clayton3dedae12013-12-06 21:45:27 +00001423GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001424GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
Greg Clayton1cb64962011-03-24 04:28:38 +00001425{
Greg Clayton32e0a752011-03-30 18:16:51 +00001426 // Packet format: "qProcessInfoPID:%i" where %i is the pid
Greg Clayton8b82f082011-04-12 05:54:46 +00001427 packet.SetFilePos(::strlen ("qProcessInfoPID:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001428 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
1429 if (pid != LLDB_INVALID_PROCESS_ID)
1430 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001431 ProcessInstanceInfo proc_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001432 if (Host::GetProcessInfo(pid, proc_info))
1433 {
1434 StreamString response;
1435 CreateProcessInfoResponse (proc_info, response);
Greg Clayton37a0a242012-04-11 00:24:49 +00001436 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001437 }
1438 }
1439 return SendErrorResponse (1);
1440}
1441
Greg Clayton3dedae12013-12-06 21:45:27 +00001442GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001443GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
1444{
1445 m_proc_infos_index = 0;
1446 m_proc_infos.Clear();
1447
Greg Clayton8b82f082011-04-12 05:54:46 +00001448 ProcessInstanceInfoMatch match_info;
1449 packet.SetFilePos(::strlen ("qfProcessInfo"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001450 if (packet.GetChar() == ':')
1451 {
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001452
Greg Clayton32e0a752011-03-30 18:16:51 +00001453 std::string key;
1454 std::string value;
1455 while (packet.GetNameColonValue(key, value))
1456 {
1457 bool success = true;
1458 if (key.compare("name") == 0)
1459 {
1460 StringExtractor extractor;
1461 extractor.GetStringRef().swap(value);
1462 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001463 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001464 }
1465 else if (key.compare("name_match") == 0)
1466 {
1467 if (value.compare("equals") == 0)
1468 {
1469 match_info.SetNameMatchType (eNameMatchEquals);
1470 }
1471 else if (value.compare("starts_with") == 0)
1472 {
1473 match_info.SetNameMatchType (eNameMatchStartsWith);
1474 }
1475 else if (value.compare("ends_with") == 0)
1476 {
1477 match_info.SetNameMatchType (eNameMatchEndsWith);
1478 }
1479 else if (value.compare("contains") == 0)
1480 {
1481 match_info.SetNameMatchType (eNameMatchContains);
1482 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001483 else if (value.compare("regex") == 0)
Greg Clayton32e0a752011-03-30 18:16:51 +00001484 {
1485 match_info.SetNameMatchType (eNameMatchRegularExpression);
1486 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001487 else
Greg Clayton32e0a752011-03-30 18:16:51 +00001488 {
1489 success = false;
1490 }
1491 }
1492 else if (key.compare("pid") == 0)
1493 {
1494 match_info.GetProcessInfo().SetProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1495 }
1496 else if (key.compare("parent_pid") == 0)
1497 {
1498 match_info.GetProcessInfo().SetParentProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1499 }
1500 else if (key.compare("uid") == 0)
1501 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001502 match_info.GetProcessInfo().SetUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001503 }
1504 else if (key.compare("gid") == 0)
1505 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001506 match_info.GetProcessInfo().SetGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001507 }
1508 else if (key.compare("euid") == 0)
1509 {
1510 match_info.GetProcessInfo().SetEffectiveUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1511 }
1512 else if (key.compare("egid") == 0)
1513 {
1514 match_info.GetProcessInfo().SetEffectiveGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1515 }
1516 else if (key.compare("all_users") == 0)
1517 {
1518 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
1519 }
1520 else if (key.compare("triple") == 0)
1521 {
Greg Claytoneb0103f2011-04-07 22:46:35 +00001522 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
Greg Clayton32e0a752011-03-30 18:16:51 +00001523 }
1524 else
1525 {
1526 success = false;
1527 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001528
Greg Clayton32e0a752011-03-30 18:16:51 +00001529 if (!success)
1530 return SendErrorResponse (2);
1531 }
1532 }
1533
1534 if (Host::FindProcesses (match_info, m_proc_infos))
1535 {
1536 // We found something, return the first item by calling the get
1537 // subsequent process info packet handler...
1538 return Handle_qsProcessInfo (packet);
1539 }
1540 return SendErrorResponse (3);
1541}
1542
Greg Clayton3dedae12013-12-06 21:45:27 +00001543GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001544GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
1545{
1546 if (m_proc_infos_index < m_proc_infos.GetSize())
1547 {
1548 StreamString response;
1549 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
1550 ++m_proc_infos_index;
Greg Clayton37a0a242012-04-11 00:24:49 +00001551 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001552 }
1553 return SendErrorResponse (4);
1554}
1555
Greg Clayton3dedae12013-12-06 21:45:27 +00001556GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001557GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
1558{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001559#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001560 // Packet format: "qUserName:%i" where %i is the uid
Greg Clayton8b82f082011-04-12 05:54:46 +00001561 packet.SetFilePos(::strlen ("qUserName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001562 uint32_t uid = packet.GetU32 (UINT32_MAX);
1563 if (uid != UINT32_MAX)
1564 {
1565 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001566 if (HostInfo::LookupUserName(uid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001567 {
1568 StreamString response;
1569 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001570 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001571 }
1572 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001573#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001574 return SendErrorResponse (5);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001575
Greg Clayton32e0a752011-03-30 18:16:51 +00001576}
1577
Greg Clayton3dedae12013-12-06 21:45:27 +00001578GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001579GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
1580{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001581#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001582 // Packet format: "qGroupName:%i" where %i is the gid
Greg Clayton8b82f082011-04-12 05:54:46 +00001583 packet.SetFilePos(::strlen ("qGroupName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001584 uint32_t gid = packet.GetU32 (UINT32_MAX);
1585 if (gid != UINT32_MAX)
1586 {
1587 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001588 if (HostInfo::LookupGroupName(gid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001589 {
1590 StreamString response;
1591 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001592 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001593 }
1594 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001595#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001596 return SendErrorResponse (6);
1597}
1598
Greg Clayton3dedae12013-12-06 21:45:27 +00001599GDBRemoteCommunication::PacketResult
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001600GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
1601{
Greg Clayton8b82f082011-04-12 05:54:46 +00001602 packet.SetFilePos(::strlen ("qSpeedTest:"));
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001603
1604 std::string key;
1605 std::string value;
1606 bool success = packet.GetNameColonValue(key, value);
1607 if (success && key.compare("response_size") == 0)
1608 {
1609 uint32_t response_size = Args::StringToUInt32(value.c_str(), 0, 0, &success);
1610 if (success)
1611 {
1612 if (response_size == 0)
1613 return SendOKResponse();
1614 StreamString response;
1615 uint32_t bytes_left = response_size;
1616 response.PutCString("data:");
1617 while (bytes_left > 0)
1618 {
1619 if (bytes_left >= 26)
1620 {
1621 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1622 bytes_left -= 26;
1623 }
1624 else
1625 {
1626 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1627 bytes_left = 0;
1628 }
1629 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001630 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001631 }
1632 }
1633 return SendErrorResponse (7);
1634}
Greg Clayton8b82f082011-04-12 05:54:46 +00001635
Greg Clayton8b82f082011-04-12 05:54:46 +00001636//
1637//static bool
1638//WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
1639//{
1640// const int time_delta_usecs = 100000;
1641// const int num_retries = timeout_in_seconds/time_delta_usecs;
1642// for (int i=0; i<num_retries; i++)
1643// {
1644// struct proc_bsdinfo bsd_info;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001645// int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
1646// (uint64_t) 0,
1647// &bsd_info,
Greg Clayton8b82f082011-04-12 05:54:46 +00001648// PROC_PIDTBSDINFO_SIZE);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001649//
Greg Clayton8b82f082011-04-12 05:54:46 +00001650// switch (error)
1651// {
1652// case EINVAL:
1653// case ENOTSUP:
1654// case ESRCH:
1655// case EPERM:
1656// return false;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001657//
Greg Clayton8b82f082011-04-12 05:54:46 +00001658// default:
1659// break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001660//
Greg Clayton8b82f082011-04-12 05:54:46 +00001661// case 0:
1662// if (bsd_info.pbi_status == SSTOP)
1663// return true;
1664// }
1665// ::usleep (time_delta_usecs);
1666// }
1667// return false;
1668//}
1669
Greg Clayton3dedae12013-12-06 21:45:27 +00001670GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001671GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
1672{
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001673 // The 'A' packet is the most over designed packet ever here with
1674 // redundant argument indexes, redundant argument lengths and needed hex
1675 // encoded argument string values. Really all that is needed is a comma
Greg Clayton8b82f082011-04-12 05:54:46 +00001676 // separated hex encoded argument value list, but we will stay true to the
1677 // documented version of the 'A' packet here...
1678
Todd Fialaaf245d12014-06-30 21:05:18 +00001679 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1680 int actual_arg_index = 0;
1681
Greg Clayton8b82f082011-04-12 05:54:46 +00001682 packet.SetFilePos(1); // Skip the 'A'
1683 bool success = true;
1684 while (success && packet.GetBytesLeft() > 0)
1685 {
1686 // Decode the decimal argument string length. This length is the
1687 // number of hex nibbles in the argument string value.
1688 const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1689 if (arg_len == UINT32_MAX)
1690 success = false;
1691 else
1692 {
1693 // Make sure the argument hex string length is followed by a comma
1694 if (packet.GetChar() != ',')
1695 success = false;
1696 else
1697 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001698 // Decode the argument index. We ignore this really because
Greg Clayton8b82f082011-04-12 05:54:46 +00001699 // who would really send down the arguments in a random order???
1700 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1701 if (arg_idx == UINT32_MAX)
1702 success = false;
1703 else
1704 {
1705 // Make sure the argument index is followed by a comma
1706 if (packet.GetChar() != ',')
1707 success = false;
1708 else
1709 {
1710 // Decode the argument string value from hex bytes
1711 // back into a UTF8 string and make sure the length
1712 // matches the one supplied in the packet
1713 std::string arg;
Todd Fialaaf245d12014-06-30 21:05:18 +00001714 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2))
Greg Clayton8b82f082011-04-12 05:54:46 +00001715 success = false;
1716 else
1717 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001718 // If there are any bytes left
Greg Clayton8b82f082011-04-12 05:54:46 +00001719 if (packet.GetBytesLeft())
1720 {
1721 if (packet.GetChar() != ',')
1722 success = false;
1723 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001724
Greg Clayton8b82f082011-04-12 05:54:46 +00001725 if (success)
1726 {
1727 if (arg_idx == 0)
1728 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
1729 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001730 if (log)
1731 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ());
1732 ++actual_arg_index;
Greg Clayton8b82f082011-04-12 05:54:46 +00001733 }
1734 }
1735 }
1736 }
1737 }
1738 }
1739 }
1740
1741 if (success)
1742 {
Todd Fiala9f377372014-01-27 20:44:50 +00001743 m_process_launch_error = LaunchProcess ();
Greg Clayton8b82f082011-04-12 05:54:46 +00001744 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1745 {
1746 return SendOKResponse ();
1747 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001748 else
1749 {
1750 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1751 if (log)
1752 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s",
1753 __FUNCTION__,
1754 m_process_launch_error.AsCString());
1755
1756 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001757 }
1758 return SendErrorResponse (8);
1759}
1760
Greg Clayton3dedae12013-12-06 21:45:27 +00001761GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001762GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
1763{
Greg Clayton8b82f082011-04-12 05:54:46 +00001764 StreamString response;
Todd Fialaaf245d12014-06-30 21:05:18 +00001765
1766 if (IsGdbServer ())
Greg Clayton8b82f082011-04-12 05:54:46 +00001767 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001768 // Fail if we don't have a current process.
1769 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1770 return SendErrorResponse (68);
1771
1772 // Make sure we set the current thread so g and p packets return
1773 // the data the gdb will expect.
1774 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1775 SetCurrentThreadID (tid);
1776
1777 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1778 if (!thread_sp)
1779 return SendErrorResponse (69);
1780
1781 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1782 }
1783 else
1784 {
1785 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here
1786 // should not be used. It is reporting process id instead of thread id. The
1787 // correct answer doesn't seem to make much sense for lldb-platform.
1788 // CONSIDER: flip to "unsupported".
1789 lldb::pid_t pid = m_process_launch_info.GetProcessID();
1790 response.Printf("QC%" PRIx64, pid);
1791
1792 // this should always be platform here
1793 assert (m_is_platform && "this code path should only be traversed for lldb-platform");
1794
1795 if (m_is_platform)
Greg Clayton8b82f082011-04-12 05:54:46 +00001796 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001797 // If we launch a process and this GDB server is acting as a platform,
1798 // then we need to clear the process launch state so we can start
1799 // launching another process. In order to launch a process a bunch or
1800 // packets need to be sent: environment packets, working directory,
1801 // disable ASLR, and many more settings. When we launch a process we
1802 // then need to know when to clear this information. Currently we are
1803 // selecting the 'qC' packet as that packet which seems to make the most
1804 // sense.
1805 if (pid != LLDB_INVALID_PROCESS_ID)
1806 {
1807 m_process_launch_info.Clear();
1808 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001809 }
1810 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001811 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00001812}
1813
1814bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00001815GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
1816{
1817 Mutex::Locker locker (m_spawned_pids_mutex);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001818 FreePortForProcess(pid);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001819 return m_spawned_pids.erase(pid) > 0;
1820}
1821bool
1822GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
1823 lldb::pid_t pid,
1824 bool exited,
1825 int signal, // Zero for no signal
1826 int status) // Exit value of process if signal is zero
1827{
1828 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1829 server->DebugserverProcessReaped (pid);
1830 return true;
1831}
1832
Todd Fiala3e92a2b2014-01-24 00:52:53 +00001833bool
1834GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
1835{
1836 // reap a process that we were debugging (but not debugserver)
1837 Mutex::Locker locker (m_spawned_pids_mutex);
1838 return m_spawned_pids.erase(pid) > 0;
1839}
1840
1841bool
1842GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
1843 lldb::pid_t pid,
1844 bool exited,
1845 int signal, // Zero for no signal
1846 int status) // Exit value of process if signal is zero
1847{
1848 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1849 server->DebuggedProcessReaped (pid);
1850 return true;
1851}
1852
Greg Clayton3dedae12013-12-06 21:45:27 +00001853GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001854GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
1855{
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001856#ifdef _WIN32
Deepak Panickal263fde02014-01-14 11:34:44 +00001857 return SendErrorResponse(9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001858#else
Todd Fiala015d8182014-07-22 23:41:36 +00001859 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1860
Greg Clayton8b82f082011-04-12 05:54:46 +00001861 // Spawn a local debugserver as a platform so we can then attach or launch
1862 // a process...
1863
1864 if (m_is_platform)
1865 {
Todd Fiala015d8182014-07-22 23:41:36 +00001866 if (log)
1867 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
1868
Greg Clayton8b82f082011-04-12 05:54:46 +00001869 // Sleep and wait a bit for debugserver to start to listen...
1870 ConnectionFileDescriptor file_conn;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001871 std::string hostname;
Sylvestre Ledrufaa63ce2013-09-28 15:57:37 +00001872 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001873 // with the TMPDIR environment variable
Greg Clayton29b8fc42013-11-21 01:44:58 +00001874 packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
1875 std::string name;
1876 std::string value;
1877 uint16_t port = UINT16_MAX;
1878 while (packet.GetNameColonValue(name, value))
Greg Clayton8b82f082011-04-12 05:54:46 +00001879 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001880 if (name.compare ("host") == 0)
1881 hostname.swap(value);
1882 else if (name.compare ("port") == 0)
1883 port = Args::StringToUInt32(value.c_str(), 0, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00001884 }
Greg Clayton29b8fc42013-11-21 01:44:58 +00001885 if (port == UINT16_MAX)
1886 port = GetNextAvailablePort();
1887
1888 // Spawn a new thread to accept the port that gets bound after
1889 // binding to port 0 (zero).
Greg Claytonfbb76342013-11-20 21:07:01 +00001890
Todd Fiala015d8182014-07-22 23:41:36 +00001891 // Spawn a debugserver and try to get the port it listens to.
1892 ProcessLaunchInfo debugserver_launch_info;
1893 if (hostname.empty())
1894 hostname = "127.0.0.1";
1895 if (log)
1896 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
1897
1898 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
1899
1900 Error error = StartDebugserverProcess (hostname.empty() ? NULL : hostname.c_str(),
1901 port,
1902 debugserver_launch_info,
1903 port);
1904
1905 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
1906
1907
1908 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1909 {
1910 Mutex::Locker locker (m_spawned_pids_mutex);
1911 m_spawned_pids.insert(debugserver_pid);
1912 if (port > 0)
1913 AssociatePortWithProcess(port, debugserver_pid);
1914 }
1915 else
1916 {
1917 if (port > 0)
1918 FreePort (port);
1919 }
1920
Greg Clayton29b8fc42013-11-21 01:44:58 +00001921 if (error.Success())
1922 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001923 if (log)
Todd Fiala015d8182014-07-22 23:41:36 +00001924 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001925
Todd Fiala015d8182014-07-22 23:41:36 +00001926 char response[256];
1927 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
1928 assert (response_len < (int)sizeof(response));
1929 PacketResult packet_result = SendPacketNoLock (response, response_len);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001930
Todd Fiala015d8182014-07-22 23:41:36 +00001931 if (packet_result != PacketResult::Success)
Greg Clayton29b8fc42013-11-21 01:44:58 +00001932 {
Todd Fiala015d8182014-07-22 23:41:36 +00001933 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1934 ::kill (debugserver_pid, SIGINT);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001935 }
Todd Fiala015d8182014-07-22 23:41:36 +00001936 return packet_result;
1937 }
1938 else
1939 {
1940 if (log)
1941 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ());
Greg Clayton8b82f082011-04-12 05:54:46 +00001942 }
1943 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001944 return SendErrorResponse (9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001945#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00001946}
1947
Todd Fiala403edc52014-01-23 22:05:44 +00001948bool
1949GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
1950{
1951 // make sure we know about this process
1952 {
1953 Mutex::Locker locker (m_spawned_pids_mutex);
1954 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1955 return false;
1956 }
1957
1958 // first try a SIGTERM (standard kill)
1959 Host::Kill (pid, SIGTERM);
1960
1961 // check if that worked
1962 for (size_t i=0; i<10; ++i)
1963 {
1964 {
1965 Mutex::Locker locker (m_spawned_pids_mutex);
1966 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1967 {
1968 // it is now killed
1969 return true;
1970 }
1971 }
1972 usleep (10000);
1973 }
1974
1975 // check one more time after the final usleep
1976 {
1977 Mutex::Locker locker (m_spawned_pids_mutex);
1978 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1979 return true;
1980 }
1981
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001982 // the launched process still lives. Now try killing it again,
Todd Fiala403edc52014-01-23 22:05:44 +00001983 // this time with an unblockable signal.
1984 Host::Kill (pid, SIGKILL);
1985
1986 for (size_t i=0; i<10; ++i)
1987 {
1988 {
1989 Mutex::Locker locker (m_spawned_pids_mutex);
1990 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1991 {
1992 // it is now killed
1993 return true;
1994 }
1995 }
1996 usleep (10000);
1997 }
1998
1999 // check one more time after the final usleep
2000 // Scope for locker
2001 {
2002 Mutex::Locker locker (m_spawned_pids_mutex);
2003 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2004 return true;
2005 }
2006
2007 // no luck - the process still lives
2008 return false;
2009}
2010
Greg Clayton3dedae12013-12-06 21:45:27 +00002011GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002012GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
2013{
Todd Fiala403edc52014-01-23 22:05:44 +00002014 packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002015
Todd Fiala403edc52014-01-23 22:05:44 +00002016 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
2017
2018 // verify that we know anything about this pid.
2019 // Scope for locker
Daniel Maleae0f8f572013-08-26 23:57:52 +00002020 {
Todd Fiala403edc52014-01-23 22:05:44 +00002021 Mutex::Locker locker (m_spawned_pids_mutex);
2022 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002023 {
Todd Fiala403edc52014-01-23 22:05:44 +00002024 // not a pid we know about
2025 return SendErrorResponse (10);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002026 }
2027 }
Todd Fiala403edc52014-01-23 22:05:44 +00002028
2029 // go ahead and attempt to kill the spawned process
2030 if (KillSpawnedProcess (pid))
2031 return SendOKResponse ();
2032 else
2033 return SendErrorResponse (11);
2034}
2035
2036GDBRemoteCommunication::PacketResult
2037GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
2038{
2039 // ignore for now if we're lldb_platform
2040 if (m_is_platform)
2041 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2042
2043 // shutdown all spawned processes
2044 std::set<lldb::pid_t> spawned_pids_copy;
2045
2046 // copy pids
2047 {
2048 Mutex::Locker locker (m_spawned_pids_mutex);
2049 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
2050 }
2051
2052 // nuke the spawned processes
2053 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
2054 {
2055 lldb::pid_t spawned_pid = *it;
2056 if (!KillSpawnedProcess (spawned_pid))
2057 {
2058 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
2059 }
2060 }
2061
Todd Fialaaf245d12014-06-30 21:05:18 +00002062 FlushInferiorOutput ();
2063
2064 // No OK response for kill packet.
2065 // return SendOKResponse ();
2066 return PacketResult::Success;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002067}
2068
Greg Clayton3dedae12013-12-06 21:45:27 +00002069GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002070GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
2071{
2072 if (m_process_launch_error.Success())
2073 return SendOKResponse();
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002074 StreamString response;
Greg Clayton8b82f082011-04-12 05:54:46 +00002075 response.PutChar('E');
2076 response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
Greg Clayton37a0a242012-04-11 00:24:49 +00002077 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00002078}
2079
Greg Clayton3dedae12013-12-06 21:45:27 +00002080GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002081GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet)
2082{
2083 packet.SetFilePos(::strlen ("QEnvironment:"));
2084 const uint32_t bytes_left = packet.GetBytesLeft();
2085 if (bytes_left > 0)
2086 {
2087 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
2088 return SendOKResponse ();
2089 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002090 return SendErrorResponse (12);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002091}
2092
Greg Clayton3dedae12013-12-06 21:45:27 +00002093GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002094GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
2095{
2096 packet.SetFilePos(::strlen ("QLaunchArch:"));
2097 const uint32_t bytes_left = packet.GetBytesLeft();
2098 if (bytes_left > 0)
2099 {
2100 const char* arch_triple = packet.Peek();
2101 ArchSpec arch_spec(arch_triple,NULL);
2102 m_process_launch_info.SetArchitecture(arch_spec);
2103 return SendOKResponse();
2104 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002105 return SendErrorResponse(13);
Greg Clayton8b82f082011-04-12 05:54:46 +00002106}
2107
Greg Clayton3dedae12013-12-06 21:45:27 +00002108GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002109GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
2110{
2111 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
2112 if (packet.GetU32(0))
2113 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
2114 else
2115 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
2116 return SendOKResponse ();
2117}
2118
Greg Clayton3dedae12013-12-06 21:45:27 +00002119GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002120GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
2121{
2122 packet.SetFilePos(::strlen ("QSetWorkingDir:"));
2123 std::string path;
2124 packet.GetHexByteString(path);
Greg Claytonfbb76342013-11-20 21:07:01 +00002125 if (m_is_platform)
2126 {
Colin Riley909bb7a2013-11-26 15:10:46 +00002127#ifdef _WIN32
2128 // Not implemented on Windows
2129 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
2130#else
Greg Claytonfbb76342013-11-20 21:07:01 +00002131 // If this packet is sent to a platform, then change the current working directory
2132 if (::chdir(path.c_str()) != 0)
2133 return SendErrorResponse(errno);
Colin Riley909bb7a2013-11-26 15:10:46 +00002134#endif
Greg Claytonfbb76342013-11-20 21:07:01 +00002135 }
2136 else
2137 {
2138 m_process_launch_info.SwapWorkingDirectory (path);
2139 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002140 return SendOKResponse ();
2141}
2142
Greg Clayton3dedae12013-12-06 21:45:27 +00002143GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002144GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
2145{
2146 StreamString response;
2147
2148 if (m_is_platform)
2149 {
2150 // If this packet is sent to a platform, then change the current working directory
2151 char cwd[PATH_MAX];
2152 if (getcwd(cwd, sizeof(cwd)) == NULL)
2153 {
2154 return SendErrorResponse(errno);
2155 }
2156 else
2157 {
2158 response.PutBytesAsRawHex8(cwd, strlen(cwd));
Greg Clayton3dedae12013-12-06 21:45:27 +00002159 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002160 }
2161 }
2162 else
2163 {
2164 const char *working_dir = m_process_launch_info.GetWorkingDirectory();
2165 if (working_dir && working_dir[0])
2166 {
2167 response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
Greg Clayton3dedae12013-12-06 21:45:27 +00002168 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002169 }
2170 else
2171 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002172 return SendErrorResponse(14);
Greg Claytonfbb76342013-11-20 21:07:01 +00002173 }
2174 }
2175}
2176
Greg Clayton3dedae12013-12-06 21:45:27 +00002177GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002178GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
2179{
2180 packet.SetFilePos(::strlen ("QSetSTDIN:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002181 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002182 std::string path;
2183 packet.GetHexByteString(path);
2184 const bool read = false;
2185 const bool write = true;
2186 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
2187 {
2188 m_process_launch_info.AppendFileAction(file_action);
2189 return SendOKResponse ();
2190 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002191 return SendErrorResponse (15);
Greg Clayton8b82f082011-04-12 05:54:46 +00002192}
2193
Greg Clayton3dedae12013-12-06 21:45:27 +00002194GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002195GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
2196{
2197 packet.SetFilePos(::strlen ("QSetSTDOUT:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002198 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002199 std::string path;
2200 packet.GetHexByteString(path);
2201 const bool read = true;
2202 const bool write = false;
2203 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
2204 {
2205 m_process_launch_info.AppendFileAction(file_action);
2206 return SendOKResponse ();
2207 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002208 return SendErrorResponse (16);
Greg Clayton8b82f082011-04-12 05:54:46 +00002209}
2210
Greg Clayton3dedae12013-12-06 21:45:27 +00002211GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002212GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
2213{
2214 packet.SetFilePos(::strlen ("QSetSTDERR:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002215 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002216 std::string path;
2217 packet.GetHexByteString(path);
2218 const bool read = true;
Greg Clayton9845a8d2012-03-06 04:01:04 +00002219 const bool write = false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002220 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
2221 {
2222 m_process_launch_info.AppendFileAction(file_action);
2223 return SendOKResponse ();
2224 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002225 return SendErrorResponse (17);
Greg Clayton8b82f082011-04-12 05:54:46 +00002226}
2227
Greg Clayton3dedae12013-12-06 21:45:27 +00002228GDBRemoteCommunication::PacketResult
Todd Fialaaf245d12014-06-30 21:05:18 +00002229GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet)
2230{
2231 if (!IsGdbServer ())
2232 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2233
2234 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2235 if (log)
2236 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2237
2238 // Ensure we have a native process.
2239 if (!m_debugged_process_sp)
2240 {
2241 if (log)
2242 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2243 return SendErrorResponse (0x36);
2244 }
2245
2246 // Pull out the signal number.
2247 packet.SetFilePos (::strlen ("C"));
2248 if (packet.GetBytesLeft () < 1)
2249 {
2250 // Shouldn't be using a C without a signal.
2251 return SendIllFormedResponse (packet, "C packet specified without signal.");
2252 }
2253 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2254 if (signo == std::numeric_limits<uint32_t>::max ())
2255 return SendIllFormedResponse (packet, "failed to parse signal number");
2256
2257 // Handle optional continue address.
2258 if (packet.GetBytesLeft () > 0)
2259 {
2260 // FIXME add continue at address support for $C{signo}[;{continue-address}].
2261 if (*packet.Peek () == ';')
2262 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2263 else
2264 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
2265 }
2266
2267 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
2268 Error error;
2269
2270 // We have two branches: what to do if a continue thread is specified (in which case we target
2271 // sending the signal to that thread), or when we don't have a continue thread set (in which
2272 // case we send a signal to the process).
2273
2274 // TODO discuss with Greg Clayton, make sure this makes sense.
2275
2276 lldb::tid_t signal_tid = GetContinueThreadID ();
2277 if (signal_tid != LLDB_INVALID_THREAD_ID)
2278 {
2279 // The resume action for the continue thread (or all threads if a continue thread is not set).
2280 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
2281
2282 // Add the action for the continue thread (or all threads when the continue thread isn't present).
2283 resume_actions.Append (action);
2284 }
2285 else
2286 {
2287 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
2288 error = m_debugged_process_sp->Signal (signo);
2289 if (error.Fail ())
2290 {
2291 if (log)
2292 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s",
2293 __FUNCTION__,
2294 m_debugged_process_sp->GetID (),
2295 error.AsCString ());
2296
2297 return SendErrorResponse (0x52);
2298 }
2299 }
2300
2301 // Resume the threads.
2302 error = m_debugged_process_sp->Resume (resume_actions);
2303 if (error.Fail ())
2304 {
2305 if (log)
2306 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s",
2307 __FUNCTION__,
2308 m_debugged_process_sp->GetID (),
2309 error.AsCString ());
2310
2311 return SendErrorResponse (0x38);
2312 }
2313
2314 // Don't send an "OK" packet; response is the stopped/exited message.
2315 return PacketResult::Success;
2316}
2317
2318GDBRemoteCommunication::PacketResult
2319GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment)
2320{
2321 if (!IsGdbServer ())
2322 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2323
2324 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2325 if (log)
2326 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2327
2328 // We reuse this method in vCont - don't double adjust the file position.
2329 if (!skip_file_pos_adjustment)
2330 packet.SetFilePos (::strlen ("c"));
2331
2332 // For now just support all continue.
2333 const bool has_continue_address = (packet.GetBytesLeft () > 0);
2334 if (has_continue_address)
2335 {
2336 if (log)
2337 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
2338 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2339 }
2340
2341 // Ensure we have a native process.
2342 if (!m_debugged_process_sp)
2343 {
2344 if (log)
2345 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2346 return SendErrorResponse (0x36);
2347 }
2348
2349 // Build the ResumeActionList
2350 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
2351
2352 Error error = m_debugged_process_sp->Resume (actions);
2353 if (error.Fail ())
2354 {
2355 if (log)
2356 {
2357 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s",
2358 __FUNCTION__,
2359 m_debugged_process_sp->GetID (),
2360 error.AsCString ());
2361 }
2362 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2363 }
2364
2365 if (log)
2366 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2367
2368 // No response required from continue.
2369 return PacketResult::Success;
2370}
2371
2372GDBRemoteCommunication::PacketResult
2373GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet)
2374{
2375 if (!IsGdbServer ())
2376 {
2377 // only llgs supports $vCont.
2378 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2379 }
2380
2381 // We handle $vCont messages for c.
2382 // TODO add C, s and S.
2383 StreamString response;
2384 response.Printf("vCont;c;C;s;S");
2385
2386 return SendPacketNoLock(response.GetData(), response.GetSize());
2387}
2388
2389GDBRemoteCommunication::PacketResult
2390GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet)
2391{
2392 if (!IsGdbServer ())
2393 {
2394 // only llgs supports $vCont
2395 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2396 }
2397
2398 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2399 if (log)
2400 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__);
2401
2402 packet.SetFilePos (::strlen ("vCont"));
2403
2404 // Check if this is all continue (no options or ";c").
2405 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0))
2406 {
2407 // Move the packet past the ";c".
2408 if (packet.GetBytesLeft ())
2409 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c"));
2410
2411 const bool skip_file_pos_adjustment = true;
2412 return Handle_c (packet, skip_file_pos_adjustment);
2413 }
2414 else if (::strcmp (packet.Peek (), ";s") == 0)
2415 {
2416 // Move past the ';', then do a simple 's'.
2417 packet.SetFilePos (packet.GetFilePos () + 1);
2418 return Handle_s (packet);
2419 }
2420
2421 // Ensure we have a native process.
2422 if (!m_debugged_process_sp)
2423 {
2424 if (log)
2425 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2426 return SendErrorResponse (0x36);
2427 }
2428
2429 ResumeActionList thread_actions;
2430
2431 while (packet.GetBytesLeft () && *packet.Peek () == ';')
2432 {
2433 // Skip the semi-colon.
2434 packet.GetChar ();
2435
2436 // Build up the thread action.
2437 ResumeAction thread_action;
2438 thread_action.tid = LLDB_INVALID_THREAD_ID;
2439 thread_action.state = eStateInvalid;
2440 thread_action.signal = 0;
2441
2442 const char action = packet.GetChar ();
2443 switch (action)
2444 {
2445 case 'C':
2446 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2447 if (thread_action.signal == 0)
2448 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
2449 // Fall through to next case...
2450
2451 case 'c':
2452 // Continue
2453 thread_action.state = eStateRunning;
2454 break;
2455
2456 case 'S':
2457 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2458 if (thread_action.signal == 0)
2459 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
2460 // Fall through to next case...
2461
2462 case 's':
2463 // Step
2464 thread_action.state = eStateStepping;
2465 break;
2466
2467 default:
2468 return SendIllFormedResponse (packet, "Unsupported vCont action");
2469 break;
2470 }
2471
2472 // Parse out optional :{thread-id} value.
2473 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
2474 {
2475 // Consume the separator.
2476 packet.GetChar ();
2477
2478 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2479 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
2480 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
2481 }
2482
2483 thread_actions.Append (thread_action);
2484 }
2485
2486 // If a default action for all other threads wasn't mentioned
2487 // then we should stop the threads.
2488 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0);
2489
2490 Error error = m_debugged_process_sp->Resume (thread_actions);
2491 if (error.Fail ())
2492 {
2493 if (log)
2494 {
2495 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s",
2496 __FUNCTION__,
2497 m_debugged_process_sp->GetID (),
2498 error.AsCString ());
2499 }
2500 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2501 }
2502
2503 if (log)
2504 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2505
2506 // No response required from vCont.
2507 return PacketResult::Success;
2508}
2509
2510GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00002511GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
2512{
2513 // Send response first before changing m_send_acks to we ack this packet
Greg Clayton3dedae12013-12-06 21:45:27 +00002514 PacketResult packet_result = SendOKResponse ();
Greg Clayton1cb64962011-03-24 04:28:38 +00002515 m_send_acks = false;
Greg Clayton3dedae12013-12-06 21:45:27 +00002516 return packet_result;
Greg Clayton1cb64962011-03-24 04:28:38 +00002517}
Daniel Maleae0f8f572013-08-26 23:57:52 +00002518
Greg Clayton3dedae12013-12-06 21:45:27 +00002519GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002520GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002521{
Greg Claytonfbb76342013-11-20 21:07:01 +00002522 packet.SetFilePos(::strlen("qPlatform_mkdir:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002523 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002524 if (packet.GetChar() == ',')
2525 {
2526 std::string path;
2527 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002528 Error error = FileSystem::MakeDirectory(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002529 if (error.Success())
2530 return SendPacketNoLock ("OK", 2);
2531 else
2532 return SendErrorResponse(error.GetError());
2533 }
2534 return SendErrorResponse(20);
Greg Claytonfbb76342013-11-20 21:07:01 +00002535}
2536
Greg Clayton3dedae12013-12-06 21:45:27 +00002537GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002538GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
2539{
2540 packet.SetFilePos(::strlen("qPlatform_chmod:"));
2541
2542 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002543 if (packet.GetChar() == ',')
2544 {
2545 std::string path;
2546 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002547 Error error = FileSystem::SetFilePermissions(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002548 if (error.Success())
2549 return SendPacketNoLock ("OK", 2);
2550 else
2551 return SendErrorResponse(error.GetError());
2552 }
2553 return SendErrorResponse(19);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002554}
2555
Greg Clayton3dedae12013-12-06 21:45:27 +00002556GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002557GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
2558{
2559 packet.SetFilePos(::strlen("vFile:open:"));
2560 std::string path;
2561 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002562 if (!path.empty())
2563 {
2564 if (packet.GetChar() == ',')
2565 {
2566 uint32_t flags = packet.GetHexMaxU32(false, 0);
2567 if (packet.GetChar() == ',')
2568 {
2569 mode_t mode = packet.GetHexMaxU32(false, 0600);
2570 Error error;
2571 int fd = ::open (path.c_str(), flags, mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002572 const int save_errno = fd == -1 ? errno : 0;
2573 StreamString response;
2574 response.PutChar('F');
2575 response.Printf("%i", fd);
2576 if (save_errno)
2577 response.Printf(",%i", save_errno);
2578 return SendPacketNoLock(response.GetData(), response.GetSize());
2579 }
2580 }
2581 }
2582 return SendErrorResponse(18);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002583}
2584
Greg Clayton3dedae12013-12-06 21:45:27 +00002585GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002586GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
2587{
2588 packet.SetFilePos(::strlen("vFile:close:"));
2589 int fd = packet.GetS32(-1);
2590 Error error;
2591 int err = -1;
2592 int save_errno = 0;
2593 if (fd >= 0)
2594 {
2595 err = close(fd);
2596 save_errno = err == -1 ? errno : 0;
2597 }
2598 else
2599 {
2600 save_errno = EINVAL;
2601 }
2602 StreamString response;
2603 response.PutChar('F');
2604 response.Printf("%i", err);
2605 if (save_errno)
2606 response.Printf(",%i", save_errno);
Greg Clayton2b98c562013-11-22 18:53:12 +00002607 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002608}
2609
Greg Clayton3dedae12013-12-06 21:45:27 +00002610GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002611GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
2612{
Virgile Belloae12a362013-08-27 16:21:49 +00002613#ifdef _WIN32
2614 // Not implemented on Windows
Greg Clayton2b98c562013-11-22 18:53:12 +00002615 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002616#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002617 StreamGDBRemote response;
2618 packet.SetFilePos(::strlen("vFile:pread:"));
2619 int fd = packet.GetS32(-1);
Greg Clayton2b98c562013-11-22 18:53:12 +00002620 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002621 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002622 uint64_t count = packet.GetU64(UINT64_MAX);
2623 if (packet.GetChar() == ',')
2624 {
2625 uint64_t offset = packet.GetU64(UINT32_MAX);
2626 if (count == UINT64_MAX)
2627 {
2628 response.Printf("F-1:%i", EINVAL);
2629 return SendPacketNoLock(response.GetData(), response.GetSize());
2630 }
2631
2632 std::string buffer(count, 0);
2633 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
2634 const int save_errno = bytes_read == -1 ? errno : 0;
2635 response.PutChar('F');
2636 response.Printf("%zi", bytes_read);
2637 if (save_errno)
2638 response.Printf(",%i", save_errno);
2639 else
2640 {
2641 response.PutChar(';');
2642 response.PutEscapedBytes(&buffer[0], bytes_read);
2643 }
2644 return SendPacketNoLock(response.GetData(), response.GetSize());
2645 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002646 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002647 return SendErrorResponse(21);
2648
Virgile Belloae12a362013-08-27 16:21:49 +00002649#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002650}
2651
Greg Clayton3dedae12013-12-06 21:45:27 +00002652GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002653GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
2654{
Virgile Belloae12a362013-08-27 16:21:49 +00002655#ifdef _WIN32
Greg Clayton2b98c562013-11-22 18:53:12 +00002656 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002657#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002658 packet.SetFilePos(::strlen("vFile:pwrite:"));
2659
2660 StreamGDBRemote response;
2661 response.PutChar('F');
2662
2663 int fd = packet.GetU32(UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002664 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002665 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002666 off_t offset = packet.GetU64(UINT32_MAX);
2667 if (packet.GetChar() == ',')
2668 {
2669 std::string buffer;
2670 if (packet.GetEscapedBinaryData(buffer))
2671 {
2672 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
2673 const int save_errno = bytes_written == -1 ? errno : 0;
2674 response.Printf("%zi", bytes_written);
2675 if (save_errno)
2676 response.Printf(",%i", save_errno);
2677 }
2678 else
2679 {
2680 response.Printf ("-1,%i", EINVAL);
2681 }
2682 return SendPacketNoLock(response.GetData(), response.GetSize());
2683 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002684 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002685 return SendErrorResponse(27);
Virgile Belloae12a362013-08-27 16:21:49 +00002686#endif
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_Size (StringExtractorGDBRemote &packet)
2691{
2692 packet.SetFilePos(::strlen("vFile:size:"));
2693 std::string path;
2694 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002695 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002696 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002697 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002698 StreamString response;
2699 response.PutChar('F');
2700 response.PutHex64(retcode);
2701 if (retcode == UINT64_MAX)
2702 {
2703 response.PutChar(',');
2704 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
2705 }
2706 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002707 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002708 return SendErrorResponse(22);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002709}
2710
Greg Clayton3dedae12013-12-06 21:45:27 +00002711GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002712GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
2713{
2714 packet.SetFilePos(::strlen("vFile:mode:"));
2715 std::string path;
2716 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002717 if (!path.empty())
2718 {
2719 Error error;
2720 const uint32_t mode = File::GetPermissions(path.c_str(), error);
2721 StreamString response;
2722 response.Printf("F%u", mode);
2723 if (mode == 0 || error.Fail())
2724 response.Printf(",%i", (int)error.GetError());
2725 return SendPacketNoLock(response.GetData(), response.GetSize());
2726 }
2727 return SendErrorResponse(23);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002728}
2729
Greg Clayton3dedae12013-12-06 21:45:27 +00002730GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002731GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
2732{
2733 packet.SetFilePos(::strlen("vFile:exists:"));
2734 std::string path;
2735 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002736 if (!path.empty())
2737 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002738 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002739 StreamString response;
2740 response.PutChar('F');
2741 response.PutChar(',');
2742 if (retcode)
2743 response.PutChar('1');
2744 else
2745 response.PutChar('0');
2746 return SendPacketNoLock(response.GetData(), response.GetSize());
2747 }
2748 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002749}
2750
Greg Clayton3dedae12013-12-06 21:45:27 +00002751GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002752GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002753{
Greg Claytonfbb76342013-11-20 21:07:01 +00002754 packet.SetFilePos(::strlen("vFile:symlink:"));
2755 std::string dst, src;
2756 packet.GetHexByteStringTerminatedBy(dst, ',');
2757 packet.GetChar(); // Skip ',' char
2758 packet.GetHexByteString(src);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002759 Error error = FileSystem::Symlink(src.c_str(), dst.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002760 StreamString response;
2761 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002762 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002763}
2764
Greg Clayton3dedae12013-12-06 21:45:27 +00002765GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002766GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
2767{
2768 packet.SetFilePos(::strlen("vFile:unlink:"));
2769 std::string path;
2770 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002771 Error error = FileSystem::Unlink(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002772 StreamString response;
2773 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002774 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002775}
2776
Greg Clayton3dedae12013-12-06 21:45:27 +00002777GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002778GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
2779{
2780 packet.SetFilePos(::strlen("qPlatform_shell:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002781 std::string path;
2782 std::string working_dir;
2783 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002784 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002785 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002786 if (packet.GetChar() == ',')
2787 {
2788 // FIXME: add timeout to qPlatform_shell packet
2789 // uint32_t timeout = packet.GetHexMaxU32(false, 32);
2790 uint32_t timeout = 10;
2791 if (packet.GetChar() == ',')
2792 packet.GetHexByteString(working_dir);
2793 int status, signo;
2794 std::string output;
2795 Error err = Host::RunShellCommand(path.c_str(),
2796 working_dir.empty() ? NULL : working_dir.c_str(),
2797 &status, &signo, &output, timeout);
2798 StreamGDBRemote response;
2799 if (err.Fail())
2800 {
2801 response.PutCString("F,");
2802 response.PutHex32(UINT32_MAX);
2803 }
2804 else
2805 {
2806 response.PutCString("F,");
2807 response.PutHex32(status);
2808 response.PutChar(',');
2809 response.PutHex32(signo);
2810 response.PutChar(',');
2811 response.PutEscapedBytes(output.c_str(), output.size());
2812 }
2813 return SendPacketNoLock(response.GetData(), response.GetSize());
2814 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002815 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002816 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002817}
2818
Todd Fialaaf245d12014-06-30 21:05:18 +00002819void
2820GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid)
2821{
2822 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code");
2823
2824 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2825 if (log)
2826 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
2827
2828 m_current_tid = tid;
2829 if (m_debugged_process_sp)
2830 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
2831}
2832
2833void
2834GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid)
2835{
2836 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code");
2837
2838 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2839 if (log)
2840 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
2841
2842 m_continue_tid = tid;
2843}
2844
2845GDBRemoteCommunication::PacketResult
2846GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet)
2847{
2848 // Handle the $? gdbremote command.
2849 if (!IsGdbServer ())
2850 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented");
2851
2852 // If no process, indicate error
2853 if (!m_debugged_process_sp)
2854 return SendErrorResponse (02);
2855
2856 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2857}
2858
2859GDBRemoteCommunication::PacketResult
2860GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
2861{
2862 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2863
2864 switch (process_state)
2865 {
2866 case eStateAttaching:
2867 case eStateLaunching:
2868 case eStateRunning:
2869 case eStateStepping:
2870 case eStateDetached:
2871 // NOTE: gdb protocol doc looks like it should return $OK
2872 // when everything is running (i.e. no stopped result).
2873 return PacketResult::Success; // Ignore
2874
2875 case eStateSuspended:
2876 case eStateStopped:
2877 case eStateCrashed:
2878 {
2879 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
2880 // Make sure we set the current thread so g and p packets return
2881 // the data the gdb will expect.
2882 SetCurrentThreadID (tid);
2883 return SendStopReplyPacketForThread (tid);
2884 }
2885
2886 case eStateInvalid:
2887 case eStateUnloaded:
2888 case eStateExited:
2889 if (flush_on_exit)
2890 FlushInferiorOutput ();
2891 return SendWResponse(m_debugged_process_sp.get());
2892
2893 default:
2894 if (log)
2895 {
2896 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s",
2897 __FUNCTION__,
2898 m_debugged_process_sp->GetID (),
2899 StateAsCString (process_state));
2900 }
2901 break;
2902 }
2903
2904 return SendErrorResponse (0);
2905}
2906
Greg Clayton3dedae12013-12-06 21:45:27 +00002907GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002908GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
2909{
Greg Clayton2b98c562013-11-22 18:53:12 +00002910 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002911}
2912
Greg Clayton3dedae12013-12-06 21:45:27 +00002913GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002914GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
2915{
Greg Clayton2b98c562013-11-22 18:53:12 +00002916 packet.SetFilePos(::strlen("vFile:MD5:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002917 std::string path;
2918 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002919 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002920 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002921 uint64_t a,b;
2922 StreamGDBRemote response;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002923 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false)
Greg Clayton2b98c562013-11-22 18:53:12 +00002924 {
2925 response.PutCString("F,");
2926 response.PutCString("x");
2927 }
2928 else
2929 {
2930 response.PutCString("F,");
2931 response.PutHex64(a);
2932 response.PutHex64(b);
2933 }
2934 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002935 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002936 return SendErrorResponse(25);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002937}
Greg Clayton2b98c562013-11-22 18:53:12 +00002938
Todd Fialaaf245d12014-06-30 21:05:18 +00002939GDBRemoteCommunication::PacketResult
2940GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
2941{
2942 // Ensure we're llgs.
2943 if (!IsGdbServer())
2944 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented");
2945
2946 // Fail if we don't have a current process.
2947 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2948 return SendErrorResponse (68);
2949
2950 // Ensure we have a thread.
2951 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
2952 if (!thread_sp)
2953 return SendErrorResponse (69);
2954
2955 // Get the register context for the first thread.
2956 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2957 if (!reg_context_sp)
2958 return SendErrorResponse (69);
2959
2960 // Parse out the register number from the request.
2961 packet.SetFilePos (strlen("qRegisterInfo"));
2962 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2963 if (reg_index == std::numeric_limits<uint32_t>::max ())
2964 return SendErrorResponse (69);
2965
2966 // Return the end of registers response if we've iterated one past the end of the register set.
2967 if (reg_index >= reg_context_sp->GetRegisterCount ())
2968 return SendErrorResponse (69);
2969
2970 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2971 if (!reg_info)
2972 return SendErrorResponse (69);
2973
2974 // Build the reginfos response.
2975 StreamGDBRemote response;
2976
2977 response.PutCString ("name:");
2978 response.PutCString (reg_info->name);
2979 response.PutChar (';');
2980
2981 if (reg_info->alt_name && reg_info->alt_name[0])
2982 {
2983 response.PutCString ("alt-name:");
2984 response.PutCString (reg_info->alt_name);
2985 response.PutChar (';');
2986 }
2987
2988 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
2989
2990 switch (reg_info->encoding)
2991 {
2992 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
2993 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
2994 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
2995 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
2996 default: break;
2997 }
2998
2999 switch (reg_info->format)
3000 {
3001 case eFormatBinary: response.PutCString ("format:binary;"); break;
3002 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
3003 case eFormatHex: response.PutCString ("format:hex;"); break;
3004 case eFormatFloat: response.PutCString ("format:float;"); break;
3005 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
3006 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
3007 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
3008 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
3009 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
3010 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
3011 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
3012 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
3013 default: break;
3014 };
3015
3016 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
3017 if (register_set_name)
3018 {
3019 response.PutCString ("set:");
3020 response.PutCString (register_set_name);
3021 response.PutChar (';');
3022 }
3023
3024 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
3025 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
3026
3027 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
3028 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3029
3030 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
3031 {
3032 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
3033 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
3034 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
3035 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
3036 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
3037 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
3038 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
3039 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
3040 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
3041 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
3042 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
3043 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
3044 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
3045 default: break;
3046 }
3047
3048 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
3049 {
3050 response.PutCString ("container-regs:");
3051 int i = 0;
3052 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3053 {
3054 if (i > 0)
3055 response.PutChar (',');
3056 response.Printf ("%" PRIx32, *reg_num);
3057 }
3058 response.PutChar (';');
3059 }
3060
3061 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
3062 {
3063 response.PutCString ("invalidate-regs:");
3064 int i = 0;
3065 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3066 {
3067 if (i > 0)
3068 response.PutChar (',');
3069 response.Printf ("%" PRIx32, *reg_num);
3070 }
3071 response.PutChar (';');
3072 }
3073
3074 return SendPacketNoLock(response.GetData(), response.GetSize());
3075}
3076
3077GDBRemoteCommunication::PacketResult
3078GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
3079{
3080 // Ensure we're llgs.
3081 if (!IsGdbServer())
3082 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented");
3083
Todd Fiala24189d42014-07-14 06:24:44 +00003084 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3085
Todd Fialaaf245d12014-06-30 21:05:18 +00003086 // Fail if we don't have a current process.
3087 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
Todd Fiala24189d42014-07-14 06:24:44 +00003088 {
3089 if (log)
3090 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
3091 return SendOKResponse ();
3092 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003093
3094 StreamGDBRemote response;
3095 response.PutChar ('m');
3096
Todd Fiala24189d42014-07-14 06:24:44 +00003097 if (log)
3098 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__);
3099
Todd Fialaaf245d12014-06-30 21:05:18 +00003100 NativeThreadProtocolSP thread_sp;
3101 uint32_t thread_index;
3102 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
3103 thread_sp;
3104 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
3105 {
Todd Fiala24189d42014-07-14 06:24:44 +00003106 if (log)
3107 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 +00003108 if (thread_index > 0)
3109 response.PutChar(',');
3110 response.Printf ("%" PRIx64, thread_sp->GetID ());
3111 }
3112
Todd Fiala24189d42014-07-14 06:24:44 +00003113 if (log)
3114 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__);
3115
Todd Fialaaf245d12014-06-30 21:05:18 +00003116 return SendPacketNoLock(response.GetData(), response.GetSize());
3117}
3118
3119GDBRemoteCommunication::PacketResult
3120GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
3121{
3122 // Ensure we're llgs.
3123 if (!IsGdbServer())
3124 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented");
3125
3126 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
3127 return SendPacketNoLock ("l", 1);
3128}
3129
3130GDBRemoteCommunication::PacketResult
3131GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet)
3132{
3133 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3134
3135 // Ensure we're llgs.
3136 if (!IsGdbServer())
3137 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented");
3138
3139 // Parse out the register number from the request.
3140 packet.SetFilePos (strlen("p"));
3141 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3142 if (reg_index == std::numeric_limits<uint32_t>::max ())
3143 {
3144 if (log)
3145 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3146 return SendErrorResponse (0x15);
3147 }
3148
3149 // Get the thread to use.
3150 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3151 if (!thread_sp)
3152 {
3153 if (log)
3154 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__);
3155 return SendErrorResponse (0x15);
3156 }
3157
3158 // Get the thread's register context.
3159 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3160 if (!reg_context_sp)
3161 {
3162 if (log)
3163 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 ());
3164 return SendErrorResponse (0x15);
3165 }
3166
3167 // Return the end of registers response if we've iterated one past the end of the register set.
3168 if (reg_index >= reg_context_sp->GetRegisterCount ())
3169 {
3170 if (log)
3171 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3172 return SendErrorResponse (0x15);
3173 }
3174
3175 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3176 if (!reg_info)
3177 {
3178 if (log)
3179 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3180 return SendErrorResponse (0x15);
3181 }
3182
3183 // Build the reginfos response.
3184 StreamGDBRemote response;
3185
3186 // Retrieve the value
3187 RegisterValue reg_value;
3188 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
3189 if (error.Fail ())
3190 {
3191 if (log)
3192 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3193 return SendErrorResponse (0x15);
3194 }
3195
3196 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
3197 if (!data)
3198 {
3199 if (log)
3200 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
3201 return SendErrorResponse (0x15);
3202 }
3203
3204 // FIXME flip as needed to get data in big/little endian format for this host.
3205 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
3206 response.PutHex8 (data[i]);
3207
3208 return SendPacketNoLock (response.GetData (), response.GetSize ());
3209}
3210
3211GDBRemoteCommunication::PacketResult
3212GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet)
3213{
3214 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3215
3216 // Ensure we're llgs.
3217 if (!IsGdbServer())
3218 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented");
3219
3220 // Ensure there is more content.
3221 if (packet.GetBytesLeft () < 1)
3222 return SendIllFormedResponse (packet, "Empty P packet");
3223
3224 // Parse out the register number from the request.
3225 packet.SetFilePos (strlen("P"));
3226 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3227 if (reg_index == std::numeric_limits<uint32_t>::max ())
3228 {
3229 if (log)
3230 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3231 return SendErrorResponse (0x29);
3232 }
3233
3234 // Note debugserver would send an E30 here.
3235 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
3236 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
3237
3238 // Get process architecture.
3239 ArchSpec process_arch;
3240 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
3241 {
3242 if (log)
3243 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__);
3244 return SendErrorResponse (0x49);
3245 }
3246
3247 // Parse out the value.
3248 const uint64_t raw_value = packet.GetHexMaxU64 (process_arch.GetByteOrder () == lldb::eByteOrderLittle, std::numeric_limits<uint64_t>::max ());
3249
3250 // Get the thread to use.
3251 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3252 if (!thread_sp)
3253 {
3254 if (log)
3255 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__);
3256 return SendErrorResponse (0x28);
3257 }
3258
3259 // Get the thread's register context.
3260 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3261 if (!reg_context_sp)
3262 {
3263 if (log)
3264 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 ());
3265 return SendErrorResponse (0x15);
3266 }
3267
3268 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3269 if (!reg_info)
3270 {
3271 if (log)
3272 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3273 return SendErrorResponse (0x48);
3274 }
3275
3276 // Return the end of registers response if we've iterated one past the end of the register set.
3277 if (reg_index >= reg_context_sp->GetRegisterCount ())
3278 {
3279 if (log)
3280 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3281 return SendErrorResponse (0x47);
3282 }
3283
3284
3285 // Build the reginfos response.
3286 StreamGDBRemote response;
3287
3288 // FIXME Could be suffixed with a thread: parameter.
3289 // That thread then needs to be fed back into the reg context retrieval above.
3290 Error error = reg_context_sp->WriteRegisterFromUnsigned (reg_info, raw_value);
3291 if (error.Fail ())
3292 {
3293 if (log)
3294 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3295 return SendErrorResponse (0x32);
3296 }
3297
3298 return SendOKResponse();
3299}
3300
3301GDBRemoteCommunicationServer::PacketResult
3302GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet)
3303{
3304 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3305
3306 // Ensure we're llgs.
3307 if (!IsGdbServer())
3308 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented");
3309
3310 // Fail if we don't have a current process.
3311 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3312 {
3313 if (log)
3314 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3315 return SendErrorResponse (0x15);
3316 }
3317
3318 // Parse out which variant of $H is requested.
3319 packet.SetFilePos (strlen("H"));
3320 if (packet.GetBytesLeft () < 1)
3321 {
3322 if (log)
3323 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__);
3324 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
3325 }
3326
3327 const char h_variant = packet.GetChar ();
3328 switch (h_variant)
3329 {
3330 case 'g':
3331 break;
3332
3333 case 'c':
3334 break;
3335
3336 default:
3337 if (log)
3338 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
3339 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3340 }
3341
3342 // Parse out the thread number.
3343 // FIXME return a parse success/fail value. All values are valid here.
3344 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
3345
3346 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
3347 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
3348 {
3349 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
3350 if (!thread_sp)
3351 {
3352 if (log)
3353 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
3354 return SendErrorResponse (0x15);
3355 }
3356 }
3357
3358 // Now switch the given thread type.
3359 switch (h_variant)
3360 {
3361 case 'g':
3362 SetCurrentThreadID (tid);
3363 break;
3364
3365 case 'c':
3366 SetContinueThreadID (tid);
3367 break;
3368
3369 default:
3370 assert (false && "unsupported $H variant - shouldn't get here");
3371 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3372 }
3373
3374 return SendOKResponse();
3375}
3376
3377GDBRemoteCommunicationServer::PacketResult
3378GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet)
3379{
3380 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3381
3382 // Ensure we're llgs.
3383 if (!IsGdbServer())
3384 {
3385 // Only supported on llgs
3386 return SendUnimplementedResponse ("");
3387 }
3388
3389 // Fail if we don't have a current process.
3390 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3391 {
3392 if (log)
3393 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3394 return SendErrorResponse (0x15);
3395 }
3396
3397 // Build the ResumeActionList - stop everything.
3398 lldb_private::ResumeActionList actions (StateType::eStateStopped, 0);
3399
3400 Error error = m_debugged_process_sp->Resume (actions);
3401 if (error.Fail ())
3402 {
3403 if (log)
3404 {
3405 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s",
3406 __FUNCTION__,
3407 m_debugged_process_sp->GetID (),
3408 error.AsCString ());
3409 }
3410 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
3411 }
3412
3413 if (log)
3414 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
3415
3416 // No response required from stop all.
3417 return PacketResult::Success;
3418}
3419
3420GDBRemoteCommunicationServer::PacketResult
3421GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet)
3422{
3423 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3424
3425 // Ensure we're llgs.
3426 if (!IsGdbServer())
3427 {
3428 // Only supported on llgs
3429 return SendUnimplementedResponse ("");
3430 }
3431
3432 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3433 {
3434 if (log)
3435 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3436 return SendErrorResponse (0x15);
3437 }
3438
3439 // Parse out the memory address.
3440 packet.SetFilePos (strlen("m"));
3441 if (packet.GetBytesLeft() < 1)
3442 return SendIllFormedResponse(packet, "Too short m packet");
3443
3444 // Read the address. Punting on validation.
3445 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3446 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3447
3448 // Validate comma.
3449 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3450 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
3451
3452 // Get # bytes to read.
3453 if (packet.GetBytesLeft() < 1)
3454 return SendIllFormedResponse(packet, "Length missing in m packet");
3455
3456 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3457 if (byte_count == 0)
3458 {
3459 if (log)
3460 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__);
3461 return PacketResult::Success;
3462 }
3463
3464 // Allocate the response buffer.
3465 std::string buf(byte_count, '\0');
3466 if (buf.empty())
3467 return SendErrorResponse (0x78);
3468
3469
3470 // Retrieve the process memory.
3471 lldb::addr_t bytes_read = 0;
3472 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
3473 if (error.Fail ())
3474 {
3475 if (log)
3476 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
3477 return SendErrorResponse (0x08);
3478 }
3479
3480 if (bytes_read == 0)
3481 {
3482 if (log)
3483 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);
3484 return SendErrorResponse (0x08);
3485 }
3486
3487 StreamGDBRemote response;
3488 for (lldb::addr_t i = 0; i < bytes_read; ++i)
3489 response.PutHex8(buf[i]);
3490
3491 return SendPacketNoLock(response.GetData(), response.GetSize());
3492}
3493
3494GDBRemoteCommunication::PacketResult
3495GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet)
3496{
3497 packet.SetFilePos(::strlen ("QSetDetachOnError:"));
3498 if (packet.GetU32(0))
3499 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError);
3500 else
3501 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError);
3502 return SendOKResponse ();
3503}
3504
3505GDBRemoteCommunicationServer::PacketResult
3506GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet)
3507{
3508 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3509
3510 // Ensure we're llgs.
3511 if (!IsGdbServer())
3512 {
3513 // Only supported on llgs
3514 return SendUnimplementedResponse ("");
3515 }
3516
3517 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3518 {
3519 if (log)
3520 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3521 return SendErrorResponse (0x15);
3522 }
3523
3524 // Parse out the memory address.
3525 packet.SetFilePos (strlen("M"));
3526 if (packet.GetBytesLeft() < 1)
3527 return SendIllFormedResponse(packet, "Too short M packet");
3528
3529 // Read the address. Punting on validation.
3530 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3531 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
3532
3533 // Validate comma.
3534 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3535 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
3536
3537 // Get # bytes to read.
3538 if (packet.GetBytesLeft() < 1)
3539 return SendIllFormedResponse(packet, "Length missing in M packet");
3540
3541 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3542 if (byte_count == 0)
3543 {
3544 if (log)
3545 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__);
3546 return PacketResult::Success;
3547 }
3548
3549 // Validate colon.
3550 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
3551 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
3552
3553 // Allocate the conversion buffer.
3554 std::vector<uint8_t> buf(byte_count, 0);
3555 if (buf.empty())
3556 return SendErrorResponse (0x78);
3557
3558 // Convert the hex memory write contents to bytes.
3559 StreamGDBRemote response;
3560 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
3561 if (convert_count != byte_count)
3562 {
3563 if (log)
3564 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);
3565 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
3566 }
3567
3568 // Write the process memory.
3569 lldb::addr_t bytes_written = 0;
3570 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
3571 if (error.Fail ())
3572 {
3573 if (log)
3574 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
3575 return SendErrorResponse (0x09);
3576 }
3577
3578 if (bytes_written == 0)
3579 {
3580 if (log)
3581 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);
3582 return SendErrorResponse (0x09);
3583 }
3584
3585 return SendOKResponse ();
3586}
3587
3588GDBRemoteCommunicationServer::PacketResult
3589GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
3590{
3591 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3592
3593 // We don't support if we're not llgs.
3594 if (!IsGdbServer())
3595 return SendUnimplementedResponse ("");
3596
3597 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
3598 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
3599 // client only asks this when a process is being debugged.
3600
3601 // Ensure we have a process running; otherwise, we can't figure this out
3602 // since we won't have a NativeProcessProtocol.
3603 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3604 {
3605 if (log)
3606 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3607 return SendErrorResponse (0x15);
3608 }
3609
3610 // Test if we can get any region back when asking for the region around NULL.
3611 MemoryRegionInfo region_info;
3612 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
3613 if (error.Fail ())
3614 {
3615 // We don't support memory region info collection for this NativeProcessProtocol.
3616 return SendUnimplementedResponse ("");
3617 }
3618
3619 return SendOKResponse();
3620}
3621
3622GDBRemoteCommunicationServer::PacketResult
3623GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
3624{
3625 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3626
3627 // We don't support if we're not llgs.
3628 if (!IsGdbServer())
3629 return SendUnimplementedResponse ("");
3630
3631 // Ensure we have a process.
3632 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3633 {
3634 if (log)
3635 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3636 return SendErrorResponse (0x15);
3637 }
3638
3639 // Parse out the memory address.
3640 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
3641 if (packet.GetBytesLeft() < 1)
3642 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
3643
3644 // Read the address. Punting on validation.
3645 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3646
3647 StreamGDBRemote response;
3648
3649 // Get the memory region info for the target address.
3650 MemoryRegionInfo region_info;
3651 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
3652 if (error.Fail ())
3653 {
3654 // Return the error message.
3655
3656 response.PutCString ("error:");
3657 response.PutCStringAsRawHex8 (error.AsCString ());
3658 response.PutChar (';');
3659 }
3660 else
3661 {
3662 // Range start and size.
3663 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
3664
3665 // Permissions.
3666 if (region_info.GetReadable () ||
3667 region_info.GetWritable () ||
3668 region_info.GetExecutable ())
3669 {
3670 // Write permissions info.
3671 response.PutCString ("permissions:");
3672
3673 if (region_info.GetReadable ())
3674 response.PutChar ('r');
3675 if (region_info.GetWritable ())
3676 response.PutChar('w');
3677 if (region_info.GetExecutable())
3678 response.PutChar ('x');
3679
3680 response.PutChar (';');
3681 }
3682 }
3683
3684 return SendPacketNoLock(response.GetData(), response.GetSize());
3685}
3686
3687GDBRemoteCommunicationServer::PacketResult
3688GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet)
3689{
3690 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3691
3692 // We don't support if we're not llgs.
3693 if (!IsGdbServer())
3694 return SendUnimplementedResponse ("");
3695
3696 // Ensure we have a process.
3697 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3698 {
3699 if (log)
3700 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3701 return SendErrorResponse (0x15);
3702 }
3703
3704 // Parse out software or hardware breakpoint requested.
3705 packet.SetFilePos (strlen("Z"));
3706 if (packet.GetBytesLeft() < 1)
3707 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
3708
3709 bool want_breakpoint = true;
3710 bool want_hardware = false;
3711
3712 const char breakpoint_type_char = packet.GetChar ();
3713 switch (breakpoint_type_char)
3714 {
3715 case '0': want_hardware = false; want_breakpoint = true; break;
3716 case '1': want_hardware = true; want_breakpoint = true; break;
3717 case '2': want_breakpoint = false; break;
3718 case '3': want_breakpoint = false; break;
3719 default:
3720 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
3721
3722 }
3723
3724 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3725 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type");
3726
3727 // FIXME implement watchpoint support.
3728 if (!want_breakpoint)
3729 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3730
3731 // Parse out the breakpoint address.
3732 if (packet.GetBytesLeft() < 1)
3733 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
3734 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3735
3736 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3737 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
3738
3739 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3740 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3741 if (kind == std::numeric_limits<uint32_t>::max ())
3742 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument");
3743
3744 if (want_breakpoint)
3745 {
3746 // Try to set the breakpoint.
3747 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware);
3748 if (error.Success ())
3749 return SendOKResponse ();
3750 else
3751 {
3752 if (log)
3753 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3754 return SendErrorResponse (0x09);
3755 }
3756 }
3757
3758 // FIXME fix up after watchpoints are handled.
3759 return SendUnimplementedResponse ("");
3760}
3761
3762GDBRemoteCommunicationServer::PacketResult
3763GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet)
3764{
3765 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3766
3767 // We don't support if we're not llgs.
3768 if (!IsGdbServer())
3769 return SendUnimplementedResponse ("");
3770
3771 // Ensure we have a process.
3772 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3773 {
3774 if (log)
3775 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3776 return SendErrorResponse (0x15);
3777 }
3778
3779 // Parse out software or hardware breakpoint requested.
3780 packet.SetFilePos (strlen("Z"));
3781 if (packet.GetBytesLeft() < 1)
3782 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
3783
3784 bool want_breakpoint = true;
3785
3786 const char breakpoint_type_char = packet.GetChar ();
3787 switch (breakpoint_type_char)
3788 {
3789 case '0': want_breakpoint = true; break;
3790 case '1': want_breakpoint = true; break;
3791 case '2': want_breakpoint = false; break;
3792 case '3': want_breakpoint = false; break;
3793 default:
3794 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
3795
3796 }
3797
3798 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3799 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type");
3800
3801 // FIXME implement watchpoint support.
3802 if (!want_breakpoint)
3803 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3804
3805 // Parse out the breakpoint address.
3806 if (packet.GetBytesLeft() < 1)
3807 return SendIllFormedResponse(packet, "Too short z packet, missing address");
3808 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3809
3810 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3811 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
3812
3813 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3814 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3815 if (kind == std::numeric_limits<uint32_t>::max ())
3816 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument");
3817
3818 if (want_breakpoint)
3819 {
3820 // Try to set the breakpoint.
3821 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr);
3822 if (error.Success ())
3823 return SendOKResponse ();
3824 else
3825 {
3826 if (log)
3827 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3828 return SendErrorResponse (0x09);
3829 }
3830 }
3831
3832 // FIXME fix up after watchpoints are handled.
3833 return SendUnimplementedResponse ("");
3834}
3835
3836GDBRemoteCommunicationServer::PacketResult
3837GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet)
3838{
3839 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
3840
3841 // We don't support if we're not llgs.
3842 if (!IsGdbServer())
3843 return SendUnimplementedResponse ("");
3844
3845 // Ensure we have a process.
3846 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3847 {
3848 if (log)
3849 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3850 return SendErrorResponse (0x32);
3851 }
3852
3853 // We first try to use a continue thread id. If any one or any all set, use the current thread.
3854 // Bail out if we don't have a thread id.
3855 lldb::tid_t tid = GetContinueThreadID ();
3856 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3857 tid = GetCurrentThreadID ();
3858 if (tid == LLDB_INVALID_THREAD_ID)
3859 return SendErrorResponse (0x33);
3860
3861 // Double check that we have such a thread.
3862 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3863 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
3864 if (!thread_sp || thread_sp->GetID () != tid)
3865 return SendErrorResponse (0x33);
3866
3867 // Create the step action for the given thread.
3868 lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
3869
3870 // Setup the actions list.
3871 lldb_private::ResumeActionList actions;
3872 actions.Append (action);
3873
3874 // All other threads stop while we're single stepping a thread.
3875 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3876 Error error = m_debugged_process_sp->Resume (actions);
3877 if (error.Fail ())
3878 {
3879 if (log)
3880 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
3881 return SendErrorResponse(0x49);
3882 }
3883
3884 // No response here - the stop or exit will come from the resulting action.
3885 return PacketResult::Success;
3886}
3887
3888GDBRemoteCommunicationServer::PacketResult
3889GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet)
3890{
3891 StreamGDBRemote response;
3892
3893 // Features common to lldb-platform and llgs.
3894 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less
3895 response.Printf ("PacketSize=%x", max_packet_size);
3896
3897 response.PutCString (";QStartNoAckMode+");
3898 response.PutCString (";QThreadSuffixSupported+");
3899 response.PutCString (";QListThreadsInStopReply+");
3900#if defined(__linux__)
3901 response.PutCString (";qXfer:auxv:read+");
3902#endif
3903
3904 return SendPacketNoLock(response.GetData(), response.GetSize());
3905}
3906
3907GDBRemoteCommunicationServer::PacketResult
3908GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet)
3909{
3910 m_thread_suffix_supported = true;
3911 return SendOKResponse();
3912}
3913
3914GDBRemoteCommunicationServer::PacketResult
3915GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet)
3916{
3917 m_list_threads_in_stop_reply = true;
3918 return SendOKResponse();
3919}
3920
3921GDBRemoteCommunicationServer::PacketResult
3922GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
3923{
3924 // We don't support if we're not llgs.
3925 if (!IsGdbServer())
3926 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
3927
3928 // *BSD impls should be able to do this too.
3929#if defined(__linux__)
3930 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3931
3932 // Parse out the offset.
3933 packet.SetFilePos (strlen("qXfer:auxv:read::"));
3934 if (packet.GetBytesLeft () < 1)
3935 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3936
3937 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3938 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
3939 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3940
3941 // Parse out comma.
3942 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
3943 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
3944
3945 // Parse out the length.
3946 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3947 if (auxv_length == std::numeric_limits<uint64_t>::max ())
3948 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
3949
3950 // Grab the auxv data if we need it.
3951 if (!m_active_auxv_buffer_sp)
3952 {
3953 // Make sure we have a valid process.
3954 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3955 {
3956 if (log)
3957 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3958 return SendErrorResponse (0x10);
3959 }
3960
3961 // Grab the auxv data.
3962 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
3963 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
3964 {
3965 // Hmm, no auxv data, call that an error.
3966 if (log)
3967 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__);
3968 m_active_auxv_buffer_sp.reset ();
3969 return SendErrorResponse (0x11);
3970 }
3971 }
3972
3973 // FIXME find out if/how I lock the stream here.
3974
3975 StreamGDBRemote response;
3976 bool done_with_buffer = false;
3977
3978 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
3979 {
3980 // We have nothing left to send. Mark the buffer as complete.
3981 response.PutChar ('l');
3982 done_with_buffer = true;
3983 }
3984 else
3985 {
3986 // Figure out how many bytes are available starting at the given offset.
3987 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
3988
3989 // Figure out how many bytes we're going to read.
3990 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
3991
3992 // Mark the response type according to whether we're reading the remainder of the auxv data.
3993 if (bytes_to_read >= bytes_remaining)
3994 {
3995 // There will be nothing left to read after this
3996 response.PutChar ('l');
3997 done_with_buffer = true;
3998 }
3999 else
4000 {
4001 // There will still be bytes to read after this request.
4002 response.PutChar ('m');
4003 }
4004
4005 // Now write the data in encoded binary form.
4006 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
4007 }
4008
4009 if (done_with_buffer)
4010 m_active_auxv_buffer_sp.reset ();
4011
4012 return SendPacketNoLock(response.GetData(), response.GetSize());
4013#else
4014 return SendUnimplementedResponse ("not implemented on this platform");
4015#endif
4016}
4017
4018GDBRemoteCommunicationServer::PacketResult
4019GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
4020{
4021 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4022
4023 // We don't support if we're not llgs.
4024 if (!IsGdbServer())
4025 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4026
4027 // Move past packet name.
4028 packet.SetFilePos (strlen ("QSaveRegisterState"));
4029
4030 // Get the thread to use.
4031 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4032 if (!thread_sp)
4033 {
4034 if (m_thread_suffix_supported)
4035 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
4036 else
4037 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4038 }
4039
4040 // Grab the register context for the thread.
4041 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4042 if (!reg_context_sp)
4043 {
4044 if (log)
4045 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 ());
4046 return SendErrorResponse (0x15);
4047 }
4048
4049 // Save registers to a buffer.
4050 DataBufferSP register_data_sp;
4051 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
4052 if (error.Fail ())
4053 {
4054 if (log)
4055 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4056 return SendErrorResponse (0x75);
4057 }
4058
4059 // Allocate a new save id.
4060 const uint32_t save_id = GetNextSavedRegistersID ();
4061 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
4062
4063 // Save the register data buffer under the save id.
4064 {
4065 Mutex::Locker locker (m_saved_registers_mutex);
4066 m_saved_registers_map[save_id] = register_data_sp;
4067 }
4068
4069 // Write the response.
4070 StreamGDBRemote response;
4071 response.Printf ("%" PRIu32, save_id);
4072 return SendPacketNoLock(response.GetData(), response.GetSize());
4073}
4074
4075GDBRemoteCommunicationServer::PacketResult
4076GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
4077{
4078 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4079
4080 // We don't support if we're not llgs.
4081 if (!IsGdbServer())
4082 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4083
4084 // Parse out save id.
4085 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
4086 if (packet.GetBytesLeft () < 1)
4087 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
4088
4089 const uint32_t save_id = packet.GetU32 (0);
4090 if (save_id == 0)
4091 {
4092 if (log)
4093 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
4094 return SendErrorResponse (0x76);
4095 }
4096
4097 // Get the thread to use.
4098 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4099 if (!thread_sp)
4100 {
4101 if (m_thread_suffix_supported)
4102 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
4103 else
4104 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4105 }
4106
4107 // Grab the register context for the thread.
4108 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4109 if (!reg_context_sp)
4110 {
4111 if (log)
4112 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 ());
4113 return SendErrorResponse (0x15);
4114 }
4115
4116 // Retrieve register state buffer, then remove from the list.
4117 DataBufferSP register_data_sp;
4118 {
4119 Mutex::Locker locker (m_saved_registers_mutex);
4120
4121 // Find the register set buffer for the given save id.
4122 auto it = m_saved_registers_map.find (save_id);
4123 if (it == m_saved_registers_map.end ())
4124 {
4125 if (log)
4126 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);
4127 return SendErrorResponse (0x77);
4128 }
4129 register_data_sp = it->second;
4130
4131 // Remove it from the map.
4132 m_saved_registers_map.erase (it);
4133 }
4134
4135 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
4136 if (error.Fail ())
4137 {
4138 if (log)
4139 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4140 return SendErrorResponse (0x77);
4141 }
4142
4143 return SendOKResponse();
4144}
4145
Todd Fiala7306cf32014-07-29 22:30:01 +00004146GDBRemoteCommunicationServer::PacketResult
4147GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet)
4148{
4149 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4150
4151 // We don't support if we're not llgs.
4152 if (!IsGdbServer())
4153 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4154
4155 // Consume the ';' after vAttach.
4156 packet.SetFilePos (strlen ("vAttach"));
4157 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
4158 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
4159
4160 // Grab the PID to which we will attach (assume hex encoding).
4161 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4162 if (pid == LLDB_INVALID_PROCESS_ID)
4163 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
4164
4165 // Attempt to attach.
4166 if (log)
4167 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
4168
4169 Error error = AttachToProcess (pid);
4170
4171 if (error.Fail ())
4172 {
4173 if (log)
4174 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
4175 return SendErrorResponse (0x01);
4176 }
4177
4178 // Notify we attached by sending a stop packet.
4179 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
4180
4181 return PacketResult::Success;
4182}
4183
Todd Fialaaf245d12014-06-30 21:05:18 +00004184void
4185GDBRemoteCommunicationServer::FlushInferiorOutput ()
4186{
4187 // If we're not monitoring an inferior's terminal, ignore this.
4188 if (!m_stdio_communication.IsConnected())
4189 return;
4190
4191 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
4192 if (log)
4193 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
4194
4195 // FIXME implement a timeout on the join.
4196 m_stdio_communication.JoinReadThread();
4197}
4198
4199void
4200GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection ()
4201{
4202 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4203
4204 // Tell the stdio connection to shut down.
4205 if (m_stdio_communication.IsConnected())
4206 {
4207 auto connection = m_stdio_communication.GetConnection();
4208 if (connection)
4209 {
4210 Error error;
4211 connection->Disconnect (&error);
4212
4213 if (error.Success ())
4214 {
4215 if (log)
4216 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
4217 }
4218 else
4219 {
4220 if (log)
4221 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
4222 }
4223 }
4224 }
4225}
4226
4227
4228lldb_private::NativeThreadProtocolSP
4229GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
4230{
4231 NativeThreadProtocolSP thread_sp;
4232
4233 // We have no thread if we don't have a process.
4234 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4235 return thread_sp;
4236
4237 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
4238 // Use the current thread in that case.
4239 if (!m_thread_suffix_supported)
4240 {
4241 const lldb::tid_t current_tid = GetCurrentThreadID ();
4242 if (current_tid == LLDB_INVALID_THREAD_ID)
4243 return thread_sp;
4244 else if (current_tid == 0)
4245 {
4246 // Pick a thread.
4247 return m_debugged_process_sp->GetThreadAtIndex (0);
4248 }
4249 else
4250 return m_debugged_process_sp->GetThreadByID (current_tid);
4251 }
4252
4253 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4254
4255 // Parse out the ';'.
4256 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
4257 {
4258 if (log)
4259 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4260 return thread_sp;
4261 }
4262
4263 if (!packet.GetBytesLeft ())
4264 return thread_sp;
4265
4266 // Parse out thread: portion.
4267 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
4268 {
4269 if (log)
4270 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4271 return thread_sp;
4272 }
4273 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
4274 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4275 if (tid != 0)
4276 return m_debugged_process_sp->GetThreadByID (tid);
4277
4278 return thread_sp;
4279}
4280
4281lldb::tid_t
4282GDBRemoteCommunicationServer::GetCurrentThreadID () const
4283{
4284 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
4285 {
4286 // Use whatever the debug process says is the current thread id
4287 // since the protocol either didn't specify or specified we want
4288 // any/all threads marked as the current thread.
4289 if (!m_debugged_process_sp)
4290 return LLDB_INVALID_THREAD_ID;
4291 return m_debugged_process_sp->GetCurrentThreadID ();
4292 }
4293 // Use the specific current thread id set by the gdb remote protocol.
4294 return m_current_tid;
4295}
4296
4297uint32_t
4298GDBRemoteCommunicationServer::GetNextSavedRegistersID ()
4299{
4300 Mutex::Locker locker (m_saved_registers_mutex);
4301 return m_next_saved_registers_id++;
4302}
4303
Todd Fialaa9882ce2014-08-28 15:46:54 +00004304void
4305GDBRemoteCommunicationServer::ClearProcessSpecificData ()
4306{
4307 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
4308 if (log)
4309 log->Printf ("GDBRemoteCommunicationServer::%s()", __FUNCTION__);
4310
4311 // Clear any auxv cached data.
4312 // *BSD impls should be able to do this too.
4313#if defined(__linux__)
4314 if (log)
4315 log->Printf ("GDBRemoteCommunicationServer::%s clearing auxv buffer (previously %s)",
4316 __FUNCTION__,
4317 m_active_auxv_buffer_sp ? "was set" : "was not set");
4318 m_active_auxv_buffer_sp.reset ();
4319#endif
4320}