blob: 7523260c13e4abe499ee32116ad8f8f6d9ab5690 [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"
Zachary Turnerfb1a0a02017-03-06 18:34:25 +000015#include "lldb/Utility/StreamGDBRemote.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000016
17// C Includes
18// C++ Includes
Tamas Berghammere13c2732015-02-11 10:29:30 +000019#include <chrono>
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include <cstring>
Tamas Berghammere13c2732015-02-11 10:29:30 +000021#include <thread>
22
23// Other libraries and framework includes
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +000024#include "lldb/Core/RegisterValue.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000025#include "lldb/Core/State.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000026#include "lldb/Host/ConnectionFileDescriptor.h"
27#include "lldb/Host/Debug.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000028#include "lldb/Host/File.h"
29#include "lldb/Host/FileSystem.h"
30#include "lldb/Host/Host.h"
31#include "lldb/Host/HostInfo.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000032#include "lldb/Host/common/NativeProcessProtocol.h"
33#include "lldb/Host/common/NativeRegisterContext.h"
34#include "lldb/Host/common/NativeThreadProtocol.h"
35#include "lldb/Interpreter/Args.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000036#include "lldb/Target/FileAction.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000037#include "lldb/Target/MemoryRegionInfo.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000038#include "lldb/Utility/DataBuffer.h"
Zachary Turner01c32432017-02-14 19:06:07 +000039#include "lldb/Utility/Endian.h"
Pavel Labath4a4bb122015-07-16 14:14:35 +000040#include "lldb/Utility/JSON.h"
Pavel Labathabadc222015-11-27 13:33:29 +000041#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000042#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000043#include "lldb/Utility/StreamString.h"
Pavel Labath5f7e5832017-02-10 12:21:22 +000044#include "lldb/Utility/UriParser.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000045#include "llvm/ADT/Triple.h"
46#include "llvm/Support/ScopedPrinter.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000047
48// Project includes
Tamas Berghammere13c2732015-02-11 10:29:30 +000049#include "ProcessGDBRemote.h"
50#include "ProcessGDBRemoteLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000051#include "Utility/StringExtractorGDBRemote.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000052
53using namespace lldb;
54using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000055using namespace lldb_private::process_gdb_remote;
Tamas Berghammer783bfc82015-06-18 20:43:56 +000056using namespace llvm;
Tamas Berghammere13c2732015-02-11 10:29:30 +000057
58//----------------------------------------------------------------------
59// GDBRemote Errors
60//----------------------------------------------------------------------
61
Kate Stoneb9c1b512016-09-06 20:57:50 +000062namespace {
63enum GDBRemoteServerError {
64 // Set to the first unused error number in literal form below
65 eErrorFirst = 29,
66 eErrorNoProcess = eErrorFirst,
67 eErrorResume,
68 eErrorExitStatus
69};
Tamas Berghammere13c2732015-02-11 10:29:30 +000070}
71
72//----------------------------------------------------------------------
73// GDBRemoteCommunicationServerLLGS constructor
74//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000075GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
76 MainLoop &mainloop)
77 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
78 "gdb-remote.server.rx_packet"),
79 m_mainloop(mainloop), m_current_tid(LLDB_INVALID_THREAD_ID),
80 m_continue_tid(LLDB_INVALID_THREAD_ID), m_debugged_process_mutex(),
81 m_debugged_process_sp(), m_stdio_communication("process.stdio"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000082 m_inferior_prev_state(StateType::eStateInvalid),
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 m_saved_registers_map(), m_next_saved_registers_id(1),
84 m_handshake_completed(false) {
85 RegisterPacketHandlers();
Tamas Berghammere13c2732015-02-11 10:29:30 +000086}
87
Kate Stoneb9c1b512016-09-06 20:57:50 +000088void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
89 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
90 &GDBRemoteCommunicationServerLLGS::Handle_C);
91 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
92 &GDBRemoteCommunicationServerLLGS::Handle_c);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
94 &GDBRemoteCommunicationServerLLGS::Handle_D);
95 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
96 &GDBRemoteCommunicationServerLLGS::Handle_H);
97 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
98 &GDBRemoteCommunicationServerLLGS::Handle_I);
99 RegisterMemberFunctionHandler(
100 StringExtractorGDBRemote::eServerPacketType_interrupt,
101 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
102 RegisterMemberFunctionHandler(
103 StringExtractorGDBRemote::eServerPacketType_m,
104 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
106 &GDBRemoteCommunicationServerLLGS::Handle_M);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
108 &GDBRemoteCommunicationServerLLGS::Handle_p);
109 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
110 &GDBRemoteCommunicationServerLLGS::Handle_P);
111 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
112 &GDBRemoteCommunicationServerLLGS::Handle_qC);
113 RegisterMemberFunctionHandler(
114 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
115 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
116 RegisterMemberFunctionHandler(
117 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
118 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
119 RegisterMemberFunctionHandler(
120 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
121 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
122 RegisterMemberFunctionHandler(
123 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
124 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
125 RegisterMemberFunctionHandler(
126 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
127 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
128 RegisterMemberFunctionHandler(
129 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
130 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
131 RegisterMemberFunctionHandler(
132 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
133 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
134 RegisterMemberFunctionHandler(
135 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
136 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
137 RegisterMemberFunctionHandler(
138 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
139 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
140 RegisterMemberFunctionHandler(
141 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
143 RegisterMemberFunctionHandler(
144 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
145 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
146 RegisterMemberFunctionHandler(
147 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
148 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
149 RegisterMemberFunctionHandler(
150 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
151 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
152 RegisterMemberFunctionHandler(
153 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
154 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
155 RegisterMemberFunctionHandler(
156 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
157 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
158 RegisterMemberFunctionHandler(
159 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
160 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
161 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
162 &GDBRemoteCommunicationServerLLGS::Handle_s);
163 RegisterMemberFunctionHandler(
164 StringExtractorGDBRemote::eServerPacketType_stop_reason,
165 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
166 RegisterMemberFunctionHandler(
167 StringExtractorGDBRemote::eServerPacketType_vAttach,
168 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
169 RegisterMemberFunctionHandler(
170 StringExtractorGDBRemote::eServerPacketType_vCont,
171 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
172 RegisterMemberFunctionHandler(
173 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
174 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
175 RegisterMemberFunctionHandler(
176 StringExtractorGDBRemote::eServerPacketType_x,
177 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
178 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
179 &GDBRemoteCommunicationServerLLGS::Handle_Z);
180 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
181 &GDBRemoteCommunicationServerLLGS::Handle_z);
Pavel Labath4a705e72017-02-24 09:29:14 +0000182 RegisterMemberFunctionHandler(
183 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
184 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000185
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +0000186 RegisterMemberFunctionHandler(
187 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
188 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
189 RegisterMemberFunctionHandler(
190 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
191 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
192 RegisterMemberFunctionHandler(
193 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
194 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
195 RegisterMemberFunctionHandler(
196 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
197 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
198 RegisterMemberFunctionHandler(
199 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
200 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
Zachary Turner97206d52017-05-12 04:51:55 +0000203 [this](StringExtractorGDBRemote packet, Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 bool &interrupt, bool &quit) {
205 quit = true;
206 return this->Handle_k(packet);
207 });
Tamas Berghammere13c2732015-02-11 10:29:30 +0000208}
209
Zachary Turner97206d52017-05-12 04:51:55 +0000210Status
211GDBRemoteCommunicationServerLLGS::SetLaunchArguments(const char *const args[],
212 int argc) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 if ((argc < 1) || !args || !args[0] || !args[0][0])
Zachary Turner97206d52017-05-12 04:51:55 +0000214 return Status("%s: no process command line specified to launch",
215 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000216
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
Zachary Turner97206d52017-05-12 04:51:55 +0000218 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000219}
220
Zachary Turner97206d52017-05-12 04:51:55 +0000221Status
222GDBRemoteCommunicationServerLLGS::SetLaunchFlags(unsigned int launch_flags) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 m_process_launch_info.GetFlags().Set(launch_flags);
Zachary Turner97206d52017-05-12 04:51:55 +0000224 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000225}
226
Zachary Turner97206d52017-05-12 04:51:55 +0000227Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 if (!m_process_launch_info.GetArguments().GetArgumentCount())
Zachary Turner97206d52017-05-12 04:51:55 +0000231 return Status("%s: no process command line specified to launch",
232 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 const bool should_forward_stdio =
235 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
236 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
237 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
238 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
239 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 const bool default_to_use_pty = true;
242 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000243
Zachary Turner97206d52017-05-12 04:51:55 +0000244 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 {
246 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
247 assert(!m_debugged_process_sp && "lldb-server creating debugged "
248 "process but one already exists");
249 error = NativeProcessProtocol::Launch(m_process_launch_info, *this,
250 m_mainloop, m_debugged_process_sp);
251 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 if (!error.Success()) {
254 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
255 m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000256 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
260 // as needed.
261 // llgs local-process debugging may specify PTY paths, which will make these
262 // file actions non-null
263 // process launch -i/e/o will also make these file actions non-null
264 // nullptr means that the traffic is expected to flow over gdb-remote protocol
265 if (should_forward_stdio) {
266 // nullptr means it's not redirected to file or pty (in case of LLGS local)
267 // at least one of stdio will be transferred pty<->gdb-remote
268 // we need to give the pty master handle to this object to read and/or write
Tamas Berghammere13c2732015-02-11 10:29:30 +0000269 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 log->Printf(
271 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
272 " setting up stdout/stderr redirection via $O gdb-remote commands",
273 __FUNCTION__, m_debugged_process_sp->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000274
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 // Setup stdout/stderr mapping from inferior to $O
276 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
277 if (terminal_fd >= 0) {
278 if (log)
279 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
280 "inferior STDIO fd to %d",
281 __FUNCTION__, terminal_fd);
282 error = SetSTDIOFileDescriptor(terminal_fd);
283 if (error.Fail())
Tamas Berghammere13c2732015-02-11 10:29:30 +0000284 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285 } else {
286 if (log)
287 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
288 "inferior STDIO since terminal fd reported as %d",
289 __FUNCTION__, terminal_fd);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000290 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291 } else {
292 if (log)
293 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
294 " skipping stdout/stderr redirection via $O: inferior will "
295 "communicate over client-provided file descriptors",
296 __FUNCTION__, m_debugged_process_sp->GetID());
297 }
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000298
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 printf("Launched '%s' as process %" PRIu64 "...\n",
300 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
301 m_process_launch_info.GetProcessID());
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000302
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 return error;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000304}
305
Zachary Turner97206d52017-05-12 04:51:55 +0000306Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
307 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308
309 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
310 if (log)
311 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
312 __FUNCTION__, pid);
313
314 // Before we try to attach, make sure we aren't already monitoring something
315 // else.
316 if (m_debugged_process_sp &&
317 m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
Zachary Turner97206d52017-05-12 04:51:55 +0000318 return Status("cannot attach to a process %" PRIu64
319 " when another process with pid %" PRIu64
320 " is being debugged.",
321 pid, m_debugged_process_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322
323 // Try to attach.
324 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop,
325 m_debugged_process_sp);
326 if (!error.Success()) {
327 fprintf(stderr, "%s: failed to attach to process %" PRIu64 ": %s",
328 __FUNCTION__, pid, error.AsCString());
329 return error;
330 }
331
332 // Setup stdout/stderr mapping from inferior.
333 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
334 if (terminal_fd >= 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000335 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
337 "inferior STDIO fd to %d",
338 __FUNCTION__, terminal_fd);
339 error = SetSTDIOFileDescriptor(terminal_fd);
340 if (error.Fail())
341 return error;
342 } else {
343 if (log)
344 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
345 "inferior STDIO since terminal fd reported as %d",
346 __FUNCTION__, terminal_fd);
347 }
348
349 printf("Attached to process %" PRIu64 "...\n", pid);
350
351 return error;
352}
353
354void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
355 NativeProcessProtocol *process) {
356 assert(process && "process cannot be NULL");
357 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
358 if (log) {
359 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
360 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
361 __FUNCTION__, process->GetID(),
362 StateAsCString(process->GetState()));
363 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000364}
365
366GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367GDBRemoteCommunicationServerLLGS::SendWResponse(
368 NativeProcessProtocol *process) {
369 assert(process && "process cannot be NULL");
370 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 // send W notification
Pavel Labath3508fc82017-06-19 12:47:50 +0000373 auto wait_status = process->GetExitStatus();
374 if (!wait_status) {
375 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
376 process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000377
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378 StreamGDBRemote response;
379 response.PutChar('E');
380 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
381 return SendPacketNoLock(response.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 }
Pavel Labath3508fc82017-06-19 12:47:50 +0000383
384 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
385 *wait_status);
386
387 StreamGDBRemote response;
388 response.Format("{0:g}", *wait_status);
389 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000390}
391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392static void AppendHexValue(StreamString &response, const uint8_t *buf,
393 uint32_t buf_size, bool swap) {
394 int64_t i;
395 if (swap) {
396 for (i = buf_size - 1; i >= 0; i--)
397 response.PutHex8(buf[i]);
398 } else {
399 for (i = 0; i < buf_size; i++)
400 response.PutHex8(buf[i]);
401 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000402}
403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404static void WriteRegisterValueInHexFixedWidth(
405 StreamString &response, NativeRegisterContextSP &reg_ctx_sp,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000406 const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
407 lldb::ByteOrder byte_order) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 RegisterValue reg_value;
409 if (!reg_value_p) {
Zachary Turner97206d52017-05-12 04:51:55 +0000410 Status error = reg_ctx_sp->ReadRegister(&reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 if (error.Success())
412 reg_value_p = &reg_value;
413 // else log.
414 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000415
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 if (reg_value_p) {
417 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
Pavel Labathe0a5b572017-01-20 14:17:16 +0000418 reg_value_p->GetByteSize(),
419 byte_order == lldb::eByteOrderLittle);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 } else {
421 // Zero-out any unreadable values.
422 if (reg_info.byte_size > 0) {
423 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
424 AppendHexValue(response, zeros.data(), zeros.size(), false);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000425 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000427}
428
Pavel Labathe0a5b572017-01-20 14:17:16 +0000429static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath4a4bb122015-07-16 14:14:35 +0000431
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
433 if (!reg_ctx_sp)
434 return nullptr;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000437
438#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 // Expedite all registers in the first register set (i.e. should be GPRs) that
440 // are not contained in other registers.
441 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
442 if (!reg_set_p)
443 return nullptr;
444 for (const uint32_t *reg_num_p = reg_set_p->registers;
445 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
446 uint32_t reg_num = *reg_num_p;
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000447#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 // Expedite only a couple of registers until we figure out why sending
449 // registers is
450 // expensive.
451 static const uint32_t k_expedited_registers[] = {
452 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
453 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
Pavel Labathc4645bb2015-10-26 16:25:28 +0000454
Pavel Labathe0a5b572017-01-20 14:17:16 +0000455 for (const uint32_t *generic_reg_p = k_expedited_registers;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
457 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
458 eRegisterKindGeneric, *generic_reg_p);
459 if (reg_num == LLDB_INVALID_REGNUM)
460 continue; // Target does not support the given register.
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000461#endif
462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 const RegisterInfo *const reg_info_p =
464 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
465 if (reg_info_p == nullptr) {
466 if (log)
467 log->Printf(
468 "%s failed to get register info for register index %" PRIu32,
469 __FUNCTION__, reg_num);
470 continue;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000471 }
472
Kate Stoneb9c1b512016-09-06 20:57:50 +0000473 if (reg_info_p->value_regs != nullptr)
474 continue; // Only expedite registers that are not contained in other
475 // registers.
Pavel Labath4a4bb122015-07-16 14:14:35 +0000476
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000478 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479 if (error.Fail()) {
480 if (log)
481 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
Pavel Labath05569f62015-07-23 09:09:29 +0000482 __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
484 reg_num, error.AsCString());
485 continue;
Pavel Labath05569f62015-07-23 09:09:29 +0000486 }
487
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 StreamString stream;
489 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000490 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491
492 register_object_sp->SetObject(
493 llvm::to_string(reg_num),
494 std::make_shared<JSONString>(stream.GetString()));
495 }
496
497 return register_object_sp;
Pavel Labath05569f62015-07-23 09:09:29 +0000498}
499
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500static const char *GetStopReasonString(StopReason stop_reason) {
501 switch (stop_reason) {
502 case eStopReasonTrace:
503 return "trace";
504 case eStopReasonBreakpoint:
505 return "breakpoint";
506 case eStopReasonWatchpoint:
507 return "watchpoint";
508 case eStopReasonSignal:
509 return "signal";
510 case eStopReasonException:
511 return "exception";
512 case eStopReasonExec:
513 return "exec";
514 case eStopReasonInstrumentation:
515 case eStopReasonInvalid:
516 case eStopReasonPlanComplete:
517 case eStopReasonThreadExiting:
518 case eStopReasonNone:
519 break; // ignored
520 }
521 return nullptr;
522}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000523
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
525 bool abridged) {
526 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000527
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000529
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 // Ensure we can get info on the given thread.
531 uint32_t thread_idx = 0;
532 for (NativeThreadProtocolSP thread_sp;
533 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
534 ++thread_idx) {
535
536 lldb::tid_t tid = thread_sp->GetID();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000537
538 // Grab the reason this thread stopped.
539 struct ThreadStopInfo tid_stop_info;
540 std::string description;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 if (!thread_sp->GetStopReason(tid_stop_info, description))
542 return nullptr;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 const int signum = tid_stop_info.details.signal.signo;
545 if (log) {
546 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
547 " tid %" PRIu64
548 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
549 __FUNCTION__, process.GetID(), tid, signum,
550 tid_stop_info.reason, tid_stop_info.details.exception.type);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000551 }
552
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
554 threads_array_sp->AppendObject(thread_obj_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000555
Pavel Labathe0a5b572017-01-20 14:17:16 +0000556 if (!abridged) {
557 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
558 thread_obj_sp->SetObject("registers", registers_sp);
559 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
562 if (signum != 0)
563 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 const std::string thread_name = thread_sp->GetName();
566 if (!thread_name.empty())
567 thread_obj_sp->SetObject("name",
568 std::make_shared<JSONString>(thread_name));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000569
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
571 thread_obj_sp->SetObject("reason",
572 std::make_shared<JSONString>(stop_reason_str));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000573
574 if (!description.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 thread_obj_sp->SetObject("description",
576 std::make_shared<JSONString>(description));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000577
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578 if ((tid_stop_info.reason == eStopReasonException) &&
579 tid_stop_info.details.exception.type) {
580 thread_obj_sp->SetObject(
581 "metype",
582 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
583
584 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
585 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
586 ++i) {
587 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
588 tid_stop_info.details.exception.data[i]));
589 }
590 thread_obj_sp->SetObject("medata", medata_array_sp);
591 }
592
593 // TODO: Expedite interesting regions of inferior memory
594 }
595
596 return threads_array_sp;
597}
598
599GDBRemoteCommunication::PacketResult
600GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
601 lldb::tid_t tid) {
602 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
603
604 // Ensure we have a debugged process.
605 if (!m_debugged_process_sp ||
606 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
607 return SendErrorResponse(50);
608
609 if (log)
610 log->Printf(
611 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
612 " tid %" PRIu64,
613 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
614
615 // Ensure we can get info on the given thread.
616 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
617 if (!thread_sp)
618 return SendErrorResponse(51);
619
620 // Grab the reason this thread stopped.
621 struct ThreadStopInfo tid_stop_info;
622 std::string description;
623 if (!thread_sp->GetStopReason(tid_stop_info, description))
624 return SendErrorResponse(52);
625
626 // FIXME implement register handling for exec'd inferiors.
627 // if (tid_stop_info.reason == eStopReasonExec)
628 // {
629 // const bool force = true;
630 // InitializeRegisters(force);
631 // }
632
633 StreamString response;
634 // Output the T packet with the thread
635 response.PutChar('T');
636 int signum = tid_stop_info.details.signal.signo;
637 if (log) {
638 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
639 " tid %" PRIu64
640 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
641 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
642 tid_stop_info.reason, tid_stop_info.details.exception.type);
643 }
644
645 // Print the signal number.
646 response.PutHex8(signum & 0xff);
647
648 // Include the tid.
649 response.Printf("thread:%" PRIx64 ";", tid);
650
651 // Include the thread name if there is one.
652 const std::string thread_name = thread_sp->GetName();
653 if (!thread_name.empty()) {
654 size_t thread_name_len = thread_name.length();
655
656 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
657 response.PutCString("name:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000658 response.PutCString(thread_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 } else {
660 // The thread name contains special chars, send as hex bytes.
661 response.PutCString("hexname:");
662 response.PutCStringAsRawHex8(thread_name.c_str());
663 }
664 response.PutChar(';');
665 }
666
667 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
668 // will send all thread IDs back in the "threads" key whose value is
669 // a list of hex thread IDs separated by commas:
670 // "threads:10a,10b,10c;"
671 // This will save the debugger from having to send a pair of qfThreadInfo
672 // and qsThreadInfo packets, but it also might take a lot of room in the
673 // stop reply packet, so it must be enabled only on systems where there
674 // are no limits on packet lengths.
675 if (m_list_threads_in_stop_reply) {
676 response.PutCString("threads:");
677
678 uint32_t thread_index = 0;
679 NativeThreadProtocolSP listed_thread_sp;
680 for (listed_thread_sp =
681 m_debugged_process_sp->GetThreadAtIndex(thread_index);
682 listed_thread_sp; ++thread_index,
683 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
684 thread_index)) {
685 if (thread_index > 0)
686 response.PutChar(',');
687 response.Printf("%" PRIx64, listed_thread_sp->GetID());
688 }
689 response.PutChar(';');
690
691 // Include JSON info that describes the stop reason for any threads
692 // that actually have stop reasons. We use the new "jstopinfo" key
693 // whose values is hex ascii JSON that contains the thread IDs
694 // thread stop info only for threads that have stop reasons. Only send
695 // this if we have more than one thread otherwise this packet has all
696 // the info it needs.
697 if (thread_index > 0) {
698 const bool threads_with_valid_stop_info_only = true;
699 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
700 *m_debugged_process_sp, threads_with_valid_stop_info_only);
701 if (threads_info_sp) {
702 response.PutCString("jstopinfo:");
703 StreamString unescaped_response;
704 threads_info_sp->Write(unescaped_response);
705 response.PutCStringAsRawHex8(unescaped_response.GetData());
706 response.PutChar(';');
707 } else if (log)
708 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
709 "jstopinfo field for pid %" PRIu64,
710 __FUNCTION__, m_debugged_process_sp->GetID());
711 }
Pavel Labathe0a5b572017-01-20 14:17:16 +0000712
713 uint32_t i = 0;
714 response.PutCString("thread-pcs");
715 char delimiter = ':';
716 for (NativeThreadProtocolSP thread_sp;
717 (thread_sp = m_debugged_process_sp->GetThreadAtIndex(i)) != nullptr;
718 ++i) {
719 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
720 if (!reg_ctx_sp)
721 continue;
722
723 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
724 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
725 const RegisterInfo *const reg_info_p =
726 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
727
728 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000729 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Pavel Labathe0a5b572017-01-20 14:17:16 +0000730 if (error.Fail()) {
731 if (log)
732 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
733 __FUNCTION__,
734 reg_info_p->name ? reg_info_p->name
735 : "<unnamed-register>",
736 reg_to_read, error.AsCString());
737 continue;
738 }
739
740 response.PutChar(delimiter);
741 delimiter = ',';
742 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
743 &reg_value, endian::InlHostByteOrder());
744 }
745
746 response.PutChar(';');
Kate Stoneb9c1b512016-09-06 20:57:50 +0000747 }
748
749 //
750 // Expedite registers.
751 //
752
753 // Grab the register context.
754 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
755 if (reg_ctx_sp) {
756 // Expedite all registers in the first register set (i.e. should be GPRs)
757 // that are not contained in other registers.
758 const RegisterSet *reg_set_p;
759 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
760 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
761 if (log)
762 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
763 "from set '%s' (registers set count: %zu)",
764 __FUNCTION__,
765 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
766 reg_set_p->num_registers);
767
768 for (const uint32_t *reg_num_p = reg_set_p->registers;
769 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
770 const RegisterInfo *const reg_info_p =
771 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
772 if (reg_info_p == nullptr) {
773 if (log)
774 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
775 "register info for register set '%s', register index "
776 "%" PRIu32,
777 __FUNCTION__,
778 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
779 *reg_num_p);
780 } else if (reg_info_p->value_regs == nullptr) {
781 // Only expediate registers that are not contained in other registers.
782 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000783 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 if (error.Success()) {
785 response.Printf("%.02x:", *reg_num_p);
786 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000787 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 response.PutChar(';');
789 } else {
790 if (log)
791 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
792 "register '%s' index %" PRIu32 ": %s",
793 __FUNCTION__, reg_info_p->name ? reg_info_p->name
794 : "<unnamed-register>",
795 *reg_num_p, error.AsCString());
796 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000797 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000799 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000801
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
803 if (reason_str != nullptr) {
804 response.Printf("reason:%s;", reason_str);
805 }
806
807 if (!description.empty()) {
808 // Description may contains special chars, send as hex bytes.
809 response.PutCString("description:");
810 response.PutCStringAsRawHex8(description.c_str());
811 response.PutChar(';');
812 } else if ((tid_stop_info.reason == eStopReasonException) &&
813 tid_stop_info.details.exception.type) {
814 response.PutCString("metype:");
815 response.PutHex64(tid_stop_info.details.exception.type);
816 response.PutCString(";mecount:");
817 response.PutHex32(tid_stop_info.details.exception.data_count);
818 response.PutChar(';');
819
820 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
821 response.PutCString("medata:");
822 response.PutHex64(tid_stop_info.details.exception.data[i]);
823 response.PutChar(';');
824 }
825 }
826
827 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000828}
829
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
831 NativeProcessProtocol *process) {
832 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000833
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
835 if (log)
836 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
837
838 PacketResult result = SendStopReasonForState(StateType::eStateExited);
839 if (result != PacketResult::Success) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000840 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
842 "notification for PID %" PRIu64 ", state: eStateExited",
843 __FUNCTION__, process->GetID());
844 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 // Close the pipe to the inferior terminal i/o if we launched it
847 // and set one up.
848 MaybeCloseInferiorTerminalConnection();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000849
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 // We are ready to exit the debug monitor.
851 m_exit_now = true;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000852}
853
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
855 NativeProcessProtocol *process) {
856 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000857
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
859 if (log)
860 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 // Send the stop reason unless this is the stop after the
863 // launch or attach.
864 switch (m_inferior_prev_state) {
865 case eStateLaunching:
866 case eStateAttaching:
867 // Don't send anything per debugserver behavior.
868 break;
869 default:
870 // In all other cases, send the stop reason.
871 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
872 if (result != PacketResult::Success) {
873 if (log)
874 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
875 "notification for PID %" PRIu64 ", state: eStateExited",
876 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000877 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 break;
879 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000880}
881
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
883 NativeProcessProtocol *process, lldb::StateType state) {
884 assert(process && "process cannot be NULL");
885 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
886 if (log) {
887 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
888 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
889 __FUNCTION__, process->GetID(), StateAsCString(state));
890 }
891
892 switch (state) {
893 case StateType::eStateRunning:
894 StartSTDIOForwarding();
895 break;
896
897 case StateType::eStateStopped:
898 // Make sure we get all of the pending stdout/stderr from the inferior
899 // and send it to the lldb host before we send the state change
900 // notification
901 SendProcessOutput();
902 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
903 // does not
904 // interfere with our protocol.
905 StopSTDIOForwarding();
906 HandleInferiorState_Stopped(process);
907 break;
908
909 case StateType::eStateExited:
910 // Same as above
911 SendProcessOutput();
912 StopSTDIOForwarding();
913 HandleInferiorState_Exited(process);
914 break;
915
916 default:
917 if (log) {
918 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
919 "change for pid %" PRIu64 ", new state: %s",
920 __FUNCTION__, process->GetID(), StateAsCString(state));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000921 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000922 break;
923 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000924
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925 // Remember the previous state reported to us.
926 m_inferior_prev_state = state;
927}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000928
Kate Stoneb9c1b512016-09-06 20:57:50 +0000929void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
930 ClearProcessSpecificData();
931}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000932
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
934 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
935
936 if (!m_handshake_completed) {
937 if (!HandshakeWithClient()) {
938 if (log)
939 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
940 "client failed, exiting",
941 __FUNCTION__);
942 m_mainloop.RequestTermination();
943 return;
944 }
945 m_handshake_completed = true;
946 }
947
948 bool interrupt = false;
949 bool done = false;
Zachary Turner97206d52017-05-12 04:51:55 +0000950 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 while (true) {
Pavel Labath1eff73c2016-11-24 10:54:49 +0000952 const PacketResult result = GetPacketAndSendResponse(
953 std::chrono::microseconds(0), error, interrupt, done);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954 if (result == PacketResult::ErrorReplyTimeout)
955 break; // No more packets in the queue
956
957 if ((result != PacketResult::Success)) {
958 if (log)
959 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
960 "failed: %s",
961 __FUNCTION__, error.AsCString());
962 m_mainloop.RequestTermination();
963 break;
964 }
965 }
966}
967
Zachary Turner97206d52017-05-12 04:51:55 +0000968Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 std::unique_ptr<Connection> &&connection) {
970 IOObjectSP read_object_sp = connection->GetReadObject();
971 GDBRemoteCommunicationServer::SetConnection(connection.release());
972
Zachary Turner97206d52017-05-12 04:51:55 +0000973 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 m_network_handle_up = m_mainloop.RegisterReadObject(
975 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
976 error);
977 return error;
978}
979
980GDBRemoteCommunication::PacketResult
981GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
982 uint32_t len) {
983 if ((buffer == nullptr) || (len == 0)) {
984 // Nothing to send.
985 return PacketResult::Success;
986 }
987
988 StreamString response;
989 response.PutChar('O');
990 response.PutBytesAsRawHex8(buffer, len);
991
992 return SendPacketNoLock(response.GetString());
993}
994
Zachary Turner97206d52017-05-12 04:51:55 +0000995Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
996 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997
998 // Set up the reading/handling of process I/O
999 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1000 new ConnectionFileDescriptor(fd, true));
1001 if (!conn_up) {
1002 error.SetErrorString("failed to create ConnectionFileDescriptor");
1003 return error;
1004 }
1005
1006 m_stdio_communication.SetCloseOnEOF(false);
1007 m_stdio_communication.SetConnection(conn_up.release());
1008 if (!m_stdio_communication.IsConnected()) {
1009 error.SetErrorString(
1010 "failed to set connection for inferior I/O communication");
1011 return error;
1012 }
1013
Zachary Turner97206d52017-05-12 04:51:55 +00001014 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015}
1016
1017void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1018 // Don't forward if not connected (e.g. when attaching).
1019 if (!m_stdio_communication.IsConnected())
1020 return;
1021
Zachary Turner97206d52017-05-12 04:51:55 +00001022 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 lldbassert(!m_stdio_handle_up);
1024 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1025 m_stdio_communication.GetConnection()->GetReadObject(),
1026 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1027
1028 if (!m_stdio_handle_up) {
1029 // Not much we can do about the failure. Log it and continue without
1030 // forwarding.
1031 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1032 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1033 "forwarding: %s",
1034 __FUNCTION__, error.AsCString());
1035 }
1036}
1037
1038void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1039 m_stdio_handle_up.reset();
1040}
1041
1042void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1043 char buffer[1024];
1044 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00001045 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 while (true) {
Pavel Labathc4063ee2016-11-25 11:58:44 +00001047 size_t bytes_read = m_stdio_communication.Read(
1048 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 switch (status) {
1050 case eConnectionStatusSuccess:
1051 SendONotification(buffer, bytes_read);
1052 break;
1053 case eConnectionStatusLostConnection:
1054 case eConnectionStatusEndOfFile:
1055 case eConnectionStatusError:
1056 case eConnectionStatusNoConnection:
1057 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1058 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1059 "forwarding as communication returned status %d (error: "
1060 "%s)",
1061 __FUNCTION__, status, error.AsCString());
1062 m_stdio_handle_up.reset();
1063 return;
1064
1065 case eConnectionStatusInterrupted:
1066 case eConnectionStatusTimedOut:
1067 return;
1068 }
1069 }
1070}
1071
1072GDBRemoteCommunication::PacketResult
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001073GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1074 StringExtractorGDBRemote &packet) {
1075 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1076 // Fail if we don't have a current process.
1077 if (!m_debugged_process_sp ||
1078 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1079 return SendErrorResponse(68);
1080
1081 if (!packet.ConsumeFront("jTraceStart:"))
1082 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1083
1084 TraceOptions options;
1085 uint64_t type = std::numeric_limits<uint64_t>::max();
1086 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1087 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1088 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1089
1090 auto json_object = StructuredData::ParseJSON(packet.Peek());
1091
1092 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001093 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001094 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1095
1096 auto json_dict = json_object->GetAsDictionary();
1097
Pavel Labath4c950232017-05-26 13:53:39 +00001098 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001099 options.setMetaDataBufferSize(metabuffersize);
1100
Pavel Labath4c950232017-05-26 13:53:39 +00001101 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001102 options.setTraceBufferSize(buffersize);
1103
Pavel Labath4c950232017-05-26 13:53:39 +00001104 json_dict->GetValueForKeyAsInteger("type", type);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001105 options.setType(static_cast<lldb::TraceType>(type));
1106
Pavel Labath4c950232017-05-26 13:53:39 +00001107 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001108 options.setThreadID(tid);
1109
1110 StructuredData::ObjectSP custom_params_sp =
1111 json_dict->GetValueForKey("params");
1112 if (custom_params_sp &&
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001113 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001114 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1115
1116 options.setTraceParams(
1117 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1118
1119 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1120 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1121 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1122 type);
1123 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1124 }
1125
1126 Status error;
1127 lldb::user_id_t uid = LLDB_INVALID_UID;
1128 uid = m_debugged_process_sp->StartTrace(options, error);
1129 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1130 if (error.Fail())
1131 return SendErrorResponse(error.GetError());
1132
1133 StreamGDBRemote response;
1134 response.Printf("%" PRIx64, uid);
1135 return SendPacketNoLock(response.GetString());
1136}
1137
1138GDBRemoteCommunication::PacketResult
1139GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1140 StringExtractorGDBRemote &packet) {
1141 // Fail if we don't have a current process.
1142 if (!m_debugged_process_sp ||
1143 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1144 return SendErrorResponse(68);
1145
1146 if (!packet.ConsumeFront("jTraceStop:"))
1147 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1148
1149 lldb::user_id_t uid = LLDB_INVALID_UID;
1150 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1151
1152 auto json_object = StructuredData::ParseJSON(packet.Peek());
1153
1154 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001155 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001156 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1157
1158 auto json_dict = json_object->GetAsDictionary();
1159
Pavel Labath4c950232017-05-26 13:53:39 +00001160 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001161 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1162
Pavel Labath4c950232017-05-26 13:53:39 +00001163 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001164
1165 Status error = m_debugged_process_sp->StopTrace(uid, tid);
1166
1167 if (error.Fail())
1168 return SendErrorResponse(error.GetError());
1169
1170 return SendOKResponse();
1171}
1172
1173GDBRemoteCommunication::PacketResult
1174GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1175 StringExtractorGDBRemote &packet) {
1176
1177 // Fail if we don't have a current process.
1178 if (!m_debugged_process_sp ||
1179 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1180 return SendErrorResponse(68);
1181
1182 if (!packet.ConsumeFront("jTraceConfigRead:"))
1183 return SendIllFormedResponse(packet,
1184 "jTraceConfigRead: Ill formed packet ");
1185
1186 lldb::user_id_t uid = LLDB_INVALID_UID;
1187 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1188
1189 auto json_object = StructuredData::ParseJSON(packet.Peek());
1190
1191 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001192 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001193 return SendIllFormedResponse(packet,
1194 "jTraceConfigRead: Ill formed packet ");
1195
1196 auto json_dict = json_object->GetAsDictionary();
1197
Pavel Labath4c950232017-05-26 13:53:39 +00001198 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001199 return SendIllFormedResponse(packet,
1200 "jTraceConfigRead: Ill formed packet ");
1201
Pavel Labath4c950232017-05-26 13:53:39 +00001202 json_dict->GetValueForKeyAsInteger("threadid", threadid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001203
1204 TraceOptions options;
1205 StreamGDBRemote response;
1206
1207 options.setThreadID(threadid);
1208 Status error = m_debugged_process_sp->GetTraceConfig(uid, options);
1209
1210 if (error.Fail())
1211 return SendErrorResponse(error.GetError());
1212
1213 StreamGDBRemote escaped_response;
1214 StructuredData::Dictionary json_packet;
1215
1216 json_packet.AddIntegerItem("type", options.getType());
1217 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1218 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1219
1220 StructuredData::DictionarySP custom_params = options.getTraceParams();
1221 if (custom_params)
1222 json_packet.AddItem("params", custom_params);
1223
1224 StreamString json_string;
1225 json_packet.Dump(json_string, false);
1226 escaped_response.PutEscapedBytes(json_string.GetData(),
1227 json_string.GetSize());
1228 return SendPacketNoLock(escaped_response.GetString());
1229}
1230
1231GDBRemoteCommunication::PacketResult
1232GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1233 StringExtractorGDBRemote &packet) {
1234
1235 // Fail if we don't have a current process.
1236 if (!m_debugged_process_sp ||
1237 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1238 return SendErrorResponse(68);
1239
1240 enum PacketType { MetaData, BufferData };
1241 PacketType tracetype = MetaData;
1242
1243 if (packet.ConsumeFront("jTraceBufferRead:"))
1244 tracetype = BufferData;
1245 else if (packet.ConsumeFront("jTraceMetaRead:"))
1246 tracetype = MetaData;
1247 else {
1248 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1249 }
1250
1251 lldb::user_id_t uid = LLDB_INVALID_UID;
1252
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001253 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001254 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001255 uint64_t offset = std::numeric_limits<uint64_t>::max();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001256
1257 auto json_object = StructuredData::ParseJSON(packet.Peek());
1258
1259 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001260 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001261 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1262
1263 auto json_dict = json_object->GetAsDictionary();
1264
Pavel Labath4c950232017-05-26 13:53:39 +00001265 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1266 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1267 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001268 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1269
Pavel Labath4c950232017-05-26 13:53:39 +00001270 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001271
1272 // Allocate the response buffer.
Ravitheja Addepally0e62a122017-05-26 14:26:14 +00001273 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1274 if (!buffer)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001275 return SendErrorResponse(0x78);
1276
1277 StreamGDBRemote response;
1278 Status error;
Ravitheja Addepally0e62a122017-05-26 14:26:14 +00001279 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001280
1281 if (tracetype == BufferData)
1282 error = m_debugged_process_sp->GetData(uid, tid, buf, offset);
1283 else if (tracetype == MetaData)
1284 error = m_debugged_process_sp->GetMetaData(uid, tid, buf, offset);
1285
1286 if (error.Fail())
1287 return SendErrorResponse(error.GetError());
1288
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001289 for (auto i : buf)
1290 response.PutHex8(i);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001291
1292 StreamGDBRemote escaped_response;
1293 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1294 return SendPacketNoLock(escaped_response.GetString());
1295}
1296
1297GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1299 StringExtractorGDBRemote &packet) {
1300 // Fail if we don't have a current process.
1301 if (!m_debugged_process_sp ||
1302 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1303 return SendErrorResponse(68);
1304
1305 lldb::pid_t pid = m_debugged_process_sp->GetID();
1306
1307 if (pid == LLDB_INVALID_PROCESS_ID)
1308 return SendErrorResponse(1);
1309
1310 ProcessInstanceInfo proc_info;
1311 if (!Host::GetProcessInfo(pid, proc_info))
1312 return SendErrorResponse(1);
1313
1314 StreamString response;
1315 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1316 return SendPacketNoLock(response.GetString());
1317}
1318
1319GDBRemoteCommunication::PacketResult
1320GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1321 // Fail if we don't have a current process.
1322 if (!m_debugged_process_sp ||
1323 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1324 return SendErrorResponse(68);
1325
1326 // Make sure we set the current thread so g and p packets return
1327 // the data the gdb will expect.
1328 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1329 SetCurrentThreadID(tid);
1330
1331 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1332 if (!thread_sp)
1333 return SendErrorResponse(69);
1334
1335 StreamString response;
1336 response.Printf("QC%" PRIx64, thread_sp->GetID());
1337
1338 return SendPacketNoLock(response.GetString());
1339}
1340
1341GDBRemoteCommunication::PacketResult
1342GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1343 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1344
1345 StopSTDIOForwarding();
1346
1347 if (!m_debugged_process_sp) {
1348 if (log)
1349 log->Printf(
1350 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1351 __FUNCTION__);
1352 return PacketResult::Success;
1353 }
1354
Zachary Turner97206d52017-05-12 04:51:55 +00001355 Status error = m_debugged_process_sp->Kill();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 if (error.Fail() && log)
1357 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1358 "process %" PRIu64 ": %s",
1359 __FUNCTION__, m_debugged_process_sp->GetID(),
1360 error.AsCString());
1361
1362 // No OK response for kill packet.
1363 // return SendOKResponse ();
1364 return PacketResult::Success;
1365}
1366
1367GDBRemoteCommunication::PacketResult
1368GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1369 StringExtractorGDBRemote &packet) {
1370 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1371 if (packet.GetU32(0))
1372 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1373 else
1374 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1375 return SendOKResponse();
1376}
1377
1378GDBRemoteCommunication::PacketResult
1379GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1380 StringExtractorGDBRemote &packet) {
1381 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1382 std::string path;
1383 packet.GetHexByteString(path);
1384 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1385 return SendOKResponse();
1386}
1387
1388GDBRemoteCommunication::PacketResult
1389GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1390 StringExtractorGDBRemote &packet) {
1391 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1392 if (working_dir) {
1393 StreamString response;
1394 response.PutCStringAsRawHex8(working_dir.GetCString());
1395 return SendPacketNoLock(response.GetString());
1396 }
1397
1398 return SendErrorResponse(14);
1399}
1400
1401GDBRemoteCommunication::PacketResult
1402GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1403 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1404 if (log)
1405 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1406
1407 // Ensure we have a native process.
1408 if (!m_debugged_process_sp) {
1409 if (log)
1410 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1411 "shared pointer",
1412 __FUNCTION__);
1413 return SendErrorResponse(0x36);
1414 }
1415
1416 // Pull out the signal number.
1417 packet.SetFilePos(::strlen("C"));
1418 if (packet.GetBytesLeft() < 1) {
1419 // Shouldn't be using a C without a signal.
1420 return SendIllFormedResponse(packet, "C packet specified without signal.");
1421 }
1422 const uint32_t signo =
1423 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1424 if (signo == std::numeric_limits<uint32_t>::max())
1425 return SendIllFormedResponse(packet, "failed to parse signal number");
1426
1427 // Handle optional continue address.
1428 if (packet.GetBytesLeft() > 0) {
1429 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1430 if (*packet.Peek() == ';')
1431 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1432 else
1433 return SendIllFormedResponse(
1434 packet, "unexpected content after $C{signal-number}");
1435 }
1436
1437 ResumeActionList resume_actions(StateType::eStateRunning, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00001438 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439
1440 // We have two branches: what to do if a continue thread is specified (in
1441 // which case we target
1442 // sending the signal to that thread), or when we don't have a continue thread
1443 // set (in which
1444 // case we send a signal to the process).
1445
1446 // TODO discuss with Greg Clayton, make sure this makes sense.
1447
1448 lldb::tid_t signal_tid = GetContinueThreadID();
1449 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1450 // The resume action for the continue thread (or all threads if a continue
1451 // thread is not set).
1452 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1453 static_cast<int>(signo)};
1454
1455 // Add the action for the continue thread (or all threads when the continue
1456 // thread isn't present).
1457 resume_actions.Append(action);
1458 } else {
1459 // Send the signal to the process since we weren't targeting a specific
1460 // continue thread with the signal.
1461 error = m_debugged_process_sp->Signal(signo);
1462 if (error.Fail()) {
1463 if (log)
1464 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1465 "signal for process %" PRIu64 ": %s",
1466 __FUNCTION__, m_debugged_process_sp->GetID(),
1467 error.AsCString());
1468
1469 return SendErrorResponse(0x52);
1470 }
1471 }
1472
1473 // Resume the threads.
1474 error = m_debugged_process_sp->Resume(resume_actions);
1475 if (error.Fail()) {
1476 if (log)
1477 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1478 "threads for process %" PRIu64 ": %s",
1479 __FUNCTION__, m_debugged_process_sp->GetID(),
1480 error.AsCString());
1481
1482 return SendErrorResponse(0x38);
1483 }
1484
1485 // Don't send an "OK" packet; response is the stopped/exited message.
1486 return PacketResult::Success;
1487}
1488
1489GDBRemoteCommunication::PacketResult
1490GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1491 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1492 if (log)
1493 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1494
1495 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1496
1497 // For now just support all continue.
1498 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1499 if (has_continue_address) {
1500 if (log)
1501 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1502 "c{address} variant [%s remains]",
1503 __FUNCTION__, packet.Peek());
1504 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1505 }
1506
1507 // Ensure we have a native process.
1508 if (!m_debugged_process_sp) {
1509 if (log)
1510 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1511 "shared pointer",
1512 __FUNCTION__);
1513 return SendErrorResponse(0x36);
1514 }
1515
1516 // Build the ResumeActionList
1517 ResumeActionList actions(StateType::eStateRunning, 0);
1518
Zachary Turner97206d52017-05-12 04:51:55 +00001519 Status error = m_debugged_process_sp->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001520 if (error.Fail()) {
1521 if (log) {
1522 log->Printf(
1523 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1524 ": %s",
1525 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1526 }
1527 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1528 }
1529
1530 if (log)
1531 log->Printf(
1532 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1533 __FUNCTION__, m_debugged_process_sp->GetID());
1534
1535 // No response required from continue.
1536 return PacketResult::Success;
1537}
1538
1539GDBRemoteCommunication::PacketResult
1540GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1541 StringExtractorGDBRemote &packet) {
1542 StreamString response;
1543 response.Printf("vCont;c;C;s;S");
1544
1545 return SendPacketNoLock(response.GetString());
1546}
1547
1548GDBRemoteCommunication::PacketResult
1549GDBRemoteCommunicationServerLLGS::Handle_vCont(
1550 StringExtractorGDBRemote &packet) {
1551 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1552 if (log)
1553 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1554 __FUNCTION__);
1555
1556 packet.SetFilePos(::strlen("vCont"));
1557
1558 if (packet.GetBytesLeft() == 0) {
1559 if (log)
1560 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1561 "vCont package",
1562 __FUNCTION__);
1563 return SendIllFormedResponse(packet, "Missing action from vCont package");
1564 }
1565
1566 // Check if this is all continue (no options or ";c").
1567 if (::strcmp(packet.Peek(), ";c") == 0) {
1568 // Move past the ';', then do a simple 'c'.
1569 packet.SetFilePos(packet.GetFilePos() + 1);
1570 return Handle_c(packet);
1571 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1572 // Move past the ';', then do a simple 's'.
1573 packet.SetFilePos(packet.GetFilePos() + 1);
1574 return Handle_s(packet);
1575 }
1576
1577 // Ensure we have a native process.
1578 if (!m_debugged_process_sp) {
1579 if (log)
1580 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1581 "shared pointer",
1582 __FUNCTION__);
1583 return SendErrorResponse(0x36);
1584 }
1585
1586 ResumeActionList thread_actions;
1587
1588 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1589 // Skip the semi-colon.
1590 packet.GetChar();
1591
1592 // Build up the thread action.
1593 ResumeAction thread_action;
1594 thread_action.tid = LLDB_INVALID_THREAD_ID;
1595 thread_action.state = eStateInvalid;
1596 thread_action.signal = 0;
1597
1598 const char action = packet.GetChar();
1599 switch (action) {
1600 case 'C':
1601 thread_action.signal = packet.GetHexMaxU32(false, 0);
1602 if (thread_action.signal == 0)
1603 return SendIllFormedResponse(
1604 packet, "Could not parse signal in vCont packet C action");
1605 LLVM_FALLTHROUGH;
1606
1607 case 'c':
1608 // Continue
1609 thread_action.state = eStateRunning;
1610 break;
1611
1612 case 'S':
1613 thread_action.signal = packet.GetHexMaxU32(false, 0);
1614 if (thread_action.signal == 0)
1615 return SendIllFormedResponse(
1616 packet, "Could not parse signal in vCont packet S action");
1617 LLVM_FALLTHROUGH;
1618
1619 case 's':
1620 // Step
1621 thread_action.state = eStateStepping;
1622 break;
Pavel Labathabadc222015-11-27 13:33:29 +00001623
Tamas Berghammere13c2732015-02-11 10:29:30 +00001624 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625 return SendIllFormedResponse(packet, "Unsupported vCont action");
1626 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00001627 }
1628
Kate Stoneb9c1b512016-09-06 20:57:50 +00001629 // Parse out optional :{thread-id} value.
1630 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1631 // Consume the separator.
1632 packet.GetChar();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001633
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1635 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1636 return SendIllFormedResponse(
1637 packet, "Could not parse thread number in vCont packet");
Pavel Labath77dc9562015-07-13 10:44:55 +00001638 }
1639
Kate Stoneb9c1b512016-09-06 20:57:50 +00001640 thread_actions.Append(thread_action);
1641 }
Pavel Labath77dc9562015-07-13 10:44:55 +00001642
Zachary Turner97206d52017-05-12 04:51:55 +00001643 Status error = m_debugged_process_sp->Resume(thread_actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001644 if (error.Fail()) {
1645 if (log) {
1646 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1647 "process %" PRIu64 ": %s",
1648 __FUNCTION__, m_debugged_process_sp->GetID(),
1649 error.AsCString());
Pavel Labath77dc9562015-07-13 10:44:55 +00001650 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001651 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1652 }
1653
1654 if (log)
1655 log->Printf(
1656 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1657 __FUNCTION__, m_debugged_process_sp->GetID());
1658
1659 // No response required from vCont.
1660 return PacketResult::Success;
Pavel Labath77dc9562015-07-13 10:44:55 +00001661}
1662
Kate Stoneb9c1b512016-09-06 20:57:50 +00001663void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1664 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1665 if (log)
1666 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1667 "id to %" PRIu64,
1668 __FUNCTION__, tid);
Pavel Labath77dc9562015-07-13 10:44:55 +00001669
Kate Stoneb9c1b512016-09-06 20:57:50 +00001670 m_current_tid = tid;
1671 if (m_debugged_process_sp)
1672 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1673}
1674
1675void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1676 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1677 if (log)
1678 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1679 "id to %" PRIu64,
1680 __FUNCTION__, tid);
1681
1682 m_continue_tid = tid;
Pavel Labath77dc9562015-07-13 10:44:55 +00001683}
1684
Tamas Berghammere13c2732015-02-11 10:29:30 +00001685GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001686GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1687 StringExtractorGDBRemote &packet) {
1688 // Handle the $? gdbremote command.
Tamas Berghammere13c2732015-02-11 10:29:30 +00001689
Kate Stoneb9c1b512016-09-06 20:57:50 +00001690 // If no process, indicate error
1691 if (!m_debugged_process_sp)
1692 return SendErrorResponse(02);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001693
Kate Stoneb9c1b512016-09-06 20:57:50 +00001694 return SendStopReasonForState(m_debugged_process_sp->GetState());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001695}
1696
1697GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001698GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1699 lldb::StateType process_state) {
1700 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00001701
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702 switch (process_state) {
1703 case eStateAttaching:
1704 case eStateLaunching:
1705 case eStateRunning:
1706 case eStateStepping:
1707 case eStateDetached:
1708 // NOTE: gdb protocol doc looks like it should return $OK
1709 // when everything is running (i.e. no stopped result).
1710 return PacketResult::Success; // Ignore
Tamas Berghammere13c2732015-02-11 10:29:30 +00001711
Kate Stoneb9c1b512016-09-06 20:57:50 +00001712 case eStateSuspended:
1713 case eStateStopped:
1714 case eStateCrashed: {
1715 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001716 // Make sure we set the current thread so g and p packets return
1717 // the data the gdb will expect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718 SetCurrentThreadID(tid);
1719 return SendStopReplyPacketForThread(tid);
1720 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001721
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722 case eStateInvalid:
1723 case eStateUnloaded:
1724 case eStateExited:
1725 return SendWResponse(m_debugged_process_sp.get());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001726
Kate Stoneb9c1b512016-09-06 20:57:50 +00001727 default:
1728 if (log) {
1729 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1730 ", current state reporting not handled: %s",
1731 __FUNCTION__, m_debugged_process_sp->GetID(),
1732 StateAsCString(process_state));
Pavel Labath424b2012015-07-28 09:06:56 +00001733 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001734 break;
1735 }
Pavel Labath424b2012015-07-28 09:06:56 +00001736
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737 return SendErrorResponse(0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001738}
1739
1740GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001741GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1742 StringExtractorGDBRemote &packet) {
1743 // Fail if we don't have a current process.
1744 if (!m_debugged_process_sp ||
1745 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1746 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001747
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 // Ensure we have a thread.
1749 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1750 if (!thread_sp)
1751 return SendErrorResponse(69);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001752
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753 // Get the register context for the first thread.
1754 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1755 if (!reg_context_sp)
1756 return SendErrorResponse(69);
1757
1758 // Parse out the register number from the request.
1759 packet.SetFilePos(strlen("qRegisterInfo"));
1760 const uint32_t reg_index =
1761 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1762 if (reg_index == std::numeric_limits<uint32_t>::max())
1763 return SendErrorResponse(69);
1764
1765 // Return the end of registers response if we've iterated one past the end of
1766 // the register set.
1767 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1768 return SendErrorResponse(69);
1769
1770 const RegisterInfo *reg_info =
1771 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1772 if (!reg_info)
1773 return SendErrorResponse(69);
1774
1775 // Build the reginfos response.
1776 StreamGDBRemote response;
1777
1778 response.PutCString("name:");
1779 response.PutCString(reg_info->name);
1780 response.PutChar(';');
1781
1782 if (reg_info->alt_name && reg_info->alt_name[0]) {
1783 response.PutCString("alt-name:");
1784 response.PutCString(reg_info->alt_name);
1785 response.PutChar(';');
1786 }
1787
1788 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1789 reg_info->byte_size * 8, reg_info->byte_offset);
1790
1791 switch (reg_info->encoding) {
1792 case eEncodingUint:
1793 response.PutCString("encoding:uint;");
1794 break;
1795 case eEncodingSint:
1796 response.PutCString("encoding:sint;");
1797 break;
1798 case eEncodingIEEE754:
1799 response.PutCString("encoding:ieee754;");
1800 break;
1801 case eEncodingVector:
1802 response.PutCString("encoding:vector;");
1803 break;
1804 default:
1805 break;
1806 }
1807
1808 switch (reg_info->format) {
1809 case eFormatBinary:
1810 response.PutCString("format:binary;");
1811 break;
1812 case eFormatDecimal:
1813 response.PutCString("format:decimal;");
1814 break;
1815 case eFormatHex:
1816 response.PutCString("format:hex;");
1817 break;
1818 case eFormatFloat:
1819 response.PutCString("format:float;");
1820 break;
1821 case eFormatVectorOfSInt8:
1822 response.PutCString("format:vector-sint8;");
1823 break;
1824 case eFormatVectorOfUInt8:
1825 response.PutCString("format:vector-uint8;");
1826 break;
1827 case eFormatVectorOfSInt16:
1828 response.PutCString("format:vector-sint16;");
1829 break;
1830 case eFormatVectorOfUInt16:
1831 response.PutCString("format:vector-uint16;");
1832 break;
1833 case eFormatVectorOfSInt32:
1834 response.PutCString("format:vector-sint32;");
1835 break;
1836 case eFormatVectorOfUInt32:
1837 response.PutCString("format:vector-uint32;");
1838 break;
1839 case eFormatVectorOfFloat32:
1840 response.PutCString("format:vector-float32;");
1841 break;
Valentina Giusticda0ae42016-09-08 14:16:45 +00001842 case eFormatVectorOfUInt64:
1843 response.PutCString("format:vector-uint64;");
1844 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001845 case eFormatVectorOfUInt128:
1846 response.PutCString("format:vector-uint128;");
1847 break;
1848 default:
1849 break;
1850 };
1851
1852 const char *const register_set_name =
1853 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1854 if (register_set_name) {
1855 response.PutCString("set:");
1856 response.PutCString(register_set_name);
1857 response.PutChar(';');
1858 }
1859
1860 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1861 LLDB_INVALID_REGNUM)
1862 response.Printf("ehframe:%" PRIu32 ";",
1863 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1864
1865 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1866 response.Printf("dwarf:%" PRIu32 ";",
1867 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1868
1869 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1870 case LLDB_REGNUM_GENERIC_PC:
1871 response.PutCString("generic:pc;");
1872 break;
1873 case LLDB_REGNUM_GENERIC_SP:
1874 response.PutCString("generic:sp;");
1875 break;
1876 case LLDB_REGNUM_GENERIC_FP:
1877 response.PutCString("generic:fp;");
1878 break;
1879 case LLDB_REGNUM_GENERIC_RA:
1880 response.PutCString("generic:ra;");
1881 break;
1882 case LLDB_REGNUM_GENERIC_FLAGS:
1883 response.PutCString("generic:flags;");
1884 break;
1885 case LLDB_REGNUM_GENERIC_ARG1:
1886 response.PutCString("generic:arg1;");
1887 break;
1888 case LLDB_REGNUM_GENERIC_ARG2:
1889 response.PutCString("generic:arg2;");
1890 break;
1891 case LLDB_REGNUM_GENERIC_ARG3:
1892 response.PutCString("generic:arg3;");
1893 break;
1894 case LLDB_REGNUM_GENERIC_ARG4:
1895 response.PutCString("generic:arg4;");
1896 break;
1897 case LLDB_REGNUM_GENERIC_ARG5:
1898 response.PutCString("generic:arg5;");
1899 break;
1900 case LLDB_REGNUM_GENERIC_ARG6:
1901 response.PutCString("generic:arg6;");
1902 break;
1903 case LLDB_REGNUM_GENERIC_ARG7:
1904 response.PutCString("generic:arg7;");
1905 break;
1906 case LLDB_REGNUM_GENERIC_ARG8:
1907 response.PutCString("generic:arg8;");
1908 break;
1909 default:
1910 break;
1911 }
1912
1913 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1914 response.PutCString("container-regs:");
1915 int i = 0;
1916 for (const uint32_t *reg_num = reg_info->value_regs;
1917 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1918 if (i > 0)
1919 response.PutChar(',');
1920 response.Printf("%" PRIx32, *reg_num);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001921 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001922 response.PutChar(';');
1923 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001924
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1926 response.PutCString("invalidate-regs:");
1927 int i = 0;
1928 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1929 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1930 if (i > 0)
1931 response.PutChar(',');
1932 response.Printf("%" PRIx32, *reg_num);
1933 }
1934 response.PutChar(';');
1935 }
1936
1937 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1938 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1939 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1940 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1941 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1942 response.PutChar(';');
1943 }
1944 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001945}
1946
1947GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001948GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1949 StringExtractorGDBRemote &packet) {
1950 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1951
1952 // Fail if we don't have a current process.
1953 if (!m_debugged_process_sp ||
1954 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00001955 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001956 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1957 "returning OK",
1958 __FUNCTION__,
1959 m_debugged_process_sp ? "invalid process id"
1960 : "null m_debugged_process_sp");
1961 return SendOKResponse();
1962 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001963
Kate Stoneb9c1b512016-09-06 20:57:50 +00001964 StreamGDBRemote response;
1965 response.PutChar('m');
1966
1967 if (log)
1968 log->Printf(
1969 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
1970 __FUNCTION__);
1971
1972 NativeThreadProtocolSP thread_sp;
1973 uint32_t thread_index;
1974 for (thread_index = 0,
1975 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
1976 thread_sp; ++thread_index,
1977 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
1978 if (log)
1979 log->Printf(
1980 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
1981 "(%s, tid=0x%" PRIx64 ")",
1982 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
1983 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
1984 if (thread_index > 0)
1985 response.PutChar(',');
1986 response.Printf("%" PRIx64, thread_sp->GetID());
1987 }
1988
1989 if (log)
1990 log->Printf(
1991 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
1992 __FUNCTION__);
1993
1994 return SendPacketNoLock(response.GetString());
1995}
1996
1997GDBRemoteCommunication::PacketResult
1998GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1999 StringExtractorGDBRemote &packet) {
2000 // FIXME for now we return the full thread list in the initial packet and
2001 // always do nothing here.
2002 return SendPacketNoLock("l");
2003}
2004
2005GDBRemoteCommunication::PacketResult
2006GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2007 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2008
2009 // Parse out the register number from the request.
2010 packet.SetFilePos(strlen("p"));
2011 const uint32_t reg_index =
2012 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2013 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2014 if (log)
2015 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2016 "parse register number from request \"%s\"",
2017 __FUNCTION__, packet.GetStringRef().c_str());
2018 return SendErrorResponse(0x15);
2019 }
2020
2021 // Get the thread to use.
2022 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2023 if (!thread_sp) {
2024 if (log)
2025 log->Printf(
2026 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
2027 __FUNCTION__);
2028 return SendErrorResponse(0x15);
2029 }
2030
2031 // Get the thread's register context.
2032 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2033 if (!reg_context_sp) {
2034 if (log)
2035 log->Printf(
2036 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2037 " failed, no register context available for the thread",
2038 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2039 return SendErrorResponse(0x15);
2040 }
2041
2042 // Return the end of registers response if we've iterated one past the end of
2043 // the register set.
2044 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2045 if (log)
2046 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2047 "register %" PRIu32 " beyond register count %" PRIu32,
2048 __FUNCTION__, reg_index,
2049 reg_context_sp->GetUserRegisterCount());
2050 return SendErrorResponse(0x15);
2051 }
2052
2053 const RegisterInfo *reg_info =
2054 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2055 if (!reg_info) {
2056 if (log)
2057 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2058 "register %" PRIu32 " returned NULL",
2059 __FUNCTION__, reg_index);
2060 return SendErrorResponse(0x15);
2061 }
2062
2063 // Build the reginfos response.
2064 StreamGDBRemote response;
2065
2066 // Retrieve the value
2067 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +00002068 Status error = reg_context_sp->ReadRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002069 if (error.Fail()) {
2070 if (log)
2071 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
2072 "requested register %" PRIu32 " (%s) failed: %s",
2073 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2074 return SendErrorResponse(0x15);
2075 }
2076
2077 const uint8_t *const data =
2078 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
2079 if (!data) {
2080 if (log)
2081 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
2082 "bytes from requested register %" PRIu32,
2083 __FUNCTION__, reg_index);
2084 return SendErrorResponse(0x15);
2085 }
2086
2087 // FIXME flip as needed to get data in big/little endian format for this host.
2088 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2089 response.PutHex8(data[i]);
2090
2091 return SendPacketNoLock(response.GetString());
2092}
2093
2094GDBRemoteCommunication::PacketResult
2095GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2096 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2097
2098 // Ensure there is more content.
2099 if (packet.GetBytesLeft() < 1)
2100 return SendIllFormedResponse(packet, "Empty P packet");
2101
2102 // Parse out the register number from the request.
2103 packet.SetFilePos(strlen("P"));
2104 const uint32_t reg_index =
2105 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2106 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2107 if (log)
2108 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2109 "parse register number from request \"%s\"",
2110 __FUNCTION__, packet.GetStringRef().c_str());
2111 return SendErrorResponse(0x29);
2112 }
2113
2114 // Note debugserver would send an E30 here.
2115 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2116 return SendIllFormedResponse(
2117 packet, "P packet missing '=' char after register number");
2118
2119 // Get process architecture.
2120 ArchSpec process_arch;
2121 if (!m_debugged_process_sp ||
2122 !m_debugged_process_sp->GetArchitecture(process_arch)) {
2123 if (log)
2124 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
2125 "inferior architecture",
2126 __FUNCTION__);
2127 return SendErrorResponse(0x49);
2128 }
2129
2130 // Parse out the value.
2131 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2132 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2133
2134 // Get the thread to use.
2135 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2136 if (!thread_sp) {
2137 if (log)
2138 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2139 "available (thread index 0)",
2140 __FUNCTION__);
2141 return SendErrorResponse(0x28);
2142 }
2143
2144 // Get the thread's register context.
2145 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2146 if (!reg_context_sp) {
2147 if (log)
2148 log->Printf(
2149 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2150 " failed, no register context available for the thread",
2151 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2152 return SendErrorResponse(0x15);
2153 }
2154
2155 const RegisterInfo *reg_info =
2156 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2157 if (!reg_info) {
2158 if (log)
2159 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2160 "register %" PRIu32 " returned NULL",
2161 __FUNCTION__, reg_index);
2162 return SendErrorResponse(0x48);
2163 }
2164
2165 // Return the end of registers response if we've iterated one past the end of
2166 // the register set.
2167 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2168 if (log)
2169 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2170 "register %" PRIu32 " beyond register count %" PRIu32,
2171 __FUNCTION__, reg_index,
2172 reg_context_sp->GetUserRegisterCount());
2173 return SendErrorResponse(0x47);
2174 }
2175
2176 // The dwarf expression are evaluate on host site
2177 // which may cause register size to change
2178 // Hence the reg_size may not be same as reg_info->bytes_size
2179 if ((reg_size != reg_info->byte_size) &&
2180 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2181 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2182 }
2183
2184 // Build the reginfos response.
2185 StreamGDBRemote response;
2186
2187 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
Zachary Turner97206d52017-05-12 04:51:55 +00002188 Status error = reg_context_sp->WriteRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189 if (error.Fail()) {
2190 if (log)
2191 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2192 "requested register %" PRIu32 " (%s) failed: %s",
2193 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2194 return SendErrorResponse(0x32);
2195 }
2196
2197 return SendOKResponse();
2198}
2199
2200GDBRemoteCommunication::PacketResult
2201GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2202 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2203
2204 // Fail if we don't have a current process.
2205 if (!m_debugged_process_sp ||
2206 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2207 if (log)
2208 log->Printf(
2209 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2210 __FUNCTION__);
2211 return SendErrorResponse(0x15);
2212 }
2213
2214 // Parse out which variant of $H is requested.
2215 packet.SetFilePos(strlen("H"));
2216 if (packet.GetBytesLeft() < 1) {
2217 if (log)
2218 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2219 "missing {g,c} variant",
2220 __FUNCTION__);
2221 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2222 }
2223
2224 const char h_variant = packet.GetChar();
2225 switch (h_variant) {
2226 case 'g':
2227 break;
2228
2229 case 'c':
2230 break;
2231
2232 default:
2233 if (log)
2234 log->Printf(
2235 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2236 __FUNCTION__, h_variant);
2237 return SendIllFormedResponse(packet,
2238 "H variant unsupported, should be c or g");
2239 }
2240
2241 // Parse out the thread number.
2242 // FIXME return a parse success/fail value. All values are valid here.
2243 const lldb::tid_t tid =
2244 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2245
2246 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2247 // (any thread).
2248 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2249 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2250 if (!thread_sp) {
2251 if (log)
2252 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2253 " not found",
2254 __FUNCTION__, tid);
2255 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002256 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002258
Kate Stoneb9c1b512016-09-06 20:57:50 +00002259 // Now switch the given thread type.
2260 switch (h_variant) {
2261 case 'g':
2262 SetCurrentThreadID(tid);
2263 break;
2264
2265 case 'c':
2266 SetContinueThreadID(tid);
2267 break;
2268
2269 default:
2270 assert(false && "unsupported $H variant - shouldn't get here");
2271 return SendIllFormedResponse(packet,
2272 "H variant unsupported, should be c or g");
2273 }
2274
2275 return SendOKResponse();
2276}
2277
2278GDBRemoteCommunication::PacketResult
2279GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2280 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2281
2282 // Fail if we don't have a current process.
2283 if (!m_debugged_process_sp ||
2284 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2285 if (log)
2286 log->Printf(
2287 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2288 __FUNCTION__);
2289 return SendErrorResponse(0x15);
2290 }
2291
2292 packet.SetFilePos(::strlen("I"));
2293 uint8_t tmp[4096];
2294 for (;;) {
2295 size_t read = packet.GetHexBytesAvail(tmp);
2296 if (read == 0) {
2297 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002298 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299 // write directly to stdin *this might block if stdin buffer is full*
2300 // TODO: enqueue this block in circular buffer and send window size to
2301 // remote host
2302 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00002303 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002304 m_stdio_communication.Write(tmp, read, status, &error);
2305 if (error.Fail()) {
2306 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002307 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002308 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002309
Kate Stoneb9c1b512016-09-06 20:57:50 +00002310 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002311}
2312
2313GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002314GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2315 StringExtractorGDBRemote &packet) {
2316 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2317
2318 // Fail if we don't have a current process.
2319 if (!m_debugged_process_sp ||
2320 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002321 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002322 log->Printf(
2323 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2324 __FUNCTION__);
2325 return SendErrorResponse(0x15);
2326 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002327
Kate Stoneb9c1b512016-09-06 20:57:50 +00002328 // Interrupt the process.
Zachary Turner97206d52017-05-12 04:51:55 +00002329 Status error = m_debugged_process_sp->Interrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002330 if (error.Fail()) {
2331 if (log) {
2332 log->Printf(
2333 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2334 ": %s",
2335 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002336 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002337 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2338 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002339
Kate Stoneb9c1b512016-09-06 20:57:50 +00002340 if (log)
2341 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2342 __FUNCTION__, m_debugged_process_sp->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002343
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344 // No response required from stop all.
2345 return PacketResult::Success;
2346}
Tamas Berghammere13c2732015-02-11 10:29:30 +00002347
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348GDBRemoteCommunication::PacketResult
2349GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2350 StringExtractorGDBRemote &packet) {
2351 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002352
Kate Stoneb9c1b512016-09-06 20:57:50 +00002353 if (!m_debugged_process_sp ||
2354 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002355 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002356 log->Printf(
2357 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2358 __FUNCTION__);
2359 return SendErrorResponse(0x15);
2360 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002361
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362 // Parse out the memory address.
2363 packet.SetFilePos(strlen("m"));
2364 if (packet.GetBytesLeft() < 1)
2365 return SendIllFormedResponse(packet, "Too short m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002366
Kate Stoneb9c1b512016-09-06 20:57:50 +00002367 // Read the address. Punting on validation.
2368 // FIXME replace with Hex U64 read with no default value that fails on failed
2369 // read.
2370 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002371
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372 // Validate comma.
2373 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2374 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002375
Kate Stoneb9c1b512016-09-06 20:57:50 +00002376 // Get # bytes to read.
2377 if (packet.GetBytesLeft() < 1)
2378 return SendIllFormedResponse(packet, "Length missing in m packet");
2379
2380 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2381 if (byte_count == 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002382 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002383 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2384 "zero-length packet",
2385 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002386 return SendOKResponse();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002388
Kate Stoneb9c1b512016-09-06 20:57:50 +00002389 // Allocate the response buffer.
2390 std::string buf(byte_count, '\0');
2391 if (buf.empty())
2392 return SendErrorResponse(0x78);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002393
Kate Stoneb9c1b512016-09-06 20:57:50 +00002394 // Retrieve the process memory.
2395 size_t bytes_read = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002396 Status error = m_debugged_process_sp->ReadMemoryWithoutTrap(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002397 read_addr, &buf[0], byte_count, bytes_read);
2398 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002399 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002400 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2401 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2402 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2403 error.AsCString());
2404 return SendErrorResponse(0x08);
2405 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002406
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 if (bytes_read == 0) {
2408 if (log)
2409 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2410 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2411 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2412 byte_count);
2413 return SendErrorResponse(0x08);
2414 }
2415
2416 StreamGDBRemote response;
2417 packet.SetFilePos(0);
2418 char kind = packet.GetChar('?');
2419 if (kind == 'x')
2420 response.PutEscapedBytes(buf.data(), byte_count);
2421 else {
2422 assert(kind == 'm');
2423 for (size_t i = 0; i < bytes_read; ++i)
2424 response.PutHex8(buf[i]);
2425 }
2426
2427 return SendPacketNoLock(response.GetString());
2428}
2429
2430GDBRemoteCommunication::PacketResult
2431GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2432 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2433
2434 if (!m_debugged_process_sp ||
2435 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2436 if (log)
2437 log->Printf(
2438 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2439 __FUNCTION__);
2440 return SendErrorResponse(0x15);
2441 }
2442
2443 // Parse out the memory address.
2444 packet.SetFilePos(strlen("M"));
2445 if (packet.GetBytesLeft() < 1)
2446 return SendIllFormedResponse(packet, "Too short M packet");
2447
2448 // Read the address. Punting on validation.
2449 // FIXME replace with Hex U64 read with no default value that fails on failed
2450 // read.
2451 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2452
2453 // Validate comma.
2454 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2455 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2456
2457 // Get # bytes to read.
2458 if (packet.GetBytesLeft() < 1)
2459 return SendIllFormedResponse(packet, "Length missing in M packet");
2460
2461 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2462 if (byte_count == 0) {
2463 if (log)
2464 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2465 "zero-length packet",
2466 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002467 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002468 }
2469
2470 // Validate colon.
2471 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2472 return SendIllFormedResponse(
2473 packet, "Comma sep missing in M packet after byte length");
2474
2475 // Allocate the conversion buffer.
2476 std::vector<uint8_t> buf(byte_count, 0);
2477 if (buf.empty())
2478 return SendErrorResponse(0x78);
2479
2480 // Convert the hex memory write contents to bytes.
2481 StreamGDBRemote response;
2482 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2483 if (convert_count != byte_count) {
2484 if (log)
2485 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2486 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2487 " bytes, but only found %" PRIu64 " to convert.",
2488 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2489 byte_count, convert_count);
2490 return SendIllFormedResponse(packet, "M content byte length specified did "
2491 "not match hex-encoded content "
2492 "length");
2493 }
2494
2495 // Write the process memory.
2496 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002497 Status error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2498 byte_count, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002499 if (error.Fail()) {
2500 if (log)
2501 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2502 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2503 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2504 error.AsCString());
2505 return SendErrorResponse(0x09);
2506 }
2507
2508 if (bytes_written == 0) {
2509 if (log)
2510 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2511 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2512 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2513 byte_count);
2514 return SendErrorResponse(0x09);
2515 }
2516
2517 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002518}
2519
2520GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002521GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2522 StringExtractorGDBRemote &packet) {
2523 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002524
Kate Stoneb9c1b512016-09-06 20:57:50 +00002525 // Currently only the NativeProcessProtocol knows if it can handle a
2526 // qMemoryRegionInfoSupported
2527 // request, but we're not guaranteed to be attached to a process. For now
2528 // we'll assume the
2529 // client only asks this when a process is being debugged.
Tamas Berghammere13c2732015-02-11 10:29:30 +00002530
Kate Stoneb9c1b512016-09-06 20:57:50 +00002531 // Ensure we have a process running; otherwise, we can't figure this out
2532 // since we won't have a NativeProcessProtocol.
2533 if (!m_debugged_process_sp ||
2534 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2535 if (log)
2536 log->Printf(
2537 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2538 __FUNCTION__);
2539 return SendErrorResponse(0x15);
2540 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002541
Kate Stoneb9c1b512016-09-06 20:57:50 +00002542 // Test if we can get any region back when asking for the region around NULL.
2543 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002544 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002545 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2546 if (error.Fail()) {
2547 // We don't support memory region info collection for this
2548 // NativeProcessProtocol.
2549 return SendUnimplementedResponse("");
2550 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002551
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002553}
2554
2555GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002556GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2557 StringExtractorGDBRemote &packet) {
2558 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002559
Kate Stoneb9c1b512016-09-06 20:57:50 +00002560 // Ensure we have a process.
2561 if (!m_debugged_process_sp ||
2562 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2563 if (log)
2564 log->Printf(
2565 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2566 __FUNCTION__);
2567 return SendErrorResponse(0x15);
2568 }
2569
2570 // Parse out the memory address.
2571 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2572 if (packet.GetBytesLeft() < 1)
2573 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2574
2575 // Read the address. Punting on validation.
2576 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2577
2578 StreamGDBRemote response;
2579
2580 // Get the memory region info for the target address.
2581 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002582 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002583 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2584 if (error.Fail()) {
2585 // Return the error message.
2586
2587 response.PutCString("error:");
2588 response.PutCStringAsRawHex8(error.AsCString());
2589 response.PutChar(';');
2590 } else {
2591 // Range start and size.
2592 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2593 region_info.GetRange().GetRangeBase(),
2594 region_info.GetRange().GetByteSize());
2595
2596 // Permissions.
2597 if (region_info.GetReadable() || region_info.GetWritable() ||
2598 region_info.GetExecutable()) {
2599 // Write permissions info.
2600 response.PutCString("permissions:");
2601
2602 if (region_info.GetReadable())
2603 response.PutChar('r');
2604 if (region_info.GetWritable())
2605 response.PutChar('w');
2606 if (region_info.GetExecutable())
2607 response.PutChar('x');
2608
2609 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002610 }
2611
Kate Stoneb9c1b512016-09-06 20:57:50 +00002612 // Name
2613 ConstString name = region_info.GetName();
2614 if (name) {
2615 response.PutCString("name:");
2616 response.PutCStringAsRawHex8(name.AsCString());
2617 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002618 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002619 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002620
Kate Stoneb9c1b512016-09-06 20:57:50 +00002621 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002622}
2623
2624GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002625GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2626 // Ensure we have a process.
2627 if (!m_debugged_process_sp ||
2628 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2629 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2630 if (log)
2631 log->Printf(
2632 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2633 __FUNCTION__);
2634 return SendErrorResponse(0x15);
2635 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002636
Kate Stoneb9c1b512016-09-06 20:57:50 +00002637 // Parse out software or hardware breakpoint or watchpoint requested.
2638 packet.SetFilePos(strlen("Z"));
2639 if (packet.GetBytesLeft() < 1)
2640 return SendIllFormedResponse(
2641 packet, "Too short Z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002642
Kate Stoneb9c1b512016-09-06 20:57:50 +00002643 bool want_breakpoint = true;
2644 bool want_hardware = false;
2645 uint32_t watch_flags = 0;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002646
Kate Stoneb9c1b512016-09-06 20:57:50 +00002647 const GDBStoppointType stoppoint_type =
2648 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2649 switch (stoppoint_type) {
2650 case eBreakpointSoftware:
2651 want_hardware = false;
2652 want_breakpoint = true;
2653 break;
2654 case eBreakpointHardware:
2655 want_hardware = true;
2656 want_breakpoint = true;
2657 break;
2658 case eWatchpointWrite:
2659 watch_flags = 1;
2660 want_hardware = true;
2661 want_breakpoint = false;
2662 break;
2663 case eWatchpointRead:
2664 watch_flags = 2;
2665 want_hardware = true;
2666 want_breakpoint = false;
2667 break;
2668 case eWatchpointReadWrite:
2669 watch_flags = 3;
2670 want_hardware = true;
2671 want_breakpoint = false;
2672 break;
2673 case eStoppointInvalid:
2674 return SendIllFormedResponse(
2675 packet, "Z packet had invalid software/hardware specifier");
2676 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002677
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2679 return SendIllFormedResponse(
2680 packet, "Malformed Z packet, expecting comma after stoppoint type");
2681
2682 // Parse out the stoppoint address.
2683 if (packet.GetBytesLeft() < 1)
2684 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2685 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2686
2687 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2688 return SendIllFormedResponse(
2689 packet, "Malformed Z packet, expecting comma after address");
2690
2691 // Parse out the stoppoint size (i.e. size hint for opcode size).
2692 const uint32_t size =
2693 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2694 if (size == std::numeric_limits<uint32_t>::max())
2695 return SendIllFormedResponse(
2696 packet, "Malformed Z packet, failed to parse size argument");
2697
2698 if (want_breakpoint) {
2699 // Try to set the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002700 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002701 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2702 if (error.Success())
2703 return SendOKResponse();
2704 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2705 if (log)
2706 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2707 " failed to set breakpoint: %s",
2708 __FUNCTION__, m_debugged_process_sp->GetID(),
2709 error.AsCString());
2710 return SendErrorResponse(0x09);
2711 } else {
2712 // Try to set the watchpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002713 const Status error = m_debugged_process_sp->SetWatchpoint(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002714 addr, size, watch_flags, want_hardware);
2715 if (error.Success())
2716 return SendOKResponse();
2717 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2718 if (log)
2719 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2720 " failed to set watchpoint: %s",
2721 __FUNCTION__, m_debugged_process_sp->GetID(),
2722 error.AsCString());
2723 return SendErrorResponse(0x09);
2724 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002725}
2726
2727GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2729 // Ensure we have a process.
2730 if (!m_debugged_process_sp ||
2731 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2732 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2733 if (log)
2734 log->Printf(
2735 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2736 __FUNCTION__);
2737 return SendErrorResponse(0x15);
2738 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002739
Kate Stoneb9c1b512016-09-06 20:57:50 +00002740 // Parse out software or hardware breakpoint or watchpoint requested.
2741 packet.SetFilePos(strlen("z"));
2742 if (packet.GetBytesLeft() < 1)
2743 return SendIllFormedResponse(
2744 packet, "Too short z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002745
Kate Stoneb9c1b512016-09-06 20:57:50 +00002746 bool want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002747 bool want_hardware = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002748
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749 const GDBStoppointType stoppoint_type =
2750 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2751 switch (stoppoint_type) {
2752 case eBreakpointHardware:
2753 want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002754 want_hardware = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002755 break;
2756 case eBreakpointSoftware:
2757 want_breakpoint = true;
2758 break;
2759 case eWatchpointWrite:
2760 want_breakpoint = false;
2761 break;
2762 case eWatchpointRead:
2763 want_breakpoint = false;
2764 break;
2765 case eWatchpointReadWrite:
2766 want_breakpoint = false;
2767 break;
2768 default:
2769 return SendIllFormedResponse(
2770 packet, "z packet had invalid software/hardware specifier");
2771 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002772
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2774 return SendIllFormedResponse(
2775 packet, "Malformed z packet, expecting comma after stoppoint type");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002776
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 // Parse out the stoppoint address.
2778 if (packet.GetBytesLeft() < 1)
2779 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2780 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002781
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2783 return SendIllFormedResponse(
2784 packet, "Malformed z packet, expecting comma after address");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002785
Kate Stoneb9c1b512016-09-06 20:57:50 +00002786 /*
2787 // Parse out the stoppoint size (i.e. size hint for opcode size).
2788 const uint32_t size = packet.GetHexMaxU32 (false,
2789 std::numeric_limits<uint32_t>::max ());
2790 if (size == std::numeric_limits<uint32_t>::max ())
2791 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2792 size argument");
2793 */
Tamas Berghammere13c2732015-02-11 10:29:30 +00002794
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 if (want_breakpoint) {
2796 // Try to clear the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002797 const Status error =
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002798 m_debugged_process_sp->RemoveBreakpoint(addr, want_hardware);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 if (error.Success())
2800 return SendOKResponse();
2801 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2802 if (log)
2803 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2804 " failed to remove breakpoint: %s",
2805 __FUNCTION__, m_debugged_process_sp->GetID(),
2806 error.AsCString());
2807 return SendErrorResponse(0x09);
2808 } else {
2809 // Try to clear the watchpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002810 const Status error = m_debugged_process_sp->RemoveWatchpoint(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811 if (error.Success())
2812 return SendOKResponse();
2813 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2814 if (log)
2815 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2816 " failed to remove watchpoint: %s",
2817 __FUNCTION__, m_debugged_process_sp->GetID(),
2818 error.AsCString());
2819 return SendErrorResponse(0x09);
2820 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002821}
2822
2823GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002824GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2825 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002826
Kate Stoneb9c1b512016-09-06 20:57:50 +00002827 // Ensure we have a process.
2828 if (!m_debugged_process_sp ||
2829 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2830 if (log)
2831 log->Printf(
2832 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2833 __FUNCTION__);
2834 return SendErrorResponse(0x32);
2835 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002836
Kate Stoneb9c1b512016-09-06 20:57:50 +00002837 // We first try to use a continue thread id. If any one or any all set, use
2838 // the current thread.
2839 // Bail out if we don't have a thread id.
2840 lldb::tid_t tid = GetContinueThreadID();
2841 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2842 tid = GetCurrentThreadID();
2843 if (tid == LLDB_INVALID_THREAD_ID)
2844 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002845
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 // Double check that we have such a thread.
2847 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2848 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2849 if (!thread_sp || thread_sp->GetID() != tid)
2850 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002851
Kate Stoneb9c1b512016-09-06 20:57:50 +00002852 // Create the step action for the given thread.
2853 ResumeAction action = {tid, eStateStepping, 0};
Tamas Berghammere13c2732015-02-11 10:29:30 +00002854
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 // Setup the actions list.
2856 ResumeActionList actions;
2857 actions.Append(action);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002858
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859 // All other threads stop while we're single stepping a thread.
2860 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00002861 Status error = m_debugged_process_sp->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002862 if (error.Fail()) {
2863 if (log)
2864 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2865 " tid %" PRIu64 " Resume() failed with error: %s",
2866 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2867 error.AsCString());
2868 return SendErrorResponse(0x49);
2869 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002870
Kate Stoneb9c1b512016-09-06 20:57:50 +00002871 // No response here - the stop or exit will come from the resulting action.
2872 return PacketResult::Success;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002873}
2874
2875GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2877 StringExtractorGDBRemote &packet) {
2878// *BSD impls should be able to do this too.
Kamil Rytarowskic93408a2017-03-21 17:27:59 +00002879#if defined(__linux__) || defined(__NetBSD__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002880 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002881
Kate Stoneb9c1b512016-09-06 20:57:50 +00002882 // Parse out the offset.
2883 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2884 if (packet.GetBytesLeft() < 1)
2885 return SendIllFormedResponse(packet,
2886 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002887
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888 const uint64_t auxv_offset =
2889 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2890 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2891 return SendIllFormedResponse(packet,
2892 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002893
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 // Parse out comma.
2895 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2896 return SendIllFormedResponse(
2897 packet, "qXfer:auxv:read:: packet missing comma after offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002898
Kate Stoneb9c1b512016-09-06 20:57:50 +00002899 // Parse out the length.
2900 const uint64_t auxv_length =
2901 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2902 if (auxv_length == std::numeric_limits<uint64_t>::max())
2903 return SendIllFormedResponse(packet,
2904 "qXfer:auxv:read:: packet missing length");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002905
Kate Stoneb9c1b512016-09-06 20:57:50 +00002906 // Grab the auxv data if we need it.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002907 if (!m_active_auxv_buffer_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002908 // Make sure we have a valid process.
2909 if (!m_debugged_process_sp ||
2910 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2911 if (log)
2912 log->Printf(
2913 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2914 __FUNCTION__);
2915 return SendErrorResponse(0x10);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002916 }
2917
Kate Stoneb9c1b512016-09-06 20:57:50 +00002918 // Grab the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002919 auto buffer_or_error = m_debugged_process_sp->GetAuxvData();
2920 if (!buffer_or_error) {
2921 std::error_code ec = buffer_or_error.getError();
2922 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2923 return SendErrorResponse(ec.value());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002924 }
Pavel Labathb7f0f452017-03-17 11:08:40 +00002925 m_active_auxv_buffer_up = std::move(*buffer_or_error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002926 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002927
Kate Stoneb9c1b512016-09-06 20:57:50 +00002928 StreamGDBRemote response;
2929 bool done_with_buffer = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002930
Pavel Labathb7f0f452017-03-17 11:08:40 +00002931 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2932 if (auxv_offset >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002933 // We have nothing left to send. Mark the buffer as complete.
2934 response.PutChar('l');
2935 done_with_buffer = true;
2936 } else {
2937 // Figure out how many bytes are available starting at the given offset.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002938 buffer = buffer.drop_front(auxv_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939
2940 // Mark the response type according to whether we're reading the remainder
2941 // of the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002942 if (auxv_length >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002943 // There will be nothing left to read after this
2944 response.PutChar('l');
2945 done_with_buffer = true;
2946 } else {
2947 // There will still be bytes to read after this request.
2948 response.PutChar('m');
Pavel Labathb7f0f452017-03-17 11:08:40 +00002949 buffer = buffer.take_front(auxv_length);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002950 }
2951
Kate Stoneb9c1b512016-09-06 20:57:50 +00002952 // Now write the data in encoded binary form.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002953 response.PutEscapedBytes(buffer.data(), buffer.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002954 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002955
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 if (done_with_buffer)
Pavel Labathb7f0f452017-03-17 11:08:40 +00002957 m_active_auxv_buffer_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958
2959 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002960#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002961 return SendUnimplementedResponse("not implemented on this platform");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002962#endif
2963}
2964
2965GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002966GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2967 StringExtractorGDBRemote &packet) {
2968 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002969
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 // Move past packet name.
2971 packet.SetFilePos(strlen("QSaveRegisterState"));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002972
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 // Get the thread to use.
2974 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2975 if (!thread_sp) {
2976 if (m_thread_suffix_supported)
2977 return SendIllFormedResponse(
2978 packet, "No thread specified in QSaveRegisterState packet");
2979 else
2980 return SendIllFormedResponse(packet,
2981 "No thread was is set with the Hg packet");
2982 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002983
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984 // Grab the register context for the thread.
2985 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2986 if (!reg_context_sp) {
2987 if (log)
2988 log->Printf(
2989 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2990 " failed, no register context available for the thread",
2991 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2992 return SendErrorResponse(0x15);
2993 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002994
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 // Save registers to a buffer.
2996 DataBufferSP register_data_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00002997 Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002998 if (error.Fail()) {
2999 if (log)
3000 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3001 " failed to save all register values: %s",
3002 __FUNCTION__, m_debugged_process_sp->GetID(),
3003 error.AsCString());
3004 return SendErrorResponse(0x75);
3005 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003006
Kate Stoneb9c1b512016-09-06 20:57:50 +00003007 // Allocate a new save id.
3008 const uint32_t save_id = GetNextSavedRegistersID();
3009 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3010 "GetNextRegisterSaveID() returned an existing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003011
Kate Stoneb9c1b512016-09-06 20:57:50 +00003012 // Save the register data buffer under the save id.
3013 {
3014 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3015 m_saved_registers_map[save_id] = register_data_sp;
3016 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003017
Kate Stoneb9c1b512016-09-06 20:57:50 +00003018 // Write the response.
3019 StreamGDBRemote response;
3020 response.Printf("%" PRIu32, save_id);
3021 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003022}
3023
3024GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003025GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3026 StringExtractorGDBRemote &packet) {
3027 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003028
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 // Parse out save id.
3030 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3031 if (packet.GetBytesLeft() < 1)
3032 return SendIllFormedResponse(
3033 packet, "QRestoreRegisterState packet missing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003034
Kate Stoneb9c1b512016-09-06 20:57:50 +00003035 const uint32_t save_id = packet.GetU32(0);
3036 if (save_id == 0) {
3037 if (log)
3038 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
3039 "packet has malformed save id, expecting decimal uint32_t",
3040 __FUNCTION__);
3041 return SendErrorResponse(0x76);
3042 }
3043
3044 // Get the thread to use.
3045 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3046 if (!thread_sp) {
3047 if (m_thread_suffix_supported)
3048 return SendIllFormedResponse(
3049 packet, "No thread specified in QRestoreRegisterState packet");
3050 else
3051 return SendIllFormedResponse(packet,
3052 "No thread was is set with the Hg packet");
3053 }
3054
3055 // Grab the register context for the thread.
3056 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3057 if (!reg_context_sp) {
3058 if (log)
3059 log->Printf(
3060 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3061 " failed, no register context available for the thread",
3062 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3063 return SendErrorResponse(0x15);
3064 }
3065
3066 // Retrieve register state buffer, then remove from the list.
3067 DataBufferSP register_data_sp;
3068 {
3069 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3070
3071 // Find the register set buffer for the given save id.
3072 auto it = m_saved_registers_map.find(save_id);
3073 if (it == m_saved_registers_map.end()) {
3074 if (log)
3075 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3076 " does not have a register set save buffer for id %" PRIu32,
3077 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
3078 return SendErrorResponse(0x77);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003079 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003080 register_data_sp = it->second;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003081
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082 // Remove it from the map.
3083 m_saved_registers_map.erase(it);
3084 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003085
Zachary Turner97206d52017-05-12 04:51:55 +00003086 Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003087 if (error.Fail()) {
3088 if (log)
3089 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3090 " failed to restore all register values: %s",
3091 __FUNCTION__, m_debugged_process_sp->GetID(),
3092 error.AsCString());
3093 return SendErrorResponse(0x77);
3094 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003095
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003097}
3098
3099GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3101 StringExtractorGDBRemote &packet) {
3102 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003103
Kate Stoneb9c1b512016-09-06 20:57:50 +00003104 // Consume the ';' after vAttach.
3105 packet.SetFilePos(strlen("vAttach"));
3106 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3107 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003108
Kate Stoneb9c1b512016-09-06 20:57:50 +00003109 // Grab the PID to which we will attach (assume hex encoding).
3110 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3111 if (pid == LLDB_INVALID_PROCESS_ID)
3112 return SendIllFormedResponse(packet,
3113 "vAttach failed to parse the process id");
3114
3115 // Attempt to attach.
3116 if (log)
3117 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3118 "pid %" PRIu64,
3119 __FUNCTION__, pid);
3120
Zachary Turner97206d52017-05-12 04:51:55 +00003121 Status error = AttachToProcess(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003122
3123 if (error.Fail()) {
3124 if (log)
3125 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3126 "pid %" PRIu64 ": %s\n",
3127 __FUNCTION__, pid, error.AsCString());
3128 return SendErrorResponse(0x01);
3129 }
3130
3131 // Notify we attached by sending a stop packet.
3132 return SendStopReasonForState(m_debugged_process_sp->GetState());
3133}
3134
3135GDBRemoteCommunication::PacketResult
3136GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3137 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3138
3139 StopSTDIOForwarding();
3140
3141 // Fail if we don't have a current process.
3142 if (!m_debugged_process_sp ||
3143 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
3144 if (log)
3145 log->Printf(
3146 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3147 __FUNCTION__);
3148 return SendErrorResponse(0x15);
3149 }
3150
3151 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3152
3153 // Consume the ';' after D.
3154 packet.SetFilePos(1);
3155 if (packet.GetBytesLeft()) {
3156 if (packet.GetChar() != ';')
3157 return SendIllFormedResponse(packet, "D missing expected ';'");
3158
3159 // Grab the PID from which we will detach (assume hex encoding).
3160 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003161 if (pid == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003162 return SendIllFormedResponse(packet, "D failed to parse the process id");
3163 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003164
Kate Stoneb9c1b512016-09-06 20:57:50 +00003165 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
3166 return SendIllFormedResponse(packet, "Invalid pid");
3167 }
3168
Zachary Turner97206d52017-05-12 04:51:55 +00003169 const Status error = m_debugged_process_sp->Detach();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003170 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003171 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003172 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3173 "pid %" PRIu64 ": %s\n",
3174 __FUNCTION__, m_debugged_process_sp->GetID(),
3175 error.AsCString());
3176 return SendErrorResponse(0x01);
3177 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003178
Kate Stoneb9c1b512016-09-06 20:57:50 +00003179 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003180}
3181
3182GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003183GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3184 StringExtractorGDBRemote &packet) {
3185 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003186
Kate Stoneb9c1b512016-09-06 20:57:50 +00003187 packet.SetFilePos(strlen("qThreadStopInfo"));
3188 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3189 if (tid == LLDB_INVALID_THREAD_ID) {
Pavel Labath4a4bb122015-07-16 14:14:35 +00003190 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003191 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3192 "parse thread id from request \"%s\"",
3193 __FUNCTION__, packet.GetStringRef().c_str());
3194 return SendErrorResponse(0x15);
3195 }
3196 return SendStopReplyPacketForThread(tid);
3197}
3198
3199GDBRemoteCommunication::PacketResult
3200GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3201 StringExtractorGDBRemote &) {
3202 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3203
3204 // Ensure we have a debugged process.
3205 if (!m_debugged_process_sp ||
3206 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
3207 return SendErrorResponse(50);
3208
3209 if (log)
3210 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
3211 "%" PRIu64,
Pavel Labath4a4bb122015-07-16 14:14:35 +00003212 __FUNCTION__, m_debugged_process_sp->GetID());
3213
Kate Stoneb9c1b512016-09-06 20:57:50 +00003214 StreamString response;
3215 const bool threads_with_valid_stop_info_only = false;
3216 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3217 *m_debugged_process_sp, threads_with_valid_stop_info_only);
3218 if (!threads_array_sp) {
3219 if (log)
3220 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
3221 "packet for pid %" PRIu64,
3222 __FUNCTION__, m_debugged_process_sp->GetID());
3223 return SendErrorResponse(52);
3224 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00003225
Kate Stoneb9c1b512016-09-06 20:57:50 +00003226 threads_array_sp->Write(response);
3227 StreamGDBRemote escaped_response;
3228 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3229 return SendPacketNoLock(escaped_response.GetString());
Pavel Labath4a4bb122015-07-16 14:14:35 +00003230}
3231
3232GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003233GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3234 StringExtractorGDBRemote &packet) {
3235 // Fail if we don't have a current process.
3236 if (!m_debugged_process_sp ||
3237 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3238 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003239
Kate Stoneb9c1b512016-09-06 20:57:50 +00003240 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3241 if (packet.GetBytesLeft() == 0)
3242 return SendOKResponse();
3243 if (packet.GetChar() != ':')
3244 return SendErrorResponse(67);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003245
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003246 auto hw_debug_cap = m_debugged_process_sp->GetHardwareDebugSupportInfo();
3247
Kate Stoneb9c1b512016-09-06 20:57:50 +00003248 StreamGDBRemote response;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003249 if (hw_debug_cap == llvm::None)
3250 response.Printf("num:0;");
3251 else
3252 response.Printf("num:%d;", hw_debug_cap->second);
3253
Kate Stoneb9c1b512016-09-06 20:57:50 +00003254 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003255}
3256
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003257GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003258GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3259 StringExtractorGDBRemote &packet) {
3260 // Fail if we don't have a current process.
3261 if (!m_debugged_process_sp ||
3262 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3263 return SendErrorResponse(67);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003264
Kate Stoneb9c1b512016-09-06 20:57:50 +00003265 packet.SetFilePos(strlen("qFileLoadAddress:"));
3266 if (packet.GetBytesLeft() == 0)
3267 return SendErrorResponse(68);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003268
Kate Stoneb9c1b512016-09-06 20:57:50 +00003269 std::string file_name;
3270 packet.GetHexByteString(file_name);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003271
Kate Stoneb9c1b512016-09-06 20:57:50 +00003272 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00003273 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003274 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3275 if (error.Fail())
3276 return SendErrorResponse(69);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003277
Kate Stoneb9c1b512016-09-06 20:57:50 +00003278 if (file_load_address == LLDB_INVALID_ADDRESS)
3279 return SendErrorResponse(1); // File not loaded
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003280
Kate Stoneb9c1b512016-09-06 20:57:50 +00003281 StreamGDBRemote response;
3282 response.PutHex64(file_load_address);
3283 return SendPacketNoLock(response.GetString());
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003284}
3285
Pavel Labath4a705e72017-02-24 09:29:14 +00003286GDBRemoteCommunication::PacketResult
3287GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3288 StringExtractorGDBRemote &packet) {
3289 std::vector<int> signals;
3290 packet.SetFilePos(strlen("QPassSignals:"));
3291
3292 // Read sequence of hex signal numbers divided by a semicolon and
3293 // optionally spaces.
3294 while (packet.GetBytesLeft() > 0) {
3295 int signal = packet.GetS32(-1, 16);
3296 if (signal < 0)
3297 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3298 signals.push_back(signal);
3299
3300 packet.SkipSpaces();
3301 char separator = packet.GetChar();
3302 if (separator == '\0')
3303 break; // End of string
3304 if (separator != ';')
3305 return SendIllFormedResponse(packet, "Invalid separator,"
3306 " expected semicolon.");
3307 }
3308
3309 // Fail if we don't have a current process.
3310 if (!m_debugged_process_sp)
3311 return SendErrorResponse(68);
3312
Zachary Turner97206d52017-05-12 04:51:55 +00003313 Status error = m_debugged_process_sp->IgnoreSignals(signals);
Pavel Labath4a705e72017-02-24 09:29:14 +00003314 if (error.Fail())
3315 return SendErrorResponse(69);
3316
3317 return SendOKResponse();
3318}
3319
Kate Stoneb9c1b512016-09-06 20:57:50 +00003320void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3321 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003322
Kate Stoneb9c1b512016-09-06 20:57:50 +00003323 // Tell the stdio connection to shut down.
3324 if (m_stdio_communication.IsConnected()) {
3325 auto connection = m_stdio_communication.GetConnection();
3326 if (connection) {
Zachary Turner97206d52017-05-12 04:51:55 +00003327 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003328 connection->Disconnect(&error);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003329
Kate Stoneb9c1b512016-09-06 20:57:50 +00003330 if (error.Success()) {
3331 if (log)
3332 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3333 "terminal stdio - SUCCESS",
3334 __FUNCTION__);
3335 } else {
3336 if (log)
3337 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3338 "terminal stdio - FAIL: %s",
3339 __FUNCTION__, error.AsCString());
3340 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003341 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003342 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003343}
3344
Kate Stoneb9c1b512016-09-06 20:57:50 +00003345NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3346 StringExtractorGDBRemote &packet) {
3347 NativeThreadProtocolSP thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003348
Kate Stoneb9c1b512016-09-06 20:57:50 +00003349 // We have no thread if we don't have a process.
3350 if (!m_debugged_process_sp ||
3351 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
Tamas Berghammere13c2732015-02-11 10:29:30 +00003352 return thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003353
Kate Stoneb9c1b512016-09-06 20:57:50 +00003354 // If the client hasn't asked for thread suffix support, there will not be a
3355 // thread suffix.
3356 // Use the current thread in that case.
3357 if (!m_thread_suffix_supported) {
3358 const lldb::tid_t current_tid = GetCurrentThreadID();
3359 if (current_tid == LLDB_INVALID_THREAD_ID)
3360 return thread_sp;
3361 else if (current_tid == 0) {
3362 // Pick a thread.
3363 return m_debugged_process_sp->GetThreadAtIndex(0);
3364 } else
3365 return m_debugged_process_sp->GetThreadByID(current_tid);
3366 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003367
Kate Stoneb9c1b512016-09-06 20:57:50 +00003368 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003369
Kate Stoneb9c1b512016-09-06 20:57:50 +00003370 // Parse out the ';'.
3371 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003372 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003373 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3374 "error: expected ';' prior to start of thread suffix: packet "
3375 "contents = '%s'",
3376 __FUNCTION__, packet.GetStringRef().c_str());
3377 return thread_sp;
3378 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003379
Kate Stoneb9c1b512016-09-06 20:57:50 +00003380 if (!packet.GetBytesLeft())
3381 return thread_sp;
3382
3383 // Parse out thread: portion.
3384 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3385 if (log)
3386 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3387 "error: expected 'thread:' but not found, packet contents = "
3388 "'%s'",
3389 __FUNCTION__, packet.GetStringRef().c_str());
3390 return thread_sp;
3391 }
3392 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3393 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3394 if (tid != 0)
3395 return m_debugged_process_sp->GetThreadByID(tid);
3396
3397 return thread_sp;
3398}
3399
3400lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3401 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3402 // Use whatever the debug process says is the current thread id
3403 // since the protocol either didn't specify or specified we want
3404 // any/all threads marked as the current thread.
3405 if (!m_debugged_process_sp)
3406 return LLDB_INVALID_THREAD_ID;
3407 return m_debugged_process_sp->GetCurrentThreadID();
3408 }
3409 // Use the specific current thread id set by the gdb remote protocol.
3410 return m_current_tid;
3411}
3412
3413uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3414 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3415 return m_next_saved_registers_id++;
3416}
3417
3418void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
Pavel Labathb7f0f452017-03-17 11:08:40 +00003419 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003420
Pavel Labathb7f0f452017-03-17 11:08:40 +00003421 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3422 m_active_auxv_buffer_up.reset();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003423}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003424
3425FileSpec
Kate Stoneb9c1b512016-09-06 20:57:50 +00003426GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3427 const ArchSpec &arch) {
3428 if (m_debugged_process_sp) {
3429 FileSpec file_spec;
3430 if (m_debugged_process_sp
3431 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3432 .Success()) {
3433 if (file_spec.Exists())
3434 return file_spec;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003435 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003436 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003437
Kate Stoneb9c1b512016-09-06 20:57:50 +00003438 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003439}