blob: 0b3bbfec202d998b99c19ed66a866c8e3269e751 [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
373 ExitType exit_type = ExitType::eExitTypeInvalid;
374 int return_code = 0;
375 std::string exit_description;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 const bool got_exit_info =
378 process->GetExitStatus(&exit_type, &return_code, exit_description);
379 if (!got_exit_info) {
380 if (log)
381 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
382 ", failed to retrieve process exit status",
383 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 StreamGDBRemote response;
386 response.PutChar('E');
387 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
388 return SendPacketNoLock(response.GetString());
389 } else {
390 if (log)
391 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
392 ", returning exit type %d, return code %d [%s]",
393 __FUNCTION__, process->GetID(), exit_type, return_code,
394 exit_description.c_str());
395
396 StreamGDBRemote response;
397
398 char return_type_code;
399 switch (exit_type) {
400 case ExitType::eExitTypeExit:
401 return_type_code = 'W';
402 break;
403 case ExitType::eExitTypeSignal:
404 return_type_code = 'X';
405 break;
406 case ExitType::eExitTypeStop:
407 return_type_code = 'S';
408 break;
409 case ExitType::eExitTypeInvalid:
410 return_type_code = 'E';
411 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000412 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 response.PutChar(return_type_code);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 // POSIX exit status limited to unsigned 8 bits.
416 response.PutHex8(return_code);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000417
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 return SendPacketNoLock(response.GetString());
419 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000420}
421
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422static void AppendHexValue(StreamString &response, const uint8_t *buf,
423 uint32_t buf_size, bool swap) {
424 int64_t i;
425 if (swap) {
426 for (i = buf_size - 1; i >= 0; i--)
427 response.PutHex8(buf[i]);
428 } else {
429 for (i = 0; i < buf_size; i++)
430 response.PutHex8(buf[i]);
431 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000432}
433
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434static void WriteRegisterValueInHexFixedWidth(
435 StreamString &response, NativeRegisterContextSP &reg_ctx_sp,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000436 const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
437 lldb::ByteOrder byte_order) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 RegisterValue reg_value;
439 if (!reg_value_p) {
Zachary Turner97206d52017-05-12 04:51:55 +0000440 Status error = reg_ctx_sp->ReadRegister(&reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 if (error.Success())
442 reg_value_p = &reg_value;
443 // else log.
444 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 if (reg_value_p) {
447 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
Pavel Labathe0a5b572017-01-20 14:17:16 +0000448 reg_value_p->GetByteSize(),
449 byte_order == lldb::eByteOrderLittle);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 } else {
451 // Zero-out any unreadable values.
452 if (reg_info.byte_size > 0) {
453 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
454 AppendHexValue(response, zeros.data(), zeros.size(), false);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000455 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000457}
458
Pavel Labathe0a5b572017-01-20 14:17:16 +0000459static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath4a4bb122015-07-16 14:14:35 +0000461
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
463 if (!reg_ctx_sp)
464 return nullptr;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000465
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000467
468#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 // Expedite all registers in the first register set (i.e. should be GPRs) that
470 // are not contained in other registers.
471 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
472 if (!reg_set_p)
473 return nullptr;
474 for (const uint32_t *reg_num_p = reg_set_p->registers;
475 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
476 uint32_t reg_num = *reg_num_p;
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000477#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 // Expedite only a couple of registers until we figure out why sending
479 // registers is
480 // expensive.
481 static const uint32_t k_expedited_registers[] = {
482 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
483 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
Pavel Labathc4645bb2015-10-26 16:25:28 +0000484
Pavel Labathe0a5b572017-01-20 14:17:16 +0000485 for (const uint32_t *generic_reg_p = k_expedited_registers;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
487 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
488 eRegisterKindGeneric, *generic_reg_p);
489 if (reg_num == LLDB_INVALID_REGNUM)
490 continue; // Target does not support the given register.
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000491#endif
492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 const RegisterInfo *const reg_info_p =
494 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
495 if (reg_info_p == nullptr) {
496 if (log)
497 log->Printf(
498 "%s failed to get register info for register index %" PRIu32,
499 __FUNCTION__, reg_num);
500 continue;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000501 }
502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 if (reg_info_p->value_regs != nullptr)
504 continue; // Only expedite registers that are not contained in other
505 // registers.
Pavel Labath4a4bb122015-07-16 14:14:35 +0000506
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000508 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 if (error.Fail()) {
510 if (log)
511 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
Pavel Labath05569f62015-07-23 09:09:29 +0000512 __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
514 reg_num, error.AsCString());
515 continue;
Pavel Labath05569f62015-07-23 09:09:29 +0000516 }
517
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 StreamString stream;
519 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000520 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521
522 register_object_sp->SetObject(
523 llvm::to_string(reg_num),
524 std::make_shared<JSONString>(stream.GetString()));
525 }
526
527 return register_object_sp;
Pavel Labath05569f62015-07-23 09:09:29 +0000528}
529
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530static const char *GetStopReasonString(StopReason stop_reason) {
531 switch (stop_reason) {
532 case eStopReasonTrace:
533 return "trace";
534 case eStopReasonBreakpoint:
535 return "breakpoint";
536 case eStopReasonWatchpoint:
537 return "watchpoint";
538 case eStopReasonSignal:
539 return "signal";
540 case eStopReasonException:
541 return "exception";
542 case eStopReasonExec:
543 return "exec";
544 case eStopReasonInstrumentation:
545 case eStopReasonInvalid:
546 case eStopReasonPlanComplete:
547 case eStopReasonThreadExiting:
548 case eStopReasonNone:
549 break; // ignored
550 }
551 return nullptr;
552}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
555 bool abridged) {
556 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 // Ensure we can get info on the given thread.
561 uint32_t thread_idx = 0;
562 for (NativeThreadProtocolSP thread_sp;
563 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
564 ++thread_idx) {
565
566 lldb::tid_t tid = thread_sp->GetID();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000567
568 // Grab the reason this thread stopped.
569 struct ThreadStopInfo tid_stop_info;
570 std::string description;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 if (!thread_sp->GetStopReason(tid_stop_info, description))
572 return nullptr;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000573
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 const int signum = tid_stop_info.details.signal.signo;
575 if (log) {
576 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
577 " tid %" PRIu64
578 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
579 __FUNCTION__, process.GetID(), tid, signum,
580 tid_stop_info.reason, tid_stop_info.details.exception.type);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000581 }
582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
584 threads_array_sp->AppendObject(thread_obj_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000585
Pavel Labathe0a5b572017-01-20 14:17:16 +0000586 if (!abridged) {
587 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
588 thread_obj_sp->SetObject("registers", registers_sp);
589 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000590
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
592 if (signum != 0)
593 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000594
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 const std::string thread_name = thread_sp->GetName();
596 if (!thread_name.empty())
597 thread_obj_sp->SetObject("name",
598 std::make_shared<JSONString>(thread_name));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000599
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
601 thread_obj_sp->SetObject("reason",
602 std::make_shared<JSONString>(stop_reason_str));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000603
604 if (!description.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 thread_obj_sp->SetObject("description",
606 std::make_shared<JSONString>(description));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000607
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 if ((tid_stop_info.reason == eStopReasonException) &&
609 tid_stop_info.details.exception.type) {
610 thread_obj_sp->SetObject(
611 "metype",
612 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
613
614 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
615 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
616 ++i) {
617 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
618 tid_stop_info.details.exception.data[i]));
619 }
620 thread_obj_sp->SetObject("medata", medata_array_sp);
621 }
622
623 // TODO: Expedite interesting regions of inferior memory
624 }
625
626 return threads_array_sp;
627}
628
629GDBRemoteCommunication::PacketResult
630GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
631 lldb::tid_t tid) {
632 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
633
634 // Ensure we have a debugged process.
635 if (!m_debugged_process_sp ||
636 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
637 return SendErrorResponse(50);
638
639 if (log)
640 log->Printf(
641 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
642 " tid %" PRIu64,
643 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
644
645 // Ensure we can get info on the given thread.
646 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
647 if (!thread_sp)
648 return SendErrorResponse(51);
649
650 // Grab the reason this thread stopped.
651 struct ThreadStopInfo tid_stop_info;
652 std::string description;
653 if (!thread_sp->GetStopReason(tid_stop_info, description))
654 return SendErrorResponse(52);
655
656 // FIXME implement register handling for exec'd inferiors.
657 // if (tid_stop_info.reason == eStopReasonExec)
658 // {
659 // const bool force = true;
660 // InitializeRegisters(force);
661 // }
662
663 StreamString response;
664 // Output the T packet with the thread
665 response.PutChar('T');
666 int signum = tid_stop_info.details.signal.signo;
667 if (log) {
668 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
669 " tid %" PRIu64
670 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
671 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
672 tid_stop_info.reason, tid_stop_info.details.exception.type);
673 }
674
675 // Print the signal number.
676 response.PutHex8(signum & 0xff);
677
678 // Include the tid.
679 response.Printf("thread:%" PRIx64 ";", tid);
680
681 // Include the thread name if there is one.
682 const std::string thread_name = thread_sp->GetName();
683 if (!thread_name.empty()) {
684 size_t thread_name_len = thread_name.length();
685
686 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
687 response.PutCString("name:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000688 response.PutCString(thread_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 } else {
690 // The thread name contains special chars, send as hex bytes.
691 response.PutCString("hexname:");
692 response.PutCStringAsRawHex8(thread_name.c_str());
693 }
694 response.PutChar(';');
695 }
696
697 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
698 // will send all thread IDs back in the "threads" key whose value is
699 // a list of hex thread IDs separated by commas:
700 // "threads:10a,10b,10c;"
701 // This will save the debugger from having to send a pair of qfThreadInfo
702 // and qsThreadInfo packets, but it also might take a lot of room in the
703 // stop reply packet, so it must be enabled only on systems where there
704 // are no limits on packet lengths.
705 if (m_list_threads_in_stop_reply) {
706 response.PutCString("threads:");
707
708 uint32_t thread_index = 0;
709 NativeThreadProtocolSP listed_thread_sp;
710 for (listed_thread_sp =
711 m_debugged_process_sp->GetThreadAtIndex(thread_index);
712 listed_thread_sp; ++thread_index,
713 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
714 thread_index)) {
715 if (thread_index > 0)
716 response.PutChar(',');
717 response.Printf("%" PRIx64, listed_thread_sp->GetID());
718 }
719 response.PutChar(';');
720
721 // Include JSON info that describes the stop reason for any threads
722 // that actually have stop reasons. We use the new "jstopinfo" key
723 // whose values is hex ascii JSON that contains the thread IDs
724 // thread stop info only for threads that have stop reasons. Only send
725 // this if we have more than one thread otherwise this packet has all
726 // the info it needs.
727 if (thread_index > 0) {
728 const bool threads_with_valid_stop_info_only = true;
729 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
730 *m_debugged_process_sp, threads_with_valid_stop_info_only);
731 if (threads_info_sp) {
732 response.PutCString("jstopinfo:");
733 StreamString unescaped_response;
734 threads_info_sp->Write(unescaped_response);
735 response.PutCStringAsRawHex8(unescaped_response.GetData());
736 response.PutChar(';');
737 } else if (log)
738 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
739 "jstopinfo field for pid %" PRIu64,
740 __FUNCTION__, m_debugged_process_sp->GetID());
741 }
Pavel Labathe0a5b572017-01-20 14:17:16 +0000742
743 uint32_t i = 0;
744 response.PutCString("thread-pcs");
745 char delimiter = ':';
746 for (NativeThreadProtocolSP thread_sp;
747 (thread_sp = m_debugged_process_sp->GetThreadAtIndex(i)) != nullptr;
748 ++i) {
749 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
750 if (!reg_ctx_sp)
751 continue;
752
753 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
754 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
755 const RegisterInfo *const reg_info_p =
756 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
757
758 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000759 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Pavel Labathe0a5b572017-01-20 14:17:16 +0000760 if (error.Fail()) {
761 if (log)
762 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
763 __FUNCTION__,
764 reg_info_p->name ? reg_info_p->name
765 : "<unnamed-register>",
766 reg_to_read, error.AsCString());
767 continue;
768 }
769
770 response.PutChar(delimiter);
771 delimiter = ',';
772 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
773 &reg_value, endian::InlHostByteOrder());
774 }
775
776 response.PutChar(';');
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 }
778
779 //
780 // Expedite registers.
781 //
782
783 // Grab the register context.
784 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
785 if (reg_ctx_sp) {
786 // Expedite all registers in the first register set (i.e. should be GPRs)
787 // that are not contained in other registers.
788 const RegisterSet *reg_set_p;
789 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
790 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
791 if (log)
792 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
793 "from set '%s' (registers set count: %zu)",
794 __FUNCTION__,
795 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
796 reg_set_p->num_registers);
797
798 for (const uint32_t *reg_num_p = reg_set_p->registers;
799 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
800 const RegisterInfo *const reg_info_p =
801 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
802 if (reg_info_p == nullptr) {
803 if (log)
804 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
805 "register info for register set '%s', register index "
806 "%" PRIu32,
807 __FUNCTION__,
808 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
809 *reg_num_p);
810 } else if (reg_info_p->value_regs == nullptr) {
811 // Only expediate registers that are not contained in other registers.
812 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000813 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 if (error.Success()) {
815 response.Printf("%.02x:", *reg_num_p);
816 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000817 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 response.PutChar(';');
819 } else {
820 if (log)
821 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
822 "register '%s' index %" PRIu32 ": %s",
823 __FUNCTION__, reg_info_p->name ? reg_info_p->name
824 : "<unnamed-register>",
825 *reg_num_p, error.AsCString());
826 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000827 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000829 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000831
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
833 if (reason_str != nullptr) {
834 response.Printf("reason:%s;", reason_str);
835 }
836
837 if (!description.empty()) {
838 // Description may contains special chars, send as hex bytes.
839 response.PutCString("description:");
840 response.PutCStringAsRawHex8(description.c_str());
841 response.PutChar(';');
842 } else if ((tid_stop_info.reason == eStopReasonException) &&
843 tid_stop_info.details.exception.type) {
844 response.PutCString("metype:");
845 response.PutHex64(tid_stop_info.details.exception.type);
846 response.PutCString(";mecount:");
847 response.PutHex32(tid_stop_info.details.exception.data_count);
848 response.PutChar(';');
849
850 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
851 response.PutCString("medata:");
852 response.PutHex64(tid_stop_info.details.exception.data[i]);
853 response.PutChar(';');
854 }
855 }
856
857 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000858}
859
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
861 NativeProcessProtocol *process) {
862 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000863
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
865 if (log)
866 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
867
868 PacketResult result = SendStopReasonForState(StateType::eStateExited);
869 if (result != PacketResult::Success) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000870 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
872 "notification for PID %" PRIu64 ", state: eStateExited",
873 __FUNCTION__, process->GetID());
874 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000875
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876 // Close the pipe to the inferior terminal i/o if we launched it
877 // and set one up.
878 MaybeCloseInferiorTerminalConnection();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000879
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 // We are ready to exit the debug monitor.
881 m_exit_now = true;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000882}
883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
885 NativeProcessProtocol *process) {
886 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
889 if (log)
890 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000891
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 // Send the stop reason unless this is the stop after the
893 // launch or attach.
894 switch (m_inferior_prev_state) {
895 case eStateLaunching:
896 case eStateAttaching:
897 // Don't send anything per debugserver behavior.
898 break;
899 default:
900 // In all other cases, send the stop reason.
901 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
902 if (result != PacketResult::Success) {
903 if (log)
904 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
905 "notification for PID %" PRIu64 ", state: eStateExited",
906 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000907 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 break;
909 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000910}
911
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
913 NativeProcessProtocol *process, lldb::StateType state) {
914 assert(process && "process cannot be NULL");
915 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
916 if (log) {
917 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
918 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
919 __FUNCTION__, process->GetID(), StateAsCString(state));
920 }
921
922 switch (state) {
923 case StateType::eStateRunning:
924 StartSTDIOForwarding();
925 break;
926
927 case StateType::eStateStopped:
928 // Make sure we get all of the pending stdout/stderr from the inferior
929 // and send it to the lldb host before we send the state change
930 // notification
931 SendProcessOutput();
932 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
933 // does not
934 // interfere with our protocol.
935 StopSTDIOForwarding();
936 HandleInferiorState_Stopped(process);
937 break;
938
939 case StateType::eStateExited:
940 // Same as above
941 SendProcessOutput();
942 StopSTDIOForwarding();
943 HandleInferiorState_Exited(process);
944 break;
945
946 default:
947 if (log) {
948 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
949 "change for pid %" PRIu64 ", new state: %s",
950 __FUNCTION__, process->GetID(), StateAsCString(state));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000951 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 break;
953 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000954
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 // Remember the previous state reported to us.
956 m_inferior_prev_state = state;
957}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000958
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
960 ClearProcessSpecificData();
961}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000962
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
964 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
965
966 if (!m_handshake_completed) {
967 if (!HandshakeWithClient()) {
968 if (log)
969 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
970 "client failed, exiting",
971 __FUNCTION__);
972 m_mainloop.RequestTermination();
973 return;
974 }
975 m_handshake_completed = true;
976 }
977
978 bool interrupt = false;
979 bool done = false;
Zachary Turner97206d52017-05-12 04:51:55 +0000980 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 while (true) {
Pavel Labath1eff73c2016-11-24 10:54:49 +0000982 const PacketResult result = GetPacketAndSendResponse(
983 std::chrono::microseconds(0), error, interrupt, done);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 if (result == PacketResult::ErrorReplyTimeout)
985 break; // No more packets in the queue
986
987 if ((result != PacketResult::Success)) {
988 if (log)
989 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
990 "failed: %s",
991 __FUNCTION__, error.AsCString());
992 m_mainloop.RequestTermination();
993 break;
994 }
995 }
996}
997
Zachary Turner97206d52017-05-12 04:51:55 +0000998Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 std::unique_ptr<Connection> &&connection) {
1000 IOObjectSP read_object_sp = connection->GetReadObject();
1001 GDBRemoteCommunicationServer::SetConnection(connection.release());
1002
Zachary Turner97206d52017-05-12 04:51:55 +00001003 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 m_network_handle_up = m_mainloop.RegisterReadObject(
1005 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1006 error);
1007 return error;
1008}
1009
1010GDBRemoteCommunication::PacketResult
1011GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1012 uint32_t len) {
1013 if ((buffer == nullptr) || (len == 0)) {
1014 // Nothing to send.
1015 return PacketResult::Success;
1016 }
1017
1018 StreamString response;
1019 response.PutChar('O');
1020 response.PutBytesAsRawHex8(buffer, len);
1021
1022 return SendPacketNoLock(response.GetString());
1023}
1024
Zachary Turner97206d52017-05-12 04:51:55 +00001025Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1026 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027
1028 // Set up the reading/handling of process I/O
1029 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1030 new ConnectionFileDescriptor(fd, true));
1031 if (!conn_up) {
1032 error.SetErrorString("failed to create ConnectionFileDescriptor");
1033 return error;
1034 }
1035
1036 m_stdio_communication.SetCloseOnEOF(false);
1037 m_stdio_communication.SetConnection(conn_up.release());
1038 if (!m_stdio_communication.IsConnected()) {
1039 error.SetErrorString(
1040 "failed to set connection for inferior I/O communication");
1041 return error;
1042 }
1043
Zachary Turner97206d52017-05-12 04:51:55 +00001044 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045}
1046
1047void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1048 // Don't forward if not connected (e.g. when attaching).
1049 if (!m_stdio_communication.IsConnected())
1050 return;
1051
Zachary Turner97206d52017-05-12 04:51:55 +00001052 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 lldbassert(!m_stdio_handle_up);
1054 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1055 m_stdio_communication.GetConnection()->GetReadObject(),
1056 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1057
1058 if (!m_stdio_handle_up) {
1059 // Not much we can do about the failure. Log it and continue without
1060 // forwarding.
1061 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1062 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1063 "forwarding: %s",
1064 __FUNCTION__, error.AsCString());
1065 }
1066}
1067
1068void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1069 m_stdio_handle_up.reset();
1070}
1071
1072void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1073 char buffer[1024];
1074 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00001075 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 while (true) {
Pavel Labathc4063ee2016-11-25 11:58:44 +00001077 size_t bytes_read = m_stdio_communication.Read(
1078 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 switch (status) {
1080 case eConnectionStatusSuccess:
1081 SendONotification(buffer, bytes_read);
1082 break;
1083 case eConnectionStatusLostConnection:
1084 case eConnectionStatusEndOfFile:
1085 case eConnectionStatusError:
1086 case eConnectionStatusNoConnection:
1087 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1088 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1089 "forwarding as communication returned status %d (error: "
1090 "%s)",
1091 __FUNCTION__, status, error.AsCString());
1092 m_stdio_handle_up.reset();
1093 return;
1094
1095 case eConnectionStatusInterrupted:
1096 case eConnectionStatusTimedOut:
1097 return;
1098 }
1099 }
1100}
1101
1102GDBRemoteCommunication::PacketResult
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001103GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1104 StringExtractorGDBRemote &packet) {
1105 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1106 // Fail if we don't have a current process.
1107 if (!m_debugged_process_sp ||
1108 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1109 return SendErrorResponse(68);
1110
1111 if (!packet.ConsumeFront("jTraceStart:"))
1112 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1113
1114 TraceOptions options;
1115 uint64_t type = std::numeric_limits<uint64_t>::max();
1116 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1117 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1118 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1119
1120 auto json_object = StructuredData::ParseJSON(packet.Peek());
1121
1122 if (!json_object ||
1123 json_object->GetType() != StructuredData::Type::eTypeDictionary)
1124 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1125
1126 auto json_dict = json_object->GetAsDictionary();
1127
1128 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
1129 metabuffersize);
1130 options.setMetaDataBufferSize(metabuffersize);
1131
1132 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
1133 options.setTraceBufferSize(buffersize);
1134
1135 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
1136 options.setType(static_cast<lldb::TraceType>(type));
1137
1138 json_dict->GetValueForKeyAsInteger<uint64_t>("threadid", tid);
1139 options.setThreadID(tid);
1140
1141 StructuredData::ObjectSP custom_params_sp =
1142 json_dict->GetValueForKey("params");
1143 if (custom_params_sp &&
1144 custom_params_sp->GetType() != StructuredData::Type::eTypeDictionary)
1145 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1146
1147 options.setTraceParams(
1148 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1149
1150 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1151 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1152 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1153 type);
1154 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1155 }
1156
1157 Status error;
1158 lldb::user_id_t uid = LLDB_INVALID_UID;
1159 uid = m_debugged_process_sp->StartTrace(options, error);
1160 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1161 if (error.Fail())
1162 return SendErrorResponse(error.GetError());
1163
1164 StreamGDBRemote response;
1165 response.Printf("%" PRIx64, uid);
1166 return SendPacketNoLock(response.GetString());
1167}
1168
1169GDBRemoteCommunication::PacketResult
1170GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1171 StringExtractorGDBRemote &packet) {
1172 // Fail if we don't have a current process.
1173 if (!m_debugged_process_sp ||
1174 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1175 return SendErrorResponse(68);
1176
1177 if (!packet.ConsumeFront("jTraceStop:"))
1178 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1179
1180 lldb::user_id_t uid = LLDB_INVALID_UID;
1181 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1182
1183 auto json_object = StructuredData::ParseJSON(packet.Peek());
1184
1185 if (!json_object ||
1186 json_object->GetType() != StructuredData::Type::eTypeDictionary)
1187 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1188
1189 auto json_dict = json_object->GetAsDictionary();
1190
1191 if (!json_dict->GetValueForKeyAsInteger<lldb::user_id_t>("traceid", uid))
1192 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1193
1194 json_dict->GetValueForKeyAsInteger<lldb::tid_t>("threadid", tid);
1195
1196 Status error = m_debugged_process_sp->StopTrace(uid, tid);
1197
1198 if (error.Fail())
1199 return SendErrorResponse(error.GetError());
1200
1201 return SendOKResponse();
1202}
1203
1204GDBRemoteCommunication::PacketResult
1205GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1206 StringExtractorGDBRemote &packet) {
1207
1208 // Fail if we don't have a current process.
1209 if (!m_debugged_process_sp ||
1210 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1211 return SendErrorResponse(68);
1212
1213 if (!packet.ConsumeFront("jTraceConfigRead:"))
1214 return SendIllFormedResponse(packet,
1215 "jTraceConfigRead: Ill formed packet ");
1216
1217 lldb::user_id_t uid = LLDB_INVALID_UID;
1218 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1219
1220 auto json_object = StructuredData::ParseJSON(packet.Peek());
1221
1222 if (!json_object ||
1223 json_object->GetType() != StructuredData::Type::eTypeDictionary)
1224 return SendIllFormedResponse(packet,
1225 "jTraceConfigRead: Ill formed packet ");
1226
1227 auto json_dict = json_object->GetAsDictionary();
1228
1229 if (!json_dict->GetValueForKeyAsInteger<lldb::user_id_t>("traceid", uid))
1230 return SendIllFormedResponse(packet,
1231 "jTraceConfigRead: Ill formed packet ");
1232
1233 json_dict->GetValueForKeyAsInteger<lldb::tid_t>("threadid", threadid);
1234
1235 TraceOptions options;
1236 StreamGDBRemote response;
1237
1238 options.setThreadID(threadid);
1239 Status error = m_debugged_process_sp->GetTraceConfig(uid, options);
1240
1241 if (error.Fail())
1242 return SendErrorResponse(error.GetError());
1243
1244 StreamGDBRemote escaped_response;
1245 StructuredData::Dictionary json_packet;
1246
1247 json_packet.AddIntegerItem("type", options.getType());
1248 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1249 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1250
1251 StructuredData::DictionarySP custom_params = options.getTraceParams();
1252 if (custom_params)
1253 json_packet.AddItem("params", custom_params);
1254
1255 StreamString json_string;
1256 json_packet.Dump(json_string, false);
1257 escaped_response.PutEscapedBytes(json_string.GetData(),
1258 json_string.GetSize());
1259 return SendPacketNoLock(escaped_response.GetString());
1260}
1261
1262GDBRemoteCommunication::PacketResult
1263GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1264 StringExtractorGDBRemote &packet) {
1265
1266 // Fail if we don't have a current process.
1267 if (!m_debugged_process_sp ||
1268 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1269 return SendErrorResponse(68);
1270
1271 enum PacketType { MetaData, BufferData };
1272 PacketType tracetype = MetaData;
1273
1274 if (packet.ConsumeFront("jTraceBufferRead:"))
1275 tracetype = BufferData;
1276 else if (packet.ConsumeFront("jTraceMetaRead:"))
1277 tracetype = MetaData;
1278 else {
1279 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1280 }
1281
1282 lldb::user_id_t uid = LLDB_INVALID_UID;
1283
1284 size_t byte_count = std::numeric_limits<size_t>::max();
1285 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1286 size_t offset = std::numeric_limits<size_t>::max();
1287
1288 auto json_object = StructuredData::ParseJSON(packet.Peek());
1289
1290 if (!json_object ||
1291 json_object->GetType() != StructuredData::Type::eTypeDictionary)
1292 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1293
1294 auto json_dict = json_object->GetAsDictionary();
1295
1296 if (!json_dict->GetValueForKeyAsInteger<lldb::user_id_t>("traceid", uid) ||
1297 !json_dict->GetValueForKeyAsInteger<uint64_t>("offset", offset) ||
1298 !json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", byte_count))
1299 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1300
1301 json_dict->GetValueForKeyAsInteger<lldb::tid_t>("threadid", tid);
1302
1303 // Allocate the response buffer.
1304 uint8_t *buffer = new (std::nothrow) uint8_t[byte_count];
1305 if (buffer == nullptr)
1306 return SendErrorResponse(0x78);
1307
1308 StreamGDBRemote response;
1309 Status error;
1310 llvm::MutableArrayRef<uint8_t> buf(buffer, byte_count);
1311
1312 if (tracetype == BufferData)
1313 error = m_debugged_process_sp->GetData(uid, tid, buf, offset);
1314 else if (tracetype == MetaData)
1315 error = m_debugged_process_sp->GetMetaData(uid, tid, buf, offset);
1316
1317 if (error.Fail())
1318 return SendErrorResponse(error.GetError());
1319
1320 for (size_t i = 0; i < buf.size(); ++i)
1321 response.PutHex8(buf[i]);
1322
1323 StreamGDBRemote escaped_response;
1324 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1325 return SendPacketNoLock(escaped_response.GetString());
1326}
1327
1328GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001329GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1330 StringExtractorGDBRemote &packet) {
1331 // Fail if we don't have a current process.
1332 if (!m_debugged_process_sp ||
1333 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1334 return SendErrorResponse(68);
1335
1336 lldb::pid_t pid = m_debugged_process_sp->GetID();
1337
1338 if (pid == LLDB_INVALID_PROCESS_ID)
1339 return SendErrorResponse(1);
1340
1341 ProcessInstanceInfo proc_info;
1342 if (!Host::GetProcessInfo(pid, proc_info))
1343 return SendErrorResponse(1);
1344
1345 StreamString response;
1346 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1347 return SendPacketNoLock(response.GetString());
1348}
1349
1350GDBRemoteCommunication::PacketResult
1351GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1352 // Fail if we don't have a current process.
1353 if (!m_debugged_process_sp ||
1354 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1355 return SendErrorResponse(68);
1356
1357 // Make sure we set the current thread so g and p packets return
1358 // the data the gdb will expect.
1359 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1360 SetCurrentThreadID(tid);
1361
1362 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1363 if (!thread_sp)
1364 return SendErrorResponse(69);
1365
1366 StreamString response;
1367 response.Printf("QC%" PRIx64, thread_sp->GetID());
1368
1369 return SendPacketNoLock(response.GetString());
1370}
1371
1372GDBRemoteCommunication::PacketResult
1373GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1374 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1375
1376 StopSTDIOForwarding();
1377
1378 if (!m_debugged_process_sp) {
1379 if (log)
1380 log->Printf(
1381 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1382 __FUNCTION__);
1383 return PacketResult::Success;
1384 }
1385
Zachary Turner97206d52017-05-12 04:51:55 +00001386 Status error = m_debugged_process_sp->Kill();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387 if (error.Fail() && log)
1388 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1389 "process %" PRIu64 ": %s",
1390 __FUNCTION__, m_debugged_process_sp->GetID(),
1391 error.AsCString());
1392
1393 // No OK response for kill packet.
1394 // return SendOKResponse ();
1395 return PacketResult::Success;
1396}
1397
1398GDBRemoteCommunication::PacketResult
1399GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1400 StringExtractorGDBRemote &packet) {
1401 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1402 if (packet.GetU32(0))
1403 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1404 else
1405 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1406 return SendOKResponse();
1407}
1408
1409GDBRemoteCommunication::PacketResult
1410GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1411 StringExtractorGDBRemote &packet) {
1412 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1413 std::string path;
1414 packet.GetHexByteString(path);
1415 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1416 return SendOKResponse();
1417}
1418
1419GDBRemoteCommunication::PacketResult
1420GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1421 StringExtractorGDBRemote &packet) {
1422 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1423 if (working_dir) {
1424 StreamString response;
1425 response.PutCStringAsRawHex8(working_dir.GetCString());
1426 return SendPacketNoLock(response.GetString());
1427 }
1428
1429 return SendErrorResponse(14);
1430}
1431
1432GDBRemoteCommunication::PacketResult
1433GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1434 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1435 if (log)
1436 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1437
1438 // Ensure we have a native process.
1439 if (!m_debugged_process_sp) {
1440 if (log)
1441 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1442 "shared pointer",
1443 __FUNCTION__);
1444 return SendErrorResponse(0x36);
1445 }
1446
1447 // Pull out the signal number.
1448 packet.SetFilePos(::strlen("C"));
1449 if (packet.GetBytesLeft() < 1) {
1450 // Shouldn't be using a C without a signal.
1451 return SendIllFormedResponse(packet, "C packet specified without signal.");
1452 }
1453 const uint32_t signo =
1454 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1455 if (signo == std::numeric_limits<uint32_t>::max())
1456 return SendIllFormedResponse(packet, "failed to parse signal number");
1457
1458 // Handle optional continue address.
1459 if (packet.GetBytesLeft() > 0) {
1460 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1461 if (*packet.Peek() == ';')
1462 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1463 else
1464 return SendIllFormedResponse(
1465 packet, "unexpected content after $C{signal-number}");
1466 }
1467
1468 ResumeActionList resume_actions(StateType::eStateRunning, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00001469 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470
1471 // We have two branches: what to do if a continue thread is specified (in
1472 // which case we target
1473 // sending the signal to that thread), or when we don't have a continue thread
1474 // set (in which
1475 // case we send a signal to the process).
1476
1477 // TODO discuss with Greg Clayton, make sure this makes sense.
1478
1479 lldb::tid_t signal_tid = GetContinueThreadID();
1480 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1481 // The resume action for the continue thread (or all threads if a continue
1482 // thread is not set).
1483 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1484 static_cast<int>(signo)};
1485
1486 // Add the action for the continue thread (or all threads when the continue
1487 // thread isn't present).
1488 resume_actions.Append(action);
1489 } else {
1490 // Send the signal to the process since we weren't targeting a specific
1491 // continue thread with the signal.
1492 error = m_debugged_process_sp->Signal(signo);
1493 if (error.Fail()) {
1494 if (log)
1495 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1496 "signal for process %" PRIu64 ": %s",
1497 __FUNCTION__, m_debugged_process_sp->GetID(),
1498 error.AsCString());
1499
1500 return SendErrorResponse(0x52);
1501 }
1502 }
1503
1504 // Resume the threads.
1505 error = m_debugged_process_sp->Resume(resume_actions);
1506 if (error.Fail()) {
1507 if (log)
1508 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1509 "threads for process %" PRIu64 ": %s",
1510 __FUNCTION__, m_debugged_process_sp->GetID(),
1511 error.AsCString());
1512
1513 return SendErrorResponse(0x38);
1514 }
1515
1516 // Don't send an "OK" packet; response is the stopped/exited message.
1517 return PacketResult::Success;
1518}
1519
1520GDBRemoteCommunication::PacketResult
1521GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1522 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1523 if (log)
1524 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1525
1526 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1527
1528 // For now just support all continue.
1529 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1530 if (has_continue_address) {
1531 if (log)
1532 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1533 "c{address} variant [%s remains]",
1534 __FUNCTION__, packet.Peek());
1535 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1536 }
1537
1538 // Ensure we have a native process.
1539 if (!m_debugged_process_sp) {
1540 if (log)
1541 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1542 "shared pointer",
1543 __FUNCTION__);
1544 return SendErrorResponse(0x36);
1545 }
1546
1547 // Build the ResumeActionList
1548 ResumeActionList actions(StateType::eStateRunning, 0);
1549
Zachary Turner97206d52017-05-12 04:51:55 +00001550 Status error = m_debugged_process_sp->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001551 if (error.Fail()) {
1552 if (log) {
1553 log->Printf(
1554 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1555 ": %s",
1556 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1557 }
1558 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1559 }
1560
1561 if (log)
1562 log->Printf(
1563 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1564 __FUNCTION__, m_debugged_process_sp->GetID());
1565
1566 // No response required from continue.
1567 return PacketResult::Success;
1568}
1569
1570GDBRemoteCommunication::PacketResult
1571GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1572 StringExtractorGDBRemote &packet) {
1573 StreamString response;
1574 response.Printf("vCont;c;C;s;S");
1575
1576 return SendPacketNoLock(response.GetString());
1577}
1578
1579GDBRemoteCommunication::PacketResult
1580GDBRemoteCommunicationServerLLGS::Handle_vCont(
1581 StringExtractorGDBRemote &packet) {
1582 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1583 if (log)
1584 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1585 __FUNCTION__);
1586
1587 packet.SetFilePos(::strlen("vCont"));
1588
1589 if (packet.GetBytesLeft() == 0) {
1590 if (log)
1591 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1592 "vCont package",
1593 __FUNCTION__);
1594 return SendIllFormedResponse(packet, "Missing action from vCont package");
1595 }
1596
1597 // Check if this is all continue (no options or ";c").
1598 if (::strcmp(packet.Peek(), ";c") == 0) {
1599 // Move past the ';', then do a simple 'c'.
1600 packet.SetFilePos(packet.GetFilePos() + 1);
1601 return Handle_c(packet);
1602 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1603 // Move past the ';', then do a simple 's'.
1604 packet.SetFilePos(packet.GetFilePos() + 1);
1605 return Handle_s(packet);
1606 }
1607
1608 // Ensure we have a native process.
1609 if (!m_debugged_process_sp) {
1610 if (log)
1611 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1612 "shared pointer",
1613 __FUNCTION__);
1614 return SendErrorResponse(0x36);
1615 }
1616
1617 ResumeActionList thread_actions;
1618
1619 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1620 // Skip the semi-colon.
1621 packet.GetChar();
1622
1623 // Build up the thread action.
1624 ResumeAction thread_action;
1625 thread_action.tid = LLDB_INVALID_THREAD_ID;
1626 thread_action.state = eStateInvalid;
1627 thread_action.signal = 0;
1628
1629 const char action = packet.GetChar();
1630 switch (action) {
1631 case 'C':
1632 thread_action.signal = packet.GetHexMaxU32(false, 0);
1633 if (thread_action.signal == 0)
1634 return SendIllFormedResponse(
1635 packet, "Could not parse signal in vCont packet C action");
1636 LLVM_FALLTHROUGH;
1637
1638 case 'c':
1639 // Continue
1640 thread_action.state = eStateRunning;
1641 break;
1642
1643 case 'S':
1644 thread_action.signal = packet.GetHexMaxU32(false, 0);
1645 if (thread_action.signal == 0)
1646 return SendIllFormedResponse(
1647 packet, "Could not parse signal in vCont packet S action");
1648 LLVM_FALLTHROUGH;
1649
1650 case 's':
1651 // Step
1652 thread_action.state = eStateStepping;
1653 break;
Pavel Labathabadc222015-11-27 13:33:29 +00001654
Tamas Berghammere13c2732015-02-11 10:29:30 +00001655 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656 return SendIllFormedResponse(packet, "Unsupported vCont action");
1657 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00001658 }
1659
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660 // Parse out optional :{thread-id} value.
1661 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1662 // Consume the separator.
1663 packet.GetChar();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001664
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1666 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1667 return SendIllFormedResponse(
1668 packet, "Could not parse thread number in vCont packet");
Pavel Labath77dc9562015-07-13 10:44:55 +00001669 }
1670
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671 thread_actions.Append(thread_action);
1672 }
Pavel Labath77dc9562015-07-13 10:44:55 +00001673
Zachary Turner97206d52017-05-12 04:51:55 +00001674 Status error = m_debugged_process_sp->Resume(thread_actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675 if (error.Fail()) {
1676 if (log) {
1677 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1678 "process %" PRIu64 ": %s",
1679 __FUNCTION__, m_debugged_process_sp->GetID(),
1680 error.AsCString());
Pavel Labath77dc9562015-07-13 10:44:55 +00001681 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001682 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1683 }
1684
1685 if (log)
1686 log->Printf(
1687 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1688 __FUNCTION__, m_debugged_process_sp->GetID());
1689
1690 // No response required from vCont.
1691 return PacketResult::Success;
Pavel Labath77dc9562015-07-13 10:44:55 +00001692}
1693
Kate Stoneb9c1b512016-09-06 20:57:50 +00001694void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1695 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1696 if (log)
1697 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1698 "id to %" PRIu64,
1699 __FUNCTION__, tid);
Pavel Labath77dc9562015-07-13 10:44:55 +00001700
Kate Stoneb9c1b512016-09-06 20:57:50 +00001701 m_current_tid = tid;
1702 if (m_debugged_process_sp)
1703 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1704}
1705
1706void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1707 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1708 if (log)
1709 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1710 "id to %" PRIu64,
1711 __FUNCTION__, tid);
1712
1713 m_continue_tid = tid;
Pavel Labath77dc9562015-07-13 10:44:55 +00001714}
1715
Tamas Berghammere13c2732015-02-11 10:29:30 +00001716GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1718 StringExtractorGDBRemote &packet) {
1719 // Handle the $? gdbremote command.
Tamas Berghammere13c2732015-02-11 10:29:30 +00001720
Kate Stoneb9c1b512016-09-06 20:57:50 +00001721 // If no process, indicate error
1722 if (!m_debugged_process_sp)
1723 return SendErrorResponse(02);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001724
Kate Stoneb9c1b512016-09-06 20:57:50 +00001725 return SendStopReasonForState(m_debugged_process_sp->GetState());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001726}
1727
1728GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1730 lldb::StateType process_state) {
1731 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00001732
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733 switch (process_state) {
1734 case eStateAttaching:
1735 case eStateLaunching:
1736 case eStateRunning:
1737 case eStateStepping:
1738 case eStateDetached:
1739 // NOTE: gdb protocol doc looks like it should return $OK
1740 // when everything is running (i.e. no stopped result).
1741 return PacketResult::Success; // Ignore
Tamas Berghammere13c2732015-02-11 10:29:30 +00001742
Kate Stoneb9c1b512016-09-06 20:57:50 +00001743 case eStateSuspended:
1744 case eStateStopped:
1745 case eStateCrashed: {
1746 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001747 // Make sure we set the current thread so g and p packets return
1748 // the data the gdb will expect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749 SetCurrentThreadID(tid);
1750 return SendStopReplyPacketForThread(tid);
1751 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001752
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753 case eStateInvalid:
1754 case eStateUnloaded:
1755 case eStateExited:
1756 return SendWResponse(m_debugged_process_sp.get());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001757
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 default:
1759 if (log) {
1760 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1761 ", current state reporting not handled: %s",
1762 __FUNCTION__, m_debugged_process_sp->GetID(),
1763 StateAsCString(process_state));
Pavel Labath424b2012015-07-28 09:06:56 +00001764 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765 break;
1766 }
Pavel Labath424b2012015-07-28 09:06:56 +00001767
Kate Stoneb9c1b512016-09-06 20:57:50 +00001768 return SendErrorResponse(0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001769}
1770
1771GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001772GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1773 StringExtractorGDBRemote &packet) {
1774 // Fail if we don't have a current process.
1775 if (!m_debugged_process_sp ||
1776 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1777 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001778
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779 // Ensure we have a thread.
1780 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1781 if (!thread_sp)
1782 return SendErrorResponse(69);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001783
Kate Stoneb9c1b512016-09-06 20:57:50 +00001784 // Get the register context for the first thread.
1785 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1786 if (!reg_context_sp)
1787 return SendErrorResponse(69);
1788
1789 // Parse out the register number from the request.
1790 packet.SetFilePos(strlen("qRegisterInfo"));
1791 const uint32_t reg_index =
1792 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1793 if (reg_index == std::numeric_limits<uint32_t>::max())
1794 return SendErrorResponse(69);
1795
1796 // Return the end of registers response if we've iterated one past the end of
1797 // the register set.
1798 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1799 return SendErrorResponse(69);
1800
1801 const RegisterInfo *reg_info =
1802 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1803 if (!reg_info)
1804 return SendErrorResponse(69);
1805
1806 // Build the reginfos response.
1807 StreamGDBRemote response;
1808
1809 response.PutCString("name:");
1810 response.PutCString(reg_info->name);
1811 response.PutChar(';');
1812
1813 if (reg_info->alt_name && reg_info->alt_name[0]) {
1814 response.PutCString("alt-name:");
1815 response.PutCString(reg_info->alt_name);
1816 response.PutChar(';');
1817 }
1818
1819 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1820 reg_info->byte_size * 8, reg_info->byte_offset);
1821
1822 switch (reg_info->encoding) {
1823 case eEncodingUint:
1824 response.PutCString("encoding:uint;");
1825 break;
1826 case eEncodingSint:
1827 response.PutCString("encoding:sint;");
1828 break;
1829 case eEncodingIEEE754:
1830 response.PutCString("encoding:ieee754;");
1831 break;
1832 case eEncodingVector:
1833 response.PutCString("encoding:vector;");
1834 break;
1835 default:
1836 break;
1837 }
1838
1839 switch (reg_info->format) {
1840 case eFormatBinary:
1841 response.PutCString("format:binary;");
1842 break;
1843 case eFormatDecimal:
1844 response.PutCString("format:decimal;");
1845 break;
1846 case eFormatHex:
1847 response.PutCString("format:hex;");
1848 break;
1849 case eFormatFloat:
1850 response.PutCString("format:float;");
1851 break;
1852 case eFormatVectorOfSInt8:
1853 response.PutCString("format:vector-sint8;");
1854 break;
1855 case eFormatVectorOfUInt8:
1856 response.PutCString("format:vector-uint8;");
1857 break;
1858 case eFormatVectorOfSInt16:
1859 response.PutCString("format:vector-sint16;");
1860 break;
1861 case eFormatVectorOfUInt16:
1862 response.PutCString("format:vector-uint16;");
1863 break;
1864 case eFormatVectorOfSInt32:
1865 response.PutCString("format:vector-sint32;");
1866 break;
1867 case eFormatVectorOfUInt32:
1868 response.PutCString("format:vector-uint32;");
1869 break;
1870 case eFormatVectorOfFloat32:
1871 response.PutCString("format:vector-float32;");
1872 break;
Valentina Giusticda0ae42016-09-08 14:16:45 +00001873 case eFormatVectorOfUInt64:
1874 response.PutCString("format:vector-uint64;");
1875 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001876 case eFormatVectorOfUInt128:
1877 response.PutCString("format:vector-uint128;");
1878 break;
1879 default:
1880 break;
1881 };
1882
1883 const char *const register_set_name =
1884 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1885 if (register_set_name) {
1886 response.PutCString("set:");
1887 response.PutCString(register_set_name);
1888 response.PutChar(';');
1889 }
1890
1891 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1892 LLDB_INVALID_REGNUM)
1893 response.Printf("ehframe:%" PRIu32 ";",
1894 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1895
1896 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1897 response.Printf("dwarf:%" PRIu32 ";",
1898 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1899
1900 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1901 case LLDB_REGNUM_GENERIC_PC:
1902 response.PutCString("generic:pc;");
1903 break;
1904 case LLDB_REGNUM_GENERIC_SP:
1905 response.PutCString("generic:sp;");
1906 break;
1907 case LLDB_REGNUM_GENERIC_FP:
1908 response.PutCString("generic:fp;");
1909 break;
1910 case LLDB_REGNUM_GENERIC_RA:
1911 response.PutCString("generic:ra;");
1912 break;
1913 case LLDB_REGNUM_GENERIC_FLAGS:
1914 response.PutCString("generic:flags;");
1915 break;
1916 case LLDB_REGNUM_GENERIC_ARG1:
1917 response.PutCString("generic:arg1;");
1918 break;
1919 case LLDB_REGNUM_GENERIC_ARG2:
1920 response.PutCString("generic:arg2;");
1921 break;
1922 case LLDB_REGNUM_GENERIC_ARG3:
1923 response.PutCString("generic:arg3;");
1924 break;
1925 case LLDB_REGNUM_GENERIC_ARG4:
1926 response.PutCString("generic:arg4;");
1927 break;
1928 case LLDB_REGNUM_GENERIC_ARG5:
1929 response.PutCString("generic:arg5;");
1930 break;
1931 case LLDB_REGNUM_GENERIC_ARG6:
1932 response.PutCString("generic:arg6;");
1933 break;
1934 case LLDB_REGNUM_GENERIC_ARG7:
1935 response.PutCString("generic:arg7;");
1936 break;
1937 case LLDB_REGNUM_GENERIC_ARG8:
1938 response.PutCString("generic:arg8;");
1939 break;
1940 default:
1941 break;
1942 }
1943
1944 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1945 response.PutCString("container-regs:");
1946 int i = 0;
1947 for (const uint32_t *reg_num = reg_info->value_regs;
1948 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1949 if (i > 0)
1950 response.PutChar(',');
1951 response.Printf("%" PRIx32, *reg_num);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001952 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001953 response.PutChar(';');
1954 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001955
Kate Stoneb9c1b512016-09-06 20:57:50 +00001956 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1957 response.PutCString("invalidate-regs:");
1958 int i = 0;
1959 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1960 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1961 if (i > 0)
1962 response.PutChar(',');
1963 response.Printf("%" PRIx32, *reg_num);
1964 }
1965 response.PutChar(';');
1966 }
1967
1968 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1969 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1970 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1971 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1972 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1973 response.PutChar(';');
1974 }
1975 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001976}
1977
1978GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001979GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1980 StringExtractorGDBRemote &packet) {
1981 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1982
1983 // Fail if we don't have a current process.
1984 if (!m_debugged_process_sp ||
1985 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00001986 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001987 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1988 "returning OK",
1989 __FUNCTION__,
1990 m_debugged_process_sp ? "invalid process id"
1991 : "null m_debugged_process_sp");
1992 return SendOKResponse();
1993 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001994
Kate Stoneb9c1b512016-09-06 20:57:50 +00001995 StreamGDBRemote response;
1996 response.PutChar('m');
1997
1998 if (log)
1999 log->Printf(
2000 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
2001 __FUNCTION__);
2002
2003 NativeThreadProtocolSP thread_sp;
2004 uint32_t thread_index;
2005 for (thread_index = 0,
2006 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
2007 thread_sp; ++thread_index,
2008 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
2009 if (log)
2010 log->Printf(
2011 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
2012 "(%s, tid=0x%" PRIx64 ")",
2013 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
2014 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
2015 if (thread_index > 0)
2016 response.PutChar(',');
2017 response.Printf("%" PRIx64, thread_sp->GetID());
2018 }
2019
2020 if (log)
2021 log->Printf(
2022 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
2023 __FUNCTION__);
2024
2025 return SendPacketNoLock(response.GetString());
2026}
2027
2028GDBRemoteCommunication::PacketResult
2029GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
2030 StringExtractorGDBRemote &packet) {
2031 // FIXME for now we return the full thread list in the initial packet and
2032 // always do nothing here.
2033 return SendPacketNoLock("l");
2034}
2035
2036GDBRemoteCommunication::PacketResult
2037GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2038 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2039
2040 // Parse out the register number from the request.
2041 packet.SetFilePos(strlen("p"));
2042 const uint32_t reg_index =
2043 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2044 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2045 if (log)
2046 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2047 "parse register number from request \"%s\"",
2048 __FUNCTION__, packet.GetStringRef().c_str());
2049 return SendErrorResponse(0x15);
2050 }
2051
2052 // Get the thread to use.
2053 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2054 if (!thread_sp) {
2055 if (log)
2056 log->Printf(
2057 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
2058 __FUNCTION__);
2059 return SendErrorResponse(0x15);
2060 }
2061
2062 // Get the thread's register context.
2063 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2064 if (!reg_context_sp) {
2065 if (log)
2066 log->Printf(
2067 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2068 " failed, no register context available for the thread",
2069 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2070 return SendErrorResponse(0x15);
2071 }
2072
2073 // Return the end of registers response if we've iterated one past the end of
2074 // the register set.
2075 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2076 if (log)
2077 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2078 "register %" PRIu32 " beyond register count %" PRIu32,
2079 __FUNCTION__, reg_index,
2080 reg_context_sp->GetUserRegisterCount());
2081 return SendErrorResponse(0x15);
2082 }
2083
2084 const RegisterInfo *reg_info =
2085 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2086 if (!reg_info) {
2087 if (log)
2088 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2089 "register %" PRIu32 " returned NULL",
2090 __FUNCTION__, reg_index);
2091 return SendErrorResponse(0x15);
2092 }
2093
2094 // Build the reginfos response.
2095 StreamGDBRemote response;
2096
2097 // Retrieve the value
2098 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +00002099 Status error = reg_context_sp->ReadRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100 if (error.Fail()) {
2101 if (log)
2102 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
2103 "requested register %" PRIu32 " (%s) failed: %s",
2104 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2105 return SendErrorResponse(0x15);
2106 }
2107
2108 const uint8_t *const data =
2109 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
2110 if (!data) {
2111 if (log)
2112 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
2113 "bytes from requested register %" PRIu32,
2114 __FUNCTION__, reg_index);
2115 return SendErrorResponse(0x15);
2116 }
2117
2118 // FIXME flip as needed to get data in big/little endian format for this host.
2119 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2120 response.PutHex8(data[i]);
2121
2122 return SendPacketNoLock(response.GetString());
2123}
2124
2125GDBRemoteCommunication::PacketResult
2126GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2127 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2128
2129 // Ensure there is more content.
2130 if (packet.GetBytesLeft() < 1)
2131 return SendIllFormedResponse(packet, "Empty P packet");
2132
2133 // Parse out the register number from the request.
2134 packet.SetFilePos(strlen("P"));
2135 const uint32_t reg_index =
2136 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2137 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2138 if (log)
2139 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2140 "parse register number from request \"%s\"",
2141 __FUNCTION__, packet.GetStringRef().c_str());
2142 return SendErrorResponse(0x29);
2143 }
2144
2145 // Note debugserver would send an E30 here.
2146 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2147 return SendIllFormedResponse(
2148 packet, "P packet missing '=' char after register number");
2149
2150 // Get process architecture.
2151 ArchSpec process_arch;
2152 if (!m_debugged_process_sp ||
2153 !m_debugged_process_sp->GetArchitecture(process_arch)) {
2154 if (log)
2155 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
2156 "inferior architecture",
2157 __FUNCTION__);
2158 return SendErrorResponse(0x49);
2159 }
2160
2161 // Parse out the value.
2162 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2163 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2164
2165 // Get the thread to use.
2166 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2167 if (!thread_sp) {
2168 if (log)
2169 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2170 "available (thread index 0)",
2171 __FUNCTION__);
2172 return SendErrorResponse(0x28);
2173 }
2174
2175 // Get the thread's register context.
2176 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2177 if (!reg_context_sp) {
2178 if (log)
2179 log->Printf(
2180 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2181 " failed, no register context available for the thread",
2182 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2183 return SendErrorResponse(0x15);
2184 }
2185
2186 const RegisterInfo *reg_info =
2187 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2188 if (!reg_info) {
2189 if (log)
2190 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2191 "register %" PRIu32 " returned NULL",
2192 __FUNCTION__, reg_index);
2193 return SendErrorResponse(0x48);
2194 }
2195
2196 // Return the end of registers response if we've iterated one past the end of
2197 // the register set.
2198 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2199 if (log)
2200 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2201 "register %" PRIu32 " beyond register count %" PRIu32,
2202 __FUNCTION__, reg_index,
2203 reg_context_sp->GetUserRegisterCount());
2204 return SendErrorResponse(0x47);
2205 }
2206
2207 // The dwarf expression are evaluate on host site
2208 // which may cause register size to change
2209 // Hence the reg_size may not be same as reg_info->bytes_size
2210 if ((reg_size != reg_info->byte_size) &&
2211 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2212 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2213 }
2214
2215 // Build the reginfos response.
2216 StreamGDBRemote response;
2217
2218 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
Zachary Turner97206d52017-05-12 04:51:55 +00002219 Status error = reg_context_sp->WriteRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 if (error.Fail()) {
2221 if (log)
2222 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2223 "requested register %" PRIu32 " (%s) failed: %s",
2224 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2225 return SendErrorResponse(0x32);
2226 }
2227
2228 return SendOKResponse();
2229}
2230
2231GDBRemoteCommunication::PacketResult
2232GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2233 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2234
2235 // Fail if we don't have a current process.
2236 if (!m_debugged_process_sp ||
2237 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2238 if (log)
2239 log->Printf(
2240 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2241 __FUNCTION__);
2242 return SendErrorResponse(0x15);
2243 }
2244
2245 // Parse out which variant of $H is requested.
2246 packet.SetFilePos(strlen("H"));
2247 if (packet.GetBytesLeft() < 1) {
2248 if (log)
2249 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2250 "missing {g,c} variant",
2251 __FUNCTION__);
2252 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2253 }
2254
2255 const char h_variant = packet.GetChar();
2256 switch (h_variant) {
2257 case 'g':
2258 break;
2259
2260 case 'c':
2261 break;
2262
2263 default:
2264 if (log)
2265 log->Printf(
2266 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2267 __FUNCTION__, h_variant);
2268 return SendIllFormedResponse(packet,
2269 "H variant unsupported, should be c or g");
2270 }
2271
2272 // Parse out the thread number.
2273 // FIXME return a parse success/fail value. All values are valid here.
2274 const lldb::tid_t tid =
2275 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2276
2277 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2278 // (any thread).
2279 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2280 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2281 if (!thread_sp) {
2282 if (log)
2283 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2284 " not found",
2285 __FUNCTION__, tid);
2286 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002287 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002289
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290 // Now switch the given thread type.
2291 switch (h_variant) {
2292 case 'g':
2293 SetCurrentThreadID(tid);
2294 break;
2295
2296 case 'c':
2297 SetContinueThreadID(tid);
2298 break;
2299
2300 default:
2301 assert(false && "unsupported $H variant - shouldn't get here");
2302 return SendIllFormedResponse(packet,
2303 "H variant unsupported, should be c or g");
2304 }
2305
2306 return SendOKResponse();
2307}
2308
2309GDBRemoteCommunication::PacketResult
2310GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2311 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2312
2313 // Fail if we don't have a current process.
2314 if (!m_debugged_process_sp ||
2315 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2316 if (log)
2317 log->Printf(
2318 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2319 __FUNCTION__);
2320 return SendErrorResponse(0x15);
2321 }
2322
2323 packet.SetFilePos(::strlen("I"));
2324 uint8_t tmp[4096];
2325 for (;;) {
2326 size_t read = packet.GetHexBytesAvail(tmp);
2327 if (read == 0) {
2328 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002329 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002330 // write directly to stdin *this might block if stdin buffer is full*
2331 // TODO: enqueue this block in circular buffer and send window size to
2332 // remote host
2333 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00002334 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002335 m_stdio_communication.Write(tmp, read, status, &error);
2336 if (error.Fail()) {
2337 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002338 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002339 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002340
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002342}
2343
2344GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002345GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2346 StringExtractorGDBRemote &packet) {
2347 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2348
2349 // Fail if we don't have a current process.
2350 if (!m_debugged_process_sp ||
2351 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002352 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002353 log->Printf(
2354 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2355 __FUNCTION__);
2356 return SendErrorResponse(0x15);
2357 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002358
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359 // Interrupt the process.
Zachary Turner97206d52017-05-12 04:51:55 +00002360 Status error = m_debugged_process_sp->Interrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361 if (error.Fail()) {
2362 if (log) {
2363 log->Printf(
2364 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2365 ": %s",
2366 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002367 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002368 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2369 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002370
Kate Stoneb9c1b512016-09-06 20:57:50 +00002371 if (log)
2372 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2373 __FUNCTION__, m_debugged_process_sp->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002374
Kate Stoneb9c1b512016-09-06 20:57:50 +00002375 // No response required from stop all.
2376 return PacketResult::Success;
2377}
Tamas Berghammere13c2732015-02-11 10:29:30 +00002378
Kate Stoneb9c1b512016-09-06 20:57:50 +00002379GDBRemoteCommunication::PacketResult
2380GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2381 StringExtractorGDBRemote &packet) {
2382 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002383
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384 if (!m_debugged_process_sp ||
2385 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002386 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387 log->Printf(
2388 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2389 __FUNCTION__);
2390 return SendErrorResponse(0x15);
2391 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002392
Kate Stoneb9c1b512016-09-06 20:57:50 +00002393 // Parse out the memory address.
2394 packet.SetFilePos(strlen("m"));
2395 if (packet.GetBytesLeft() < 1)
2396 return SendIllFormedResponse(packet, "Too short m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002397
Kate Stoneb9c1b512016-09-06 20:57:50 +00002398 // Read the address. Punting on validation.
2399 // FIXME replace with Hex U64 read with no default value that fails on failed
2400 // read.
2401 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002402
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 // Validate comma.
2404 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2405 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002406
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 // Get # bytes to read.
2408 if (packet.GetBytesLeft() < 1)
2409 return SendIllFormedResponse(packet, "Length missing in m packet");
2410
2411 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2412 if (byte_count == 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002413 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002414 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2415 "zero-length packet",
2416 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002417 return SendOKResponse();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002419
Kate Stoneb9c1b512016-09-06 20:57:50 +00002420 // Allocate the response buffer.
2421 std::string buf(byte_count, '\0');
2422 if (buf.empty())
2423 return SendErrorResponse(0x78);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002424
Kate Stoneb9c1b512016-09-06 20:57:50 +00002425 // Retrieve the process memory.
2426 size_t bytes_read = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002427 Status error = m_debugged_process_sp->ReadMemoryWithoutTrap(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002428 read_addr, &buf[0], byte_count, bytes_read);
2429 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002430 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002431 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2432 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2433 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2434 error.AsCString());
2435 return SendErrorResponse(0x08);
2436 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002437
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438 if (bytes_read == 0) {
2439 if (log)
2440 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2441 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2442 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2443 byte_count);
2444 return SendErrorResponse(0x08);
2445 }
2446
2447 StreamGDBRemote response;
2448 packet.SetFilePos(0);
2449 char kind = packet.GetChar('?');
2450 if (kind == 'x')
2451 response.PutEscapedBytes(buf.data(), byte_count);
2452 else {
2453 assert(kind == 'm');
2454 for (size_t i = 0; i < bytes_read; ++i)
2455 response.PutHex8(buf[i]);
2456 }
2457
2458 return SendPacketNoLock(response.GetString());
2459}
2460
2461GDBRemoteCommunication::PacketResult
2462GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2463 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2464
2465 if (!m_debugged_process_sp ||
2466 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2467 if (log)
2468 log->Printf(
2469 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2470 __FUNCTION__);
2471 return SendErrorResponse(0x15);
2472 }
2473
2474 // Parse out the memory address.
2475 packet.SetFilePos(strlen("M"));
2476 if (packet.GetBytesLeft() < 1)
2477 return SendIllFormedResponse(packet, "Too short M packet");
2478
2479 // Read the address. Punting on validation.
2480 // FIXME replace with Hex U64 read with no default value that fails on failed
2481 // read.
2482 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2483
2484 // Validate comma.
2485 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2486 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2487
2488 // Get # bytes to read.
2489 if (packet.GetBytesLeft() < 1)
2490 return SendIllFormedResponse(packet, "Length missing in M packet");
2491
2492 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2493 if (byte_count == 0) {
2494 if (log)
2495 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2496 "zero-length packet",
2497 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002498 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002499 }
2500
2501 // Validate colon.
2502 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2503 return SendIllFormedResponse(
2504 packet, "Comma sep missing in M packet after byte length");
2505
2506 // Allocate the conversion buffer.
2507 std::vector<uint8_t> buf(byte_count, 0);
2508 if (buf.empty())
2509 return SendErrorResponse(0x78);
2510
2511 // Convert the hex memory write contents to bytes.
2512 StreamGDBRemote response;
2513 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2514 if (convert_count != byte_count) {
2515 if (log)
2516 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2517 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2518 " bytes, but only found %" PRIu64 " to convert.",
2519 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2520 byte_count, convert_count);
2521 return SendIllFormedResponse(packet, "M content byte length specified did "
2522 "not match hex-encoded content "
2523 "length");
2524 }
2525
2526 // Write the process memory.
2527 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002528 Status error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2529 byte_count, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530 if (error.Fail()) {
2531 if (log)
2532 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2533 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2534 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2535 error.AsCString());
2536 return SendErrorResponse(0x09);
2537 }
2538
2539 if (bytes_written == 0) {
2540 if (log)
2541 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2542 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2543 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2544 byte_count);
2545 return SendErrorResponse(0x09);
2546 }
2547
2548 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002549}
2550
2551GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2553 StringExtractorGDBRemote &packet) {
2554 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002555
Kate Stoneb9c1b512016-09-06 20:57:50 +00002556 // Currently only the NativeProcessProtocol knows if it can handle a
2557 // qMemoryRegionInfoSupported
2558 // request, but we're not guaranteed to be attached to a process. For now
2559 // we'll assume the
2560 // client only asks this when a process is being debugged.
Tamas Berghammere13c2732015-02-11 10:29:30 +00002561
Kate Stoneb9c1b512016-09-06 20:57:50 +00002562 // Ensure we have a process running; otherwise, we can't figure this out
2563 // since we won't have a NativeProcessProtocol.
2564 if (!m_debugged_process_sp ||
2565 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2566 if (log)
2567 log->Printf(
2568 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2569 __FUNCTION__);
2570 return SendErrorResponse(0x15);
2571 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002572
Kate Stoneb9c1b512016-09-06 20:57:50 +00002573 // Test if we can get any region back when asking for the region around NULL.
2574 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002575 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002576 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2577 if (error.Fail()) {
2578 // We don't support memory region info collection for this
2579 // NativeProcessProtocol.
2580 return SendUnimplementedResponse("");
2581 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002582
Kate Stoneb9c1b512016-09-06 20:57:50 +00002583 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002584}
2585
2586GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002587GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2588 StringExtractorGDBRemote &packet) {
2589 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002590
Kate Stoneb9c1b512016-09-06 20:57:50 +00002591 // Ensure we have a process.
2592 if (!m_debugged_process_sp ||
2593 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2594 if (log)
2595 log->Printf(
2596 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2597 __FUNCTION__);
2598 return SendErrorResponse(0x15);
2599 }
2600
2601 // Parse out the memory address.
2602 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2603 if (packet.GetBytesLeft() < 1)
2604 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2605
2606 // Read the address. Punting on validation.
2607 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2608
2609 StreamGDBRemote response;
2610
2611 // Get the memory region info for the target address.
2612 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002613 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002614 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2615 if (error.Fail()) {
2616 // Return the error message.
2617
2618 response.PutCString("error:");
2619 response.PutCStringAsRawHex8(error.AsCString());
2620 response.PutChar(';');
2621 } else {
2622 // Range start and size.
2623 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2624 region_info.GetRange().GetRangeBase(),
2625 region_info.GetRange().GetByteSize());
2626
2627 // Permissions.
2628 if (region_info.GetReadable() || region_info.GetWritable() ||
2629 region_info.GetExecutable()) {
2630 // Write permissions info.
2631 response.PutCString("permissions:");
2632
2633 if (region_info.GetReadable())
2634 response.PutChar('r');
2635 if (region_info.GetWritable())
2636 response.PutChar('w');
2637 if (region_info.GetExecutable())
2638 response.PutChar('x');
2639
2640 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002641 }
2642
Kate Stoneb9c1b512016-09-06 20:57:50 +00002643 // Name
2644 ConstString name = region_info.GetName();
2645 if (name) {
2646 response.PutCString("name:");
2647 response.PutCStringAsRawHex8(name.AsCString());
2648 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002649 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002650 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002651
Kate Stoneb9c1b512016-09-06 20:57:50 +00002652 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002653}
2654
2655GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002656GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2657 // Ensure we have a process.
2658 if (!m_debugged_process_sp ||
2659 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2660 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2661 if (log)
2662 log->Printf(
2663 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2664 __FUNCTION__);
2665 return SendErrorResponse(0x15);
2666 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002667
Kate Stoneb9c1b512016-09-06 20:57:50 +00002668 // Parse out software or hardware breakpoint or watchpoint requested.
2669 packet.SetFilePos(strlen("Z"));
2670 if (packet.GetBytesLeft() < 1)
2671 return SendIllFormedResponse(
2672 packet, "Too short Z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002673
Kate Stoneb9c1b512016-09-06 20:57:50 +00002674 bool want_breakpoint = true;
2675 bool want_hardware = false;
2676 uint32_t watch_flags = 0;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002677
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 const GDBStoppointType stoppoint_type =
2679 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2680 switch (stoppoint_type) {
2681 case eBreakpointSoftware:
2682 want_hardware = false;
2683 want_breakpoint = true;
2684 break;
2685 case eBreakpointHardware:
2686 want_hardware = true;
2687 want_breakpoint = true;
2688 break;
2689 case eWatchpointWrite:
2690 watch_flags = 1;
2691 want_hardware = true;
2692 want_breakpoint = false;
2693 break;
2694 case eWatchpointRead:
2695 watch_flags = 2;
2696 want_hardware = true;
2697 want_breakpoint = false;
2698 break;
2699 case eWatchpointReadWrite:
2700 watch_flags = 3;
2701 want_hardware = true;
2702 want_breakpoint = false;
2703 break;
2704 case eStoppointInvalid:
2705 return SendIllFormedResponse(
2706 packet, "Z packet had invalid software/hardware specifier");
2707 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002708
Kate Stoneb9c1b512016-09-06 20:57:50 +00002709 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2710 return SendIllFormedResponse(
2711 packet, "Malformed Z packet, expecting comma after stoppoint type");
2712
2713 // Parse out the stoppoint address.
2714 if (packet.GetBytesLeft() < 1)
2715 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2716 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2717
2718 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2719 return SendIllFormedResponse(
2720 packet, "Malformed Z packet, expecting comma after address");
2721
2722 // Parse out the stoppoint size (i.e. size hint for opcode size).
2723 const uint32_t size =
2724 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2725 if (size == std::numeric_limits<uint32_t>::max())
2726 return SendIllFormedResponse(
2727 packet, "Malformed Z packet, failed to parse size argument");
2728
2729 if (want_breakpoint) {
2730 // Try to set the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002731 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2733 if (error.Success())
2734 return SendOKResponse();
2735 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2736 if (log)
2737 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2738 " failed to set breakpoint: %s",
2739 __FUNCTION__, m_debugged_process_sp->GetID(),
2740 error.AsCString());
2741 return SendErrorResponse(0x09);
2742 } else {
2743 // Try to set the watchpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002744 const Status error = m_debugged_process_sp->SetWatchpoint(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745 addr, size, watch_flags, want_hardware);
2746 if (error.Success())
2747 return SendOKResponse();
2748 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2749 if (log)
2750 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2751 " failed to set watchpoint: %s",
2752 __FUNCTION__, m_debugged_process_sp->GetID(),
2753 error.AsCString());
2754 return SendErrorResponse(0x09);
2755 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002756}
2757
2758GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2760 // Ensure we have a process.
2761 if (!m_debugged_process_sp ||
2762 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2763 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2764 if (log)
2765 log->Printf(
2766 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2767 __FUNCTION__);
2768 return SendErrorResponse(0x15);
2769 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002770
Kate Stoneb9c1b512016-09-06 20:57:50 +00002771 // Parse out software or hardware breakpoint or watchpoint requested.
2772 packet.SetFilePos(strlen("z"));
2773 if (packet.GetBytesLeft() < 1)
2774 return SendIllFormedResponse(
2775 packet, "Too short z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002776
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 bool want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002778 bool want_hardware = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002779
Kate Stoneb9c1b512016-09-06 20:57:50 +00002780 const GDBStoppointType stoppoint_type =
2781 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2782 switch (stoppoint_type) {
2783 case eBreakpointHardware:
2784 want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002785 want_hardware = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002786 break;
2787 case eBreakpointSoftware:
2788 want_breakpoint = true;
2789 break;
2790 case eWatchpointWrite:
2791 want_breakpoint = false;
2792 break;
2793 case eWatchpointRead:
2794 want_breakpoint = false;
2795 break;
2796 case eWatchpointReadWrite:
2797 want_breakpoint = false;
2798 break;
2799 default:
2800 return SendIllFormedResponse(
2801 packet, "z packet had invalid software/hardware specifier");
2802 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002803
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2805 return SendIllFormedResponse(
2806 packet, "Malformed z packet, expecting comma after stoppoint type");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002807
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808 // Parse out the stoppoint address.
2809 if (packet.GetBytesLeft() < 1)
2810 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2811 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002812
Kate Stoneb9c1b512016-09-06 20:57:50 +00002813 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2814 return SendIllFormedResponse(
2815 packet, "Malformed z packet, expecting comma after address");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002816
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 /*
2818 // Parse out the stoppoint size (i.e. size hint for opcode size).
2819 const uint32_t size = packet.GetHexMaxU32 (false,
2820 std::numeric_limits<uint32_t>::max ());
2821 if (size == std::numeric_limits<uint32_t>::max ())
2822 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2823 size argument");
2824 */
Tamas Berghammere13c2732015-02-11 10:29:30 +00002825
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 if (want_breakpoint) {
2827 // Try to clear the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002828 const Status error =
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002829 m_debugged_process_sp->RemoveBreakpoint(addr, want_hardware);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 if (error.Success())
2831 return SendOKResponse();
2832 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2833 if (log)
2834 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2835 " failed to remove breakpoint: %s",
2836 __FUNCTION__, m_debugged_process_sp->GetID(),
2837 error.AsCString());
2838 return SendErrorResponse(0x09);
2839 } else {
2840 // Try to clear the watchpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002841 const Status error = m_debugged_process_sp->RemoveWatchpoint(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002842 if (error.Success())
2843 return SendOKResponse();
2844 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2845 if (log)
2846 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2847 " failed to remove watchpoint: %s",
2848 __FUNCTION__, m_debugged_process_sp->GetID(),
2849 error.AsCString());
2850 return SendErrorResponse(0x09);
2851 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002852}
2853
2854GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2856 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002857
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858 // Ensure we have a process.
2859 if (!m_debugged_process_sp ||
2860 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2861 if (log)
2862 log->Printf(
2863 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2864 __FUNCTION__);
2865 return SendErrorResponse(0x32);
2866 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002867
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868 // We first try to use a continue thread id. If any one or any all set, use
2869 // the current thread.
2870 // Bail out if we don't have a thread id.
2871 lldb::tid_t tid = GetContinueThreadID();
2872 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2873 tid = GetCurrentThreadID();
2874 if (tid == LLDB_INVALID_THREAD_ID)
2875 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002876
Kate Stoneb9c1b512016-09-06 20:57:50 +00002877 // Double check that we have such a thread.
2878 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2879 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2880 if (!thread_sp || thread_sp->GetID() != tid)
2881 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002882
Kate Stoneb9c1b512016-09-06 20:57:50 +00002883 // Create the step action for the given thread.
2884 ResumeAction action = {tid, eStateStepping, 0};
Tamas Berghammere13c2732015-02-11 10:29:30 +00002885
Kate Stoneb9c1b512016-09-06 20:57:50 +00002886 // Setup the actions list.
2887 ResumeActionList actions;
2888 actions.Append(action);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002889
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 // All other threads stop while we're single stepping a thread.
2891 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00002892 Status error = m_debugged_process_sp->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002893 if (error.Fail()) {
2894 if (log)
2895 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2896 " tid %" PRIu64 " Resume() failed with error: %s",
2897 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2898 error.AsCString());
2899 return SendErrorResponse(0x49);
2900 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002901
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 // No response here - the stop or exit will come from the resulting action.
2903 return PacketResult::Success;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002904}
2905
2906GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002907GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2908 StringExtractorGDBRemote &packet) {
2909// *BSD impls should be able to do this too.
Kamil Rytarowskic93408a2017-03-21 17:27:59 +00002910#if defined(__linux__) || defined(__NetBSD__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002911 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002912
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 // Parse out the offset.
2914 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2915 if (packet.GetBytesLeft() < 1)
2916 return SendIllFormedResponse(packet,
2917 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002918
Kate Stoneb9c1b512016-09-06 20:57:50 +00002919 const uint64_t auxv_offset =
2920 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2921 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2922 return SendIllFormedResponse(packet,
2923 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002924
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 // Parse out comma.
2926 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2927 return SendIllFormedResponse(
2928 packet, "qXfer:auxv:read:: packet missing comma after offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002929
Kate Stoneb9c1b512016-09-06 20:57:50 +00002930 // Parse out the length.
2931 const uint64_t auxv_length =
2932 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2933 if (auxv_length == std::numeric_limits<uint64_t>::max())
2934 return SendIllFormedResponse(packet,
2935 "qXfer:auxv:read:: packet missing length");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002936
Kate Stoneb9c1b512016-09-06 20:57:50 +00002937 // Grab the auxv data if we need it.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002938 if (!m_active_auxv_buffer_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939 // Make sure we have a valid process.
2940 if (!m_debugged_process_sp ||
2941 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2942 if (log)
2943 log->Printf(
2944 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2945 __FUNCTION__);
2946 return SendErrorResponse(0x10);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002947 }
2948
Kate Stoneb9c1b512016-09-06 20:57:50 +00002949 // Grab the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002950 auto buffer_or_error = m_debugged_process_sp->GetAuxvData();
2951 if (!buffer_or_error) {
2952 std::error_code ec = buffer_or_error.getError();
2953 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2954 return SendErrorResponse(ec.value());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002955 }
Pavel Labathb7f0f452017-03-17 11:08:40 +00002956 m_active_auxv_buffer_up = std::move(*buffer_or_error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002958
Kate Stoneb9c1b512016-09-06 20:57:50 +00002959 StreamGDBRemote response;
2960 bool done_with_buffer = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002961
Pavel Labathb7f0f452017-03-17 11:08:40 +00002962 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2963 if (auxv_offset >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 // We have nothing left to send. Mark the buffer as complete.
2965 response.PutChar('l');
2966 done_with_buffer = true;
2967 } else {
2968 // Figure out how many bytes are available starting at the given offset.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002969 buffer = buffer.drop_front(auxv_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970
2971 // Mark the response type according to whether we're reading the remainder
2972 // of the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002973 if (auxv_length >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002974 // There will be nothing left to read after this
2975 response.PutChar('l');
2976 done_with_buffer = true;
2977 } else {
2978 // There will still be bytes to read after this request.
2979 response.PutChar('m');
Pavel Labathb7f0f452017-03-17 11:08:40 +00002980 buffer = buffer.take_front(auxv_length);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002981 }
2982
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983 // Now write the data in encoded binary form.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002984 response.PutEscapedBytes(buffer.data(), buffer.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002986
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 if (done_with_buffer)
Pavel Labathb7f0f452017-03-17 11:08:40 +00002988 m_active_auxv_buffer_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002989
2990 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002991#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 return SendUnimplementedResponse("not implemented on this platform");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002993#endif
2994}
2995
2996GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002997GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2998 StringExtractorGDBRemote &packet) {
2999 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003000
Kate Stoneb9c1b512016-09-06 20:57:50 +00003001 // Move past packet name.
3002 packet.SetFilePos(strlen("QSaveRegisterState"));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003003
Kate Stoneb9c1b512016-09-06 20:57:50 +00003004 // Get the thread to use.
3005 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3006 if (!thread_sp) {
3007 if (m_thread_suffix_supported)
3008 return SendIllFormedResponse(
3009 packet, "No thread specified in QSaveRegisterState packet");
3010 else
3011 return SendIllFormedResponse(packet,
3012 "No thread was is set with the Hg packet");
3013 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003014
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015 // Grab the register context for the thread.
3016 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3017 if (!reg_context_sp) {
3018 if (log)
3019 log->Printf(
3020 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3021 " failed, no register context available for the thread",
3022 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3023 return SendErrorResponse(0x15);
3024 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003025
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 // Save registers to a buffer.
3027 DataBufferSP register_data_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003028 Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 if (error.Fail()) {
3030 if (log)
3031 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3032 " failed to save all register values: %s",
3033 __FUNCTION__, m_debugged_process_sp->GetID(),
3034 error.AsCString());
3035 return SendErrorResponse(0x75);
3036 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003037
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038 // Allocate a new save id.
3039 const uint32_t save_id = GetNextSavedRegistersID();
3040 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3041 "GetNextRegisterSaveID() returned an existing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003042
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043 // Save the register data buffer under the save id.
3044 {
3045 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3046 m_saved_registers_map[save_id] = register_data_sp;
3047 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003048
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049 // Write the response.
3050 StreamGDBRemote response;
3051 response.Printf("%" PRIu32, save_id);
3052 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003053}
3054
3055GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003056GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3057 StringExtractorGDBRemote &packet) {
3058 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003059
Kate Stoneb9c1b512016-09-06 20:57:50 +00003060 // Parse out save id.
3061 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3062 if (packet.GetBytesLeft() < 1)
3063 return SendIllFormedResponse(
3064 packet, "QRestoreRegisterState packet missing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003065
Kate Stoneb9c1b512016-09-06 20:57:50 +00003066 const uint32_t save_id = packet.GetU32(0);
3067 if (save_id == 0) {
3068 if (log)
3069 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
3070 "packet has malformed save id, expecting decimal uint32_t",
3071 __FUNCTION__);
3072 return SendErrorResponse(0x76);
3073 }
3074
3075 // Get the thread to use.
3076 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3077 if (!thread_sp) {
3078 if (m_thread_suffix_supported)
3079 return SendIllFormedResponse(
3080 packet, "No thread specified in QRestoreRegisterState packet");
3081 else
3082 return SendIllFormedResponse(packet,
3083 "No thread was is set with the Hg packet");
3084 }
3085
3086 // Grab the register context for the thread.
3087 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3088 if (!reg_context_sp) {
3089 if (log)
3090 log->Printf(
3091 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3092 " failed, no register context available for the thread",
3093 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3094 return SendErrorResponse(0x15);
3095 }
3096
3097 // Retrieve register state buffer, then remove from the list.
3098 DataBufferSP register_data_sp;
3099 {
3100 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3101
3102 // Find the register set buffer for the given save id.
3103 auto it = m_saved_registers_map.find(save_id);
3104 if (it == m_saved_registers_map.end()) {
3105 if (log)
3106 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3107 " does not have a register set save buffer for id %" PRIu32,
3108 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
3109 return SendErrorResponse(0x77);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003110 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003111 register_data_sp = it->second;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003112
Kate Stoneb9c1b512016-09-06 20:57:50 +00003113 // Remove it from the map.
3114 m_saved_registers_map.erase(it);
3115 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003116
Zachary Turner97206d52017-05-12 04:51:55 +00003117 Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003118 if (error.Fail()) {
3119 if (log)
3120 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3121 " failed to restore all register values: %s",
3122 __FUNCTION__, m_debugged_process_sp->GetID(),
3123 error.AsCString());
3124 return SendErrorResponse(0x77);
3125 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003126
Kate Stoneb9c1b512016-09-06 20:57:50 +00003127 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003128}
3129
3130GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3132 StringExtractorGDBRemote &packet) {
3133 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003134
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135 // Consume the ';' after vAttach.
3136 packet.SetFilePos(strlen("vAttach"));
3137 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3138 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003139
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140 // Grab the PID to which we will attach (assume hex encoding).
3141 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3142 if (pid == LLDB_INVALID_PROCESS_ID)
3143 return SendIllFormedResponse(packet,
3144 "vAttach failed to parse the process id");
3145
3146 // Attempt to attach.
3147 if (log)
3148 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3149 "pid %" PRIu64,
3150 __FUNCTION__, pid);
3151
Zachary Turner97206d52017-05-12 04:51:55 +00003152 Status error = AttachToProcess(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003153
3154 if (error.Fail()) {
3155 if (log)
3156 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3157 "pid %" PRIu64 ": %s\n",
3158 __FUNCTION__, pid, error.AsCString());
3159 return SendErrorResponse(0x01);
3160 }
3161
3162 // Notify we attached by sending a stop packet.
3163 return SendStopReasonForState(m_debugged_process_sp->GetState());
3164}
3165
3166GDBRemoteCommunication::PacketResult
3167GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3168 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3169
3170 StopSTDIOForwarding();
3171
3172 // Fail if we don't have a current process.
3173 if (!m_debugged_process_sp ||
3174 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
3175 if (log)
3176 log->Printf(
3177 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3178 __FUNCTION__);
3179 return SendErrorResponse(0x15);
3180 }
3181
3182 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3183
3184 // Consume the ';' after D.
3185 packet.SetFilePos(1);
3186 if (packet.GetBytesLeft()) {
3187 if (packet.GetChar() != ';')
3188 return SendIllFormedResponse(packet, "D missing expected ';'");
3189
3190 // Grab the PID from which we will detach (assume hex encoding).
3191 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003192 if (pid == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003193 return SendIllFormedResponse(packet, "D failed to parse the process id");
3194 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003195
Kate Stoneb9c1b512016-09-06 20:57:50 +00003196 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
3197 return SendIllFormedResponse(packet, "Invalid pid");
3198 }
3199
Zachary Turner97206d52017-05-12 04:51:55 +00003200 const Status error = m_debugged_process_sp->Detach();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003201 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003202 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003203 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3204 "pid %" PRIu64 ": %s\n",
3205 __FUNCTION__, m_debugged_process_sp->GetID(),
3206 error.AsCString());
3207 return SendErrorResponse(0x01);
3208 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003209
Kate Stoneb9c1b512016-09-06 20:57:50 +00003210 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003211}
3212
3213GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003214GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3215 StringExtractorGDBRemote &packet) {
3216 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003217
Kate Stoneb9c1b512016-09-06 20:57:50 +00003218 packet.SetFilePos(strlen("qThreadStopInfo"));
3219 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3220 if (tid == LLDB_INVALID_THREAD_ID) {
Pavel Labath4a4bb122015-07-16 14:14:35 +00003221 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003222 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3223 "parse thread id from request \"%s\"",
3224 __FUNCTION__, packet.GetStringRef().c_str());
3225 return SendErrorResponse(0x15);
3226 }
3227 return SendStopReplyPacketForThread(tid);
3228}
3229
3230GDBRemoteCommunication::PacketResult
3231GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3232 StringExtractorGDBRemote &) {
3233 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3234
3235 // Ensure we have a debugged process.
3236 if (!m_debugged_process_sp ||
3237 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
3238 return SendErrorResponse(50);
3239
3240 if (log)
3241 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
3242 "%" PRIu64,
Pavel Labath4a4bb122015-07-16 14:14:35 +00003243 __FUNCTION__, m_debugged_process_sp->GetID());
3244
Kate Stoneb9c1b512016-09-06 20:57:50 +00003245 StreamString response;
3246 const bool threads_with_valid_stop_info_only = false;
3247 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3248 *m_debugged_process_sp, threads_with_valid_stop_info_only);
3249 if (!threads_array_sp) {
3250 if (log)
3251 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
3252 "packet for pid %" PRIu64,
3253 __FUNCTION__, m_debugged_process_sp->GetID());
3254 return SendErrorResponse(52);
3255 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00003256
Kate Stoneb9c1b512016-09-06 20:57:50 +00003257 threads_array_sp->Write(response);
3258 StreamGDBRemote escaped_response;
3259 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3260 return SendPacketNoLock(escaped_response.GetString());
Pavel Labath4a4bb122015-07-16 14:14:35 +00003261}
3262
3263GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003264GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3265 StringExtractorGDBRemote &packet) {
3266 // Fail if we don't have a current process.
3267 if (!m_debugged_process_sp ||
3268 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3269 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003270
Kate Stoneb9c1b512016-09-06 20:57:50 +00003271 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3272 if (packet.GetBytesLeft() == 0)
3273 return SendOKResponse();
3274 if (packet.GetChar() != ':')
3275 return SendErrorResponse(67);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003276
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003277 auto hw_debug_cap = m_debugged_process_sp->GetHardwareDebugSupportInfo();
3278
Kate Stoneb9c1b512016-09-06 20:57:50 +00003279 StreamGDBRemote response;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003280 if (hw_debug_cap == llvm::None)
3281 response.Printf("num:0;");
3282 else
3283 response.Printf("num:%d;", hw_debug_cap->second);
3284
Kate Stoneb9c1b512016-09-06 20:57:50 +00003285 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003286}
3287
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003288GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003289GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3290 StringExtractorGDBRemote &packet) {
3291 // Fail if we don't have a current process.
3292 if (!m_debugged_process_sp ||
3293 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3294 return SendErrorResponse(67);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003295
Kate Stoneb9c1b512016-09-06 20:57:50 +00003296 packet.SetFilePos(strlen("qFileLoadAddress:"));
3297 if (packet.GetBytesLeft() == 0)
3298 return SendErrorResponse(68);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003299
Kate Stoneb9c1b512016-09-06 20:57:50 +00003300 std::string file_name;
3301 packet.GetHexByteString(file_name);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003302
Kate Stoneb9c1b512016-09-06 20:57:50 +00003303 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00003304 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003305 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3306 if (error.Fail())
3307 return SendErrorResponse(69);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003308
Kate Stoneb9c1b512016-09-06 20:57:50 +00003309 if (file_load_address == LLDB_INVALID_ADDRESS)
3310 return SendErrorResponse(1); // File not loaded
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003311
Kate Stoneb9c1b512016-09-06 20:57:50 +00003312 StreamGDBRemote response;
3313 response.PutHex64(file_load_address);
3314 return SendPacketNoLock(response.GetString());
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003315}
3316
Pavel Labath4a705e72017-02-24 09:29:14 +00003317GDBRemoteCommunication::PacketResult
3318GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3319 StringExtractorGDBRemote &packet) {
3320 std::vector<int> signals;
3321 packet.SetFilePos(strlen("QPassSignals:"));
3322
3323 // Read sequence of hex signal numbers divided by a semicolon and
3324 // optionally spaces.
3325 while (packet.GetBytesLeft() > 0) {
3326 int signal = packet.GetS32(-1, 16);
3327 if (signal < 0)
3328 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3329 signals.push_back(signal);
3330
3331 packet.SkipSpaces();
3332 char separator = packet.GetChar();
3333 if (separator == '\0')
3334 break; // End of string
3335 if (separator != ';')
3336 return SendIllFormedResponse(packet, "Invalid separator,"
3337 " expected semicolon.");
3338 }
3339
3340 // Fail if we don't have a current process.
3341 if (!m_debugged_process_sp)
3342 return SendErrorResponse(68);
3343
Zachary Turner97206d52017-05-12 04:51:55 +00003344 Status error = m_debugged_process_sp->IgnoreSignals(signals);
Pavel Labath4a705e72017-02-24 09:29:14 +00003345 if (error.Fail())
3346 return SendErrorResponse(69);
3347
3348 return SendOKResponse();
3349}
3350
Kate Stoneb9c1b512016-09-06 20:57:50 +00003351void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3352 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003353
Kate Stoneb9c1b512016-09-06 20:57:50 +00003354 // Tell the stdio connection to shut down.
3355 if (m_stdio_communication.IsConnected()) {
3356 auto connection = m_stdio_communication.GetConnection();
3357 if (connection) {
Zachary Turner97206d52017-05-12 04:51:55 +00003358 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003359 connection->Disconnect(&error);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003360
Kate Stoneb9c1b512016-09-06 20:57:50 +00003361 if (error.Success()) {
3362 if (log)
3363 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3364 "terminal stdio - SUCCESS",
3365 __FUNCTION__);
3366 } else {
3367 if (log)
3368 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3369 "terminal stdio - FAIL: %s",
3370 __FUNCTION__, error.AsCString());
3371 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003372 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003373 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003374}
3375
Kate Stoneb9c1b512016-09-06 20:57:50 +00003376NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3377 StringExtractorGDBRemote &packet) {
3378 NativeThreadProtocolSP thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003379
Kate Stoneb9c1b512016-09-06 20:57:50 +00003380 // We have no thread if we don't have a process.
3381 if (!m_debugged_process_sp ||
3382 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
Tamas Berghammere13c2732015-02-11 10:29:30 +00003383 return thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003384
Kate Stoneb9c1b512016-09-06 20:57:50 +00003385 // If the client hasn't asked for thread suffix support, there will not be a
3386 // thread suffix.
3387 // Use the current thread in that case.
3388 if (!m_thread_suffix_supported) {
3389 const lldb::tid_t current_tid = GetCurrentThreadID();
3390 if (current_tid == LLDB_INVALID_THREAD_ID)
3391 return thread_sp;
3392 else if (current_tid == 0) {
3393 // Pick a thread.
3394 return m_debugged_process_sp->GetThreadAtIndex(0);
3395 } else
3396 return m_debugged_process_sp->GetThreadByID(current_tid);
3397 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003398
Kate Stoneb9c1b512016-09-06 20:57:50 +00003399 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003400
Kate Stoneb9c1b512016-09-06 20:57:50 +00003401 // Parse out the ';'.
3402 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003403 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003404 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3405 "error: expected ';' prior to start of thread suffix: packet "
3406 "contents = '%s'",
3407 __FUNCTION__, packet.GetStringRef().c_str());
3408 return thread_sp;
3409 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003410
Kate Stoneb9c1b512016-09-06 20:57:50 +00003411 if (!packet.GetBytesLeft())
3412 return thread_sp;
3413
3414 // Parse out thread: portion.
3415 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3416 if (log)
3417 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3418 "error: expected 'thread:' but not found, packet contents = "
3419 "'%s'",
3420 __FUNCTION__, packet.GetStringRef().c_str());
3421 return thread_sp;
3422 }
3423 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3424 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3425 if (tid != 0)
3426 return m_debugged_process_sp->GetThreadByID(tid);
3427
3428 return thread_sp;
3429}
3430
3431lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3432 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3433 // Use whatever the debug process says is the current thread id
3434 // since the protocol either didn't specify or specified we want
3435 // any/all threads marked as the current thread.
3436 if (!m_debugged_process_sp)
3437 return LLDB_INVALID_THREAD_ID;
3438 return m_debugged_process_sp->GetCurrentThreadID();
3439 }
3440 // Use the specific current thread id set by the gdb remote protocol.
3441 return m_current_tid;
3442}
3443
3444uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3445 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3446 return m_next_saved_registers_id++;
3447}
3448
3449void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
Pavel Labathb7f0f452017-03-17 11:08:40 +00003450 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003451
Pavel Labathb7f0f452017-03-17 11:08:40 +00003452 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3453 m_active_auxv_buffer_up.reset();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003454}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003455
3456FileSpec
Kate Stoneb9c1b512016-09-06 20:57:50 +00003457GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3458 const ArchSpec &arch) {
3459 if (m_debugged_process_sp) {
3460 FileSpec file_spec;
3461 if (m_debugged_process_sp
3462 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3463 .Success()) {
3464 if (file_spec.Exists())
3465 return file_spec;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003466 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003467 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003468
Kate Stoneb9c1b512016-09-06 20:57:50 +00003469 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003470}