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