blob: 1a48f59346bc420dbbcd1e683c58ecf141498e92 [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationServer.cpp ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Sylvestre Ledrud28b9932013-09-28 15:23:41 +000010#include <errno.h>
Greg Clayton576d8832011-03-22 04:00:09 +000011
Zachary Turner0ec7baa2014-07-01 00:18:46 +000012#include "lldb/Host/Config.h"
13
Greg Clayton576d8832011-03-22 04:00:09 +000014#include "GDBRemoteCommunicationServer.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000015#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000016
17// C Includes
18// C++ Includes
Todd Fialaaf245d12014-06-30 21:05:18 +000019#include <cstring>
Todd Fiala2850b1b2014-06-30 23:51:35 +000020#include <chrono>
21#include <thread>
Todd Fialaaf245d12014-06-30 21:05:18 +000022
Greg Clayton576d8832011-03-22 04:00:09 +000023// Other libraries and framework includes
24#include "llvm/ADT/Triple.h"
25#include "lldb/Interpreter/Args.h"
26#include "lldb/Core/ConnectionFileDescriptor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000027#include "lldb/Core/Debugger.h"
Greg Clayton576d8832011-03-22 04:00:09 +000028#include "lldb/Core/Log.h"
29#include "lldb/Core/State.h"
30#include "lldb/Core/StreamString.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000031#include "lldb/Host/Debug.h"
Enrico Granataf2bbf712011-07-15 02:26:42 +000032#include "lldb/Host/Endian.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000033#include "lldb/Host/File.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000034#include "lldb/Host/FileSystem.h"
Greg Clayton576d8832011-03-22 04:00:09 +000035#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000036#include "lldb/Host/HostInfo.h"
Greg Clayton576d8832011-03-22 04:00:09 +000037#include "lldb/Host/TimeValue.h"
Zachary Turner696b5282014-08-14 16:01:25 +000038#include "lldb/Target/FileAction.h"
Todd Fialab8b49ec2014-01-28 00:34:23 +000039#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000040#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Target/NativeRegisterContext.h"
Todd Fiala24189d42014-07-14 06:24:44 +000042#include "Host/common/NativeProcessProtocol.h"
43#include "Host/common/NativeThreadProtocol.h"
Greg Clayton576d8832011-03-22 04:00:09 +000044
45// Project includes
46#include "Utility/StringExtractorGDBRemote.h"
47#include "ProcessGDBRemote.h"
48#include "ProcessGDBRemoteLog.h"
49
50using namespace lldb;
51using namespace lldb_private;
52
53//----------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +000054// GDBRemote Errors
55//----------------------------------------------------------------------
56
57namespace
58{
59 enum GDBRemoteServerError
60 {
61 // Set to the first unused error number in literal form below
62 eErrorFirst = 29,
63 eErrorNoProcess = eErrorFirst,
64 eErrorResume,
65 eErrorExitStatus
66 };
67}
68
69//----------------------------------------------------------------------
Greg Clayton576d8832011-03-22 04:00:09 +000070// GDBRemoteCommunicationServer constructor
71//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000072GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform) :
73 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
Todd Fialab8b49ec2014-01-28 00:34:23 +000074 m_platform_sp (Platform::GetDefaultPlatform ()),
Greg Clayton8b82f082011-04-12 05:54:46 +000075 m_async_thread (LLDB_INVALID_HOST_THREAD),
76 m_process_launch_info (),
77 m_process_launch_error (),
Daniel Maleae0f8f572013-08-26 23:57:52 +000078 m_spawned_pids (),
79 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton8b82f082011-04-12 05:54:46 +000080 m_proc_infos (),
81 m_proc_infos_index (0),
Greg Clayton2b98c562013-11-22 18:53:12 +000082 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +000083 m_port_offset(0),
84 m_current_tid (LLDB_INVALID_THREAD_ID),
85 m_continue_tid (LLDB_INVALID_THREAD_ID),
86 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
87 m_debugged_process_sp (),
88 m_debugger_sp (),
89 m_stdio_communication ("process.stdio"),
90 m_exit_now (false),
91 m_inferior_prev_state (StateType::eStateInvalid),
92 m_thread_suffix_supported (false),
93 m_list_threads_in_stop_reply (false),
94 m_active_auxv_buffer_sp (),
95 m_saved_registers_mutex (),
96 m_saved_registers_map (),
97 m_next_saved_registers_id (1)
Greg Clayton576d8832011-03-22 04:00:09 +000098{
Todd Fialaaf245d12014-06-30 21:05:18 +000099 assert(is_platform && "must be lldb-platform if debugger is not specified");
Greg Clayton576d8832011-03-22 04:00:09 +0000100}
101
Todd Fialab8b49ec2014-01-28 00:34:23 +0000102GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform,
Todd Fialaaf245d12014-06-30 21:05:18 +0000103 const lldb::PlatformSP& platform_sp,
104 lldb::DebuggerSP &debugger_sp) :
Todd Fialab8b49ec2014-01-28 00:34:23 +0000105 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
106 m_platform_sp (platform_sp),
107 m_async_thread (LLDB_INVALID_HOST_THREAD),
108 m_process_launch_info (),
109 m_process_launch_error (),
110 m_spawned_pids (),
111 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
112 m_proc_infos (),
113 m_proc_infos_index (0),
114 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000115 m_port_offset(0),
116 m_current_tid (LLDB_INVALID_THREAD_ID),
117 m_continue_tid (LLDB_INVALID_THREAD_ID),
118 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
119 m_debugged_process_sp (),
120 m_debugger_sp (debugger_sp),
121 m_stdio_communication ("process.stdio"),
122 m_exit_now (false),
123 m_inferior_prev_state (StateType::eStateInvalid),
124 m_thread_suffix_supported (false),
125 m_list_threads_in_stop_reply (false),
126 m_active_auxv_buffer_sp (),
127 m_saved_registers_mutex (),
128 m_saved_registers_map (),
129 m_next_saved_registers_id (1)
Todd Fialab8b49ec2014-01-28 00:34:23 +0000130{
131 assert(platform_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000132 assert((is_platform || debugger_sp) && "must specify non-NULL debugger_sp when lldb-gdbserver");
Todd Fialab8b49ec2014-01-28 00:34:23 +0000133}
134
Greg Clayton576d8832011-03-22 04:00:09 +0000135//----------------------------------------------------------------------
136// Destructor
137//----------------------------------------------------------------------
138GDBRemoteCommunicationServer::~GDBRemoteCommunicationServer()
139{
140}
141
Todd Fialaaf245d12014-06-30 21:05:18 +0000142GDBRemoteCommunication::PacketResult
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000143GDBRemoteCommunicationServer::GetPacketAndSendResponse (uint32_t timeout_usec,
Greg Clayton1cb64962011-03-24 04:28:38 +0000144 Error &error,
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000145 bool &interrupt,
Greg Claytond314e812011-03-23 00:09:55 +0000146 bool &quit)
Greg Clayton576d8832011-03-22 04:00:09 +0000147{
148 StringExtractorGDBRemote packet;
Todd Fialaaf245d12014-06-30 21:05:18 +0000149
Greg Clayton3dedae12013-12-06 21:45:27 +0000150 PacketResult packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
151 if (packet_result == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000152 {
153 const StringExtractorGDBRemote::ServerPacketType packet_type = packet.GetServerPacketType ();
154 switch (packet_type)
155 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000156 case StringExtractorGDBRemote::eServerPacketType_nack:
157 case StringExtractorGDBRemote::eServerPacketType_ack:
158 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000159
Greg Clayton3dedae12013-12-06 21:45:27 +0000160 case StringExtractorGDBRemote::eServerPacketType_invalid:
161 error.SetErrorString("invalid packet");
162 quit = true;
163 break;
Greg Claytond314e812011-03-23 00:09:55 +0000164
Greg Clayton3dedae12013-12-06 21:45:27 +0000165 default:
166 case StringExtractorGDBRemote::eServerPacketType_unimplemented:
167 packet_result = SendUnimplementedResponse (packet.GetStringRef().c_str());
168 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000169
Greg Clayton3dedae12013-12-06 21:45:27 +0000170 case StringExtractorGDBRemote::eServerPacketType_A:
171 packet_result = Handle_A (packet);
172 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000173
Greg Clayton3dedae12013-12-06 21:45:27 +0000174 case StringExtractorGDBRemote::eServerPacketType_qfProcessInfo:
175 packet_result = Handle_qfProcessInfo (packet);
176 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000177
Greg Clayton3dedae12013-12-06 21:45:27 +0000178 case StringExtractorGDBRemote::eServerPacketType_qsProcessInfo:
179 packet_result = Handle_qsProcessInfo (packet);
180 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000181
Greg Clayton3dedae12013-12-06 21:45:27 +0000182 case StringExtractorGDBRemote::eServerPacketType_qC:
183 packet_result = Handle_qC (packet);
184 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000185
Greg Clayton3dedae12013-12-06 21:45:27 +0000186 case StringExtractorGDBRemote::eServerPacketType_qHostInfo:
187 packet_result = Handle_qHostInfo (packet);
188 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000189
Greg Clayton3dedae12013-12-06 21:45:27 +0000190 case StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer:
191 packet_result = Handle_qLaunchGDBServer (packet);
192 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000193
Greg Clayton3dedae12013-12-06 21:45:27 +0000194 case StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess:
195 packet_result = Handle_qKillSpawnedProcess (packet);
196 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000197
Todd Fiala403edc52014-01-23 22:05:44 +0000198 case StringExtractorGDBRemote::eServerPacketType_k:
199 packet_result = Handle_k (packet);
Todd Fialaaf245d12014-06-30 21:05:18 +0000200 quit = true;
Todd Fiala403edc52014-01-23 22:05:44 +0000201 break;
202
Greg Clayton3dedae12013-12-06 21:45:27 +0000203 case StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess:
204 packet_result = Handle_qLaunchSuccess (packet);
205 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000206
Greg Clayton3dedae12013-12-06 21:45:27 +0000207 case StringExtractorGDBRemote::eServerPacketType_qGroupName:
208 packet_result = Handle_qGroupName (packet);
209 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000210
Todd Fialaaf245d12014-06-30 21:05:18 +0000211 case StringExtractorGDBRemote::eServerPacketType_qProcessInfo:
212 packet_result = Handle_qProcessInfo (packet);
213 break;
214
Greg Clayton3dedae12013-12-06 21:45:27 +0000215 case StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID:
216 packet_result = Handle_qProcessInfoPID (packet);
217 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000218
Greg Clayton3dedae12013-12-06 21:45:27 +0000219 case StringExtractorGDBRemote::eServerPacketType_qSpeedTest:
220 packet_result = Handle_qSpeedTest (packet);
221 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000222
Greg Clayton3dedae12013-12-06 21:45:27 +0000223 case StringExtractorGDBRemote::eServerPacketType_qUserName:
224 packet_result = Handle_qUserName (packet);
225 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000226
Greg Clayton3dedae12013-12-06 21:45:27 +0000227 case StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir:
228 packet_result = Handle_qGetWorkingDir(packet);
229 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000230
Greg Clayton3dedae12013-12-06 21:45:27 +0000231 case StringExtractorGDBRemote::eServerPacketType_QEnvironment:
232 packet_result = Handle_QEnvironment (packet);
233 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000234
Greg Clayton3dedae12013-12-06 21:45:27 +0000235 case StringExtractorGDBRemote::eServerPacketType_QLaunchArch:
236 packet_result = Handle_QLaunchArch (packet);
237 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000238
Greg Clayton3dedae12013-12-06 21:45:27 +0000239 case StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR:
240 packet_result = Handle_QSetDisableASLR (packet);
241 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000242
Jim Ingham106d0282014-06-25 02:32:56 +0000243 case StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError:
244 packet_result = Handle_QSetDetachOnError (packet);
245 break;
246
Greg Clayton3dedae12013-12-06 21:45:27 +0000247 case StringExtractorGDBRemote::eServerPacketType_QSetSTDIN:
248 packet_result = Handle_QSetSTDIN (packet);
249 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000250
Greg Clayton3dedae12013-12-06 21:45:27 +0000251 case StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT:
252 packet_result = Handle_QSetSTDOUT (packet);
253 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000254
Greg Clayton3dedae12013-12-06 21:45:27 +0000255 case StringExtractorGDBRemote::eServerPacketType_QSetSTDERR:
256 packet_result = Handle_QSetSTDERR (packet);
257 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000258
Greg Clayton3dedae12013-12-06 21:45:27 +0000259 case StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir:
260 packet_result = Handle_QSetWorkingDir (packet);
261 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000262
Greg Clayton3dedae12013-12-06 21:45:27 +0000263 case StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode:
264 packet_result = Handle_QStartNoAckMode (packet);
265 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000266
Greg Clayton3dedae12013-12-06 21:45:27 +0000267 case StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir:
268 packet_result = Handle_qPlatform_mkdir (packet);
269 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000270
Greg Clayton3dedae12013-12-06 21:45:27 +0000271 case StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod:
272 packet_result = Handle_qPlatform_chmod (packet);
273 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000274
Greg Clayton3dedae12013-12-06 21:45:27 +0000275 case StringExtractorGDBRemote::eServerPacketType_qPlatform_shell:
276 packet_result = Handle_qPlatform_shell (packet);
277 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000278
Todd Fialaaf245d12014-06-30 21:05:18 +0000279 case StringExtractorGDBRemote::eServerPacketType_C:
280 packet_result = Handle_C (packet);
281 break;
282
283 case StringExtractorGDBRemote::eServerPacketType_c:
284 packet_result = Handle_c (packet);
285 break;
286
287 case StringExtractorGDBRemote::eServerPacketType_vCont:
288 packet_result = Handle_vCont (packet);
289 break;
290
291 case StringExtractorGDBRemote::eServerPacketType_vCont_actions:
292 packet_result = Handle_vCont_actions (packet);
293 break;
294
295 case StringExtractorGDBRemote::eServerPacketType_stop_reason: // ?
296 packet_result = Handle_stop_reason (packet);
297 break;
298
Greg Clayton3dedae12013-12-06 21:45:27 +0000299 case StringExtractorGDBRemote::eServerPacketType_vFile_open:
300 packet_result = Handle_vFile_Open (packet);
301 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000302
Greg Clayton3dedae12013-12-06 21:45:27 +0000303 case StringExtractorGDBRemote::eServerPacketType_vFile_close:
304 packet_result = Handle_vFile_Close (packet);
305 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000306
Greg Clayton3dedae12013-12-06 21:45:27 +0000307 case StringExtractorGDBRemote::eServerPacketType_vFile_pread:
308 packet_result = Handle_vFile_pRead (packet);
309 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000310
Greg Clayton3dedae12013-12-06 21:45:27 +0000311 case StringExtractorGDBRemote::eServerPacketType_vFile_pwrite:
312 packet_result = Handle_vFile_pWrite (packet);
313 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000314
Greg Clayton3dedae12013-12-06 21:45:27 +0000315 case StringExtractorGDBRemote::eServerPacketType_vFile_size:
316 packet_result = Handle_vFile_Size (packet);
317 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000318
Greg Clayton3dedae12013-12-06 21:45:27 +0000319 case StringExtractorGDBRemote::eServerPacketType_vFile_mode:
320 packet_result = Handle_vFile_Mode (packet);
321 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000322
Greg Clayton3dedae12013-12-06 21:45:27 +0000323 case StringExtractorGDBRemote::eServerPacketType_vFile_exists:
324 packet_result = Handle_vFile_Exists (packet);
325 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000326
Greg Clayton3dedae12013-12-06 21:45:27 +0000327 case StringExtractorGDBRemote::eServerPacketType_vFile_stat:
328 packet_result = Handle_vFile_Stat (packet);
329 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000330
Greg Clayton3dedae12013-12-06 21:45:27 +0000331 case StringExtractorGDBRemote::eServerPacketType_vFile_md5:
332 packet_result = Handle_vFile_MD5 (packet);
333 break;
334
335 case StringExtractorGDBRemote::eServerPacketType_vFile_symlink:
336 packet_result = Handle_vFile_symlink (packet);
337 break;
338
339 case StringExtractorGDBRemote::eServerPacketType_vFile_unlink:
340 packet_result = Handle_vFile_unlink (packet);
341 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000342
343 case StringExtractorGDBRemote::eServerPacketType_qRegisterInfo:
344 packet_result = Handle_qRegisterInfo (packet);
345 break;
346
347 case StringExtractorGDBRemote::eServerPacketType_qfThreadInfo:
348 packet_result = Handle_qfThreadInfo (packet);
349 break;
350
351 case StringExtractorGDBRemote::eServerPacketType_qsThreadInfo:
352 packet_result = Handle_qsThreadInfo (packet);
353 break;
354
355 case StringExtractorGDBRemote::eServerPacketType_p:
356 packet_result = Handle_p (packet);
357 break;
358
359 case StringExtractorGDBRemote::eServerPacketType_P:
360 packet_result = Handle_P (packet);
361 break;
362
363 case StringExtractorGDBRemote::eServerPacketType_H:
364 packet_result = Handle_H (packet);
365 break;
366
367 case StringExtractorGDBRemote::eServerPacketType_m:
368 packet_result = Handle_m (packet);
369 break;
370
371 case StringExtractorGDBRemote::eServerPacketType_M:
372 packet_result = Handle_M (packet);
373 break;
374
375 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported:
376 packet_result = Handle_qMemoryRegionInfoSupported (packet);
377 break;
378
379 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo:
380 packet_result = Handle_qMemoryRegionInfo (packet);
381 break;
382
383 case StringExtractorGDBRemote::eServerPacketType_interrupt:
384 if (IsGdbServer ())
385 packet_result = Handle_interrupt (packet);
386 else
387 {
388 error.SetErrorString("interrupt received");
389 interrupt = true;
390 }
391 break;
392
393 case StringExtractorGDBRemote::eServerPacketType_Z:
394 packet_result = Handle_Z (packet);
395 break;
396
397 case StringExtractorGDBRemote::eServerPacketType_z:
398 packet_result = Handle_z (packet);
399 break;
400
401 case StringExtractorGDBRemote::eServerPacketType_s:
402 packet_result = Handle_s (packet);
403 break;
404
405 case StringExtractorGDBRemote::eServerPacketType_qSupported:
406 packet_result = Handle_qSupported (packet);
407 break;
408
409 case StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported:
410 packet_result = Handle_QThreadSuffixSupported (packet);
411 break;
412
413 case StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply:
414 packet_result = Handle_QListThreadsInStopReply (packet);
415 break;
416
417 case StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read:
418 packet_result = Handle_qXfer_auxv_read (packet);
419 break;
420
421 case StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState:
422 packet_result = Handle_QSaveRegisterState (packet);
423 break;
424
425 case StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState:
426 packet_result = Handle_QRestoreRegisterState (packet);
427 break;
Todd Fiala7306cf32014-07-29 22:30:01 +0000428
429 case StringExtractorGDBRemote::eServerPacketType_vAttach:
430 packet_result = Handle_vAttach (packet);
431 break;
Todd Fiala1109ed42014-09-10 21:28:38 +0000432
433 case StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo:
434 packet_result = Handle_qThreadStopInfo (packet);
435 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000436 }
Greg Clayton576d8832011-03-22 04:00:09 +0000437 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000438 else
439 {
440 if (!IsConnected())
Greg Clayton3dedae12013-12-06 21:45:27 +0000441 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000442 error.SetErrorString("lost connection");
Greg Clayton3dedae12013-12-06 21:45:27 +0000443 quit = true;
444 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000445 else
Greg Clayton3dedae12013-12-06 21:45:27 +0000446 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000447 error.SetErrorString("timeout");
Greg Clayton3dedae12013-12-06 21:45:27 +0000448 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000449 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000450
451 // Check if anything occurred that would force us to want to exit.
452 if (m_exit_now)
453 quit = true;
454
455 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000456}
457
Todd Fiala403edc52014-01-23 22:05:44 +0000458lldb_private::Error
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000459GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc)
Todd Fiala403edc52014-01-23 22:05:44 +0000460{
461 if ((argc < 1) || !args || !args[0] || !args[0][0])
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000462 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
Todd Fiala403edc52014-01-23 22:05:44 +0000463
Todd Fiala403edc52014-01-23 22:05:44 +0000464 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000465 return lldb_private::Error ();
466}
467
468lldb_private::Error
469GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags)
470{
Todd Fiala403edc52014-01-23 22:05:44 +0000471 m_process_launch_info.GetFlags ().Set (launch_flags);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000472 return lldb_private::Error ();
473}
474
475lldb_private::Error
476GDBRemoteCommunicationServer::LaunchProcess ()
477{
Todd Fialaaf245d12014-06-30 21:05:18 +0000478 // FIXME This looks an awful lot like we could override this in
479 // derived classes, one for lldb-platform, the other for lldb-gdbserver.
480 if (IsGdbServer ())
481 return LaunchDebugServerProcess ();
482 else
483 return LaunchPlatformProcess ();
484}
485
486lldb_private::Error
487GDBRemoteCommunicationServer::LaunchDebugServerProcess ()
488{
489 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
490
491 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
492 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
493
494 lldb_private::Error error;
495 {
496 Mutex::Locker locker (m_debugged_process_mutex);
497 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
498 error = m_platform_sp->LaunchNativeProcess (
499 m_process_launch_info,
500 *this,
501 m_debugged_process_sp);
502 }
503
504 if (!error.Success ())
505 {
506 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
507 return error;
508 }
509
510 // Setup stdout/stderr mapping from inferior.
511 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
512 if (terminal_fd >= 0)
513 {
514 if (log)
515 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
516 error = SetSTDIOFileDescriptor (terminal_fd);
517 if (error.Fail ())
518 return error;
519 }
520 else
521 {
522 if (log)
523 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
524 }
525
526 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
527
528 // Add to list of spawned processes.
529 lldb::pid_t pid;
530 if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
531 {
532 // add to spawned pids
533 {
534 Mutex::Locker locker (m_spawned_pids_mutex);
535 // On an lldb-gdbserver, we would expect there to be only one.
536 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
537 m_spawned_pids.insert (pid);
538 }
539 }
540
541 if (error.Success ())
542 {
543 if (log)
544 log->Printf ("GDBRemoteCommunicationServer::%s beginning check to wait for launched application to hit first stop", __FUNCTION__);
545
546 int iteration = 0;
547 // Wait for the process to hit its first stop state.
548 while (!StateIsStoppedState (m_debugged_process_sp->GetState (), false))
549 {
550 if (log)
551 log->Printf ("GDBRemoteCommunicationServer::%s waiting for launched process to hit first stop (%d)...", __FUNCTION__, iteration++);
552
Todd Fiala2850b1b2014-06-30 23:51:35 +0000553 // FIXME use a finer granularity.
554 std::this_thread::sleep_for(std::chrono::seconds(1));
Todd Fialaaf245d12014-06-30 21:05:18 +0000555 }
556
557 if (log)
558 log->Printf ("GDBRemoteCommunicationServer::%s launched application has hit first stop", __FUNCTION__);
559
560 }
561
562 return error;
563}
564
565lldb_private::Error
566GDBRemoteCommunicationServer::LaunchPlatformProcess ()
567{
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000568 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
569 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
570
571 // specify the process monitor if not already set. This should
572 // generally be what happens since we need to reap started
573 // processes.
574 if (!m_process_launch_info.GetMonitorProcessCallback ())
575 m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false);
Todd Fiala403edc52014-01-23 22:05:44 +0000576
Todd Fialab8b49ec2014-01-28 00:34:23 +0000577 lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
Todd Fiala403edc52014-01-23 22:05:44 +0000578 if (!error.Success ())
579 {
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000580 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
Todd Fiala403edc52014-01-23 22:05:44 +0000581 return error;
582 }
583
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000584 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 +0000585
586 // add to list of spawned processes. On an lldb-gdbserver, we
587 // would expect there to be only one.
588 lldb::pid_t pid;
589 if ( (pid = m_process_launch_info.GetProcessID()) != LLDB_INVALID_PROCESS_ID )
590 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000591 // add to spawned pids
592 {
593 Mutex::Locker locker (m_spawned_pids_mutex);
594 m_spawned_pids.insert(pid);
595 }
Todd Fiala403edc52014-01-23 22:05:44 +0000596 }
597
598 return error;
599}
600
Todd Fialaaf245d12014-06-30 21:05:18 +0000601lldb_private::Error
602GDBRemoteCommunicationServer::AttachToProcess (lldb::pid_t pid)
603{
604 Error error;
605
606 if (!IsGdbServer ())
607 {
608 error.SetErrorString("cannot AttachToProcess () unless process is lldb-gdbserver");
609 return error;
610 }
611
612 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
613 if (log)
614 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64, __FUNCTION__, pid);
615
616 // Scope for mutex locker.
617 {
618 // Before we try to attach, make sure we aren't already monitoring something else.
619 Mutex::Locker locker (m_spawned_pids_mutex);
620 if (!m_spawned_pids.empty ())
621 {
622 error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
623 return error;
624 }
625
626 // Try to attach.
627 error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp);
628 if (!error.Success ())
629 {
630 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
631 return error;
632 }
633
634 // Setup stdout/stderr mapping from inferior.
635 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
636 if (terminal_fd >= 0)
637 {
638 if (log)
639 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
640 error = SetSTDIOFileDescriptor (terminal_fd);
641 if (error.Fail ())
642 return error;
643 }
644 else
645 {
646 if (log)
647 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
648 }
649
650 printf ("Attached to process %" PRIu64 "...\n", pid);
651
652 // Add to list of spawned processes.
653 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
654 m_spawned_pids.insert (pid);
655
656 return error;
657 }
658}
659
660void
661GDBRemoteCommunicationServer::InitializeDelegate (lldb_private::NativeProcessProtocol *process)
662{
663 assert (process && "process cannot be NULL");
664 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
665 if (log)
666 {
667 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
668 __FUNCTION__,
669 process->GetID (),
670 StateAsCString (process->GetState ()));
671 }
672}
673
674GDBRemoteCommunication::PacketResult
675GDBRemoteCommunicationServer::SendWResponse (lldb_private::NativeProcessProtocol *process)
676{
677 assert (process && "process cannot be NULL");
678 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
679
680 // send W notification
681 ExitType exit_type = ExitType::eExitTypeInvalid;
682 int return_code = 0;
683 std::string exit_description;
684
685 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
686 if (!got_exit_info)
687 {
688 if (log)
689 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
690
691 StreamGDBRemote response;
692 response.PutChar ('E');
693 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
694 return SendPacketNoLock(response.GetData(), response.GetSize());
695 }
696 else
697 {
698 if (log)
699 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 ());
700
701 StreamGDBRemote response;
702
703 char return_type_code;
704 switch (exit_type)
705 {
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000706 case ExitType::eExitTypeExit:
707 return_type_code = 'W';
708 break;
709 case ExitType::eExitTypeSignal:
710 return_type_code = 'X';
711 break;
712 case ExitType::eExitTypeStop:
713 return_type_code = 'S';
714 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000715 case ExitType::eExitTypeInvalid:
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000716 return_type_code = 'E';
717 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000718 }
719 response.PutChar (return_type_code);
720
721 // POSIX exit status limited to unsigned 8 bits.
722 response.PutHex8 (return_code);
723
724 return SendPacketNoLock(response.GetData(), response.GetSize());
725 }
726}
727
728static void
729AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
730{
731 int64_t i;
732 if (swap)
733 {
734 for (i = buf_size-1; i >= 0; i--)
735 response.PutHex8 (buf[i]);
736 }
737 else
738 {
739 for (i = 0; i < buf_size; i++)
740 response.PutHex8 (buf[i]);
741 }
742}
743
744static void
745WriteRegisterValueInHexFixedWidth (StreamString &response,
746 NativeRegisterContextSP &reg_ctx_sp,
747 const RegisterInfo &reg_info,
748 const RegisterValue *reg_value_p)
749{
750 RegisterValue reg_value;
751 if (!reg_value_p)
752 {
753 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
754 if (error.Success ())
755 reg_value_p = &reg_value;
756 // else log.
757 }
758
759 if (reg_value_p)
760 {
761 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
762 }
763 else
764 {
765 // Zero-out any unreadable values.
766 if (reg_info.byte_size > 0)
767 {
768 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
769 AppendHexValue (response, zeros.data(), zeros.size(), false);
770 }
771 }
772}
773
774// WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
775
776
777static void
778WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response,
779 NativeRegisterContextSP &reg_ctx_sp,
780 const RegisterInfo &reg_info,
781 const RegisterValue &reg_value)
782{
783 // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
784 // gdb register number, and VVVVVVVV is the correct number of hex bytes
785 // as ASCII for the register value.
786 if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM)
787 return;
788
789 response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]);
790 WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, &reg_value);
791 response.PutChar (';');
792}
793
794
795GDBRemoteCommunication::PacketResult
796GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid)
797{
798 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
799
800 // Ensure we're llgs.
801 if (!IsGdbServer ())
802 {
803 // Only supported on llgs
804 return SendUnimplementedResponse ("");
805 }
806
807 // Ensure we have a debugged process.
808 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
809 return SendErrorResponse (50);
810
811 if (log)
812 log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
813 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
814
815 // Ensure we can get info on the given thread.
816 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
817 if (!thread_sp)
818 return SendErrorResponse (51);
819
820 // Grab the reason this thread stopped.
821 struct ThreadStopInfo tid_stop_info;
822 if (!thread_sp->GetStopReason (tid_stop_info))
823 return SendErrorResponse (52);
824
825 const bool did_exec = tid_stop_info.reason == eStopReasonExec;
826 // FIXME implement register handling for exec'd inferiors.
827 // if (did_exec)
828 // {
829 // const bool force = true;
830 // InitializeRegisters(force);
831 // }
832
833 StreamString response;
834 // Output the T packet with the thread
835 response.PutChar ('T');
836 int signum = tid_stop_info.details.signal.signo;
837 if (log)
838 {
839 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
840 __FUNCTION__,
841 m_debugged_process_sp->GetID (),
842 tid,
843 signum,
844 tid_stop_info.reason,
845 tid_stop_info.details.exception.type);
846 }
847
848 switch (tid_stop_info.reason)
849 {
850 case eStopReasonSignal:
851 case eStopReasonException:
852 signum = thread_sp->TranslateStopInfoToGdbSignal (tid_stop_info);
853 break;
854 default:
855 signum = 0;
856 if (log)
857 {
858 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " has stop reason %d, using signo = 0 in stop reply response",
859 __FUNCTION__,
860 m_debugged_process_sp->GetID (),
861 tid,
862 tid_stop_info.reason);
863 }
864 break;
865 }
866
867 // Print the signal number.
868 response.PutHex8 (signum & 0xff);
869
870 // Include the tid.
871 response.Printf ("thread:%" PRIx64 ";", tid);
872
873 // Include the thread name if there is one.
Todd Fiala7206c6d2014-09-12 22:51:49 +0000874 const std::string thread_name = thread_sp->GetName ();
875 if (!thread_name.empty ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000876 {
Todd Fiala7206c6d2014-09-12 22:51:49 +0000877 size_t thread_name_len = thread_name.length ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000878
Todd Fiala7206c6d2014-09-12 22:51:49 +0000879 if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
Todd Fialaaf245d12014-06-30 21:05:18 +0000880 {
881 response.PutCString ("name:");
Todd Fiala7206c6d2014-09-12 22:51:49 +0000882 response.PutCString (thread_name.c_str ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000883 }
884 else
885 {
886 // The thread name contains special chars, send as hex bytes.
887 response.PutCString ("hexname:");
Todd Fiala7206c6d2014-09-12 22:51:49 +0000888 response.PutCStringAsRawHex8 (thread_name.c_str ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000889 }
890 response.PutChar (';');
891 }
892
893 // FIXME look for analog
894 // thread_identifier_info_data_t thread_ident_info;
895 // if (DNBThreadGetIdentifierInfo (pid, tid, &thread_ident_info))
896 // {
897 // if (thread_ident_info.dispatch_qaddr != 0)
898 // ostrm << std::hex << "qaddr:" << thread_ident_info.dispatch_qaddr << ';';
899 // }
900
901 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
902 // will send all thread IDs back in the "threads" key whose value is
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000903 // a list of hex thread IDs separated by commas:
Todd Fialaaf245d12014-06-30 21:05:18 +0000904 // "threads:10a,10b,10c;"
905 // This will save the debugger from having to send a pair of qfThreadInfo
906 // and qsThreadInfo packets, but it also might take a lot of room in the
907 // stop reply packet, so it must be enabled only on systems where there
908 // are no limits on packet lengths.
909 if (m_list_threads_in_stop_reply)
910 {
911 response.PutCString ("threads:");
912
913 uint32_t thread_index = 0;
914 NativeThreadProtocolSP listed_thread_sp;
915 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))
916 {
917 if (thread_index > 0)
918 response.PutChar (',');
919 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
920 }
921 response.PutChar (';');
922 }
923
924 //
925 // Expedite registers.
926 //
927
928 // Grab the register context.
929 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
930 if (reg_ctx_sp)
931 {
932 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
933 const RegisterSet *reg_set_p;
934 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
935 {
936 if (log)
937 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);
938
939 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
940 {
941 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
942 if (reg_info_p == nullptr)
943 {
944 if (log)
945 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);
946 }
947 else if (reg_info_p->value_regs == nullptr)
948 {
949 // Only expediate registers that are not contained in other registers.
950 RegisterValue reg_value;
951 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
952 if (error.Success ())
953 WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
954 else
955 {
956 if (log)
957 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 ());
958
959 }
960 }
961 }
962 }
963 }
964
965 if (did_exec)
966 {
967 response.PutCString ("reason:exec;");
968 }
969 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
970 {
971 response.PutCString ("metype:");
972 response.PutHex64 (tid_stop_info.details.exception.type);
973 response.PutCString (";mecount:");
974 response.PutHex32 (tid_stop_info.details.exception.data_count);
975 response.PutChar (';');
976
977 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
978 {
979 response.PutCString ("medata:");
980 response.PutHex64 (tid_stop_info.details.exception.data[i]);
981 response.PutChar (';');
982 }
983 }
984
985 return SendPacketNoLock (response.GetData(), response.GetSize());
986}
987
988void
989GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
990{
991 assert (process && "process cannot be NULL");
992
993 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
994 if (log)
995 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
996
997 // Send the exit result, and don't flush output.
998 // Note: flushing output here would join the inferior stdio reflection thread, which
999 // would gunk up the waitpid monitor thread that is calling this.
1000 PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
1001 if (result != PacketResult::Success)
1002 {
1003 if (log)
1004 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1005 }
1006
1007 // Remove the process from the list of spawned pids.
1008 {
1009 Mutex::Locker locker (m_spawned_pids_mutex);
1010 if (m_spawned_pids.erase (process->GetID ()) < 1)
1011 {
1012 if (log)
1013 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
1014
1015 }
1016 }
1017
1018 // FIXME can't do this yet - since process state propagation is currently
1019 // synchronous, it is running off the NativeProcessProtocol's innards and
1020 // will tear down the NPP while it still has code to execute.
1021#if 0
1022 // Clear the NativeProcessProtocol pointer.
1023 {
1024 Mutex::Locker locker (m_debugged_process_mutex);
1025 m_debugged_process_sp.reset();
1026 }
1027#endif
1028
1029 // Close the pipe to the inferior terminal i/o if we launched it
1030 // and set one up. Otherwise, 'k' and its flush of stdio could
1031 // end up waiting on a thread join that will never end. Consider
1032 // adding a timeout to the connection thread join call so we
1033 // can avoid that scenario altogether.
1034 MaybeCloseInferiorTerminalConnection ();
1035
1036 // We are ready to exit the debug monitor.
1037 m_exit_now = true;
1038}
1039
1040void
1041GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
1042{
1043 assert (process && "process cannot be NULL");
1044
1045 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1046 if (log)
1047 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1048
1049 // Send the stop reason unless this is the stop after the
1050 // launch or attach.
1051 switch (m_inferior_prev_state)
1052 {
1053 case eStateLaunching:
1054 case eStateAttaching:
1055 // Don't send anything per debugserver behavior.
1056 break;
1057 default:
1058 // In all other cases, send the stop reason.
1059 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
1060 if (result != PacketResult::Success)
1061 {
1062 if (log)
1063 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1064 }
1065 break;
1066 }
1067}
1068
1069void
1070GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
1071{
1072 assert (process && "process cannot be NULL");
1073 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1074 if (log)
1075 {
1076 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
1077 __FUNCTION__,
1078 process->GetID (),
1079 StateAsCString (state));
1080 }
1081
1082 switch (state)
1083 {
1084 case StateType::eStateExited:
1085 HandleInferiorState_Exited (process);
1086 break;
1087
1088 case StateType::eStateStopped:
1089 HandleInferiorState_Stopped (process);
1090 break;
1091
1092 default:
1093 if (log)
1094 {
1095 log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
1096 __FUNCTION__,
1097 process->GetID (),
1098 StateAsCString (state));
1099 }
1100 break;
1101 }
1102
1103 // Remember the previous state reported to us.
1104 m_inferior_prev_state = state;
1105}
1106
Todd Fialaa9882ce2014-08-28 15:46:54 +00001107void
1108GDBRemoteCommunicationServer::DidExec (NativeProcessProtocol *process)
1109{
1110 ClearProcessSpecificData ();
1111}
1112
Todd Fialaaf245d12014-06-30 21:05:18 +00001113GDBRemoteCommunication::PacketResult
1114GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len)
1115{
1116 if ((buffer == nullptr) || (len == 0))
1117 {
1118 // Nothing to send.
1119 return PacketResult::Success;
1120 }
1121
1122 StreamString response;
1123 response.PutChar ('O');
1124 response.PutBytesAsRawHex8 (buffer, len);
1125
1126 return SendPacketNoLock (response.GetData (), response.GetSize ());
1127}
1128
1129lldb_private::Error
1130GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd)
1131{
1132 Error error;
1133
1134 // Set up the Read Thread for reading/handling process I/O
1135 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
1136 if (!conn_up)
1137 {
1138 error.SetErrorString ("failed to create ConnectionFileDescriptor");
1139 return error;
1140 }
1141
1142 m_stdio_communication.SetConnection (conn_up.release());
1143 if (!m_stdio_communication.IsConnected ())
1144 {
1145 error.SetErrorString ("failed to set connection for inferior I/O communication");
1146 return error;
1147 }
1148
1149 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1150 m_stdio_communication.StartReadThread();
1151
1152 return error;
1153}
1154
1155void
1156GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1157{
1158 GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton);
1159 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
1160}
1161
Greg Clayton3dedae12013-12-06 21:45:27 +00001162GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001163GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
Greg Clayton576d8832011-03-22 04:00:09 +00001164{
Greg Clayton32e0a752011-03-30 18:16:51 +00001165 // TODO: Log the packet we aren't handling...
Greg Clayton37a0a242012-04-11 00:24:49 +00001166 return SendPacketNoLock ("", 0);
Greg Clayton576d8832011-03-22 04:00:09 +00001167}
1168
Todd Fialaaf245d12014-06-30 21:05:18 +00001169
Greg Clayton3dedae12013-12-06 21:45:27 +00001170GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001171GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
1172{
1173 char packet[16];
1174 int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
Andy Gibbsa297a972013-06-19 19:04:53 +00001175 assert (packet_len < (int)sizeof(packet));
Greg Clayton37a0a242012-04-11 00:24:49 +00001176 return SendPacketNoLock (packet, packet_len);
Greg Clayton32e0a752011-03-30 18:16:51 +00001177}
1178
Todd Fialaaf245d12014-06-30 21:05:18 +00001179GDBRemoteCommunication::PacketResult
1180GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message)
1181{
1182 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
1183 if (log)
1184 log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : "");
1185 return SendErrorResponse (0x03);
1186}
Greg Clayton32e0a752011-03-30 18:16:51 +00001187
Greg Clayton3dedae12013-12-06 21:45:27 +00001188GDBRemoteCommunication::PacketResult
Greg Clayton1cb64962011-03-24 04:28:38 +00001189GDBRemoteCommunicationServer::SendOKResponse ()
1190{
Greg Clayton37a0a242012-04-11 00:24:49 +00001191 return SendPacketNoLock ("OK", 2);
Greg Clayton1cb64962011-03-24 04:28:38 +00001192}
1193
1194bool
1195GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
1196{
Greg Clayton3dedae12013-12-06 21:45:27 +00001197 return GetAck() == PacketResult::Success;
Greg Clayton1cb64962011-03-24 04:28:38 +00001198}
Greg Clayton576d8832011-03-22 04:00:09 +00001199
Greg Clayton3dedae12013-12-06 21:45:27 +00001200GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001201GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
Greg Clayton576d8832011-03-22 04:00:09 +00001202{
1203 StreamString response;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001204
Greg Clayton576d8832011-03-22 04:00:09 +00001205 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
1206
Zachary Turner13b18262014-08-20 16:42:51 +00001207 ArchSpec host_arch(HostInfo::GetArchitecture());
Greg Clayton576d8832011-03-22 04:00:09 +00001208 const llvm::Triple &host_triple = host_arch.GetTriple();
Greg Clayton1cb64962011-03-24 04:28:38 +00001209 response.PutCString("triple:");
Greg Clayton44272a42014-09-18 00:18:32 +00001210 response.PutCStringAsRawHex8(host_triple.getTriple().c_str());
Greg Clayton1cb64962011-03-24 04:28:38 +00001211 response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001212
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001213 const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
1214 if (distribution_id)
1215 {
1216 response.PutCString("distribution_id:");
1217 response.PutCStringAsRawHex8(distribution_id);
1218 response.PutCString(";");
1219 }
1220
Todd Fialaaf245d12014-06-30 21:05:18 +00001221 // Only send out MachO info when lldb-platform/llgs is running on a MachO host.
1222#if defined(__APPLE__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001223 uint32_t cpu = host_arch.GetMachOCPUType();
1224 uint32_t sub = host_arch.GetMachOCPUSubType();
1225 if (cpu != LLDB_INVALID_CPUTYPE)
1226 response.Printf ("cputype:%u;", cpu);
1227 if (sub != LLDB_INVALID_CPUTYPE)
1228 response.Printf ("cpusubtype:%u;", sub);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001229
Enrico Granata1c5431a2012-07-13 23:55:22 +00001230 if (cpu == ArchSpec::kCore_arm_any)
Enrico Granataf04a2192012-07-13 23:18:48 +00001231 response.Printf("watchpoint_exceptions_received:before;"); // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
1232 else
1233 response.Printf("watchpoint_exceptions_received:after;");
Todd Fialaaf245d12014-06-30 21:05:18 +00001234#else
1235 response.Printf("watchpoint_exceptions_received:after;");
1236#endif
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001237
Greg Clayton576d8832011-03-22 04:00:09 +00001238 switch (lldb::endian::InlHostByteOrder())
1239 {
1240 case eByteOrderBig: response.PutCString ("endian:big;"); break;
1241 case eByteOrderLittle: response.PutCString ("endian:little;"); break;
1242 case eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1243 default: response.PutCString ("endian:unknown;"); break;
1244 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001245
Greg Clayton1cb64962011-03-24 04:28:38 +00001246 uint32_t major = UINT32_MAX;
1247 uint32_t minor = UINT32_MAX;
1248 uint32_t update = UINT32_MAX;
Zachary Turner97a14e62014-08-19 17:18:29 +00001249 if (HostInfo::GetOSVersion(major, minor, update))
Greg Clayton1cb64962011-03-24 04:28:38 +00001250 {
1251 if (major != UINT32_MAX)
1252 {
1253 response.Printf("os_version:%u", major);
1254 if (minor != UINT32_MAX)
1255 {
1256 response.Printf(".%u", minor);
1257 if (update != UINT32_MAX)
1258 response.Printf(".%u", update);
1259 }
1260 response.PutChar(';');
1261 }
1262 }
1263
1264 std::string s;
Zachary Turner97a14e62014-08-19 17:18:29 +00001265#if !defined(__linux__)
1266 if (HostInfo::GetOSBuildString(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001267 {
1268 response.PutCString ("os_build:");
1269 response.PutCStringAsRawHex8(s.c_str());
1270 response.PutChar(';');
1271 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001272 if (HostInfo::GetOSKernelDescription(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001273 {
1274 response.PutCString ("os_kernel:");
1275 response.PutCStringAsRawHex8(s.c_str());
1276 response.PutChar(';');
1277 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001278#endif
1279
Greg Clayton2b98c562013-11-22 18:53:12 +00001280#if defined(__APPLE__)
1281
Todd Fiala013434e2014-07-09 01:29:05 +00001282#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001283 // For iOS devices, we are connected through a USB Mux so we never pretend
1284 // to actually have a hostname as far as the remote lldb that is connecting
1285 // to this lldb-platform is concerned
1286 response.PutCString ("hostname:");
Greg Clayton16810922014-02-27 19:38:18 +00001287 response.PutCStringAsRawHex8("127.0.0.1");
Greg Clayton2b98c562013-11-22 18:53:12 +00001288 response.PutChar(';');
Todd Fiala013434e2014-07-09 01:29:05 +00001289#else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001290 if (HostInfo::GetHostname(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001291 {
1292 response.PutCString ("hostname:");
1293 response.PutCStringAsRawHex8(s.c_str());
1294 response.PutChar(';');
1295 }
Todd Fiala013434e2014-07-09 01:29:05 +00001296#endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001297
1298#else // #if defined(__APPLE__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001299 if (HostInfo::GetHostname(s))
Greg Clayton2b98c562013-11-22 18:53:12 +00001300 {
1301 response.PutCString ("hostname:");
1302 response.PutCStringAsRawHex8(s.c_str());
1303 response.PutChar(';');
1304 }
1305#endif // #if defined(__APPLE__)
1306
Greg Clayton3dedae12013-12-06 21:45:27 +00001307 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001308}
Greg Clayton1cb64962011-03-24 04:28:38 +00001309
Greg Clayton32e0a752011-03-30 18:16:51 +00001310static void
Greg Clayton8b82f082011-04-12 05:54:46 +00001311CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
Greg Clayton32e0a752011-03-30 18:16:51 +00001312{
Daniel Malead01b2952012-11-29 21:49:15 +00001313 response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
Greg Clayton32e0a752011-03-30 18:16:51 +00001314 proc_info.GetProcessID(),
1315 proc_info.GetParentProcessID(),
Greg Clayton8b82f082011-04-12 05:54:46 +00001316 proc_info.GetUserID(),
1317 proc_info.GetGroupID(),
Greg Clayton32e0a752011-03-30 18:16:51 +00001318 proc_info.GetEffectiveUserID(),
1319 proc_info.GetEffectiveGroupID());
1320 response.PutCString ("name:");
1321 response.PutCStringAsRawHex8(proc_info.GetName());
1322 response.PutChar(';');
1323 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1324 if (proc_arch.IsValid())
1325 {
1326 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1327 response.PutCString("triple:");
Greg Clayton44272a42014-09-18 00:18:32 +00001328 response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001329 response.PutChar(';');
1330 }
1331}
Greg Clayton1cb64962011-03-24 04:28:38 +00001332
Todd Fialaaf245d12014-06-30 21:05:18 +00001333static void
1334CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response)
1335{
1336 response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1337 proc_info.GetProcessID(),
1338 proc_info.GetParentProcessID(),
1339 proc_info.GetUserID(),
1340 proc_info.GetGroupID(),
1341 proc_info.GetEffectiveUserID(),
1342 proc_info.GetEffectiveGroupID());
1343
1344 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1345 if (proc_arch.IsValid())
1346 {
Todd Fialac540dd02014-08-26 18:21:02 +00001347 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1348#if defined(__APPLE__)
1349 // We'll send cputype/cpusubtype.
Todd Fialaaf245d12014-06-30 21:05:18 +00001350 const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1351 if (cpu_type != 0)
1352 response.Printf ("cputype:%" PRIx32 ";", cpu_type);
1353
1354 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1355 if (cpu_subtype != 0)
1356 response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype);
Todd Fialac540dd02014-08-26 18:21:02 +00001357
Todd Fialaaf245d12014-06-30 21:05:18 +00001358
Todd Fialaaf245d12014-06-30 21:05:18 +00001359 const std::string vendor = proc_triple.getVendorName ();
1360 if (!vendor.empty ())
1361 response.Printf ("vendor:%s;", vendor.c_str ());
Todd Fialac540dd02014-08-26 18:21:02 +00001362#else
1363 // We'll send the triple.
Greg Clayton44272a42014-09-18 00:18:32 +00001364 response.PutCString("triple:");
1365 response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1366 response.PutChar(';');
1367
Todd Fialac540dd02014-08-26 18:21:02 +00001368#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001369 std::string ostype = proc_triple.getOSName ();
1370 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1371 if (proc_triple.getVendor () == llvm::Triple::Apple)
1372 {
1373 switch (proc_triple.getArch ())
1374 {
1375 case llvm::Triple::arm:
Todd Fialad8eaa172014-07-23 14:37:35 +00001376 case llvm::Triple::aarch64:
Todd Fialaaf245d12014-06-30 21:05:18 +00001377 ostype = "ios";
1378 break;
1379 default:
1380 // No change.
1381 break;
1382 }
1383 }
1384 response.Printf ("ostype:%s;", ostype.c_str ());
1385
1386
1387 switch (proc_arch.GetByteOrder ())
1388 {
1389 case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break;
1390 case lldb::eByteOrderBig: response.PutCString ("endian:big;"); break;
1391 case lldb::eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1392 default:
1393 // Nothing.
1394 break;
1395 }
1396
1397 if (proc_triple.isArch64Bit ())
1398 response.PutCString ("ptrsize:8;");
1399 else if (proc_triple.isArch32Bit ())
1400 response.PutCString ("ptrsize:4;");
1401 else if (proc_triple.isArch16Bit ())
1402 response.PutCString ("ptrsize:2;");
1403 }
1404
1405}
1406
1407
1408GDBRemoteCommunication::PacketResult
1409GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1410{
1411 // Only the gdb server handles this.
1412 if (!IsGdbServer ())
1413 return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
1414
1415 // Fail if we don't have a current process.
1416 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1417 return SendErrorResponse (68);
1418
1419 ProcessInstanceInfo proc_info;
1420 if (Host::GetProcessInfo (m_debugged_process_sp->GetID (), proc_info))
1421 {
1422 StreamString response;
1423 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1424 return SendPacketNoLock (response.GetData (), response.GetSize ());
1425 }
1426
1427 return SendErrorResponse (1);
1428}
1429
Greg Clayton3dedae12013-12-06 21:45:27 +00001430GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001431GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
Greg Clayton1cb64962011-03-24 04:28:38 +00001432{
Greg Clayton32e0a752011-03-30 18:16:51 +00001433 // Packet format: "qProcessInfoPID:%i" where %i is the pid
Greg Clayton8b82f082011-04-12 05:54:46 +00001434 packet.SetFilePos(::strlen ("qProcessInfoPID:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001435 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
1436 if (pid != LLDB_INVALID_PROCESS_ID)
1437 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001438 ProcessInstanceInfo proc_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001439 if (Host::GetProcessInfo(pid, proc_info))
1440 {
1441 StreamString response;
1442 CreateProcessInfoResponse (proc_info, response);
Greg Clayton37a0a242012-04-11 00:24:49 +00001443 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001444 }
1445 }
1446 return SendErrorResponse (1);
1447}
1448
Greg Clayton3dedae12013-12-06 21:45:27 +00001449GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001450GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
1451{
1452 m_proc_infos_index = 0;
1453 m_proc_infos.Clear();
1454
Greg Clayton8b82f082011-04-12 05:54:46 +00001455 ProcessInstanceInfoMatch match_info;
1456 packet.SetFilePos(::strlen ("qfProcessInfo"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001457 if (packet.GetChar() == ':')
1458 {
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001459
Greg Clayton32e0a752011-03-30 18:16:51 +00001460 std::string key;
1461 std::string value;
1462 while (packet.GetNameColonValue(key, value))
1463 {
1464 bool success = true;
1465 if (key.compare("name") == 0)
1466 {
1467 StringExtractor extractor;
1468 extractor.GetStringRef().swap(value);
1469 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001470 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001471 }
1472 else if (key.compare("name_match") == 0)
1473 {
1474 if (value.compare("equals") == 0)
1475 {
1476 match_info.SetNameMatchType (eNameMatchEquals);
1477 }
1478 else if (value.compare("starts_with") == 0)
1479 {
1480 match_info.SetNameMatchType (eNameMatchStartsWith);
1481 }
1482 else if (value.compare("ends_with") == 0)
1483 {
1484 match_info.SetNameMatchType (eNameMatchEndsWith);
1485 }
1486 else if (value.compare("contains") == 0)
1487 {
1488 match_info.SetNameMatchType (eNameMatchContains);
1489 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001490 else if (value.compare("regex") == 0)
Greg Clayton32e0a752011-03-30 18:16:51 +00001491 {
1492 match_info.SetNameMatchType (eNameMatchRegularExpression);
1493 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001494 else
Greg Clayton32e0a752011-03-30 18:16:51 +00001495 {
1496 success = false;
1497 }
1498 }
1499 else if (key.compare("pid") == 0)
1500 {
1501 match_info.GetProcessInfo().SetProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1502 }
1503 else if (key.compare("parent_pid") == 0)
1504 {
1505 match_info.GetProcessInfo().SetParentProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1506 }
1507 else if (key.compare("uid") == 0)
1508 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001509 match_info.GetProcessInfo().SetUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001510 }
1511 else if (key.compare("gid") == 0)
1512 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001513 match_info.GetProcessInfo().SetGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001514 }
1515 else if (key.compare("euid") == 0)
1516 {
1517 match_info.GetProcessInfo().SetEffectiveUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1518 }
1519 else if (key.compare("egid") == 0)
1520 {
1521 match_info.GetProcessInfo().SetEffectiveGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1522 }
1523 else if (key.compare("all_users") == 0)
1524 {
1525 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
1526 }
1527 else if (key.compare("triple") == 0)
1528 {
Greg Claytoneb0103f2011-04-07 22:46:35 +00001529 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
Greg Clayton32e0a752011-03-30 18:16:51 +00001530 }
1531 else
1532 {
1533 success = false;
1534 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001535
Greg Clayton32e0a752011-03-30 18:16:51 +00001536 if (!success)
1537 return SendErrorResponse (2);
1538 }
1539 }
1540
1541 if (Host::FindProcesses (match_info, m_proc_infos))
1542 {
1543 // We found something, return the first item by calling the get
1544 // subsequent process info packet handler...
1545 return Handle_qsProcessInfo (packet);
1546 }
1547 return SendErrorResponse (3);
1548}
1549
Greg Clayton3dedae12013-12-06 21:45:27 +00001550GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001551GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
1552{
1553 if (m_proc_infos_index < m_proc_infos.GetSize())
1554 {
1555 StreamString response;
1556 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
1557 ++m_proc_infos_index;
Greg Clayton37a0a242012-04-11 00:24:49 +00001558 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001559 }
1560 return SendErrorResponse (4);
1561}
1562
Greg Clayton3dedae12013-12-06 21:45:27 +00001563GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001564GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
1565{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001566#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001567 // Packet format: "qUserName:%i" where %i is the uid
Greg Clayton8b82f082011-04-12 05:54:46 +00001568 packet.SetFilePos(::strlen ("qUserName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001569 uint32_t uid = packet.GetU32 (UINT32_MAX);
1570 if (uid != UINT32_MAX)
1571 {
1572 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001573 if (HostInfo::LookupUserName(uid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001574 {
1575 StreamString response;
1576 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001577 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001578 }
1579 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001580#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001581 return SendErrorResponse (5);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001582
Greg Clayton32e0a752011-03-30 18:16:51 +00001583}
1584
Greg Clayton3dedae12013-12-06 21:45:27 +00001585GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001586GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
1587{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001588#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001589 // Packet format: "qGroupName:%i" where %i is the gid
Greg Clayton8b82f082011-04-12 05:54:46 +00001590 packet.SetFilePos(::strlen ("qGroupName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001591 uint32_t gid = packet.GetU32 (UINT32_MAX);
1592 if (gid != UINT32_MAX)
1593 {
1594 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001595 if (HostInfo::LookupGroupName(gid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001596 {
1597 StreamString response;
1598 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001599 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001600 }
1601 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001602#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001603 return SendErrorResponse (6);
1604}
1605
Greg Clayton3dedae12013-12-06 21:45:27 +00001606GDBRemoteCommunication::PacketResult
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001607GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
1608{
Greg Clayton8b82f082011-04-12 05:54:46 +00001609 packet.SetFilePos(::strlen ("qSpeedTest:"));
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001610
1611 std::string key;
1612 std::string value;
1613 bool success = packet.GetNameColonValue(key, value);
1614 if (success && key.compare("response_size") == 0)
1615 {
1616 uint32_t response_size = Args::StringToUInt32(value.c_str(), 0, 0, &success);
1617 if (success)
1618 {
1619 if (response_size == 0)
1620 return SendOKResponse();
1621 StreamString response;
1622 uint32_t bytes_left = response_size;
1623 response.PutCString("data:");
1624 while (bytes_left > 0)
1625 {
1626 if (bytes_left >= 26)
1627 {
1628 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1629 bytes_left -= 26;
1630 }
1631 else
1632 {
1633 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1634 bytes_left = 0;
1635 }
1636 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001637 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001638 }
1639 }
1640 return SendErrorResponse (7);
1641}
Greg Clayton8b82f082011-04-12 05:54:46 +00001642
Greg Clayton8b82f082011-04-12 05:54:46 +00001643//
1644//static bool
1645//WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
1646//{
1647// const int time_delta_usecs = 100000;
1648// const int num_retries = timeout_in_seconds/time_delta_usecs;
1649// for (int i=0; i<num_retries; i++)
1650// {
1651// struct proc_bsdinfo bsd_info;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001652// int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
1653// (uint64_t) 0,
1654// &bsd_info,
Greg Clayton8b82f082011-04-12 05:54:46 +00001655// PROC_PIDTBSDINFO_SIZE);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001656//
Greg Clayton8b82f082011-04-12 05:54:46 +00001657// switch (error)
1658// {
1659// case EINVAL:
1660// case ENOTSUP:
1661// case ESRCH:
1662// case EPERM:
1663// return false;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001664//
Greg Clayton8b82f082011-04-12 05:54:46 +00001665// default:
1666// break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001667//
Greg Clayton8b82f082011-04-12 05:54:46 +00001668// case 0:
1669// if (bsd_info.pbi_status == SSTOP)
1670// return true;
1671// }
1672// ::usleep (time_delta_usecs);
1673// }
1674// return false;
1675//}
1676
Greg Clayton3dedae12013-12-06 21:45:27 +00001677GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001678GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
1679{
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001680 // The 'A' packet is the most over designed packet ever here with
1681 // redundant argument indexes, redundant argument lengths and needed hex
1682 // encoded argument string values. Really all that is needed is a comma
Greg Clayton8b82f082011-04-12 05:54:46 +00001683 // separated hex encoded argument value list, but we will stay true to the
1684 // documented version of the 'A' packet here...
1685
Todd Fialaaf245d12014-06-30 21:05:18 +00001686 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1687 int actual_arg_index = 0;
1688
Greg Clayton8b82f082011-04-12 05:54:46 +00001689 packet.SetFilePos(1); // Skip the 'A'
1690 bool success = true;
1691 while (success && packet.GetBytesLeft() > 0)
1692 {
1693 // Decode the decimal argument string length. This length is the
1694 // number of hex nibbles in the argument string value.
1695 const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1696 if (arg_len == UINT32_MAX)
1697 success = false;
1698 else
1699 {
1700 // Make sure the argument hex string length is followed by a comma
1701 if (packet.GetChar() != ',')
1702 success = false;
1703 else
1704 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001705 // Decode the argument index. We ignore this really because
Greg Clayton8b82f082011-04-12 05:54:46 +00001706 // who would really send down the arguments in a random order???
1707 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1708 if (arg_idx == UINT32_MAX)
1709 success = false;
1710 else
1711 {
1712 // Make sure the argument index is followed by a comma
1713 if (packet.GetChar() != ',')
1714 success = false;
1715 else
1716 {
1717 // Decode the argument string value from hex bytes
1718 // back into a UTF8 string and make sure the length
1719 // matches the one supplied in the packet
1720 std::string arg;
Todd Fialaaf245d12014-06-30 21:05:18 +00001721 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2))
Greg Clayton8b82f082011-04-12 05:54:46 +00001722 success = false;
1723 else
1724 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001725 // If there are any bytes left
Greg Clayton8b82f082011-04-12 05:54:46 +00001726 if (packet.GetBytesLeft())
1727 {
1728 if (packet.GetChar() != ',')
1729 success = false;
1730 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001731
Greg Clayton8b82f082011-04-12 05:54:46 +00001732 if (success)
1733 {
1734 if (arg_idx == 0)
1735 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
1736 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001737 if (log)
1738 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ());
1739 ++actual_arg_index;
Greg Clayton8b82f082011-04-12 05:54:46 +00001740 }
1741 }
1742 }
1743 }
1744 }
1745 }
1746 }
1747
1748 if (success)
1749 {
Todd Fiala9f377372014-01-27 20:44:50 +00001750 m_process_launch_error = LaunchProcess ();
Greg Clayton8b82f082011-04-12 05:54:46 +00001751 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1752 {
1753 return SendOKResponse ();
1754 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001755 else
1756 {
1757 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1758 if (log)
1759 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s",
1760 __FUNCTION__,
1761 m_process_launch_error.AsCString());
1762
1763 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001764 }
1765 return SendErrorResponse (8);
1766}
1767
Greg Clayton3dedae12013-12-06 21:45:27 +00001768GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001769GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
1770{
Greg Clayton8b82f082011-04-12 05:54:46 +00001771 StreamString response;
Todd Fialaaf245d12014-06-30 21:05:18 +00001772
1773 if (IsGdbServer ())
Greg Clayton8b82f082011-04-12 05:54:46 +00001774 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001775 // Fail if we don't have a current process.
1776 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1777 return SendErrorResponse (68);
1778
1779 // Make sure we set the current thread so g and p packets return
1780 // the data the gdb will expect.
1781 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1782 SetCurrentThreadID (tid);
1783
1784 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1785 if (!thread_sp)
1786 return SendErrorResponse (69);
1787
1788 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1789 }
1790 else
1791 {
1792 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here
1793 // should not be used. It is reporting process id instead of thread id. The
1794 // correct answer doesn't seem to make much sense for lldb-platform.
1795 // CONSIDER: flip to "unsupported".
1796 lldb::pid_t pid = m_process_launch_info.GetProcessID();
1797 response.Printf("QC%" PRIx64, pid);
1798
1799 // this should always be platform here
1800 assert (m_is_platform && "this code path should only be traversed for lldb-platform");
1801
1802 if (m_is_platform)
Greg Clayton8b82f082011-04-12 05:54:46 +00001803 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001804 // If we launch a process and this GDB server is acting as a platform,
1805 // then we need to clear the process launch state so we can start
1806 // launching another process. In order to launch a process a bunch or
1807 // packets need to be sent: environment packets, working directory,
1808 // disable ASLR, and many more settings. When we launch a process we
1809 // then need to know when to clear this information. Currently we are
1810 // selecting the 'qC' packet as that packet which seems to make the most
1811 // sense.
1812 if (pid != LLDB_INVALID_PROCESS_ID)
1813 {
1814 m_process_launch_info.Clear();
1815 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001816 }
1817 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001818 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00001819}
1820
1821bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00001822GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
1823{
1824 Mutex::Locker locker (m_spawned_pids_mutex);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001825 FreePortForProcess(pid);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001826 return m_spawned_pids.erase(pid) > 0;
1827}
1828bool
1829GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
1830 lldb::pid_t pid,
1831 bool exited,
1832 int signal, // Zero for no signal
1833 int status) // Exit value of process if signal is zero
1834{
1835 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1836 server->DebugserverProcessReaped (pid);
1837 return true;
1838}
1839
Todd Fiala3e92a2b2014-01-24 00:52:53 +00001840bool
1841GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
1842{
1843 // reap a process that we were debugging (but not debugserver)
1844 Mutex::Locker locker (m_spawned_pids_mutex);
1845 return m_spawned_pids.erase(pid) > 0;
1846}
1847
1848bool
1849GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
1850 lldb::pid_t pid,
1851 bool exited,
1852 int signal, // Zero for no signal
1853 int status) // Exit value of process if signal is zero
1854{
1855 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1856 server->DebuggedProcessReaped (pid);
1857 return true;
1858}
1859
Greg Clayton3dedae12013-12-06 21:45:27 +00001860GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001861GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
1862{
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001863#ifdef _WIN32
Deepak Panickal263fde02014-01-14 11:34:44 +00001864 return SendErrorResponse(9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001865#else
Todd Fiala015d8182014-07-22 23:41:36 +00001866 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1867
Greg Clayton8b82f082011-04-12 05:54:46 +00001868 // Spawn a local debugserver as a platform so we can then attach or launch
1869 // a process...
1870
1871 if (m_is_platform)
1872 {
Todd Fiala015d8182014-07-22 23:41:36 +00001873 if (log)
1874 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
1875
Greg Clayton8b82f082011-04-12 05:54:46 +00001876 // Sleep and wait a bit for debugserver to start to listen...
1877 ConnectionFileDescriptor file_conn;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001878 std::string hostname;
Sylvestre Ledrufaa63ce2013-09-28 15:57:37 +00001879 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001880 // with the TMPDIR environment variable
Greg Clayton29b8fc42013-11-21 01:44:58 +00001881 packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
1882 std::string name;
1883 std::string value;
1884 uint16_t port = UINT16_MAX;
1885 while (packet.GetNameColonValue(name, value))
Greg Clayton8b82f082011-04-12 05:54:46 +00001886 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001887 if (name.compare ("host") == 0)
1888 hostname.swap(value);
1889 else if (name.compare ("port") == 0)
1890 port = Args::StringToUInt32(value.c_str(), 0, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00001891 }
Greg Clayton29b8fc42013-11-21 01:44:58 +00001892 if (port == UINT16_MAX)
1893 port = GetNextAvailablePort();
1894
1895 // Spawn a new thread to accept the port that gets bound after
1896 // binding to port 0 (zero).
Greg Claytonfbb76342013-11-20 21:07:01 +00001897
Todd Fiala015d8182014-07-22 23:41:36 +00001898 // Spawn a debugserver and try to get the port it listens to.
1899 ProcessLaunchInfo debugserver_launch_info;
1900 if (hostname.empty())
1901 hostname = "127.0.0.1";
1902 if (log)
1903 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
1904
1905 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
1906
1907 Error error = StartDebugserverProcess (hostname.empty() ? NULL : hostname.c_str(),
1908 port,
1909 debugserver_launch_info,
1910 port);
1911
1912 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
1913
1914
1915 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1916 {
1917 Mutex::Locker locker (m_spawned_pids_mutex);
1918 m_spawned_pids.insert(debugserver_pid);
1919 if (port > 0)
1920 AssociatePortWithProcess(port, debugserver_pid);
1921 }
1922 else
1923 {
1924 if (port > 0)
1925 FreePort (port);
1926 }
1927
Greg Clayton29b8fc42013-11-21 01:44:58 +00001928 if (error.Success())
1929 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001930 if (log)
Todd Fiala015d8182014-07-22 23:41:36 +00001931 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001932
Todd Fiala015d8182014-07-22 23:41:36 +00001933 char response[256];
1934 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
1935 assert (response_len < (int)sizeof(response));
1936 PacketResult packet_result = SendPacketNoLock (response, response_len);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001937
Todd Fiala015d8182014-07-22 23:41:36 +00001938 if (packet_result != PacketResult::Success)
Greg Clayton29b8fc42013-11-21 01:44:58 +00001939 {
Todd Fiala015d8182014-07-22 23:41:36 +00001940 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1941 ::kill (debugserver_pid, SIGINT);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001942 }
Todd Fiala015d8182014-07-22 23:41:36 +00001943 return packet_result;
1944 }
1945 else
1946 {
1947 if (log)
1948 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ());
Greg Clayton8b82f082011-04-12 05:54:46 +00001949 }
1950 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001951 return SendErrorResponse (9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001952#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00001953}
1954
Todd Fiala403edc52014-01-23 22:05:44 +00001955bool
1956GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
1957{
1958 // make sure we know about this process
1959 {
1960 Mutex::Locker locker (m_spawned_pids_mutex);
1961 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1962 return false;
1963 }
1964
1965 // first try a SIGTERM (standard kill)
1966 Host::Kill (pid, SIGTERM);
1967
1968 // check if that worked
1969 for (size_t i=0; i<10; ++i)
1970 {
1971 {
1972 Mutex::Locker locker (m_spawned_pids_mutex);
1973 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1974 {
1975 // it is now killed
1976 return true;
1977 }
1978 }
1979 usleep (10000);
1980 }
1981
1982 // check one more time after the final usleep
1983 {
1984 Mutex::Locker locker (m_spawned_pids_mutex);
1985 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1986 return true;
1987 }
1988
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001989 // the launched process still lives. Now try killing it again,
Todd Fiala403edc52014-01-23 22:05:44 +00001990 // this time with an unblockable signal.
1991 Host::Kill (pid, SIGKILL);
1992
1993 for (size_t i=0; i<10; ++i)
1994 {
1995 {
1996 Mutex::Locker locker (m_spawned_pids_mutex);
1997 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1998 {
1999 // it is now killed
2000 return true;
2001 }
2002 }
2003 usleep (10000);
2004 }
2005
2006 // check one more time after the final usleep
2007 // Scope for locker
2008 {
2009 Mutex::Locker locker (m_spawned_pids_mutex);
2010 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2011 return true;
2012 }
2013
2014 // no luck - the process still lives
2015 return false;
2016}
2017
Greg Clayton3dedae12013-12-06 21:45:27 +00002018GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002019GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
2020{
Todd Fiala403edc52014-01-23 22:05:44 +00002021 packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002022
Todd Fiala403edc52014-01-23 22:05:44 +00002023 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
2024
2025 // verify that we know anything about this pid.
2026 // Scope for locker
Daniel Maleae0f8f572013-08-26 23:57:52 +00002027 {
Todd Fiala403edc52014-01-23 22:05:44 +00002028 Mutex::Locker locker (m_spawned_pids_mutex);
2029 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002030 {
Todd Fiala403edc52014-01-23 22:05:44 +00002031 // not a pid we know about
2032 return SendErrorResponse (10);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002033 }
2034 }
Todd Fiala403edc52014-01-23 22:05:44 +00002035
2036 // go ahead and attempt to kill the spawned process
2037 if (KillSpawnedProcess (pid))
2038 return SendOKResponse ();
2039 else
2040 return SendErrorResponse (11);
2041}
2042
2043GDBRemoteCommunication::PacketResult
2044GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
2045{
2046 // ignore for now if we're lldb_platform
2047 if (m_is_platform)
2048 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2049
2050 // shutdown all spawned processes
2051 std::set<lldb::pid_t> spawned_pids_copy;
2052
2053 // copy pids
2054 {
2055 Mutex::Locker locker (m_spawned_pids_mutex);
2056 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
2057 }
2058
2059 // nuke the spawned processes
2060 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
2061 {
2062 lldb::pid_t spawned_pid = *it;
2063 if (!KillSpawnedProcess (spawned_pid))
2064 {
2065 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
2066 }
2067 }
2068
Todd Fialaaf245d12014-06-30 21:05:18 +00002069 FlushInferiorOutput ();
2070
2071 // No OK response for kill packet.
2072 // return SendOKResponse ();
2073 return PacketResult::Success;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002074}
2075
Greg Clayton3dedae12013-12-06 21:45:27 +00002076GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002077GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
2078{
2079 if (m_process_launch_error.Success())
2080 return SendOKResponse();
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002081 StreamString response;
Greg Clayton8b82f082011-04-12 05:54:46 +00002082 response.PutChar('E');
2083 response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
Greg Clayton37a0a242012-04-11 00:24:49 +00002084 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00002085}
2086
Greg Clayton3dedae12013-12-06 21:45:27 +00002087GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002088GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet)
2089{
2090 packet.SetFilePos(::strlen ("QEnvironment:"));
2091 const uint32_t bytes_left = packet.GetBytesLeft();
2092 if (bytes_left > 0)
2093 {
2094 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
2095 return SendOKResponse ();
2096 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002097 return SendErrorResponse (12);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002098}
2099
Greg Clayton3dedae12013-12-06 21:45:27 +00002100GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002101GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
2102{
2103 packet.SetFilePos(::strlen ("QLaunchArch:"));
2104 const uint32_t bytes_left = packet.GetBytesLeft();
2105 if (bytes_left > 0)
2106 {
2107 const char* arch_triple = packet.Peek();
2108 ArchSpec arch_spec(arch_triple,NULL);
2109 m_process_launch_info.SetArchitecture(arch_spec);
2110 return SendOKResponse();
2111 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002112 return SendErrorResponse(13);
Greg Clayton8b82f082011-04-12 05:54:46 +00002113}
2114
Greg Clayton3dedae12013-12-06 21:45:27 +00002115GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002116GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
2117{
2118 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
2119 if (packet.GetU32(0))
2120 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
2121 else
2122 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
2123 return SendOKResponse ();
2124}
2125
Greg Clayton3dedae12013-12-06 21:45:27 +00002126GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002127GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
2128{
2129 packet.SetFilePos(::strlen ("QSetWorkingDir:"));
2130 std::string path;
2131 packet.GetHexByteString(path);
Greg Claytonfbb76342013-11-20 21:07:01 +00002132 if (m_is_platform)
2133 {
Colin Riley909bb7a2013-11-26 15:10:46 +00002134#ifdef _WIN32
2135 // Not implemented on Windows
2136 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
2137#else
Greg Claytonfbb76342013-11-20 21:07:01 +00002138 // If this packet is sent to a platform, then change the current working directory
2139 if (::chdir(path.c_str()) != 0)
2140 return SendErrorResponse(errno);
Colin Riley909bb7a2013-11-26 15:10:46 +00002141#endif
Greg Claytonfbb76342013-11-20 21:07:01 +00002142 }
2143 else
2144 {
2145 m_process_launch_info.SwapWorkingDirectory (path);
2146 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002147 return SendOKResponse ();
2148}
2149
Greg Clayton3dedae12013-12-06 21:45:27 +00002150GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002151GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
2152{
2153 StreamString response;
2154
2155 if (m_is_platform)
2156 {
2157 // If this packet is sent to a platform, then change the current working directory
2158 char cwd[PATH_MAX];
2159 if (getcwd(cwd, sizeof(cwd)) == NULL)
2160 {
2161 return SendErrorResponse(errno);
2162 }
2163 else
2164 {
2165 response.PutBytesAsRawHex8(cwd, strlen(cwd));
Greg Clayton3dedae12013-12-06 21:45:27 +00002166 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002167 }
2168 }
2169 else
2170 {
2171 const char *working_dir = m_process_launch_info.GetWorkingDirectory();
2172 if (working_dir && working_dir[0])
2173 {
2174 response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
Greg Clayton3dedae12013-12-06 21:45:27 +00002175 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002176 }
2177 else
2178 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002179 return SendErrorResponse(14);
Greg Claytonfbb76342013-11-20 21:07:01 +00002180 }
2181 }
2182}
2183
Greg Clayton3dedae12013-12-06 21:45:27 +00002184GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002185GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
2186{
2187 packet.SetFilePos(::strlen ("QSetSTDIN:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002188 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002189 std::string path;
2190 packet.GetHexByteString(path);
2191 const bool read = false;
2192 const bool write = true;
2193 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
2194 {
2195 m_process_launch_info.AppendFileAction(file_action);
2196 return SendOKResponse ();
2197 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002198 return SendErrorResponse (15);
Greg Clayton8b82f082011-04-12 05:54:46 +00002199}
2200
Greg Clayton3dedae12013-12-06 21:45:27 +00002201GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002202GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
2203{
2204 packet.SetFilePos(::strlen ("QSetSTDOUT:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002205 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002206 std::string path;
2207 packet.GetHexByteString(path);
2208 const bool read = true;
2209 const bool write = false;
2210 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
2211 {
2212 m_process_launch_info.AppendFileAction(file_action);
2213 return SendOKResponse ();
2214 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002215 return SendErrorResponse (16);
Greg Clayton8b82f082011-04-12 05:54:46 +00002216}
2217
Greg Clayton3dedae12013-12-06 21:45:27 +00002218GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002219GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
2220{
2221 packet.SetFilePos(::strlen ("QSetSTDERR:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002222 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002223 std::string path;
2224 packet.GetHexByteString(path);
2225 const bool read = true;
Greg Clayton9845a8d2012-03-06 04:01:04 +00002226 const bool write = false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002227 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
2228 {
2229 m_process_launch_info.AppendFileAction(file_action);
2230 return SendOKResponse ();
2231 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002232 return SendErrorResponse (17);
Greg Clayton8b82f082011-04-12 05:54:46 +00002233}
2234
Greg Clayton3dedae12013-12-06 21:45:27 +00002235GDBRemoteCommunication::PacketResult
Todd Fialaaf245d12014-06-30 21:05:18 +00002236GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet)
2237{
2238 if (!IsGdbServer ())
2239 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2240
2241 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2242 if (log)
2243 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2244
2245 // Ensure we have a native process.
2246 if (!m_debugged_process_sp)
2247 {
2248 if (log)
2249 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2250 return SendErrorResponse (0x36);
2251 }
2252
2253 // Pull out the signal number.
2254 packet.SetFilePos (::strlen ("C"));
2255 if (packet.GetBytesLeft () < 1)
2256 {
2257 // Shouldn't be using a C without a signal.
2258 return SendIllFormedResponse (packet, "C packet specified without signal.");
2259 }
2260 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2261 if (signo == std::numeric_limits<uint32_t>::max ())
2262 return SendIllFormedResponse (packet, "failed to parse signal number");
2263
2264 // Handle optional continue address.
2265 if (packet.GetBytesLeft () > 0)
2266 {
2267 // FIXME add continue at address support for $C{signo}[;{continue-address}].
2268 if (*packet.Peek () == ';')
2269 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2270 else
2271 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
2272 }
2273
2274 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
2275 Error error;
2276
2277 // We have two branches: what to do if a continue thread is specified (in which case we target
2278 // sending the signal to that thread), or when we don't have a continue thread set (in which
2279 // case we send a signal to the process).
2280
2281 // TODO discuss with Greg Clayton, make sure this makes sense.
2282
2283 lldb::tid_t signal_tid = GetContinueThreadID ();
2284 if (signal_tid != LLDB_INVALID_THREAD_ID)
2285 {
2286 // The resume action for the continue thread (or all threads if a continue thread is not set).
2287 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
2288
2289 // Add the action for the continue thread (or all threads when the continue thread isn't present).
2290 resume_actions.Append (action);
2291 }
2292 else
2293 {
2294 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
2295 error = m_debugged_process_sp->Signal (signo);
2296 if (error.Fail ())
2297 {
2298 if (log)
2299 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s",
2300 __FUNCTION__,
2301 m_debugged_process_sp->GetID (),
2302 error.AsCString ());
2303
2304 return SendErrorResponse (0x52);
2305 }
2306 }
2307
2308 // Resume the threads.
2309 error = m_debugged_process_sp->Resume (resume_actions);
2310 if (error.Fail ())
2311 {
2312 if (log)
2313 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s",
2314 __FUNCTION__,
2315 m_debugged_process_sp->GetID (),
2316 error.AsCString ());
2317
2318 return SendErrorResponse (0x38);
2319 }
2320
2321 // Don't send an "OK" packet; response is the stopped/exited message.
2322 return PacketResult::Success;
2323}
2324
2325GDBRemoteCommunication::PacketResult
2326GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment)
2327{
2328 if (!IsGdbServer ())
2329 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2330
2331 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2332 if (log)
2333 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2334
2335 // We reuse this method in vCont - don't double adjust the file position.
2336 if (!skip_file_pos_adjustment)
2337 packet.SetFilePos (::strlen ("c"));
2338
2339 // For now just support all continue.
2340 const bool has_continue_address = (packet.GetBytesLeft () > 0);
2341 if (has_continue_address)
2342 {
2343 if (log)
2344 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
2345 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2346 }
2347
2348 // Ensure we have a native process.
2349 if (!m_debugged_process_sp)
2350 {
2351 if (log)
2352 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2353 return SendErrorResponse (0x36);
2354 }
2355
2356 // Build the ResumeActionList
2357 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
2358
2359 Error error = m_debugged_process_sp->Resume (actions);
2360 if (error.Fail ())
2361 {
2362 if (log)
2363 {
2364 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s",
2365 __FUNCTION__,
2366 m_debugged_process_sp->GetID (),
2367 error.AsCString ());
2368 }
2369 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2370 }
2371
2372 if (log)
2373 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2374
2375 // No response required from continue.
2376 return PacketResult::Success;
2377}
2378
2379GDBRemoteCommunication::PacketResult
2380GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet)
2381{
2382 if (!IsGdbServer ())
2383 {
2384 // only llgs supports $vCont.
2385 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2386 }
2387
Todd Fialaaf245d12014-06-30 21:05:18 +00002388 StreamString response;
2389 response.Printf("vCont;c;C;s;S");
2390
2391 return SendPacketNoLock(response.GetData(), response.GetSize());
2392}
2393
2394GDBRemoteCommunication::PacketResult
2395GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet)
2396{
2397 if (!IsGdbServer ())
2398 {
2399 // only llgs supports $vCont
2400 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2401 }
2402
2403 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2404 if (log)
2405 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__);
2406
2407 packet.SetFilePos (::strlen ("vCont"));
2408
2409 // Check if this is all continue (no options or ";c").
2410 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0))
2411 {
2412 // Move the packet past the ";c".
2413 if (packet.GetBytesLeft ())
2414 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c"));
2415
2416 const bool skip_file_pos_adjustment = true;
2417 return Handle_c (packet, skip_file_pos_adjustment);
2418 }
2419 else if (::strcmp (packet.Peek (), ";s") == 0)
2420 {
2421 // Move past the ';', then do a simple 's'.
2422 packet.SetFilePos (packet.GetFilePos () + 1);
2423 return Handle_s (packet);
2424 }
2425
2426 // Ensure we have a native process.
2427 if (!m_debugged_process_sp)
2428 {
2429 if (log)
2430 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2431 return SendErrorResponse (0x36);
2432 }
2433
2434 ResumeActionList thread_actions;
2435
2436 while (packet.GetBytesLeft () && *packet.Peek () == ';')
2437 {
2438 // Skip the semi-colon.
2439 packet.GetChar ();
2440
2441 // Build up the thread action.
2442 ResumeAction thread_action;
2443 thread_action.tid = LLDB_INVALID_THREAD_ID;
2444 thread_action.state = eStateInvalid;
2445 thread_action.signal = 0;
2446
2447 const char action = packet.GetChar ();
2448 switch (action)
2449 {
2450 case 'C':
2451 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2452 if (thread_action.signal == 0)
2453 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
2454 // Fall through to next case...
2455
2456 case 'c':
2457 // Continue
2458 thread_action.state = eStateRunning;
2459 break;
2460
2461 case 'S':
2462 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2463 if (thread_action.signal == 0)
2464 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
2465 // Fall through to next case...
2466
2467 case 's':
2468 // Step
2469 thread_action.state = eStateStepping;
2470 break;
2471
2472 default:
2473 return SendIllFormedResponse (packet, "Unsupported vCont action");
2474 break;
2475 }
2476
2477 // Parse out optional :{thread-id} value.
2478 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
2479 {
2480 // Consume the separator.
2481 packet.GetChar ();
2482
2483 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2484 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
2485 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
2486 }
2487
2488 thread_actions.Append (thread_action);
2489 }
2490
2491 // If a default action for all other threads wasn't mentioned
2492 // then we should stop the threads.
2493 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0);
2494
2495 Error error = m_debugged_process_sp->Resume (thread_actions);
2496 if (error.Fail ())
2497 {
2498 if (log)
2499 {
2500 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s",
2501 __FUNCTION__,
2502 m_debugged_process_sp->GetID (),
2503 error.AsCString ());
2504 }
2505 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2506 }
2507
2508 if (log)
2509 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2510
2511 // No response required from vCont.
2512 return PacketResult::Success;
2513}
2514
2515GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00002516GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
2517{
2518 // Send response first before changing m_send_acks to we ack this packet
Greg Clayton3dedae12013-12-06 21:45:27 +00002519 PacketResult packet_result = SendOKResponse ();
Greg Clayton1cb64962011-03-24 04:28:38 +00002520 m_send_acks = false;
Greg Clayton3dedae12013-12-06 21:45:27 +00002521 return packet_result;
Greg Clayton1cb64962011-03-24 04:28:38 +00002522}
Daniel Maleae0f8f572013-08-26 23:57:52 +00002523
Greg Clayton3dedae12013-12-06 21:45:27 +00002524GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002525GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002526{
Greg Claytonfbb76342013-11-20 21:07:01 +00002527 packet.SetFilePos(::strlen("qPlatform_mkdir:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002528 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002529 if (packet.GetChar() == ',')
2530 {
2531 std::string path;
2532 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002533 Error error = FileSystem::MakeDirectory(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002534 if (error.Success())
2535 return SendPacketNoLock ("OK", 2);
2536 else
2537 return SendErrorResponse(error.GetError());
2538 }
2539 return SendErrorResponse(20);
Greg Claytonfbb76342013-11-20 21:07:01 +00002540}
2541
Greg Clayton3dedae12013-12-06 21:45:27 +00002542GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002543GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
2544{
2545 packet.SetFilePos(::strlen("qPlatform_chmod:"));
2546
2547 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002548 if (packet.GetChar() == ',')
2549 {
2550 std::string path;
2551 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002552 Error error = FileSystem::SetFilePermissions(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002553 if (error.Success())
2554 return SendPacketNoLock ("OK", 2);
2555 else
2556 return SendErrorResponse(error.GetError());
2557 }
2558 return SendErrorResponse(19);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002559}
2560
Greg Clayton3dedae12013-12-06 21:45:27 +00002561GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002562GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
2563{
2564 packet.SetFilePos(::strlen("vFile:open:"));
2565 std::string path;
2566 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002567 if (!path.empty())
2568 {
2569 if (packet.GetChar() == ',')
2570 {
2571 uint32_t flags = packet.GetHexMaxU32(false, 0);
2572 if (packet.GetChar() == ',')
2573 {
2574 mode_t mode = packet.GetHexMaxU32(false, 0600);
2575 Error error;
2576 int fd = ::open (path.c_str(), flags, mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002577 const int save_errno = fd == -1 ? errno : 0;
2578 StreamString response;
2579 response.PutChar('F');
2580 response.Printf("%i", fd);
2581 if (save_errno)
2582 response.Printf(",%i", save_errno);
2583 return SendPacketNoLock(response.GetData(), response.GetSize());
2584 }
2585 }
2586 }
2587 return SendErrorResponse(18);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002588}
2589
Greg Clayton3dedae12013-12-06 21:45:27 +00002590GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002591GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
2592{
2593 packet.SetFilePos(::strlen("vFile:close:"));
2594 int fd = packet.GetS32(-1);
2595 Error error;
2596 int err = -1;
2597 int save_errno = 0;
2598 if (fd >= 0)
2599 {
2600 err = close(fd);
2601 save_errno = err == -1 ? errno : 0;
2602 }
2603 else
2604 {
2605 save_errno = EINVAL;
2606 }
2607 StreamString response;
2608 response.PutChar('F');
2609 response.Printf("%i", err);
2610 if (save_errno)
2611 response.Printf(",%i", save_errno);
Greg Clayton2b98c562013-11-22 18:53:12 +00002612 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002613}
2614
Greg Clayton3dedae12013-12-06 21:45:27 +00002615GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002616GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
2617{
Virgile Belloae12a362013-08-27 16:21:49 +00002618#ifdef _WIN32
2619 // Not implemented on Windows
Greg Clayton2b98c562013-11-22 18:53:12 +00002620 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002621#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002622 StreamGDBRemote response;
2623 packet.SetFilePos(::strlen("vFile:pread:"));
2624 int fd = packet.GetS32(-1);
Greg Clayton2b98c562013-11-22 18:53:12 +00002625 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002626 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002627 uint64_t count = packet.GetU64(UINT64_MAX);
2628 if (packet.GetChar() == ',')
2629 {
2630 uint64_t offset = packet.GetU64(UINT32_MAX);
2631 if (count == UINT64_MAX)
2632 {
2633 response.Printf("F-1:%i", EINVAL);
2634 return SendPacketNoLock(response.GetData(), response.GetSize());
2635 }
2636
2637 std::string buffer(count, 0);
2638 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
2639 const int save_errno = bytes_read == -1 ? errno : 0;
2640 response.PutChar('F');
2641 response.Printf("%zi", bytes_read);
2642 if (save_errno)
2643 response.Printf(",%i", save_errno);
2644 else
2645 {
2646 response.PutChar(';');
2647 response.PutEscapedBytes(&buffer[0], bytes_read);
2648 }
2649 return SendPacketNoLock(response.GetData(), response.GetSize());
2650 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002651 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002652 return SendErrorResponse(21);
2653
Virgile Belloae12a362013-08-27 16:21:49 +00002654#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002655}
2656
Greg Clayton3dedae12013-12-06 21:45:27 +00002657GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002658GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
2659{
Virgile Belloae12a362013-08-27 16:21:49 +00002660#ifdef _WIN32
Greg Clayton2b98c562013-11-22 18:53:12 +00002661 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002662#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002663 packet.SetFilePos(::strlen("vFile:pwrite:"));
2664
2665 StreamGDBRemote response;
2666 response.PutChar('F');
2667
2668 int fd = packet.GetU32(UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002669 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002670 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002671 off_t offset = packet.GetU64(UINT32_MAX);
2672 if (packet.GetChar() == ',')
2673 {
2674 std::string buffer;
2675 if (packet.GetEscapedBinaryData(buffer))
2676 {
2677 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
2678 const int save_errno = bytes_written == -1 ? errno : 0;
2679 response.Printf("%zi", bytes_written);
2680 if (save_errno)
2681 response.Printf(",%i", save_errno);
2682 }
2683 else
2684 {
2685 response.Printf ("-1,%i", EINVAL);
2686 }
2687 return SendPacketNoLock(response.GetData(), response.GetSize());
2688 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002689 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002690 return SendErrorResponse(27);
Virgile Belloae12a362013-08-27 16:21:49 +00002691#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002692}
2693
Greg Clayton3dedae12013-12-06 21:45:27 +00002694GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002695GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet)
2696{
2697 packet.SetFilePos(::strlen("vFile:size:"));
2698 std::string path;
2699 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002700 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002701 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002702 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002703 StreamString response;
2704 response.PutChar('F');
2705 response.PutHex64(retcode);
2706 if (retcode == UINT64_MAX)
2707 {
2708 response.PutChar(',');
2709 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
2710 }
2711 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002712 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002713 return SendErrorResponse(22);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002714}
2715
Greg Clayton3dedae12013-12-06 21:45:27 +00002716GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002717GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
2718{
2719 packet.SetFilePos(::strlen("vFile:mode:"));
2720 std::string path;
2721 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002722 if (!path.empty())
2723 {
2724 Error error;
2725 const uint32_t mode = File::GetPermissions(path.c_str(), error);
2726 StreamString response;
2727 response.Printf("F%u", mode);
2728 if (mode == 0 || error.Fail())
2729 response.Printf(",%i", (int)error.GetError());
2730 return SendPacketNoLock(response.GetData(), response.GetSize());
2731 }
2732 return SendErrorResponse(23);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002733}
2734
Greg Clayton3dedae12013-12-06 21:45:27 +00002735GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002736GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
2737{
2738 packet.SetFilePos(::strlen("vFile:exists:"));
2739 std::string path;
2740 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002741 if (!path.empty())
2742 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002743 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002744 StreamString response;
2745 response.PutChar('F');
2746 response.PutChar(',');
2747 if (retcode)
2748 response.PutChar('1');
2749 else
2750 response.PutChar('0');
2751 return SendPacketNoLock(response.GetData(), response.GetSize());
2752 }
2753 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002754}
2755
Greg Clayton3dedae12013-12-06 21:45:27 +00002756GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002757GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002758{
Greg Claytonfbb76342013-11-20 21:07:01 +00002759 packet.SetFilePos(::strlen("vFile:symlink:"));
2760 std::string dst, src;
2761 packet.GetHexByteStringTerminatedBy(dst, ',');
2762 packet.GetChar(); // Skip ',' char
2763 packet.GetHexByteString(src);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002764 Error error = FileSystem::Symlink(src.c_str(), dst.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002765 StreamString response;
2766 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002767 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002768}
2769
Greg Clayton3dedae12013-12-06 21:45:27 +00002770GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002771GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
2772{
2773 packet.SetFilePos(::strlen("vFile:unlink:"));
2774 std::string path;
2775 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002776 Error error = FileSystem::Unlink(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002777 StreamString response;
2778 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002779 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002780}
2781
Greg Clayton3dedae12013-12-06 21:45:27 +00002782GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002783GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
2784{
2785 packet.SetFilePos(::strlen("qPlatform_shell:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002786 std::string path;
2787 std::string working_dir;
2788 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002789 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002790 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002791 if (packet.GetChar() == ',')
2792 {
2793 // FIXME: add timeout to qPlatform_shell packet
2794 // uint32_t timeout = packet.GetHexMaxU32(false, 32);
2795 uint32_t timeout = 10;
2796 if (packet.GetChar() == ',')
2797 packet.GetHexByteString(working_dir);
2798 int status, signo;
2799 std::string output;
2800 Error err = Host::RunShellCommand(path.c_str(),
2801 working_dir.empty() ? NULL : working_dir.c_str(),
2802 &status, &signo, &output, timeout);
2803 StreamGDBRemote response;
2804 if (err.Fail())
2805 {
2806 response.PutCString("F,");
2807 response.PutHex32(UINT32_MAX);
2808 }
2809 else
2810 {
2811 response.PutCString("F,");
2812 response.PutHex32(status);
2813 response.PutChar(',');
2814 response.PutHex32(signo);
2815 response.PutChar(',');
2816 response.PutEscapedBytes(output.c_str(), output.size());
2817 }
2818 return SendPacketNoLock(response.GetData(), response.GetSize());
2819 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002820 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002821 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002822}
2823
Todd Fialaaf245d12014-06-30 21:05:18 +00002824void
2825GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid)
2826{
2827 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code");
2828
2829 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2830 if (log)
2831 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
2832
2833 m_current_tid = tid;
2834 if (m_debugged_process_sp)
2835 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
2836}
2837
2838void
2839GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid)
2840{
2841 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code");
2842
2843 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2844 if (log)
2845 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
2846
2847 m_continue_tid = tid;
2848}
2849
2850GDBRemoteCommunication::PacketResult
2851GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet)
2852{
2853 // Handle the $? gdbremote command.
2854 if (!IsGdbServer ())
2855 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented");
2856
2857 // If no process, indicate error
2858 if (!m_debugged_process_sp)
2859 return SendErrorResponse (02);
2860
2861 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2862}
2863
2864GDBRemoteCommunication::PacketResult
2865GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
2866{
2867 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2868
2869 switch (process_state)
2870 {
2871 case eStateAttaching:
2872 case eStateLaunching:
2873 case eStateRunning:
2874 case eStateStepping:
2875 case eStateDetached:
2876 // NOTE: gdb protocol doc looks like it should return $OK
2877 // when everything is running (i.e. no stopped result).
2878 return PacketResult::Success; // Ignore
2879
2880 case eStateSuspended:
2881 case eStateStopped:
2882 case eStateCrashed:
2883 {
2884 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
2885 // Make sure we set the current thread so g and p packets return
2886 // the data the gdb will expect.
2887 SetCurrentThreadID (tid);
2888 return SendStopReplyPacketForThread (tid);
2889 }
2890
2891 case eStateInvalid:
2892 case eStateUnloaded:
2893 case eStateExited:
2894 if (flush_on_exit)
2895 FlushInferiorOutput ();
2896 return SendWResponse(m_debugged_process_sp.get());
2897
2898 default:
2899 if (log)
2900 {
2901 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s",
2902 __FUNCTION__,
2903 m_debugged_process_sp->GetID (),
2904 StateAsCString (process_state));
2905 }
2906 break;
2907 }
2908
2909 return SendErrorResponse (0);
2910}
2911
Greg Clayton3dedae12013-12-06 21:45:27 +00002912GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002913GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
2914{
Greg Clayton2b98c562013-11-22 18:53:12 +00002915 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002916}
2917
Greg Clayton3dedae12013-12-06 21:45:27 +00002918GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002919GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
2920{
Greg Clayton2b98c562013-11-22 18:53:12 +00002921 packet.SetFilePos(::strlen("vFile:MD5:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002922 std::string path;
2923 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002924 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002925 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002926 uint64_t a,b;
2927 StreamGDBRemote response;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002928 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false)
Greg Clayton2b98c562013-11-22 18:53:12 +00002929 {
2930 response.PutCString("F,");
2931 response.PutCString("x");
2932 }
2933 else
2934 {
2935 response.PutCString("F,");
2936 response.PutHex64(a);
2937 response.PutHex64(b);
2938 }
2939 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002940 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002941 return SendErrorResponse(25);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002942}
Greg Clayton2b98c562013-11-22 18:53:12 +00002943
Todd Fialaaf245d12014-06-30 21:05:18 +00002944GDBRemoteCommunication::PacketResult
2945GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
2946{
2947 // Ensure we're llgs.
2948 if (!IsGdbServer())
2949 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented");
2950
2951 // Fail if we don't have a current process.
2952 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2953 return SendErrorResponse (68);
2954
2955 // Ensure we have a thread.
2956 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
2957 if (!thread_sp)
2958 return SendErrorResponse (69);
2959
2960 // Get the register context for the first thread.
2961 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2962 if (!reg_context_sp)
2963 return SendErrorResponse (69);
2964
2965 // Parse out the register number from the request.
2966 packet.SetFilePos (strlen("qRegisterInfo"));
2967 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2968 if (reg_index == std::numeric_limits<uint32_t>::max ())
2969 return SendErrorResponse (69);
2970
2971 // Return the end of registers response if we've iterated one past the end of the register set.
2972 if (reg_index >= reg_context_sp->GetRegisterCount ())
2973 return SendErrorResponse (69);
2974
2975 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2976 if (!reg_info)
2977 return SendErrorResponse (69);
2978
2979 // Build the reginfos response.
2980 StreamGDBRemote response;
2981
2982 response.PutCString ("name:");
2983 response.PutCString (reg_info->name);
2984 response.PutChar (';');
2985
2986 if (reg_info->alt_name && reg_info->alt_name[0])
2987 {
2988 response.PutCString ("alt-name:");
2989 response.PutCString (reg_info->alt_name);
2990 response.PutChar (';');
2991 }
2992
2993 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
2994
2995 switch (reg_info->encoding)
2996 {
2997 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
2998 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
2999 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
3000 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
3001 default: break;
3002 }
3003
3004 switch (reg_info->format)
3005 {
3006 case eFormatBinary: response.PutCString ("format:binary;"); break;
3007 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
3008 case eFormatHex: response.PutCString ("format:hex;"); break;
3009 case eFormatFloat: response.PutCString ("format:float;"); break;
3010 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
3011 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
3012 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
3013 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
3014 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
3015 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
3016 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
3017 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
3018 default: break;
3019 };
3020
3021 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
3022 if (register_set_name)
3023 {
3024 response.PutCString ("set:");
3025 response.PutCString (register_set_name);
3026 response.PutChar (';');
3027 }
3028
3029 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
3030 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
3031
3032 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
3033 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3034
3035 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
3036 {
3037 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
3038 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
3039 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
3040 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
3041 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
3042 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
3043 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
3044 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
3045 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
3046 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
3047 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
3048 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
3049 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
3050 default: break;
3051 }
3052
3053 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
3054 {
3055 response.PutCString ("container-regs:");
3056 int i = 0;
3057 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3058 {
3059 if (i > 0)
3060 response.PutChar (',');
3061 response.Printf ("%" PRIx32, *reg_num);
3062 }
3063 response.PutChar (';');
3064 }
3065
3066 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
3067 {
3068 response.PutCString ("invalidate-regs:");
3069 int i = 0;
3070 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3071 {
3072 if (i > 0)
3073 response.PutChar (',');
3074 response.Printf ("%" PRIx32, *reg_num);
3075 }
3076 response.PutChar (';');
3077 }
3078
3079 return SendPacketNoLock(response.GetData(), response.GetSize());
3080}
3081
3082GDBRemoteCommunication::PacketResult
3083GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
3084{
3085 // Ensure we're llgs.
3086 if (!IsGdbServer())
3087 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented");
3088
Todd Fiala24189d42014-07-14 06:24:44 +00003089 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3090
Todd Fialaaf245d12014-06-30 21:05:18 +00003091 // Fail if we don't have a current process.
3092 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
Todd Fiala24189d42014-07-14 06:24:44 +00003093 {
3094 if (log)
3095 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
3096 return SendOKResponse ();
3097 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003098
3099 StreamGDBRemote response;
3100 response.PutChar ('m');
3101
Todd Fiala24189d42014-07-14 06:24:44 +00003102 if (log)
3103 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__);
3104
Todd Fialaaf245d12014-06-30 21:05:18 +00003105 NativeThreadProtocolSP thread_sp;
3106 uint32_t thread_index;
3107 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
3108 thread_sp;
3109 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
3110 {
Todd Fiala24189d42014-07-14 06:24:44 +00003111 if (log)
3112 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 +00003113 if (thread_index > 0)
3114 response.PutChar(',');
3115 response.Printf ("%" PRIx64, thread_sp->GetID ());
3116 }
3117
Todd Fiala24189d42014-07-14 06:24:44 +00003118 if (log)
3119 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__);
3120
Todd Fialaaf245d12014-06-30 21:05:18 +00003121 return SendPacketNoLock(response.GetData(), response.GetSize());
3122}
3123
3124GDBRemoteCommunication::PacketResult
3125GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
3126{
3127 // Ensure we're llgs.
3128 if (!IsGdbServer())
3129 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented");
3130
3131 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
3132 return SendPacketNoLock ("l", 1);
3133}
3134
3135GDBRemoteCommunication::PacketResult
3136GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet)
3137{
3138 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3139
3140 // Ensure we're llgs.
3141 if (!IsGdbServer())
3142 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented");
3143
3144 // Parse out the register number from the request.
3145 packet.SetFilePos (strlen("p"));
3146 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3147 if (reg_index == std::numeric_limits<uint32_t>::max ())
3148 {
3149 if (log)
3150 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3151 return SendErrorResponse (0x15);
3152 }
3153
3154 // Get the thread to use.
3155 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3156 if (!thread_sp)
3157 {
3158 if (log)
3159 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__);
3160 return SendErrorResponse (0x15);
3161 }
3162
3163 // Get the thread's register context.
3164 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3165 if (!reg_context_sp)
3166 {
3167 if (log)
3168 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 ());
3169 return SendErrorResponse (0x15);
3170 }
3171
3172 // Return the end of registers response if we've iterated one past the end of the register set.
3173 if (reg_index >= reg_context_sp->GetRegisterCount ())
3174 {
3175 if (log)
3176 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3177 return SendErrorResponse (0x15);
3178 }
3179
3180 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3181 if (!reg_info)
3182 {
3183 if (log)
3184 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3185 return SendErrorResponse (0x15);
3186 }
3187
3188 // Build the reginfos response.
3189 StreamGDBRemote response;
3190
3191 // Retrieve the value
3192 RegisterValue reg_value;
3193 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
3194 if (error.Fail ())
3195 {
3196 if (log)
3197 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3198 return SendErrorResponse (0x15);
3199 }
3200
3201 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
3202 if (!data)
3203 {
3204 if (log)
3205 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
3206 return SendErrorResponse (0x15);
3207 }
3208
3209 // FIXME flip as needed to get data in big/little endian format for this host.
3210 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
3211 response.PutHex8 (data[i]);
3212
3213 return SendPacketNoLock (response.GetData (), response.GetSize ());
3214}
3215
3216GDBRemoteCommunication::PacketResult
3217GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet)
3218{
3219 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3220
3221 // Ensure we're llgs.
3222 if (!IsGdbServer())
3223 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented");
3224
3225 // Ensure there is more content.
3226 if (packet.GetBytesLeft () < 1)
3227 return SendIllFormedResponse (packet, "Empty P packet");
3228
3229 // Parse out the register number from the request.
3230 packet.SetFilePos (strlen("P"));
3231 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3232 if (reg_index == std::numeric_limits<uint32_t>::max ())
3233 {
3234 if (log)
3235 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3236 return SendErrorResponse (0x29);
3237 }
3238
3239 // Note debugserver would send an E30 here.
3240 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
3241 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
3242
3243 // Get process architecture.
3244 ArchSpec process_arch;
3245 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
3246 {
3247 if (log)
3248 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__);
3249 return SendErrorResponse (0x49);
3250 }
3251
3252 // Parse out the value.
3253 const uint64_t raw_value = packet.GetHexMaxU64 (process_arch.GetByteOrder () == lldb::eByteOrderLittle, std::numeric_limits<uint64_t>::max ());
3254
3255 // Get the thread to use.
3256 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3257 if (!thread_sp)
3258 {
3259 if (log)
3260 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__);
3261 return SendErrorResponse (0x28);
3262 }
3263
3264 // Get the thread's register context.
3265 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3266 if (!reg_context_sp)
3267 {
3268 if (log)
3269 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 ());
3270 return SendErrorResponse (0x15);
3271 }
3272
3273 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3274 if (!reg_info)
3275 {
3276 if (log)
3277 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3278 return SendErrorResponse (0x48);
3279 }
3280
3281 // Return the end of registers response if we've iterated one past the end of the register set.
3282 if (reg_index >= reg_context_sp->GetRegisterCount ())
3283 {
3284 if (log)
3285 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3286 return SendErrorResponse (0x47);
3287 }
3288
3289
3290 // Build the reginfos response.
3291 StreamGDBRemote response;
3292
3293 // FIXME Could be suffixed with a thread: parameter.
3294 // That thread then needs to be fed back into the reg context retrieval above.
3295 Error error = reg_context_sp->WriteRegisterFromUnsigned (reg_info, raw_value);
3296 if (error.Fail ())
3297 {
3298 if (log)
3299 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3300 return SendErrorResponse (0x32);
3301 }
3302
3303 return SendOKResponse();
3304}
3305
3306GDBRemoteCommunicationServer::PacketResult
3307GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet)
3308{
3309 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3310
3311 // Ensure we're llgs.
3312 if (!IsGdbServer())
3313 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented");
3314
3315 // Fail if we don't have a current process.
3316 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3317 {
3318 if (log)
3319 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3320 return SendErrorResponse (0x15);
3321 }
3322
3323 // Parse out which variant of $H is requested.
3324 packet.SetFilePos (strlen("H"));
3325 if (packet.GetBytesLeft () < 1)
3326 {
3327 if (log)
3328 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__);
3329 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
3330 }
3331
3332 const char h_variant = packet.GetChar ();
3333 switch (h_variant)
3334 {
3335 case 'g':
3336 break;
3337
3338 case 'c':
3339 break;
3340
3341 default:
3342 if (log)
3343 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
3344 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3345 }
3346
3347 // Parse out the thread number.
3348 // FIXME return a parse success/fail value. All values are valid here.
3349 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
3350
3351 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
3352 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
3353 {
3354 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
3355 if (!thread_sp)
3356 {
3357 if (log)
3358 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
3359 return SendErrorResponse (0x15);
3360 }
3361 }
3362
3363 // Now switch the given thread type.
3364 switch (h_variant)
3365 {
3366 case 'g':
3367 SetCurrentThreadID (tid);
3368 break;
3369
3370 case 'c':
3371 SetContinueThreadID (tid);
3372 break;
3373
3374 default:
3375 assert (false && "unsupported $H variant - shouldn't get here");
3376 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3377 }
3378
3379 return SendOKResponse();
3380}
3381
3382GDBRemoteCommunicationServer::PacketResult
3383GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet)
3384{
3385 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3386
3387 // Ensure we're llgs.
3388 if (!IsGdbServer())
3389 {
3390 // Only supported on llgs
3391 return SendUnimplementedResponse ("");
3392 }
3393
3394 // Fail if we don't have a current process.
3395 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3396 {
3397 if (log)
3398 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3399 return SendErrorResponse (0x15);
3400 }
3401
Todd Fiala511e5cd2014-09-11 23:29:14 +00003402 // Interrupt the process.
3403 Error error = m_debugged_process_sp->Interrupt ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003404 if (error.Fail ())
3405 {
3406 if (log)
3407 {
3408 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s",
3409 __FUNCTION__,
3410 m_debugged_process_sp->GetID (),
3411 error.AsCString ());
3412 }
3413 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
3414 }
3415
3416 if (log)
3417 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
3418
3419 // No response required from stop all.
3420 return PacketResult::Success;
3421}
3422
3423GDBRemoteCommunicationServer::PacketResult
3424GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet)
3425{
3426 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3427
3428 // Ensure we're llgs.
3429 if (!IsGdbServer())
3430 {
3431 // Only supported on llgs
3432 return SendUnimplementedResponse ("");
3433 }
3434
3435 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3436 {
3437 if (log)
3438 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3439 return SendErrorResponse (0x15);
3440 }
3441
3442 // Parse out the memory address.
3443 packet.SetFilePos (strlen("m"));
3444 if (packet.GetBytesLeft() < 1)
3445 return SendIllFormedResponse(packet, "Too short m packet");
3446
3447 // Read the address. Punting on validation.
3448 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3449 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3450
3451 // Validate comma.
3452 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3453 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
3454
3455 // Get # bytes to read.
3456 if (packet.GetBytesLeft() < 1)
3457 return SendIllFormedResponse(packet, "Length missing in m packet");
3458
3459 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3460 if (byte_count == 0)
3461 {
3462 if (log)
3463 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__);
3464 return PacketResult::Success;
3465 }
3466
3467 // Allocate the response buffer.
3468 std::string buf(byte_count, '\0');
3469 if (buf.empty())
3470 return SendErrorResponse (0x78);
3471
3472
3473 // Retrieve the process memory.
3474 lldb::addr_t bytes_read = 0;
3475 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
3476 if (error.Fail ())
3477 {
3478 if (log)
3479 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
3480 return SendErrorResponse (0x08);
3481 }
3482
3483 if (bytes_read == 0)
3484 {
3485 if (log)
3486 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);
3487 return SendErrorResponse (0x08);
3488 }
3489
3490 StreamGDBRemote response;
3491 for (lldb::addr_t i = 0; i < bytes_read; ++i)
3492 response.PutHex8(buf[i]);
3493
3494 return SendPacketNoLock(response.GetData(), response.GetSize());
3495}
3496
3497GDBRemoteCommunication::PacketResult
3498GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet)
3499{
3500 packet.SetFilePos(::strlen ("QSetDetachOnError:"));
3501 if (packet.GetU32(0))
3502 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError);
3503 else
3504 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError);
3505 return SendOKResponse ();
3506}
3507
3508GDBRemoteCommunicationServer::PacketResult
3509GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet)
3510{
3511 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3512
3513 // Ensure we're llgs.
3514 if (!IsGdbServer())
3515 {
3516 // Only supported on llgs
3517 return SendUnimplementedResponse ("");
3518 }
3519
3520 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3521 {
3522 if (log)
3523 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3524 return SendErrorResponse (0x15);
3525 }
3526
3527 // Parse out the memory address.
3528 packet.SetFilePos (strlen("M"));
3529 if (packet.GetBytesLeft() < 1)
3530 return SendIllFormedResponse(packet, "Too short M packet");
3531
3532 // Read the address. Punting on validation.
3533 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3534 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
3535
3536 // Validate comma.
3537 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3538 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
3539
3540 // Get # bytes to read.
3541 if (packet.GetBytesLeft() < 1)
3542 return SendIllFormedResponse(packet, "Length missing in M packet");
3543
3544 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3545 if (byte_count == 0)
3546 {
3547 if (log)
3548 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__);
3549 return PacketResult::Success;
3550 }
3551
3552 // Validate colon.
3553 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
3554 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
3555
3556 // Allocate the conversion buffer.
3557 std::vector<uint8_t> buf(byte_count, 0);
3558 if (buf.empty())
3559 return SendErrorResponse (0x78);
3560
3561 // Convert the hex memory write contents to bytes.
3562 StreamGDBRemote response;
3563 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
3564 if (convert_count != byte_count)
3565 {
3566 if (log)
3567 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);
3568 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
3569 }
3570
3571 // Write the process memory.
3572 lldb::addr_t bytes_written = 0;
3573 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
3574 if (error.Fail ())
3575 {
3576 if (log)
3577 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
3578 return SendErrorResponse (0x09);
3579 }
3580
3581 if (bytes_written == 0)
3582 {
3583 if (log)
3584 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);
3585 return SendErrorResponse (0x09);
3586 }
3587
3588 return SendOKResponse ();
3589}
3590
3591GDBRemoteCommunicationServer::PacketResult
3592GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
3593{
3594 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3595
3596 // We don't support if we're not llgs.
3597 if (!IsGdbServer())
3598 return SendUnimplementedResponse ("");
3599
3600 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
3601 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
3602 // client only asks this when a process is being debugged.
3603
3604 // Ensure we have a process running; otherwise, we can't figure this out
3605 // since we won't have a NativeProcessProtocol.
3606 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3607 {
3608 if (log)
3609 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3610 return SendErrorResponse (0x15);
3611 }
3612
3613 // Test if we can get any region back when asking for the region around NULL.
3614 MemoryRegionInfo region_info;
3615 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
3616 if (error.Fail ())
3617 {
3618 // We don't support memory region info collection for this NativeProcessProtocol.
3619 return SendUnimplementedResponse ("");
3620 }
3621
3622 return SendOKResponse();
3623}
3624
3625GDBRemoteCommunicationServer::PacketResult
3626GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
3627{
3628 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3629
3630 // We don't support if we're not llgs.
3631 if (!IsGdbServer())
3632 return SendUnimplementedResponse ("");
3633
3634 // Ensure we have a process.
3635 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3636 {
3637 if (log)
3638 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3639 return SendErrorResponse (0x15);
3640 }
3641
3642 // Parse out the memory address.
3643 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
3644 if (packet.GetBytesLeft() < 1)
3645 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
3646
3647 // Read the address. Punting on validation.
3648 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3649
3650 StreamGDBRemote response;
3651
3652 // Get the memory region info for the target address.
3653 MemoryRegionInfo region_info;
3654 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
3655 if (error.Fail ())
3656 {
3657 // Return the error message.
3658
3659 response.PutCString ("error:");
3660 response.PutCStringAsRawHex8 (error.AsCString ());
3661 response.PutChar (';');
3662 }
3663 else
3664 {
3665 // Range start and size.
3666 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
3667
3668 // Permissions.
3669 if (region_info.GetReadable () ||
3670 region_info.GetWritable () ||
3671 region_info.GetExecutable ())
3672 {
3673 // Write permissions info.
3674 response.PutCString ("permissions:");
3675
3676 if (region_info.GetReadable ())
3677 response.PutChar ('r');
3678 if (region_info.GetWritable ())
3679 response.PutChar('w');
3680 if (region_info.GetExecutable())
3681 response.PutChar ('x');
3682
3683 response.PutChar (';');
3684 }
3685 }
3686
3687 return SendPacketNoLock(response.GetData(), response.GetSize());
3688}
3689
3690GDBRemoteCommunicationServer::PacketResult
3691GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet)
3692{
3693 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3694
3695 // We don't support if we're not llgs.
3696 if (!IsGdbServer())
3697 return SendUnimplementedResponse ("");
3698
3699 // Ensure we have a process.
3700 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3701 {
3702 if (log)
3703 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3704 return SendErrorResponse (0x15);
3705 }
3706
3707 // Parse out software or hardware breakpoint requested.
3708 packet.SetFilePos (strlen("Z"));
3709 if (packet.GetBytesLeft() < 1)
3710 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
3711
3712 bool want_breakpoint = true;
3713 bool want_hardware = false;
3714
3715 const char breakpoint_type_char = packet.GetChar ();
3716 switch (breakpoint_type_char)
3717 {
3718 case '0': want_hardware = false; want_breakpoint = true; break;
3719 case '1': want_hardware = true; want_breakpoint = true; break;
3720 case '2': want_breakpoint = false; break;
3721 case '3': want_breakpoint = false; break;
3722 default:
3723 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
3724
3725 }
3726
3727 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3728 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type");
3729
3730 // FIXME implement watchpoint support.
3731 if (!want_breakpoint)
3732 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3733
3734 // Parse out the breakpoint address.
3735 if (packet.GetBytesLeft() < 1)
3736 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
3737 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3738
3739 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3740 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
3741
3742 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3743 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3744 if (kind == std::numeric_limits<uint32_t>::max ())
3745 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument");
3746
3747 if (want_breakpoint)
3748 {
3749 // Try to set the breakpoint.
3750 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware);
3751 if (error.Success ())
3752 return SendOKResponse ();
3753 else
3754 {
3755 if (log)
3756 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3757 return SendErrorResponse (0x09);
3758 }
3759 }
3760
3761 // FIXME fix up after watchpoints are handled.
3762 return SendUnimplementedResponse ("");
3763}
3764
3765GDBRemoteCommunicationServer::PacketResult
3766GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet)
3767{
3768 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3769
3770 // We don't support if we're not llgs.
3771 if (!IsGdbServer())
3772 return SendUnimplementedResponse ("");
3773
3774 // Ensure we have a process.
3775 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3776 {
3777 if (log)
3778 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3779 return SendErrorResponse (0x15);
3780 }
3781
3782 // Parse out software or hardware breakpoint requested.
3783 packet.SetFilePos (strlen("Z"));
3784 if (packet.GetBytesLeft() < 1)
3785 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
3786
3787 bool want_breakpoint = true;
3788
3789 const char breakpoint_type_char = packet.GetChar ();
3790 switch (breakpoint_type_char)
3791 {
3792 case '0': want_breakpoint = true; break;
3793 case '1': want_breakpoint = true; break;
3794 case '2': want_breakpoint = false; break;
3795 case '3': want_breakpoint = false; break;
3796 default:
3797 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
3798
3799 }
3800
3801 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3802 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type");
3803
3804 // FIXME implement watchpoint support.
3805 if (!want_breakpoint)
3806 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3807
3808 // Parse out the breakpoint address.
3809 if (packet.GetBytesLeft() < 1)
3810 return SendIllFormedResponse(packet, "Too short z packet, missing address");
3811 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3812
3813 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3814 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
3815
3816 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3817 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3818 if (kind == std::numeric_limits<uint32_t>::max ())
3819 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument");
3820
3821 if (want_breakpoint)
3822 {
3823 // Try to set the breakpoint.
3824 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr);
3825 if (error.Success ())
3826 return SendOKResponse ();
3827 else
3828 {
3829 if (log)
3830 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3831 return SendErrorResponse (0x09);
3832 }
3833 }
3834
3835 // FIXME fix up after watchpoints are handled.
3836 return SendUnimplementedResponse ("");
3837}
3838
3839GDBRemoteCommunicationServer::PacketResult
3840GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet)
3841{
3842 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
3843
3844 // We don't support if we're not llgs.
3845 if (!IsGdbServer())
3846 return SendUnimplementedResponse ("");
3847
3848 // Ensure we have a process.
3849 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3850 {
3851 if (log)
3852 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3853 return SendErrorResponse (0x32);
3854 }
3855
3856 // We first try to use a continue thread id. If any one or any all set, use the current thread.
3857 // Bail out if we don't have a thread id.
3858 lldb::tid_t tid = GetContinueThreadID ();
3859 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3860 tid = GetCurrentThreadID ();
3861 if (tid == LLDB_INVALID_THREAD_ID)
3862 return SendErrorResponse (0x33);
3863
3864 // Double check that we have such a thread.
3865 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3866 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
3867 if (!thread_sp || thread_sp->GetID () != tid)
3868 return SendErrorResponse (0x33);
3869
3870 // Create the step action for the given thread.
3871 lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
3872
3873 // Setup the actions list.
3874 lldb_private::ResumeActionList actions;
3875 actions.Append (action);
3876
3877 // All other threads stop while we're single stepping a thread.
3878 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3879 Error error = m_debugged_process_sp->Resume (actions);
3880 if (error.Fail ())
3881 {
3882 if (log)
3883 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
3884 return SendErrorResponse(0x49);
3885 }
3886
3887 // No response here - the stop or exit will come from the resulting action.
3888 return PacketResult::Success;
3889}
3890
3891GDBRemoteCommunicationServer::PacketResult
3892GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet)
3893{
3894 StreamGDBRemote response;
3895
3896 // Features common to lldb-platform and llgs.
3897 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less
3898 response.Printf ("PacketSize=%x", max_packet_size);
3899
3900 response.PutCString (";QStartNoAckMode+");
3901 response.PutCString (";QThreadSuffixSupported+");
3902 response.PutCString (";QListThreadsInStopReply+");
3903#if defined(__linux__)
3904 response.PutCString (";qXfer:auxv:read+");
3905#endif
3906
3907 return SendPacketNoLock(response.GetData(), response.GetSize());
3908}
3909
3910GDBRemoteCommunicationServer::PacketResult
3911GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet)
3912{
3913 m_thread_suffix_supported = true;
3914 return SendOKResponse();
3915}
3916
3917GDBRemoteCommunicationServer::PacketResult
3918GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet)
3919{
3920 m_list_threads_in_stop_reply = true;
3921 return SendOKResponse();
3922}
3923
3924GDBRemoteCommunicationServer::PacketResult
3925GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
3926{
3927 // We don't support if we're not llgs.
3928 if (!IsGdbServer())
3929 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
3930
3931 // *BSD impls should be able to do this too.
3932#if defined(__linux__)
3933 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3934
3935 // Parse out the offset.
3936 packet.SetFilePos (strlen("qXfer:auxv:read::"));
3937 if (packet.GetBytesLeft () < 1)
3938 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3939
3940 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3941 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
3942 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3943
3944 // Parse out comma.
3945 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
3946 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
3947
3948 // Parse out the length.
3949 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3950 if (auxv_length == std::numeric_limits<uint64_t>::max ())
3951 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
3952
3953 // Grab the auxv data if we need it.
3954 if (!m_active_auxv_buffer_sp)
3955 {
3956 // Make sure we have a valid process.
3957 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3958 {
3959 if (log)
3960 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3961 return SendErrorResponse (0x10);
3962 }
3963
3964 // Grab the auxv data.
3965 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
3966 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
3967 {
3968 // Hmm, no auxv data, call that an error.
3969 if (log)
3970 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__);
3971 m_active_auxv_buffer_sp.reset ();
3972 return SendErrorResponse (0x11);
3973 }
3974 }
3975
3976 // FIXME find out if/how I lock the stream here.
3977
3978 StreamGDBRemote response;
3979 bool done_with_buffer = false;
3980
3981 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
3982 {
3983 // We have nothing left to send. Mark the buffer as complete.
3984 response.PutChar ('l');
3985 done_with_buffer = true;
3986 }
3987 else
3988 {
3989 // Figure out how many bytes are available starting at the given offset.
3990 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
3991
3992 // Figure out how many bytes we're going to read.
3993 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
3994
3995 // Mark the response type according to whether we're reading the remainder of the auxv data.
3996 if (bytes_to_read >= bytes_remaining)
3997 {
3998 // There will be nothing left to read after this
3999 response.PutChar ('l');
4000 done_with_buffer = true;
4001 }
4002 else
4003 {
4004 // There will still be bytes to read after this request.
4005 response.PutChar ('m');
4006 }
4007
4008 // Now write the data in encoded binary form.
4009 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
4010 }
4011
4012 if (done_with_buffer)
4013 m_active_auxv_buffer_sp.reset ();
4014
4015 return SendPacketNoLock(response.GetData(), response.GetSize());
4016#else
4017 return SendUnimplementedResponse ("not implemented on this platform");
4018#endif
4019}
4020
4021GDBRemoteCommunicationServer::PacketResult
4022GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
4023{
4024 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4025
4026 // We don't support if we're not llgs.
4027 if (!IsGdbServer())
4028 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4029
4030 // Move past packet name.
4031 packet.SetFilePos (strlen ("QSaveRegisterState"));
4032
4033 // Get the thread to use.
4034 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4035 if (!thread_sp)
4036 {
4037 if (m_thread_suffix_supported)
4038 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
4039 else
4040 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4041 }
4042
4043 // Grab the register context for the thread.
4044 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4045 if (!reg_context_sp)
4046 {
4047 if (log)
4048 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 ());
4049 return SendErrorResponse (0x15);
4050 }
4051
4052 // Save registers to a buffer.
4053 DataBufferSP register_data_sp;
4054 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
4055 if (error.Fail ())
4056 {
4057 if (log)
4058 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4059 return SendErrorResponse (0x75);
4060 }
4061
4062 // Allocate a new save id.
4063 const uint32_t save_id = GetNextSavedRegistersID ();
4064 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
4065
4066 // Save the register data buffer under the save id.
4067 {
4068 Mutex::Locker locker (m_saved_registers_mutex);
4069 m_saved_registers_map[save_id] = register_data_sp;
4070 }
4071
4072 // Write the response.
4073 StreamGDBRemote response;
4074 response.Printf ("%" PRIu32, save_id);
4075 return SendPacketNoLock(response.GetData(), response.GetSize());
4076}
4077
4078GDBRemoteCommunicationServer::PacketResult
4079GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
4080{
4081 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4082
4083 // We don't support if we're not llgs.
4084 if (!IsGdbServer())
4085 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4086
4087 // Parse out save id.
4088 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
4089 if (packet.GetBytesLeft () < 1)
4090 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
4091
4092 const uint32_t save_id = packet.GetU32 (0);
4093 if (save_id == 0)
4094 {
4095 if (log)
4096 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
4097 return SendErrorResponse (0x76);
4098 }
4099
4100 // Get the thread to use.
4101 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4102 if (!thread_sp)
4103 {
4104 if (m_thread_suffix_supported)
4105 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
4106 else
4107 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4108 }
4109
4110 // Grab the register context for the thread.
4111 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4112 if (!reg_context_sp)
4113 {
4114 if (log)
4115 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 ());
4116 return SendErrorResponse (0x15);
4117 }
4118
4119 // Retrieve register state buffer, then remove from the list.
4120 DataBufferSP register_data_sp;
4121 {
4122 Mutex::Locker locker (m_saved_registers_mutex);
4123
4124 // Find the register set buffer for the given save id.
4125 auto it = m_saved_registers_map.find (save_id);
4126 if (it == m_saved_registers_map.end ())
4127 {
4128 if (log)
4129 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);
4130 return SendErrorResponse (0x77);
4131 }
4132 register_data_sp = it->second;
4133
4134 // Remove it from the map.
4135 m_saved_registers_map.erase (it);
4136 }
4137
4138 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
4139 if (error.Fail ())
4140 {
4141 if (log)
4142 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4143 return SendErrorResponse (0x77);
4144 }
4145
4146 return SendOKResponse();
4147}
4148
Todd Fiala7306cf32014-07-29 22:30:01 +00004149GDBRemoteCommunicationServer::PacketResult
4150GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet)
4151{
4152 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4153
4154 // We don't support if we're not llgs.
4155 if (!IsGdbServer())
4156 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4157
4158 // Consume the ';' after vAttach.
4159 packet.SetFilePos (strlen ("vAttach"));
4160 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
4161 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
4162
4163 // Grab the PID to which we will attach (assume hex encoding).
4164 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4165 if (pid == LLDB_INVALID_PROCESS_ID)
4166 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
4167
4168 // Attempt to attach.
4169 if (log)
4170 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
4171
4172 Error error = AttachToProcess (pid);
4173
4174 if (error.Fail ())
4175 {
4176 if (log)
4177 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
4178 return SendErrorResponse (0x01);
4179 }
4180
4181 // Notify we attached by sending a stop packet.
4182 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
4183
4184 return PacketResult::Success;
4185}
4186
Todd Fiala1109ed42014-09-10 21:28:38 +00004187GDBRemoteCommunicationServer::PacketResult
4188GDBRemoteCommunicationServer::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
4189{
4190 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4191
4192 // We don't support if we're not llgs.
4193 if (!IsGdbServer())
4194 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4195
4196 packet.SetFilePos (strlen("qThreadStopInfo"));
4197 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
4198 if (tid == LLDB_INVALID_THREAD_ID)
4199 {
4200 if (log)
4201 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
4202 return SendErrorResponse (0x15);
4203 }
4204 return SendStopReplyPacketForThread (tid);
4205}
4206
Todd Fialaaf245d12014-06-30 21:05:18 +00004207void
4208GDBRemoteCommunicationServer::FlushInferiorOutput ()
4209{
4210 // If we're not monitoring an inferior's terminal, ignore this.
4211 if (!m_stdio_communication.IsConnected())
4212 return;
4213
4214 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
4215 if (log)
4216 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
4217
4218 // FIXME implement a timeout on the join.
4219 m_stdio_communication.JoinReadThread();
4220}
4221
4222void
4223GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection ()
4224{
4225 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4226
4227 // Tell the stdio connection to shut down.
4228 if (m_stdio_communication.IsConnected())
4229 {
4230 auto connection = m_stdio_communication.GetConnection();
4231 if (connection)
4232 {
4233 Error error;
4234 connection->Disconnect (&error);
4235
4236 if (error.Success ())
4237 {
4238 if (log)
4239 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
4240 }
4241 else
4242 {
4243 if (log)
4244 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
4245 }
4246 }
4247 }
4248}
4249
4250
4251lldb_private::NativeThreadProtocolSP
4252GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
4253{
4254 NativeThreadProtocolSP thread_sp;
4255
4256 // We have no thread if we don't have a process.
4257 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4258 return thread_sp;
4259
4260 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
4261 // Use the current thread in that case.
4262 if (!m_thread_suffix_supported)
4263 {
4264 const lldb::tid_t current_tid = GetCurrentThreadID ();
4265 if (current_tid == LLDB_INVALID_THREAD_ID)
4266 return thread_sp;
4267 else if (current_tid == 0)
4268 {
4269 // Pick a thread.
4270 return m_debugged_process_sp->GetThreadAtIndex (0);
4271 }
4272 else
4273 return m_debugged_process_sp->GetThreadByID (current_tid);
4274 }
4275
4276 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4277
4278 // Parse out the ';'.
4279 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
4280 {
4281 if (log)
4282 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4283 return thread_sp;
4284 }
4285
4286 if (!packet.GetBytesLeft ())
4287 return thread_sp;
4288
4289 // Parse out thread: portion.
4290 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
4291 {
4292 if (log)
4293 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4294 return thread_sp;
4295 }
4296 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
4297 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4298 if (tid != 0)
4299 return m_debugged_process_sp->GetThreadByID (tid);
4300
4301 return thread_sp;
4302}
4303
4304lldb::tid_t
4305GDBRemoteCommunicationServer::GetCurrentThreadID () const
4306{
4307 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
4308 {
4309 // Use whatever the debug process says is the current thread id
4310 // since the protocol either didn't specify or specified we want
4311 // any/all threads marked as the current thread.
4312 if (!m_debugged_process_sp)
4313 return LLDB_INVALID_THREAD_ID;
4314 return m_debugged_process_sp->GetCurrentThreadID ();
4315 }
4316 // Use the specific current thread id set by the gdb remote protocol.
4317 return m_current_tid;
4318}
4319
4320uint32_t
4321GDBRemoteCommunicationServer::GetNextSavedRegistersID ()
4322{
4323 Mutex::Locker locker (m_saved_registers_mutex);
4324 return m_next_saved_registers_id++;
4325}
4326
Todd Fialaa9882ce2014-08-28 15:46:54 +00004327void
4328GDBRemoteCommunicationServer::ClearProcessSpecificData ()
4329{
4330 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
4331 if (log)
4332 log->Printf ("GDBRemoteCommunicationServer::%s()", __FUNCTION__);
4333
4334 // Clear any auxv cached data.
4335 // *BSD impls should be able to do this too.
4336#if defined(__linux__)
4337 if (log)
4338 log->Printf ("GDBRemoteCommunicationServer::%s clearing auxv buffer (previously %s)",
4339 __FUNCTION__,
4340 m_active_auxv_buffer_sp ? "was set" : "was not set");
4341 m_active_auxv_buffer_sp.reset ();
4342#endif
4343}