blob: 8f1ad8697012c6bfd46c208ec6f3367e3ae968db [file] [log] [blame]
Tamas Berghammere13c2732015-02-11 10:29:30 +00001//===-- GDBRemoteCommunicationServerLLGS.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
10#include <errno.h>
11
12#include "lldb/Host/Config.h"
13
14#include "GDBRemoteCommunicationServerLLGS.h"
15#include "lldb/Core/StreamGDBRemote.h"
16
17// C Includes
18// C++ Includes
19#include <cstring>
20#include <chrono>
21#include <thread>
22
23// Other libraries and framework includes
24#include "llvm/ADT/Triple.h"
25#include "lldb/Interpreter/Args.h"
Zachary Turner90aff472015-03-03 23:36:51 +000026#include "lldb/Core/DataBuffer.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000027#include "lldb/Core/Log.h"
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +000028#include "lldb/Core/RegisterValue.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000029#include "lldb/Core/State.h"
30#include "lldb/Core/StreamString.h"
31#include "lldb/Host/ConnectionFileDescriptor.h"
32#include "lldb/Host/Debug.h"
33#include "lldb/Host/Endian.h"
34#include "lldb/Host/File.h"
35#include "lldb/Host/FileSystem.h"
36#include "lldb/Host/Host.h"
37#include "lldb/Host/HostInfo.h"
38#include "lldb/Host/StringConvert.h"
39#include "lldb/Host/TimeValue.h"
40#include "lldb/Target/FileAction.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000041#include "lldb/Target/MemoryRegionInfo.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000042#include "lldb/Target/Platform.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000043#include "lldb/Host/common/NativeRegisterContext.h"
44#include "lldb/Host/common/NativeProcessProtocol.h"
45#include "lldb/Host/common/NativeThreadProtocol.h"
Pavel Labath4a4bb122015-07-16 14:14:35 +000046#include "lldb/Utility/JSON.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000047
48// Project includes
49#include "Utility/StringExtractorGDBRemote.h"
50#include "Utility/UriParser.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53
54using namespace lldb;
55using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000056using namespace lldb_private::process_gdb_remote;
Tamas Berghammer783bfc82015-06-18 20:43:56 +000057using namespace llvm;
Tamas Berghammere13c2732015-02-11 10:29:30 +000058
59//----------------------------------------------------------------------
60// GDBRemote Errors
61//----------------------------------------------------------------------
62
63namespace
64{
65 enum GDBRemoteServerError
66 {
67 // Set to the first unused error number in literal form below
68 eErrorFirst = 29,
69 eErrorNoProcess = eErrorFirst,
70 eErrorResume,
71 eErrorExitStatus
72 };
73}
74
75//----------------------------------------------------------------------
76// GDBRemoteCommunicationServerLLGS constructor
77//----------------------------------------------------------------------
78GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
Pavel Labath77dc9562015-07-13 10:44:55 +000079 const lldb::PlatformSP& platform_sp,
80 MainLoop &mainloop) :
Tamas Berghammere13c2732015-02-11 10:29:30 +000081 GDBRemoteCommunicationServerCommon ("gdb-remote.server", "gdb-remote.server.rx_packet"),
82 m_platform_sp (platform_sp),
Pavel Labath77dc9562015-07-13 10:44:55 +000083 m_mainloop (mainloop),
Tamas Berghammere13c2732015-02-11 10:29:30 +000084 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 (),
Tamas Berghammere13c2732015-02-11 10:29:30 +000088 m_stdio_communication ("process.stdio"),
89 m_inferior_prev_state (StateType::eStateInvalid),
90 m_active_auxv_buffer_sp (),
91 m_saved_registers_mutex (),
92 m_saved_registers_map (),
Pavel Labath77dc9562015-07-13 10:44:55 +000093 m_next_saved_registers_id (1),
94 m_handshake_completed (false)
Tamas Berghammere13c2732015-02-11 10:29:30 +000095{
96 assert(platform_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +000097 RegisterPacketHandlers();
98}
99
Tamas Berghammere13c2732015-02-11 10:29:30 +0000100void
101GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers()
102{
Tamas Berghammere13c2732015-02-11 10:29:30 +0000103 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
104 &GDBRemoteCommunicationServerLLGS::Handle_C);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
106 &GDBRemoteCommunicationServerLLGS::Handle_c);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
108 &GDBRemoteCommunicationServerLLGS::Handle_D);
109 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
110 &GDBRemoteCommunicationServerLLGS::Handle_H);
111 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
112 &GDBRemoteCommunicationServerLLGS::Handle_I);
113 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
114 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
115 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_m,
116 &GDBRemoteCommunicationServerLLGS::Handle_m);
117 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
118 &GDBRemoteCommunicationServerLLGS::Handle_M);
119 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
120 &GDBRemoteCommunicationServerLLGS::Handle_p);
121 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
122 &GDBRemoteCommunicationServerLLGS::Handle_P);
123 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
124 &GDBRemoteCommunicationServerLLGS::Handle_qC);
125 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
126 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
Tamas Berghammer783bfc82015-06-18 20:43:56 +0000127 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
128 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000129 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
130 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
131 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
132 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
133 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
134 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
135 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
136 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
137 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
138 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
139 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
140 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
141 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
143 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
144 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
145 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
146 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
147 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
148 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
149 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
150 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
Pavel Labath4a4bb122015-07-16 14:14:35 +0000151 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
152 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000153 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
154 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
155 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
156 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
157 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
158 &GDBRemoteCommunicationServerLLGS::Handle_s);
159 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_stop_reason,
160 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
161 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vAttach,
162 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
163 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont,
164 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
165 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont_actions,
166 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
167 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
168 &GDBRemoteCommunicationServerLLGS::Handle_Z);
169 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
170 &GDBRemoteCommunicationServerLLGS::Handle_z);
171
172 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
173 [this](StringExtractorGDBRemote packet,
174 Error &error,
175 bool &interrupt,
176 bool &quit)
177 {
178 quit = true;
179 return this->Handle_k (packet);
180 });
181}
182
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000183Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000184GDBRemoteCommunicationServerLLGS::SetLaunchArguments (const char *const args[], int argc)
185{
186 if ((argc < 1) || !args || !args[0] || !args[0][0])
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000187 return Error ("%s: no process command line specified to launch", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000188
189 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000190 return Error ();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000191}
192
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000193Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000194GDBRemoteCommunicationServerLLGS::SetLaunchFlags (unsigned int launch_flags)
195{
196 m_process_launch_info.GetFlags ().Set (launch_flags);
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000197 return Error ();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000198}
199
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000200Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000201GDBRemoteCommunicationServerLLGS::LaunchProcess ()
202{
203 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
204
205 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000206 return Error ("%s: no process command line specified to launch", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000207
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000208 Error error;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000209 {
210 Mutex::Locker locker (m_debugged_process_mutex);
211 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
Pavel Labathd5b310f2015-07-09 11:51:11 +0000212 error = NativeProcessProtocol::Launch(
Tamas Berghammere13c2732015-02-11 10:29:30 +0000213 m_process_launch_info,
214 *this,
Pavel Labath19cbe962015-07-21 13:20:32 +0000215 m_mainloop,
Tamas Berghammere13c2732015-02-11 10:29:30 +0000216 m_debugged_process_sp);
217 }
218
219 if (!error.Success ())
220 {
221 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
222 return error;
223 }
224
Vince Harron4a8abd32015-02-13 19:15:24 +0000225 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
226 // as needed.
227 // llgs local-process debugging may specify PTY paths, which will make these
228 // file actions non-null
229 // process launch -i/e/o will also make these file actions non-null
230 // nullptr means that the traffic is expected to flow over gdb-remote protocol
231 if (
232 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
233 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
234 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
235 )
Tamas Berghammere13c2732015-02-11 10:29:30 +0000236 {
Vince Harron4a8abd32015-02-13 19:15:24 +0000237 // nullptr means it's not redirected to file or pty (in case of LLGS local)
238 // at least one of stdio will be transferred pty<->gdb-remote
239 // we need to give the pty master handle to this object to read and/or write
Tamas Berghammere13c2732015-02-11 10:29:30 +0000240 if (log)
241 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
242
243 // Setup stdout/stderr mapping from inferior to $O
244 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
245 if (terminal_fd >= 0)
246 {
247 if (log)
248 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
249 error = SetSTDIOFileDescriptor (terminal_fd);
250 if (error.Fail ())
251 return error;
252 }
253 else
254 {
255 if (log)
256 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
257 }
258 }
259 else
260 {
261 if (log)
262 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " skipping stdout/stderr redirection via $O: inferior will communicate over client-provided file descriptors", __FUNCTION__, m_debugged_process_sp->GetID ());
263 }
264
265 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
266
Tamas Berghammere13c2732015-02-11 10:29:30 +0000267 return error;
268}
269
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000270Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000271GDBRemoteCommunicationServerLLGS::AttachToProcess (lldb::pid_t pid)
272{
273 Error error;
274
275 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
276 if (log)
277 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, __FUNCTION__, pid);
278
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000279 // Before we try to attach, make sure we aren't already monitoring something else.
280 if (m_debugged_process_sp && m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
281 return Error("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, m_debugged_process_sp->GetID());
282
283 // Try to attach.
284 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop, m_debugged_process_sp);
285 if (!error.Success ())
Tamas Berghammere13c2732015-02-11 10:29:30 +0000286 {
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000287 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000288 return error;
289 }
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000290
291 // Setup stdout/stderr mapping from inferior.
292 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
293 if (terminal_fd >= 0)
294 {
295 if (log)
296 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
297 error = SetSTDIOFileDescriptor (terminal_fd);
298 if (error.Fail ())
299 return error;
300 }
301 else
302 {
303 if (log)
304 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
305 }
306
307 printf ("Attached to process %" PRIu64 "...\n", pid);
308
309 return error;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000310}
311
312void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000313GDBRemoteCommunicationServerLLGS::InitializeDelegate (NativeProcessProtocol *process)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000314{
315 assert (process && "process cannot be NULL");
316 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
317 if (log)
318 {
319 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
320 __FUNCTION__,
321 process->GetID (),
322 StateAsCString (process->GetState ()));
323 }
324}
325
326GDBRemoteCommunication::PacketResult
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000327GDBRemoteCommunicationServerLLGS::SendWResponse (NativeProcessProtocol *process)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000328{
329 assert (process && "process cannot be NULL");
330 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
331
332 // send W notification
333 ExitType exit_type = ExitType::eExitTypeInvalid;
334 int return_code = 0;
335 std::string exit_description;
336
337 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
338 if (!got_exit_info)
339 {
340 if (log)
341 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
342
343 StreamGDBRemote response;
344 response.PutChar ('E');
345 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
346 return SendPacketNoLock(response.GetData(), response.GetSize());
347 }
348 else
349 {
350 if (log)
351 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", returning exit type %d, return code %d [%s]", __FUNCTION__, process->GetID (), exit_type, return_code, exit_description.c_str ());
352
353 StreamGDBRemote response;
354
355 char return_type_code;
356 switch (exit_type)
357 {
358 case ExitType::eExitTypeExit:
359 return_type_code = 'W';
360 break;
361 case ExitType::eExitTypeSignal:
362 return_type_code = 'X';
363 break;
364 case ExitType::eExitTypeStop:
365 return_type_code = 'S';
366 break;
367 case ExitType::eExitTypeInvalid:
368 return_type_code = 'E';
369 break;
370 }
371 response.PutChar (return_type_code);
372
373 // POSIX exit status limited to unsigned 8 bits.
374 response.PutHex8 (return_code);
375
376 return SendPacketNoLock(response.GetData(), response.GetSize());
377 }
378}
379
380static void
381AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
382{
383 int64_t i;
384 if (swap)
385 {
386 for (i = buf_size-1; i >= 0; i--)
387 response.PutHex8 (buf[i]);
388 }
389 else
390 {
391 for (i = 0; i < buf_size; i++)
392 response.PutHex8 (buf[i]);
393 }
394}
395
396static void
397WriteRegisterValueInHexFixedWidth (StreamString &response,
398 NativeRegisterContextSP &reg_ctx_sp,
399 const RegisterInfo &reg_info,
400 const RegisterValue *reg_value_p)
401{
402 RegisterValue reg_value;
403 if (!reg_value_p)
404 {
405 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
406 if (error.Success ())
407 reg_value_p = &reg_value;
408 // else log.
409 }
410
411 if (reg_value_p)
412 {
413 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
414 }
415 else
416 {
417 // Zero-out any unreadable values.
418 if (reg_info.byte_size > 0)
419 {
420 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
421 AppendHexValue (response, zeros.data(), zeros.size(), false);
422 }
423 }
424}
425
Pavel Labath4a4bb122015-07-16 14:14:35 +0000426static JSONObject::SP
427GetRegistersAsJSON(NativeThreadProtocol &thread)
428{
429 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
430
431 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext ();
432 if (! reg_ctx_sp)
433 return nullptr;
434
435 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000436
437#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
Pavel Labath4a4bb122015-07-16 14:14:35 +0000438 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
439 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
440 if (! reg_set_p)
441 return nullptr;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000442 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
443 {
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000444 uint32_t reg_num = *reg_num_p;
445#else
446 // Expedite only a couple of registers until we figure out why sending registers is
447 // expensive.
448 static const uint32_t k_expedited_registers[] = {
449 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP, LLDB_REGNUM_GENERIC_RA
450 };
451 for (uint32_t generic_reg: k_expedited_registers)
452 {
453 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric, generic_reg);
454 if (reg_num == LLDB_INVALID_REGNUM)
455 continue; // Target does not support the given register.
456#endif
457
458 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
Pavel Labath4a4bb122015-07-16 14:14:35 +0000459 if (reg_info_p == nullptr)
460 {
461 if (log)
462 log->Printf("%s failed to get register info for register index %" PRIu32,
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000463 __FUNCTION__, reg_num);
Pavel Labath4a4bb122015-07-16 14:14:35 +0000464 continue;
465 }
466
467 if (reg_info_p->value_regs != nullptr)
468 continue; // Only expedite registers that are not contained in other registers.
469
470 RegisterValue reg_value;
471 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
472 if (error.Fail())
473 {
474 if (log)
475 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", __FUNCTION__,
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000476 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", reg_num,
Pavel Labath4a4bb122015-07-16 14:14:35 +0000477 error.AsCString ());
478 continue;
479 }
480
481 StreamString stream;
482 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p, &reg_value);
483
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000484 register_object_sp->SetObject(std::to_string(reg_num),
Pavel Labath4a4bb122015-07-16 14:14:35 +0000485 std::make_shared<JSONString>(stream.GetString()));
486 }
487
488 return register_object_sp;
489}
490
491static const char *
492GetStopReasonString(StopReason stop_reason)
493{
494 switch (stop_reason)
495 {
496 case eStopReasonTrace:
497 return "trace";
498 case eStopReasonBreakpoint:
499 return "breakpoint";
500 case eStopReasonWatchpoint:
501 return "watchpoint";
502 case eStopReasonSignal:
503 return "signal";
504 case eStopReasonException:
505 return "exception";
506 case eStopReasonExec:
507 return "exec";
508 case eStopReasonInstrumentation:
509 case eStopReasonInvalid:
510 case eStopReasonPlanComplete:
511 case eStopReasonThreadExiting:
512 case eStopReasonNone:
513 break; // ignored
514 }
515 return nullptr;
516}
517
Pavel Labath05569f62015-07-23 09:09:29 +0000518static JSONArray::SP
519GetJSONThreadsInfo(NativeProcessProtocol &process, bool threads_with_valid_stop_info_only)
520{
521 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
522
523 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
524
525 // Ensure we can get info on the given thread.
526 uint32_t thread_idx = 0;
527 for ( NativeThreadProtocolSP thread_sp;
528 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
529 ++thread_idx)
530 {
531
532 lldb::tid_t tid = thread_sp->GetID();
533
534 // Grab the reason this thread stopped.
535 struct ThreadStopInfo tid_stop_info;
536 std::string description;
537 if (!thread_sp->GetStopReason (tid_stop_info, description))
538 return nullptr;
539
540 const int signum = tid_stop_info.details.signal.signo;
541 if (log)
542 {
543 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
544 __FUNCTION__,
545 process.GetID (),
546 tid,
547 signum,
548 tid_stop_info.reason,
549 tid_stop_info.details.exception.type);
550 }
551
552 if (threads_with_valid_stop_info_only && tid_stop_info.reason == eStopReasonNone)
553 continue; // No stop reason, skip this thread completely.
554
555 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
556 threads_array_sp->AppendObject(thread_obj_sp);
557
558 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
559 if (signum != 0)
560 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(uint64_t(signum)));
561
562 const std::string thread_name = thread_sp->GetName ();
563 if (! thread_name.empty())
564 thread_obj_sp->SetObject("name", std::make_shared<JSONString>(thread_name));
565
566 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
567 thread_obj_sp->SetObject("reason", std::make_shared<JSONString>(stop_reason_str));
568
569 if (! description.empty())
570 thread_obj_sp->SetObject("description", std::make_shared<JSONString>(description));
571
572 if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
573 {
574 thread_obj_sp->SetObject("metype",
575 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
576
577 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
578 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
579 {
580 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
581 tid_stop_info.details.exception.data[i]));
582 }
583 thread_obj_sp->SetObject("medata", medata_array_sp);
584 }
585
586 if (threads_with_valid_stop_info_only)
587 continue; // Only send the abridged stop info.
588
589 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
590 thread_obj_sp->SetObject("registers", registers_sp);
591
592 // TODO: Expedite interesting regions of inferior memory
593 }
594
595 return threads_array_sp;
596}
597
Tamas Berghammere13c2732015-02-11 10:29:30 +0000598GDBRemoteCommunication::PacketResult
599GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread (lldb::tid_t tid)
600{
601 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
602
603 // Ensure we have a debugged process.
604 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
605 return SendErrorResponse (50);
606
607 if (log)
608 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
609 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
610
611 // Ensure we can get info on the given thread.
612 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
613 if (!thread_sp)
614 return SendErrorResponse (51);
615
616 // Grab the reason this thread stopped.
617 struct ThreadStopInfo tid_stop_info;
618 std::string description;
619 if (!thread_sp->GetStopReason (tid_stop_info, description))
620 return SendErrorResponse (52);
621
622 // FIXME implement register handling for exec'd inferiors.
623 // if (tid_stop_info.reason == eStopReasonExec)
624 // {
625 // const bool force = true;
626 // InitializeRegisters(force);
627 // }
628
629 StreamString response;
630 // Output the T packet with the thread
631 response.PutChar ('T');
632 int signum = tid_stop_info.details.signal.signo;
633 if (log)
634 {
635 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
636 __FUNCTION__,
637 m_debugged_process_sp->GetID (),
638 tid,
639 signum,
640 tid_stop_info.reason,
641 tid_stop_info.details.exception.type);
642 }
643
644 // Print the signal number.
645 response.PutHex8 (signum & 0xff);
646
647 // Include the tid.
648 response.Printf ("thread:%" PRIx64 ";", tid);
649
650 // Include the thread name if there is one.
651 const std::string thread_name = thread_sp->GetName ();
652 if (!thread_name.empty ())
653 {
654 size_t thread_name_len = thread_name.length ();
655
656 if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
657 {
658 response.PutCString ("name:");
659 response.PutCString (thread_name.c_str ());
660 }
661 else
662 {
663 // The thread name contains special chars, send as hex bytes.
664 response.PutCString ("hexname:");
665 response.PutCStringAsRawHex8 (thread_name.c_str ());
666 }
667 response.PutChar (';');
668 }
669
670 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
671 // will send all thread IDs back in the "threads" key whose value is
672 // a list of hex thread IDs separated by commas:
673 // "threads:10a,10b,10c;"
674 // This will save the debugger from having to send a pair of qfThreadInfo
675 // and qsThreadInfo packets, but it also might take a lot of room in the
676 // stop reply packet, so it must be enabled only on systems where there
677 // are no limits on packet lengths.
678 if (m_list_threads_in_stop_reply)
679 {
680 response.PutCString ("threads:");
681
682 uint32_t thread_index = 0;
683 NativeThreadProtocolSP listed_thread_sp;
684 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))
685 {
686 if (thread_index > 0)
687 response.PutChar (',');
688 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
689 }
690 response.PutChar (';');
Pavel Labath05569f62015-07-23 09:09:29 +0000691
692 // Include JSON info that describes the stop reason for any threads
693 // that actually have stop reasons. We use the new "jstopinfo" key
694 // whose values is hex ascii JSON that contains the thread IDs
695 // thread stop info only for threads that have stop reasons. Only send
696 // this if we have more than one thread otherwise this packet has all
697 // the info it needs.
698 if (thread_index > 0)
699 {
700 const bool threads_with_valid_stop_info_only = true;
701 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
702 threads_with_valid_stop_info_only);
703 if (threads_info_sp)
704 {
705 response.PutCString("jstopinfo:");
706 StreamString unescaped_response;
707 threads_info_sp->Write(unescaped_response);
708 response.PutCStringAsRawHex8(unescaped_response.GetData());
709 response.PutChar(';');
710 }
711 else if (log)
712 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a jstopinfo field for pid %" PRIu64,
713 __FUNCTION__, m_debugged_process_sp->GetID());
714
715 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000716 }
717
718 //
719 // Expedite registers.
720 //
721
722 // Grab the register context.
723 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
724 if (reg_ctx_sp)
725 {
726 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
727 const RegisterSet *reg_set_p;
728 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
729 {
730 if (log)
731 log->Printf ("GDBRemoteCommunicationServerLLGS::%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);
732
733 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
734 {
735 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
736 if (reg_info_p == nullptr)
737 {
738 if (log)
739 log->Printf ("GDBRemoteCommunicationServerLLGS::%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);
740 }
741 else if (reg_info_p->value_regs == nullptr)
742 {
743 // Only expediate registers that are not contained in other registers.
744 RegisterValue reg_value;
745 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
746 if (error.Success ())
Chaoren Lincaf31142015-02-17 15:41:28 +0000747 {
748 response.Printf ("%.02x:", *reg_num_p);
749 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p, &reg_value);
750 response.PutChar (';');
751 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000752 else
753 {
754 if (log)
755 log->Printf ("GDBRemoteCommunicationServerLLGS::%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 ());
756
757 }
758 }
759 }
760 }
761 }
762
Pavel Labath4a4bb122015-07-16 14:14:35 +0000763 const char* reason_str = GetStopReasonString(tid_stop_info.reason);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000764 if (reason_str != nullptr)
765 {
766 response.Printf ("reason:%s;", reason_str);
767 }
768
769 if (!description.empty())
770 {
771 // Description may contains special chars, send as hex bytes.
772 response.PutCString ("description:");
773 response.PutCStringAsRawHex8 (description.c_str ());
774 response.PutChar (';');
775 }
776 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
777 {
778 response.PutCString ("metype:");
779 response.PutHex64 (tid_stop_info.details.exception.type);
780 response.PutCString (";mecount:");
781 response.PutHex32 (tid_stop_info.details.exception.data_count);
782 response.PutChar (';');
783
784 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
785 {
786 response.PutCString ("medata:");
787 response.PutHex64 (tid_stop_info.details.exception.data[i]);
788 response.PutChar (';');
789 }
790 }
791
792 return SendPacketNoLock (response.GetData(), response.GetSize());
793}
794
795void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000796GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited (NativeProcessProtocol *process)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000797{
798 assert (process && "process cannot be NULL");
799
800 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
801 if (log)
802 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
803
Pavel Labathc7749c32015-07-21 13:20:25 +0000804 PacketResult result = SendStopReasonForState(StateType::eStateExited);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000805 if (result != PacketResult::Success)
806 {
807 if (log)
808 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
809 }
810
Tamas Berghammere13c2732015-02-11 10:29:30 +0000811 // Close the pipe to the inferior terminal i/o if we launched it
Pavel Labathc7749c32015-07-21 13:20:25 +0000812 // and set one up.
Tamas Berghammere13c2732015-02-11 10:29:30 +0000813 MaybeCloseInferiorTerminalConnection ();
814
815 // We are ready to exit the debug monitor.
816 m_exit_now = true;
817}
818
819void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000820GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped (NativeProcessProtocol *process)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000821{
822 assert (process && "process cannot be NULL");
823
824 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
825 if (log)
826 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
827
828 // Send the stop reason unless this is the stop after the
829 // launch or attach.
830 switch (m_inferior_prev_state)
831 {
832 case eStateLaunching:
833 case eStateAttaching:
834 // Don't send anything per debugserver behavior.
835 break;
836 default:
837 // In all other cases, send the stop reason.
Pavel Labathc7749c32015-07-21 13:20:25 +0000838 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000839 if (result != PacketResult::Success)
840 {
841 if (log)
842 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
843 }
844 break;
845 }
846}
847
848void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000849GDBRemoteCommunicationServerLLGS::ProcessStateChanged (NativeProcessProtocol *process, lldb::StateType state)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000850{
851 assert (process && "process cannot be NULL");
852 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
853 if (log)
854 {
855 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
856 __FUNCTION__,
857 process->GetID (),
858 StateAsCString (state));
859 }
860
Vince Harron43d79052015-04-15 10:40:51 +0000861 // Make sure we get all of the pending stdout/stderr from the inferior
862 // and send it to the lldb host before we send the state change
863 // notification
Pavel Labathc7749c32015-07-21 13:20:25 +0000864 SendProcessOutput();
Vince Harron43d79052015-04-15 10:40:51 +0000865
Tamas Berghammere13c2732015-02-11 10:29:30 +0000866 switch (state)
867 {
868 case StateType::eStateExited:
869 HandleInferiorState_Exited (process);
870 break;
871
872 case StateType::eStateStopped:
873 HandleInferiorState_Stopped (process);
874 break;
875
876 default:
877 if (log)
878 {
879 log->Printf ("GDBRemoteCommunicationServerLLGS::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
880 __FUNCTION__,
881 process->GetID (),
882 StateAsCString (state));
883 }
884 break;
885 }
886
887 // Remember the previous state reported to us.
888 m_inferior_prev_state = state;
889}
890
891void
892GDBRemoteCommunicationServerLLGS::DidExec (NativeProcessProtocol *process)
893{
894 ClearProcessSpecificData ();
895}
896
Pavel Labath77dc9562015-07-13 10:44:55 +0000897void
898GDBRemoteCommunicationServerLLGS::DataAvailableCallback ()
899{
900 Log *log (GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
901
902 if (! m_handshake_completed)
903 {
904 if (! HandshakeWithClient())
905 {
906 if(log)
907 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with client failed, exiting",
908 __FUNCTION__);
Pavel Labath77dc9562015-07-13 10:44:55 +0000909 m_mainloop.RequestTermination();
910 return;
911 }
912 m_handshake_completed = true;
913 }
914
915 bool interrupt = false;
916 bool done = false;
917 Error error;
918 while (true)
919 {
920 const PacketResult result = GetPacketAndSendResponse (0, error, interrupt, done);
921 if (result == PacketResult::ErrorReplyTimeout)
922 break; // No more packets in the queue
923
924 if ((result != PacketResult::Success))
925 {
926 if(log)
927 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet failed: %s",
928 __FUNCTION__, error.AsCString());
Pavel Labath77dc9562015-07-13 10:44:55 +0000929 m_mainloop.RequestTermination();
930 break;
931 }
932 }
933}
934
935Error
936GDBRemoteCommunicationServerLLGS::InitializeConnection (std::unique_ptr<Connection> &&connection)
937{
938 IOObjectSP read_object_sp = connection->GetReadObject();
939 GDBRemoteCommunicationServer::SetConnection(connection.release());
940
941 Error error;
Pavel Labathc7749c32015-07-21 13:20:25 +0000942 m_network_handle_up = m_mainloop.RegisterReadObject(read_object_sp,
Pavel Labath77dc9562015-07-13 10:44:55 +0000943 [this] (MainLoopBase &) { DataAvailableCallback(); }, error);
944 return error;
945}
946
Tamas Berghammere13c2732015-02-11 10:29:30 +0000947GDBRemoteCommunication::PacketResult
948GDBRemoteCommunicationServerLLGS::SendONotification (const char *buffer, uint32_t len)
949{
950 if ((buffer == nullptr) || (len == 0))
951 {
952 // Nothing to send.
953 return PacketResult::Success;
954 }
955
956 StreamString response;
957 response.PutChar ('O');
958 response.PutBytesAsRawHex8 (buffer, len);
959
960 return SendPacketNoLock (response.GetData (), response.GetSize ());
961}
962
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000963Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000964GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor (int fd)
965{
966 Error error;
967
Pavel Labathc7749c32015-07-21 13:20:25 +0000968 // Set up the reading/handling of process I/O
Tamas Berghammere13c2732015-02-11 10:29:30 +0000969 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
970 if (!conn_up)
971 {
972 error.SetErrorString ("failed to create ConnectionFileDescriptor");
973 return error;
974 }
975
Pavel Labathc7749c32015-07-21 13:20:25 +0000976 Mutex::Locker locker(m_stdio_communication_mutex);
Tamas Berghammer00bdca62015-03-19 14:58:36 +0000977 m_stdio_communication.SetCloseOnEOF (false);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000978 m_stdio_communication.SetConnection (conn_up.release());
979 if (!m_stdio_communication.IsConnected ())
980 {
981 error.SetErrorString ("failed to set connection for inferior I/O communication");
982 return error;
983 }
984
Vince Harron4a8abd32015-02-13 19:15:24 +0000985 // llgs local-process debugging may specify PTY paths, which will make these
986 // file actions non-null
987 // process launch -e/o will also make these file actions non-null
988 // nullptr means that the traffic is expected to flow over gdb-remote protocol
989 if (
990 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
991 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
992 )
993 {
994 // output from the process must be forwarded over gdb-remote
Pavel Labathc7749c32015-07-21 13:20:25 +0000995 m_stdio_handle_up = m_mainloop.RegisterReadObject(
996 m_stdio_communication.GetConnection()->GetReadObject(),
997 [this] (MainLoopBase &) { SendProcessOutput(); }, error);
998 if (! m_stdio_handle_up)
999 {
1000 m_stdio_communication.Disconnect();
1001 return error;
1002 }
Vince Harron4a8abd32015-02-13 19:15:24 +00001003 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001004
Pavel Labathc7749c32015-07-21 13:20:25 +00001005 return Error();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001006}
1007
1008void
Pavel Labathc7749c32015-07-21 13:20:25 +00001009GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding()
Tamas Berghammere13c2732015-02-11 10:29:30 +00001010{
Pavel Labathc7749c32015-07-21 13:20:25 +00001011 Mutex::Locker locker(m_stdio_communication_mutex);
1012 m_stdio_handle_up.reset();
1013}
1014
1015void
1016GDBRemoteCommunicationServerLLGS::SendProcessOutput()
1017{
1018 char buffer[1024];
1019 ConnectionStatus status;
1020 Error error;
1021 Mutex::Locker locker(m_stdio_communication_mutex);
1022 while (true)
1023 {
1024 size_t bytes_read = m_stdio_communication.Read(buffer, sizeof buffer, 0, status, &error);
1025 switch (status)
1026 {
1027 case eConnectionStatusSuccess:
1028 SendONotification(buffer, bytes_read);
1029 break;
1030 case eConnectionStatusLostConnection:
1031 case eConnectionStatusEndOfFile:
1032 case eConnectionStatusError:
1033 case eConnectionStatusNoConnection:
1034 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1035 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio forwarding as communication returned status %d (error: %s)", __FUNCTION__, status, error.AsCString());
1036 m_stdio_handle_up.reset();
1037 return;
1038
1039 case eConnectionStatusInterrupted:
1040 case eConnectionStatusTimedOut:
1041 return;
1042 }
1043 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001044}
1045
1046GDBRemoteCommunication::PacketResult
1047GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1048{
1049 // Fail if we don't have a current process.
1050 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1051 return SendErrorResponse (68);
1052
1053 lldb::pid_t pid = m_debugged_process_sp->GetID ();
1054
1055 if (pid == LLDB_INVALID_PROCESS_ID)
1056 return SendErrorResponse (1);
1057
1058 ProcessInstanceInfo proc_info;
1059 if (!Host::GetProcessInfo (pid, proc_info))
1060 return SendErrorResponse (1);
1061
1062 StreamString response;
1063 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1064 return SendPacketNoLock (response.GetData (), response.GetSize ());
1065}
1066
1067GDBRemoteCommunication::PacketResult
1068GDBRemoteCommunicationServerLLGS::Handle_qC (StringExtractorGDBRemote &packet)
1069{
1070 // Fail if we don't have a current process.
1071 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1072 return SendErrorResponse (68);
1073
1074 // Make sure we set the current thread so g and p packets return
1075 // the data the gdb will expect.
1076 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1077 SetCurrentThreadID (tid);
1078
1079 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1080 if (!thread_sp)
1081 return SendErrorResponse (69);
1082
1083 StreamString response;
1084 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1085
1086 return SendPacketNoLock (response.GetData(), response.GetSize());
1087}
1088
Tamas Berghammere13c2732015-02-11 10:29:30 +00001089GDBRemoteCommunication::PacketResult
1090GDBRemoteCommunicationServerLLGS::Handle_k (StringExtractorGDBRemote &packet)
1091{
Pavel Labath424b2012015-07-28 09:06:56 +00001092 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00001093
Pavel Labathc7749c32015-07-21 13:20:25 +00001094 StopSTDIOForwarding();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001095
Pavel Labath424b2012015-07-28 09:06:56 +00001096 if (! m_debugged_process_sp)
1097 {
1098 if (log)
1099 log->Printf("GDBRemoteCommunicationServerLLGS::%s No debugged process found.", __FUNCTION__);
1100 return PacketResult::Success;
1101 }
1102
1103 Error error = m_debugged_process_sp->Kill();
1104 if (error.Fail() && log)
1105 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged process %" PRIu64 ": %s",
1106 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1107
Tamas Berghammere13c2732015-02-11 10:29:30 +00001108 // No OK response for kill packet.
1109 // return SendOKResponse ();
1110 return PacketResult::Success;
1111}
1112
1113GDBRemoteCommunication::PacketResult
1114GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
1115{
1116 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
1117 if (packet.GetU32(0))
1118 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
1119 else
1120 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
1121 return SendOKResponse ();
1122}
1123
1124GDBRemoteCommunication::PacketResult
1125GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
1126{
1127 packet.SetFilePos (::strlen ("QSetWorkingDir:"));
1128 std::string path;
1129 packet.GetHexByteString (path);
Chaoren Lind3173f32015-05-29 19:52:29 +00001130 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
Tamas Berghammere13c2732015-02-11 10:29:30 +00001131 return SendOKResponse ();
1132}
1133
1134GDBRemoteCommunication::PacketResult
1135GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
1136{
Chaoren Lind3173f32015-05-29 19:52:29 +00001137 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1138 if (working_dir)
Tamas Berghammere13c2732015-02-11 10:29:30 +00001139 {
1140 StreamString response;
Chaoren Lind3173f32015-05-29 19:52:29 +00001141 response.PutCStringAsRawHex8(working_dir.GetCString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001142 return SendPacketNoLock(response.GetData(), response.GetSize());
1143 }
1144
1145 return SendErrorResponse(14);
1146}
1147
1148GDBRemoteCommunication::PacketResult
1149GDBRemoteCommunicationServerLLGS::Handle_C (StringExtractorGDBRemote &packet)
1150{
1151 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1152 if (log)
1153 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1154
1155 // Ensure we have a native process.
1156 if (!m_debugged_process_sp)
1157 {
1158 if (log)
1159 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1160 return SendErrorResponse (0x36);
1161 }
1162
1163 // Pull out the signal number.
1164 packet.SetFilePos (::strlen ("C"));
1165 if (packet.GetBytesLeft () < 1)
1166 {
1167 // Shouldn't be using a C without a signal.
1168 return SendIllFormedResponse (packet, "C packet specified without signal.");
1169 }
1170 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1171 if (signo == std::numeric_limits<uint32_t>::max ())
1172 return SendIllFormedResponse (packet, "failed to parse signal number");
1173
1174 // Handle optional continue address.
1175 if (packet.GetBytesLeft () > 0)
1176 {
1177 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1178 if (*packet.Peek () == ';')
1179 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1180 else
1181 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
1182 }
1183
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001184 ResumeActionList resume_actions (StateType::eStateRunning, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001185 Error error;
1186
1187 // We have two branches: what to do if a continue thread is specified (in which case we target
1188 // sending the signal to that thread), or when we don't have a continue thread set (in which
1189 // case we send a signal to the process).
1190
1191 // TODO discuss with Greg Clayton, make sure this makes sense.
1192
1193 lldb::tid_t signal_tid = GetContinueThreadID ();
1194 if (signal_tid != LLDB_INVALID_THREAD_ID)
1195 {
1196 // The resume action for the continue thread (or all threads if a continue thread is not set).
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001197 ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
Tamas Berghammere13c2732015-02-11 10:29:30 +00001198
1199 // Add the action for the continue thread (or all threads when the continue thread isn't present).
1200 resume_actions.Append (action);
1201 }
1202 else
1203 {
1204 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
1205 error = m_debugged_process_sp->Signal (signo);
1206 if (error.Fail ())
1207 {
1208 if (log)
1209 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send signal for process %" PRIu64 ": %s",
1210 __FUNCTION__,
1211 m_debugged_process_sp->GetID (),
1212 error.AsCString ());
1213
1214 return SendErrorResponse (0x52);
1215 }
1216 }
1217
1218 // Resume the threads.
1219 error = m_debugged_process_sp->Resume (resume_actions);
1220 if (error.Fail ())
1221 {
1222 if (log)
1223 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to resume threads for process %" PRIu64 ": %s",
1224 __FUNCTION__,
1225 m_debugged_process_sp->GetID (),
1226 error.AsCString ());
1227
1228 return SendErrorResponse (0x38);
1229 }
1230
1231 // Don't send an "OK" packet; response is the stopped/exited message.
1232 return PacketResult::Success;
1233}
1234
1235GDBRemoteCommunication::PacketResult
1236GDBRemoteCommunicationServerLLGS::Handle_c (StringExtractorGDBRemote &packet)
1237{
1238 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1239 if (log)
1240 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1241
1242 packet.SetFilePos (packet.GetFilePos() + ::strlen ("c"));
1243
1244 // For now just support all continue.
1245 const bool has_continue_address = (packet.GetBytesLeft () > 0);
1246 if (has_continue_address)
1247 {
1248 if (log)
1249 log->Printf ("GDBRemoteCommunicationServerLLGS::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
1250 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1251 }
1252
1253 // Ensure we have a native process.
1254 if (!m_debugged_process_sp)
1255 {
1256 if (log)
1257 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1258 return SendErrorResponse (0x36);
1259 }
1260
1261 // Build the ResumeActionList
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001262 ResumeActionList actions (StateType::eStateRunning, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001263
1264 Error error = m_debugged_process_sp->Resume (actions);
1265 if (error.Fail ())
1266 {
1267 if (log)
1268 {
1269 log->Printf ("GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64 ": %s",
1270 __FUNCTION__,
1271 m_debugged_process_sp->GetID (),
1272 error.AsCString ());
1273 }
1274 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1275 }
1276
1277 if (log)
1278 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1279
1280 // No response required from continue.
1281 return PacketResult::Success;
1282}
1283
1284GDBRemoteCommunication::PacketResult
1285GDBRemoteCommunicationServerLLGS::Handle_vCont_actions (StringExtractorGDBRemote &packet)
1286{
1287 StreamString response;
1288 response.Printf("vCont;c;C;s;S");
1289
1290 return SendPacketNoLock(response.GetData(), response.GetSize());
1291}
1292
1293GDBRemoteCommunication::PacketResult
1294GDBRemoteCommunicationServerLLGS::Handle_vCont (StringExtractorGDBRemote &packet)
1295{
1296 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1297 if (log)
1298 log->Printf ("GDBRemoteCommunicationServerLLGS::%s handling vCont packet", __FUNCTION__);
1299
1300 packet.SetFilePos (::strlen ("vCont"));
1301
1302 if (packet.GetBytesLeft() == 0)
1303 {
1304 if (log)
1305 log->Printf ("GDBRemoteCommunicationServerLLGS::%s missing action from vCont package", __FUNCTION__);
1306 return SendIllFormedResponse (packet, "Missing action from vCont package");
1307 }
1308
1309 // Check if this is all continue (no options or ";c").
1310 if (::strcmp (packet.Peek (), ";c") == 0)
1311 {
1312 // Move past the ';', then do a simple 'c'.
1313 packet.SetFilePos (packet.GetFilePos () + 1);
1314 return Handle_c (packet);
1315 }
1316 else if (::strcmp (packet.Peek (), ";s") == 0)
1317 {
1318 // Move past the ';', then do a simple 's'.
1319 packet.SetFilePos (packet.GetFilePos () + 1);
1320 return Handle_s (packet);
1321 }
1322
1323 // Ensure we have a native process.
1324 if (!m_debugged_process_sp)
1325 {
1326 if (log)
1327 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1328 return SendErrorResponse (0x36);
1329 }
1330
1331 ResumeActionList thread_actions;
1332
1333 while (packet.GetBytesLeft () && *packet.Peek () == ';')
1334 {
1335 // Skip the semi-colon.
1336 packet.GetChar ();
1337
1338 // Build up the thread action.
1339 ResumeAction thread_action;
1340 thread_action.tid = LLDB_INVALID_THREAD_ID;
1341 thread_action.state = eStateInvalid;
1342 thread_action.signal = 0;
1343
1344 const char action = packet.GetChar ();
1345 switch (action)
1346 {
1347 case 'C':
1348 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1349 if (thread_action.signal == 0)
1350 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
1351 // Fall through to next case...
1352
1353 case 'c':
1354 // Continue
1355 thread_action.state = eStateRunning;
1356 break;
1357
1358 case 'S':
1359 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1360 if (thread_action.signal == 0)
1361 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
1362 // Fall through to next case...
1363
1364 case 's':
1365 // Step
1366 thread_action.state = eStateStepping;
1367 break;
1368
1369 default:
1370 return SendIllFormedResponse (packet, "Unsupported vCont action");
1371 break;
1372 }
1373
1374 // Parse out optional :{thread-id} value.
1375 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
1376 {
1377 // Consume the separator.
1378 packet.GetChar ();
1379
1380 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
1381 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1382 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
1383 }
1384
1385 thread_actions.Append (thread_action);
1386 }
1387
1388 Error error = m_debugged_process_sp->Resume (thread_actions);
1389 if (error.Fail ())
1390 {
1391 if (log)
1392 {
1393 log->Printf ("GDBRemoteCommunicationServerLLGS::%s vCont failed for process %" PRIu64 ": %s",
1394 __FUNCTION__,
1395 m_debugged_process_sp->GetID (),
1396 error.AsCString ());
1397 }
1398 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1399 }
1400
1401 if (log)
1402 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1403
1404 // No response required from vCont.
1405 return PacketResult::Success;
1406}
1407
1408void
1409GDBRemoteCommunicationServerLLGS::SetCurrentThreadID (lldb::tid_t tid)
1410{
1411 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1412 if (log)
1413 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
1414
1415 m_current_tid = tid;
1416 if (m_debugged_process_sp)
1417 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
1418}
1419
1420void
1421GDBRemoteCommunicationServerLLGS::SetContinueThreadID (lldb::tid_t tid)
1422{
1423 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1424 if (log)
1425 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
1426
1427 m_continue_tid = tid;
1428}
1429
1430GDBRemoteCommunication::PacketResult
1431GDBRemoteCommunicationServerLLGS::Handle_stop_reason (StringExtractorGDBRemote &packet)
1432{
1433 // Handle the $? gdbremote command.
1434
1435 // If no process, indicate error
1436 if (!m_debugged_process_sp)
1437 return SendErrorResponse (02);
1438
Pavel Labathc7749c32015-07-21 13:20:25 +00001439 return SendStopReasonForState (m_debugged_process_sp->GetState());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001440}
1441
1442GDBRemoteCommunication::PacketResult
Pavel Labathc7749c32015-07-21 13:20:25 +00001443GDBRemoteCommunicationServerLLGS::SendStopReasonForState (lldb::StateType process_state)
Tamas Berghammere13c2732015-02-11 10:29:30 +00001444{
1445 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1446
1447 switch (process_state)
1448 {
1449 case eStateAttaching:
1450 case eStateLaunching:
1451 case eStateRunning:
1452 case eStateStepping:
1453 case eStateDetached:
1454 // NOTE: gdb protocol doc looks like it should return $OK
1455 // when everything is running (i.e. no stopped result).
1456 return PacketResult::Success; // Ignore
1457
1458 case eStateSuspended:
1459 case eStateStopped:
1460 case eStateCrashed:
1461 {
1462 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1463 // Make sure we set the current thread so g and p packets return
1464 // the data the gdb will expect.
1465 SetCurrentThreadID (tid);
1466 return SendStopReplyPacketForThread (tid);
1467 }
1468
1469 case eStateInvalid:
1470 case eStateUnloaded:
1471 case eStateExited:
Tamas Berghammere13c2732015-02-11 10:29:30 +00001472 return SendWResponse(m_debugged_process_sp.get());
1473
1474 default:
1475 if (log)
1476 {
1477 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", current state reporting not handled: %s",
1478 __FUNCTION__,
1479 m_debugged_process_sp->GetID (),
1480 StateAsCString (process_state));
1481 }
1482 break;
1483 }
1484
1485 return SendErrorResponse (0);
1486}
1487
1488GDBRemoteCommunication::PacketResult
1489GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
1490{
1491 // Fail if we don't have a current process.
1492 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1493 return SendErrorResponse (68);
1494
1495 // Ensure we have a thread.
1496 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
1497 if (!thread_sp)
1498 return SendErrorResponse (69);
1499
1500 // Get the register context for the first thread.
1501 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1502 if (!reg_context_sp)
1503 return SendErrorResponse (69);
1504
1505 // Parse out the register number from the request.
1506 packet.SetFilePos (strlen("qRegisterInfo"));
1507 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1508 if (reg_index == std::numeric_limits<uint32_t>::max ())
1509 return SendErrorResponse (69);
1510
1511 // Return the end of registers response if we've iterated one past the end of the register set.
1512 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1513 return SendErrorResponse (69);
1514
1515 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1516 if (!reg_info)
1517 return SendErrorResponse (69);
1518
1519 // Build the reginfos response.
1520 StreamGDBRemote response;
1521
1522 response.PutCString ("name:");
1523 response.PutCString (reg_info->name);
1524 response.PutChar (';');
1525
1526 if (reg_info->alt_name && reg_info->alt_name[0])
1527 {
1528 response.PutCString ("alt-name:");
1529 response.PutCString (reg_info->alt_name);
1530 response.PutChar (';');
1531 }
1532
1533 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
1534
1535 switch (reg_info->encoding)
1536 {
1537 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
1538 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
1539 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
1540 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
1541 default: break;
1542 }
1543
1544 switch (reg_info->format)
1545 {
1546 case eFormatBinary: response.PutCString ("format:binary;"); break;
1547 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
1548 case eFormatHex: response.PutCString ("format:hex;"); break;
1549 case eFormatFloat: response.PutCString ("format:float;"); break;
1550 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
1551 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
1552 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
1553 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
1554 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
1555 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
1556 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
1557 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
1558 default: break;
1559 };
1560
1561 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1562 if (register_set_name)
1563 {
1564 response.PutCString ("set:");
1565 response.PutCString (register_set_name);
1566 response.PutChar (';');
1567 }
1568
Jason Molendaa18f7072015-08-15 01:21:01 +00001569 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
1570 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001571
1572 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1573 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1574
1575 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
1576 {
1577 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
1578 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
1579 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
1580 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
1581 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
1582 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
1583 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
1584 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
1585 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
1586 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
1587 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
1588 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
1589 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
1590 default: break;
1591 }
1592
1593 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
1594 {
1595 response.PutCString ("container-regs:");
1596 int i = 0;
1597 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1598 {
1599 if (i > 0)
1600 response.PutChar (',');
1601 response.Printf ("%" PRIx32, *reg_num);
1602 }
1603 response.PutChar (';');
1604 }
1605
1606 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
1607 {
1608 response.PutCString ("invalidate-regs:");
1609 int i = 0;
1610 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1611 {
1612 if (i > 0)
1613 response.PutChar (',');
1614 response.Printf ("%" PRIx32, *reg_num);
1615 }
1616 response.PutChar (';');
1617 }
1618
1619 return SendPacketNoLock(response.GetData(), response.GetSize());
1620}
1621
1622GDBRemoteCommunication::PacketResult
1623GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
1624{
1625 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1626
1627 // Fail if we don't have a current process.
1628 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1629 {
1630 if (log)
1631 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
1632 return SendOKResponse ();
1633 }
1634
1635 StreamGDBRemote response;
1636 response.PutChar ('m');
1637
1638 if (log)
1639 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() starting thread iteration", __FUNCTION__);
1640
1641 NativeThreadProtocolSP thread_sp;
1642 uint32_t thread_index;
1643 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
1644 thread_sp;
1645 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
1646 {
1647 if (log)
1648 log->Printf ("GDBRemoteCommunicationServerLLGS::%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);
1649 if (thread_index > 0)
1650 response.PutChar(',');
1651 response.Printf ("%" PRIx64, thread_sp->GetID ());
1652 }
1653
1654 if (log)
1655 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() finished thread iteration", __FUNCTION__);
1656
1657 return SendPacketNoLock(response.GetData(), response.GetSize());
1658}
1659
1660GDBRemoteCommunication::PacketResult
1661GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
1662{
1663 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
1664 return SendPacketNoLock ("l", 1);
1665}
1666
1667GDBRemoteCommunication::PacketResult
1668GDBRemoteCommunicationServerLLGS::Handle_p (StringExtractorGDBRemote &packet)
1669{
1670 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1671
1672 // Parse out the register number from the request.
1673 packet.SetFilePos (strlen("p"));
1674 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1675 if (reg_index == std::numeric_limits<uint32_t>::max ())
1676 {
1677 if (log)
1678 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1679 return SendErrorResponse (0x15);
1680 }
1681
1682 // Get the thread to use.
1683 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1684 if (!thread_sp)
1685 {
1686 if (log)
1687 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available", __FUNCTION__);
1688 return SendErrorResponse (0x15);
1689 }
1690
1691 // Get the thread's register context.
1692 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1693 if (!reg_context_sp)
1694 {
1695 if (log)
1696 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
1697 return SendErrorResponse (0x15);
1698 }
1699
1700 // Return the end of registers response if we've iterated one past the end of the register set.
1701 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1702 {
1703 if (log)
1704 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1705 return SendErrorResponse (0x15);
1706 }
1707
1708 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1709 if (!reg_info)
1710 {
1711 if (log)
1712 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1713 return SendErrorResponse (0x15);
1714 }
1715
1716 // Build the reginfos response.
1717 StreamGDBRemote response;
1718
1719 // Retrieve the value
1720 RegisterValue reg_value;
1721 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
1722 if (error.Fail ())
1723 {
1724 if (log)
1725 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1726 return SendErrorResponse (0x15);
1727 }
1728
1729 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
1730 if (!data)
1731 {
1732 if (log)
1733 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
1734 return SendErrorResponse (0x15);
1735 }
1736
1737 // FIXME flip as needed to get data in big/little endian format for this host.
1738 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
1739 response.PutHex8 (data[i]);
1740
1741 return SendPacketNoLock (response.GetData (), response.GetSize ());
1742}
1743
1744GDBRemoteCommunication::PacketResult
1745GDBRemoteCommunicationServerLLGS::Handle_P (StringExtractorGDBRemote &packet)
1746{
1747 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1748
1749 // Ensure there is more content.
1750 if (packet.GetBytesLeft () < 1)
1751 return SendIllFormedResponse (packet, "Empty P packet");
1752
1753 // Parse out the register number from the request.
1754 packet.SetFilePos (strlen("P"));
1755 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1756 if (reg_index == std::numeric_limits<uint32_t>::max ())
1757 {
1758 if (log)
1759 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1760 return SendErrorResponse (0x29);
1761 }
1762
1763 // Note debugserver would send an E30 here.
1764 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
1765 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
1766
1767 // Get process architecture.
1768 ArchSpec process_arch;
1769 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
1770 {
1771 if (log)
1772 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to retrieve inferior architecture", __FUNCTION__);
1773 return SendErrorResponse (0x49);
1774 }
1775
1776 // Parse out the value.
1777 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1778 size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes));
1779
1780 // Get the thread to use.
1781 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1782 if (!thread_sp)
1783 {
1784 if (log)
1785 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available (thread index 0)", __FUNCTION__);
1786 return SendErrorResponse (0x28);
1787 }
1788
1789 // Get the thread's register context.
1790 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1791 if (!reg_context_sp)
1792 {
1793 if (log)
1794 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
1795 return SendErrorResponse (0x15);
1796 }
1797
1798 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index);
1799 if (!reg_info)
1800 {
1801 if (log)
1802 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1803 return SendErrorResponse (0x48);
1804 }
1805
1806 // Return the end of registers response if we've iterated one past the end of the register set.
1807 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1808 {
1809 if (log)
1810 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1811 return SendErrorResponse (0x47);
1812 }
1813
1814 if (reg_size != reg_info->byte_size)
1815 {
1816 return SendIllFormedResponse (packet, "P packet register size is incorrect");
1817 }
1818
1819 // Build the reginfos response.
1820 StreamGDBRemote response;
1821
1822 RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
1823 Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
1824 if (error.Fail ())
1825 {
1826 if (log)
1827 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1828 return SendErrorResponse (0x32);
1829 }
1830
1831 return SendOKResponse();
1832}
1833
1834GDBRemoteCommunication::PacketResult
1835GDBRemoteCommunicationServerLLGS::Handle_H (StringExtractorGDBRemote &packet)
1836{
1837 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1838
1839 // Fail if we don't have a current process.
1840 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1841 {
1842 if (log)
1843 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1844 return SendErrorResponse (0x15);
1845 }
1846
1847 // Parse out which variant of $H is requested.
1848 packet.SetFilePos (strlen("H"));
1849 if (packet.GetBytesLeft () < 1)
1850 {
1851 if (log)
1852 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, H command missing {g,c} variant", __FUNCTION__);
1853 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
1854 }
1855
1856 const char h_variant = packet.GetChar ();
1857 switch (h_variant)
1858 {
1859 case 'g':
1860 break;
1861
1862 case 'c':
1863 break;
1864
1865 default:
1866 if (log)
1867 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
1868 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1869 }
1870
1871 // Parse out the thread number.
1872 // FIXME return a parse success/fail value. All values are valid here.
1873 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
1874
1875 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
1876 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
1877 {
1878 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
1879 if (!thread_sp)
1880 {
1881 if (log)
1882 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
1883 return SendErrorResponse (0x15);
1884 }
1885 }
1886
1887 // Now switch the given thread type.
1888 switch (h_variant)
1889 {
1890 case 'g':
1891 SetCurrentThreadID (tid);
1892 break;
1893
1894 case 'c':
1895 SetContinueThreadID (tid);
1896 break;
1897
1898 default:
1899 assert (false && "unsupported $H variant - shouldn't get here");
1900 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1901 }
1902
1903 return SendOKResponse();
1904}
1905
1906GDBRemoteCommunication::PacketResult
1907GDBRemoteCommunicationServerLLGS::Handle_I (StringExtractorGDBRemote &packet)
1908{
1909 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1910
1911 // Fail if we don't have a current process.
1912 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1913 {
1914 if (log)
1915 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1916 return SendErrorResponse (0x15);
1917 }
1918
1919 packet.SetFilePos (::strlen("I"));
1920 char tmp[4096];
1921 for (;;)
1922 {
1923 size_t read = packet.GetHexBytesAvail(tmp, sizeof(tmp));
1924 if (read == 0)
1925 {
1926 break;
1927 }
1928 // write directly to stdin *this might block if stdin buffer is full*
1929 // TODO: enqueue this block in circular buffer and send window size to remote host
1930 ConnectionStatus status;
1931 Error error;
Pavel Labathc7749c32015-07-21 13:20:25 +00001932 Mutex::Locker locker(m_stdio_communication_mutex);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001933 m_stdio_communication.Write(tmp, read, status, &error);
1934 if (error.Fail())
1935 {
1936 return SendErrorResponse (0x15);
1937 }
1938 }
1939
1940 return SendOKResponse();
1941}
1942
1943GDBRemoteCommunication::PacketResult
1944GDBRemoteCommunicationServerLLGS::Handle_interrupt (StringExtractorGDBRemote &packet)
1945{
1946 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1947
1948 // Fail if we don't have a current process.
1949 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1950 {
1951 if (log)
1952 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1953 return SendErrorResponse (0x15);
1954 }
1955
1956 // Interrupt the process.
1957 Error error = m_debugged_process_sp->Interrupt ();
1958 if (error.Fail ())
1959 {
1960 if (log)
1961 {
1962 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64 ": %s",
1963 __FUNCTION__,
1964 m_debugged_process_sp->GetID (),
1965 error.AsCString ());
1966 }
1967 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1968 }
1969
1970 if (log)
1971 log->Printf ("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1972
1973 // No response required from stop all.
1974 return PacketResult::Success;
1975}
1976
1977GDBRemoteCommunication::PacketResult
1978GDBRemoteCommunicationServerLLGS::Handle_m (StringExtractorGDBRemote &packet)
1979{
1980 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1981
1982 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1983 {
1984 if (log)
1985 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1986 return SendErrorResponse (0x15);
1987 }
1988
1989 // Parse out the memory address.
1990 packet.SetFilePos (strlen("m"));
1991 if (packet.GetBytesLeft() < 1)
1992 return SendIllFormedResponse(packet, "Too short m packet");
1993
1994 // Read the address. Punting on validation.
1995 // FIXME replace with Hex U64 read with no default value that fails on failed read.
1996 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
1997
1998 // Validate comma.
1999 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2000 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2001
2002 // Get # bytes to read.
2003 if (packet.GetBytesLeft() < 1)
2004 return SendIllFormedResponse(packet, "Length missing in m packet");
2005
2006 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2007 if (byte_count == 0)
2008 {
2009 if (log)
2010 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to read: zero-length packet", __FUNCTION__);
2011 return PacketResult::Success;
2012 }
2013
2014 // Allocate the response buffer.
2015 std::string buf(byte_count, '\0');
2016 if (buf.empty())
2017 return SendErrorResponse (0x78);
2018
2019
2020 // Retrieve the process memory.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002021 size_t bytes_read = 0;
2022 Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(read_addr, &buf[0], byte_count, bytes_read);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002023 if (error.Fail ())
2024 {
2025 if (log)
2026 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
2027 return SendErrorResponse (0x08);
2028 }
2029
2030 if (bytes_read == 0)
2031 {
2032 if (log)
Ilia Kd50ea2f2015-05-15 09:15:27 +00002033 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, byte_count);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002034 return SendErrorResponse (0x08);
2035 }
2036
2037 StreamGDBRemote response;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002038 for (size_t i = 0; i < bytes_read; ++i)
Tamas Berghammere13c2732015-02-11 10:29:30 +00002039 response.PutHex8(buf[i]);
2040
2041 return SendPacketNoLock(response.GetData(), response.GetSize());
2042}
2043
2044GDBRemoteCommunication::PacketResult
2045GDBRemoteCommunicationServerLLGS::Handle_M (StringExtractorGDBRemote &packet)
2046{
2047 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2048
2049 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2050 {
2051 if (log)
2052 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2053 return SendErrorResponse (0x15);
2054 }
2055
2056 // Parse out the memory address.
2057 packet.SetFilePos (strlen("M"));
2058 if (packet.GetBytesLeft() < 1)
2059 return SendIllFormedResponse(packet, "Too short M packet");
2060
2061 // Read the address. Punting on validation.
2062 // FIXME replace with Hex U64 read with no default value that fails on failed read.
2063 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2064
2065 // Validate comma.
2066 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2067 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2068
2069 // Get # bytes to read.
2070 if (packet.GetBytesLeft() < 1)
2071 return SendIllFormedResponse(packet, "Length missing in M packet");
2072
2073 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2074 if (byte_count == 0)
2075 {
2076 if (log)
2077 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to write: zero-length packet", __FUNCTION__);
2078 return PacketResult::Success;
2079 }
2080
2081 // Validate colon.
2082 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2083 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
2084
2085 // Allocate the conversion buffer.
2086 std::vector<uint8_t> buf(byte_count, 0);
2087 if (buf.empty())
2088 return SendErrorResponse (0x78);
2089
2090 // Convert the hex memory write contents to bytes.
2091 StreamGDBRemote response;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002092 const uint64_t convert_count = packet.GetHexBytes(&buf[0], byte_count, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002093 if (convert_count != byte_count)
2094 {
2095 if (log)
2096 log->Printf ("GDBRemoteCommunicationServerLLGS::%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);
2097 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
2098 }
2099
2100 // Write the process memory.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002101 size_t bytes_written = 0;
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002102 Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002103 if (error.Fail ())
2104 {
2105 if (log)
2106 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
2107 return SendErrorResponse (0x09);
2108 }
2109
2110 if (bytes_written == 0)
2111 {
2112 if (log)
Ilia Kd50ea2f2015-05-15 09:15:27 +00002113 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, byte_count);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002114 return SendErrorResponse (0x09);
2115 }
2116
2117 return SendOKResponse ();
2118}
2119
2120GDBRemoteCommunication::PacketResult
2121GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
2122{
2123 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2124
2125 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
2126 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
2127 // client only asks this when a process is being debugged.
2128
2129 // Ensure we have a process running; otherwise, we can't figure this out
2130 // since we won't have a NativeProcessProtocol.
2131 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2132 {
2133 if (log)
2134 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2135 return SendErrorResponse (0x15);
2136 }
2137
2138 // Test if we can get any region back when asking for the region around NULL.
2139 MemoryRegionInfo region_info;
2140 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
2141 if (error.Fail ())
2142 {
2143 // We don't support memory region info collection for this NativeProcessProtocol.
2144 return SendUnimplementedResponse ("");
2145 }
2146
2147 return SendOKResponse();
2148}
2149
2150GDBRemoteCommunication::PacketResult
2151GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
2152{
2153 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2154
2155 // Ensure we have a process.
2156 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2157 {
2158 if (log)
2159 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2160 return SendErrorResponse (0x15);
2161 }
2162
2163 // Parse out the memory address.
2164 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
2165 if (packet.GetBytesLeft() < 1)
2166 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2167
2168 // Read the address. Punting on validation.
2169 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2170
2171 StreamGDBRemote response;
2172
2173 // Get the memory region info for the target address.
2174 MemoryRegionInfo region_info;
2175 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
2176 if (error.Fail ())
2177 {
2178 // Return the error message.
2179
2180 response.PutCString ("error:");
2181 response.PutCStringAsRawHex8 (error.AsCString ());
2182 response.PutChar (';');
2183 }
2184 else
2185 {
2186 // Range start and size.
2187 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
2188
2189 // Permissions.
2190 if (region_info.GetReadable () ||
2191 region_info.GetWritable () ||
2192 region_info.GetExecutable ())
2193 {
2194 // Write permissions info.
2195 response.PutCString ("permissions:");
2196
2197 if (region_info.GetReadable ())
2198 response.PutChar ('r');
2199 if (region_info.GetWritable ())
2200 response.PutChar('w');
2201 if (region_info.GetExecutable())
2202 response.PutChar ('x');
2203
2204 response.PutChar (';');
2205 }
2206 }
2207
2208 return SendPacketNoLock(response.GetData(), response.GetSize());
2209}
2210
2211GDBRemoteCommunication::PacketResult
2212GDBRemoteCommunicationServerLLGS::Handle_Z (StringExtractorGDBRemote &packet)
2213{
2214 // Ensure we have a process.
2215 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2216 {
2217 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2218 if (log)
2219 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2220 return SendErrorResponse (0x15);
2221 }
2222
2223 // Parse out software or hardware breakpoint or watchpoint requested.
2224 packet.SetFilePos (strlen("Z"));
2225 if (packet.GetBytesLeft() < 1)
2226 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
2227
2228 bool want_breakpoint = true;
2229 bool want_hardware = false;
Omair Javaidcf8eb9d2015-08-12 11:30:21 +00002230 uint32_t watch_flags = 0;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002231
2232 const GDBStoppointType stoppoint_type =
2233 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2234 switch (stoppoint_type)
2235 {
2236 case eBreakpointSoftware:
2237 want_hardware = false; want_breakpoint = true; break;
2238 case eBreakpointHardware:
2239 want_hardware = true; want_breakpoint = true; break;
2240 case eWatchpointWrite:
Omair Javaidcf8eb9d2015-08-12 11:30:21 +00002241 watch_flags = 1;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002242 want_hardware = true; want_breakpoint = false; break;
2243 case eWatchpointRead:
Omair Javaidcf8eb9d2015-08-12 11:30:21 +00002244 watch_flags = 2;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002245 want_hardware = true; want_breakpoint = false; break;
2246 case eWatchpointReadWrite:
Omair Javaidcf8eb9d2015-08-12 11:30:21 +00002247 watch_flags = 3;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002248 want_hardware = true; want_breakpoint = false; break;
2249 case eStoppointInvalid:
2250 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
2251
2252 }
2253
2254 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2255 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type");
2256
2257 // Parse out the stoppoint address.
2258 if (packet.GetBytesLeft() < 1)
2259 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2260 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2261
2262 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2263 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
2264
2265 // Parse out the stoppoint size (i.e. size hint for opcode size).
2266 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2267 if (size == std::numeric_limits<uint32_t>::max ())
2268 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument");
2269
2270 if (want_breakpoint)
2271 {
2272 // Try to set the breakpoint.
2273 const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware);
2274 if (error.Success ())
2275 return SendOKResponse ();
2276 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2277 if (log)
2278 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2279 " failed to set breakpoint: %s",
2280 __FUNCTION__,
2281 m_debugged_process_sp->GetID (),
2282 error.AsCString ());
2283 return SendErrorResponse (0x09);
2284 }
2285 else
2286 {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002287 // Try to set the watchpoint.
2288 const Error error = m_debugged_process_sp->SetWatchpoint (
2289 addr, size, watch_flags, want_hardware);
2290 if (error.Success ())
2291 return SendOKResponse ();
2292 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2293 if (log)
2294 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2295 " failed to set watchpoint: %s",
2296 __FUNCTION__,
2297 m_debugged_process_sp->GetID (),
2298 error.AsCString ());
2299 return SendErrorResponse (0x09);
2300 }
2301}
2302
2303GDBRemoteCommunication::PacketResult
2304GDBRemoteCommunicationServerLLGS::Handle_z (StringExtractorGDBRemote &packet)
2305{
2306 // Ensure we have a process.
2307 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2308 {
2309 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2310 if (log)
2311 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2312 return SendErrorResponse (0x15);
2313 }
2314
2315 // Parse out software or hardware breakpoint or watchpoint requested.
2316 packet.SetFilePos (strlen("z"));
2317 if (packet.GetBytesLeft() < 1)
2318 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
2319
2320 bool want_breakpoint = true;
2321
2322 const GDBStoppointType stoppoint_type =
2323 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2324 switch (stoppoint_type)
2325 {
2326 case eBreakpointHardware: want_breakpoint = true; break;
2327 case eBreakpointSoftware: want_breakpoint = true; break;
2328 case eWatchpointWrite: want_breakpoint = false; break;
2329 case eWatchpointRead: want_breakpoint = false; break;
2330 case eWatchpointReadWrite: want_breakpoint = false; break;
2331 default:
2332 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
2333
2334 }
2335
2336 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2337 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type");
2338
2339 // Parse out the stoppoint address.
2340 if (packet.GetBytesLeft() < 1)
2341 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2342 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2343
2344 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2345 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
2346
2347 /*
2348 // Parse out the stoppoint size (i.e. size hint for opcode size).
2349 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2350 if (size == std::numeric_limits<uint32_t>::max ())
2351 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument");
2352 */
2353
2354 if (want_breakpoint)
2355 {
2356 // Try to clear the breakpoint.
2357 const Error error = m_debugged_process_sp->RemoveBreakpoint (addr);
2358 if (error.Success ())
2359 return SendOKResponse ();
2360 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2361 if (log)
2362 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2363 " failed to remove breakpoint: %s",
2364 __FUNCTION__,
2365 m_debugged_process_sp->GetID (),
2366 error.AsCString ());
2367 return SendErrorResponse (0x09);
2368 }
2369 else
2370 {
2371 // Try to clear the watchpoint.
2372 const Error error = m_debugged_process_sp->RemoveWatchpoint (addr);
2373 if (error.Success ())
2374 return SendOKResponse ();
2375 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2376 if (log)
2377 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2378 " failed to remove watchpoint: %s",
2379 __FUNCTION__,
2380 m_debugged_process_sp->GetID (),
2381 error.AsCString ());
2382 return SendErrorResponse (0x09);
2383 }
2384}
2385
2386GDBRemoteCommunication::PacketResult
2387GDBRemoteCommunicationServerLLGS::Handle_s (StringExtractorGDBRemote &packet)
2388{
2389 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2390
2391 // Ensure we have a process.
2392 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2393 {
2394 if (log)
2395 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2396 return SendErrorResponse (0x32);
2397 }
2398
2399 // We first try to use a continue thread id. If any one or any all set, use the current thread.
2400 // Bail out if we don't have a thread id.
2401 lldb::tid_t tid = GetContinueThreadID ();
2402 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2403 tid = GetCurrentThreadID ();
2404 if (tid == LLDB_INVALID_THREAD_ID)
2405 return SendErrorResponse (0x33);
2406
2407 // Double check that we have such a thread.
2408 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2409 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
2410 if (!thread_sp || thread_sp->GetID () != tid)
2411 return SendErrorResponse (0x33);
2412
2413 // Create the step action for the given thread.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002414 ResumeAction action = { tid, eStateStepping, 0 };
Tamas Berghammere13c2732015-02-11 10:29:30 +00002415
2416 // Setup the actions list.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002417 ResumeActionList actions;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002418 actions.Append (action);
2419
2420 // All other threads stop while we're single stepping a thread.
2421 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2422 Error error = m_debugged_process_sp->Resume (actions);
2423 if (error.Fail ())
2424 {
2425 if (log)
2426 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
2427 return SendErrorResponse(0x49);
2428 }
2429
2430 // No response here - the stop or exit will come from the resulting action.
2431 return PacketResult::Success;
2432}
2433
2434GDBRemoteCommunication::PacketResult
2435GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
2436{
2437 // *BSD impls should be able to do this too.
2438#if defined(__linux__)
2439 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2440
2441 // Parse out the offset.
2442 packet.SetFilePos (strlen("qXfer:auxv:read::"));
2443 if (packet.GetBytesLeft () < 1)
2444 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2445
2446 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2447 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
2448 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2449
2450 // Parse out comma.
2451 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
2452 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
2453
2454 // Parse out the length.
2455 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2456 if (auxv_length == std::numeric_limits<uint64_t>::max ())
2457 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
2458
2459 // Grab the auxv data if we need it.
2460 if (!m_active_auxv_buffer_sp)
2461 {
2462 // Make sure we have a valid process.
2463 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2464 {
2465 if (log)
2466 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2467 return SendErrorResponse (0x10);
2468 }
2469
2470 // Grab the auxv data.
2471 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
2472 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
2473 {
2474 // Hmm, no auxv data, call that an error.
2475 if (log)
2476 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data retrieved", __FUNCTION__);
2477 m_active_auxv_buffer_sp.reset ();
2478 return SendErrorResponse (0x11);
2479 }
2480 }
2481
2482 // FIXME find out if/how I lock the stream here.
2483
2484 StreamGDBRemote response;
2485 bool done_with_buffer = false;
2486
2487 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
2488 {
2489 // We have nothing left to send. Mark the buffer as complete.
2490 response.PutChar ('l');
2491 done_with_buffer = true;
2492 }
2493 else
2494 {
2495 // Figure out how many bytes are available starting at the given offset.
2496 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
2497
2498 // Figure out how many bytes we're going to read.
2499 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2500
2501 // Mark the response type according to whether we're reading the remainder of the auxv data.
2502 if (bytes_to_read >= bytes_remaining)
2503 {
2504 // There will be nothing left to read after this
2505 response.PutChar ('l');
2506 done_with_buffer = true;
2507 }
2508 else
2509 {
2510 // There will still be bytes to read after this request.
2511 response.PutChar ('m');
2512 }
2513
2514 // Now write the data in encoded binary form.
2515 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
2516 }
2517
2518 if (done_with_buffer)
2519 m_active_auxv_buffer_sp.reset ();
2520
2521 return SendPacketNoLock(response.GetData(), response.GetSize());
2522#else
2523 return SendUnimplementedResponse ("not implemented on this platform");
2524#endif
2525}
2526
2527GDBRemoteCommunication::PacketResult
2528GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
2529{
2530 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2531
2532 // Move past packet name.
2533 packet.SetFilePos (strlen ("QSaveRegisterState"));
2534
2535 // Get the thread to use.
2536 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2537 if (!thread_sp)
2538 {
2539 if (m_thread_suffix_supported)
2540 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
2541 else
2542 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2543 }
2544
2545 // Grab the register context for the thread.
2546 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2547 if (!reg_context_sp)
2548 {
2549 if (log)
2550 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
2551 return SendErrorResponse (0x15);
2552 }
2553
2554 // Save registers to a buffer.
2555 DataBufferSP register_data_sp;
2556 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
2557 if (error.Fail ())
2558 {
2559 if (log)
2560 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2561 return SendErrorResponse (0x75);
2562 }
2563
2564 // Allocate a new save id.
2565 const uint32_t save_id = GetNextSavedRegistersID ();
2566 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
2567
2568 // Save the register data buffer under the save id.
2569 {
2570 Mutex::Locker locker (m_saved_registers_mutex);
2571 m_saved_registers_map[save_id] = register_data_sp;
2572 }
2573
2574 // Write the response.
2575 StreamGDBRemote response;
2576 response.Printf ("%" PRIu32, save_id);
2577 return SendPacketNoLock(response.GetData(), response.GetSize());
2578}
2579
2580GDBRemoteCommunication::PacketResult
2581GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
2582{
2583 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2584
2585 // Parse out save id.
2586 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
2587 if (packet.GetBytesLeft () < 1)
2588 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
2589
2590 const uint32_t save_id = packet.GetU32 (0);
2591 if (save_id == 0)
2592 {
2593 if (log)
2594 log->Printf ("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
2595 return SendErrorResponse (0x76);
2596 }
2597
2598 // Get the thread to use.
2599 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2600 if (!thread_sp)
2601 {
2602 if (m_thread_suffix_supported)
2603 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
2604 else
2605 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2606 }
2607
2608 // Grab the register context for the thread.
2609 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2610 if (!reg_context_sp)
2611 {
2612 if (log)
2613 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
2614 return SendErrorResponse (0x15);
2615 }
2616
2617 // Retrieve register state buffer, then remove from the list.
2618 DataBufferSP register_data_sp;
2619 {
2620 Mutex::Locker locker (m_saved_registers_mutex);
2621
2622 // Find the register set buffer for the given save id.
2623 auto it = m_saved_registers_map.find (save_id);
2624 if (it == m_saved_registers_map.end ())
2625 {
2626 if (log)
2627 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " does not have a register set save buffer for id %" PRIu32, __FUNCTION__, m_debugged_process_sp->GetID (), save_id);
2628 return SendErrorResponse (0x77);
2629 }
2630 register_data_sp = it->second;
2631
2632 // Remove it from the map.
2633 m_saved_registers_map.erase (it);
2634 }
2635
2636 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
2637 if (error.Fail ())
2638 {
2639 if (log)
2640 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2641 return SendErrorResponse (0x77);
2642 }
2643
2644 return SendOKResponse();
2645}
2646
2647GDBRemoteCommunication::PacketResult
2648GDBRemoteCommunicationServerLLGS::Handle_vAttach (StringExtractorGDBRemote &packet)
2649{
2650 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2651
2652 // Consume the ';' after vAttach.
2653 packet.SetFilePos (strlen ("vAttach"));
2654 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
2655 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
2656
2657 // Grab the PID to which we will attach (assume hex encoding).
2658 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2659 if (pid == LLDB_INVALID_PROCESS_ID)
2660 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
2661
2662 // Attempt to attach.
2663 if (log)
2664 log->Printf ("GDBRemoteCommunicationServerLLGS::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
2665
2666 Error error = AttachToProcess (pid);
2667
2668 if (error.Fail ())
2669 {
2670 if (log)
2671 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
2672 return SendErrorResponse (0x01);
2673 }
2674
2675 // Notify we attached by sending a stop packet.
Pavel Labathc7749c32015-07-21 13:20:25 +00002676 return SendStopReasonForState (m_debugged_process_sp->GetState ());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002677}
2678
2679GDBRemoteCommunication::PacketResult
2680GDBRemoteCommunicationServerLLGS::Handle_D (StringExtractorGDBRemote &packet)
2681{
2682 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2683
Pavel Labathc7749c32015-07-21 13:20:25 +00002684 StopSTDIOForwarding();
2685
Tamas Berghammere13c2732015-02-11 10:29:30 +00002686 // Fail if we don't have a current process.
2687 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2688 {
2689 if (log)
2690 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2691 return SendErrorResponse (0x15);
2692 }
2693
Tamas Berghammere13c2732015-02-11 10:29:30 +00002694 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2695
2696 // Consume the ';' after D.
2697 packet.SetFilePos (1);
2698 if (packet.GetBytesLeft ())
2699 {
2700 if (packet.GetChar () != ';')
2701 return SendIllFormedResponse (packet, "D missing expected ';'");
2702
2703 // Grab the PID from which we will detach (assume hex encoding).
2704 pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2705 if (pid == LLDB_INVALID_PROCESS_ID)
2706 return SendIllFormedResponse (packet, "D failed to parse the process id");
2707 }
2708
2709 if (pid != LLDB_INVALID_PROCESS_ID &&
2710 m_debugged_process_sp->GetID () != pid)
2711 {
2712 return SendIllFormedResponse (packet, "Invalid pid");
2713 }
2714
Tamas Berghammere13c2732015-02-11 10:29:30 +00002715 const Error error = m_debugged_process_sp->Detach ();
2716 if (error.Fail ())
2717 {
2718 if (log)
2719 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to detach from pid %" PRIu64 ": %s\n",
2720 __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2721 return SendErrorResponse (0x01);
2722 }
2723
Tamas Berghammere13c2732015-02-11 10:29:30 +00002724 return SendOKResponse ();
2725}
2726
2727GDBRemoteCommunication::PacketResult
2728GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
2729{
2730 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2731
2732 packet.SetFilePos (strlen("qThreadStopInfo"));
2733 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2734 if (tid == LLDB_INVALID_THREAD_ID)
2735 {
2736 if (log)
2737 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
2738 return SendErrorResponse (0x15);
2739 }
2740 return SendStopReplyPacketForThread (tid);
2741}
2742
2743GDBRemoteCommunication::PacketResult
Pavel Labath4a4bb122015-07-16 14:14:35 +00002744GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo (StringExtractorGDBRemote &)
2745{
2746 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2747
2748 // Ensure we have a debugged process.
2749 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2750 return SendErrorResponse (50);
2751
2752 if (log)
2753 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64,
2754 __FUNCTION__, m_debugged_process_sp->GetID());
2755
Pavel Labath4a4bb122015-07-16 14:14:35 +00002756
2757 StreamString response;
Pavel Labath05569f62015-07-23 09:09:29 +00002758 const bool threads_with_valid_stop_info_only = false;
2759 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
2760 threads_with_valid_stop_info_only);
2761 if (! threads_array_sp)
2762 {
2763 if (log)
2764 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a packet for pid %" PRIu64,
2765 __FUNCTION__, m_debugged_process_sp->GetID());
2766 return SendErrorResponse(52);
2767 }
2768
2769 threads_array_sp->Write(response);
Pavel Labath4a4bb122015-07-16 14:14:35 +00002770 StreamGDBRemote escaped_response;
2771 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
2772 return SendPacketNoLock (escaped_response.GetData(), escaped_response.GetSize());
2773}
2774
2775GDBRemoteCommunication::PacketResult
Tamas Berghammere13c2732015-02-11 10:29:30 +00002776GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet)
2777{
2778 // Fail if we don't have a current process.
2779 if (!m_debugged_process_sp ||
2780 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2781 return SendErrorResponse (68);
2782
2783 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
2784 if (packet.GetBytesLeft() == 0)
2785 return SendOKResponse();
2786 if (packet.GetChar() != ':')
2787 return SendErrorResponse(67);
2788
2789 uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
2790 StreamGDBRemote response;
2791 response.Printf ("num:%d;", num);
2792 return SendPacketNoLock(response.GetData(), response.GetSize());
2793}
2794
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002795GDBRemoteCommunication::PacketResult
2796GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress (StringExtractorGDBRemote &packet)
2797{
2798 // Fail if we don't have a current process.
2799 if (!m_debugged_process_sp ||
2800 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2801 return SendErrorResponse(67);
2802
2803 packet.SetFilePos(strlen("qFileLoadAddress:"));
2804 if (packet.GetBytesLeft() == 0)
2805 return SendErrorResponse(68);
2806
2807 std::string file_name;
2808 packet.GetHexByteString(file_name);
2809
2810 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
2811 Error error = m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
2812 if (error.Fail())
2813 return SendErrorResponse(69);
2814
2815 if (file_load_address == LLDB_INVALID_ADDRESS)
2816 return SendErrorResponse(1); // File not loaded
2817
2818 StreamGDBRemote response;
2819 response.PutHex64(file_load_address);
2820 return SendPacketNoLock(response.GetData(), response.GetSize());
2821}
2822
Tamas Berghammere13c2732015-02-11 10:29:30 +00002823void
Tamas Berghammere13c2732015-02-11 10:29:30 +00002824GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection ()
2825{
2826 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2827
Pavel Labathc7749c32015-07-21 13:20:25 +00002828 Mutex::Locker locker(m_stdio_communication_mutex);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002829 // Tell the stdio connection to shut down.
2830 if (m_stdio_communication.IsConnected())
2831 {
2832 auto connection = m_stdio_communication.GetConnection();
2833 if (connection)
2834 {
2835 Error error;
2836 connection->Disconnect (&error);
2837
2838 if (error.Success ())
2839 {
2840 if (log)
2841 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
2842 }
2843 else
2844 {
2845 if (log)
2846 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
2847 }
2848 }
2849 }
2850}
2851
2852
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002853NativeThreadProtocolSP
Tamas Berghammere13c2732015-02-11 10:29:30 +00002854GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
2855{
2856 NativeThreadProtocolSP thread_sp;
2857
2858 // We have no thread if we don't have a process.
2859 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2860 return thread_sp;
2861
2862 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
2863 // Use the current thread in that case.
2864 if (!m_thread_suffix_supported)
2865 {
2866 const lldb::tid_t current_tid = GetCurrentThreadID ();
2867 if (current_tid == LLDB_INVALID_THREAD_ID)
2868 return thread_sp;
2869 else if (current_tid == 0)
2870 {
2871 // Pick a thread.
2872 return m_debugged_process_sp->GetThreadAtIndex (0);
2873 }
2874 else
2875 return m_debugged_process_sp->GetThreadByID (current_tid);
2876 }
2877
2878 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2879
2880 // Parse out the ';'.
2881 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
2882 {
2883 if (log)
2884 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2885 return thread_sp;
2886 }
2887
2888 if (!packet.GetBytesLeft ())
2889 return thread_sp;
2890
2891 // Parse out thread: portion.
2892 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
2893 {
2894 if (log)
2895 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2896 return thread_sp;
2897 }
2898 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
2899 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
2900 if (tid != 0)
2901 return m_debugged_process_sp->GetThreadByID (tid);
2902
2903 return thread_sp;
2904}
2905
2906lldb::tid_t
2907GDBRemoteCommunicationServerLLGS::GetCurrentThreadID () const
2908{
2909 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
2910 {
2911 // Use whatever the debug process says is the current thread id
2912 // since the protocol either didn't specify or specified we want
2913 // any/all threads marked as the current thread.
2914 if (!m_debugged_process_sp)
2915 return LLDB_INVALID_THREAD_ID;
2916 return m_debugged_process_sp->GetCurrentThreadID ();
2917 }
2918 // Use the specific current thread id set by the gdb remote protocol.
2919 return m_current_tid;
2920}
2921
2922uint32_t
2923GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID ()
2924{
2925 Mutex::Locker locker (m_saved_registers_mutex);
2926 return m_next_saved_registers_id++;
2927}
2928
2929void
2930GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData ()
2931{
2932 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
2933 if (log)
2934 log->Printf ("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
2935
2936 // Clear any auxv cached data.
2937 // *BSD impls should be able to do this too.
2938#if defined(__linux__)
2939 if (log)
2940 log->Printf ("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer (previously %s)",
2941 __FUNCTION__,
2942 m_active_auxv_buffer_sp ? "was set" : "was not set");
2943 m_active_auxv_buffer_sp.reset ();
2944#endif
2945}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002946
2947FileSpec
2948GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string& module_path,
2949 const ArchSpec& arch)
2950{
2951 if (m_debugged_process_sp)
2952 {
2953 FileSpec file_spec;
2954 if (m_debugged_process_sp->GetLoadedModuleFileSpec(module_path.c_str(), file_spec).Success())
2955 {
2956 if (file_spec.Exists())
2957 return file_spec;
2958 }
2959 }
2960
2961 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
2962}