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