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