blob: dddda311bb65e926796b80c8d3480e1cb0746c66 [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(
Pavel Labath96e600f2017-07-07 11:02:19 +000076 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
78 "gdb-remote.server.rx_packet"),
Pavel Labath96e600f2017-07-07 11:02:19 +000079 m_mainloop(mainloop), m_process_factory(process_factory),
80 m_stdio_communication("process.stdio") {
Kate Stoneb9c1b512016-09-06 20:57:50 +000081 RegisterPacketHandlers();
Tamas Berghammere13c2732015-02-11 10:29:30 +000082}
83
Kate Stoneb9c1b512016-09-06 20:57:50 +000084void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
85 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
86 &GDBRemoteCommunicationServerLLGS::Handle_C);
87 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
88 &GDBRemoteCommunicationServerLLGS::Handle_c);
89 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
90 &GDBRemoteCommunicationServerLLGS::Handle_D);
91 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
92 &GDBRemoteCommunicationServerLLGS::Handle_H);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
94 &GDBRemoteCommunicationServerLLGS::Handle_I);
95 RegisterMemberFunctionHandler(
96 StringExtractorGDBRemote::eServerPacketType_interrupt,
97 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
98 RegisterMemberFunctionHandler(
99 StringExtractorGDBRemote::eServerPacketType_m,
100 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
101 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
102 &GDBRemoteCommunicationServerLLGS::Handle_M);
103 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
104 &GDBRemoteCommunicationServerLLGS::Handle_p);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
106 &GDBRemoteCommunicationServerLLGS::Handle_P);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
108 &GDBRemoteCommunicationServerLLGS::Handle_qC);
109 RegisterMemberFunctionHandler(
110 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
111 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
112 RegisterMemberFunctionHandler(
113 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
114 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
115 RegisterMemberFunctionHandler(
116 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
117 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
118 RegisterMemberFunctionHandler(
119 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
120 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
121 RegisterMemberFunctionHandler(
122 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
123 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
124 RegisterMemberFunctionHandler(
125 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
126 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
127 RegisterMemberFunctionHandler(
128 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
129 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
130 RegisterMemberFunctionHandler(
131 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
132 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
133 RegisterMemberFunctionHandler(
134 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
135 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
136 RegisterMemberFunctionHandler(
137 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
138 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
139 RegisterMemberFunctionHandler(
140 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
141 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
142 RegisterMemberFunctionHandler(
143 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
144 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
145 RegisterMemberFunctionHandler(
146 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
147 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
148 RegisterMemberFunctionHandler(
149 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
150 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
151 RegisterMemberFunctionHandler(
152 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
153 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
154 RegisterMemberFunctionHandler(
155 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
156 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
157 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
158 &GDBRemoteCommunicationServerLLGS::Handle_s);
159 RegisterMemberFunctionHandler(
160 StringExtractorGDBRemote::eServerPacketType_stop_reason,
161 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
162 RegisterMemberFunctionHandler(
163 StringExtractorGDBRemote::eServerPacketType_vAttach,
164 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
165 RegisterMemberFunctionHandler(
166 StringExtractorGDBRemote::eServerPacketType_vCont,
167 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
168 RegisterMemberFunctionHandler(
169 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
170 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
171 RegisterMemberFunctionHandler(
172 StringExtractorGDBRemote::eServerPacketType_x,
173 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
174 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
175 &GDBRemoteCommunicationServerLLGS::Handle_Z);
176 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
177 &GDBRemoteCommunicationServerLLGS::Handle_z);
Pavel Labath4a705e72017-02-24 09:29:14 +0000178 RegisterMemberFunctionHandler(
179 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
180 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000181
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +0000182 RegisterMemberFunctionHandler(
183 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
184 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
185 RegisterMemberFunctionHandler(
186 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
187 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
188 RegisterMemberFunctionHandler(
189 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
190 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
191 RegisterMemberFunctionHandler(
192 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
193 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
194 RegisterMemberFunctionHandler(
195 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
196 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
Zachary Turner97206d52017-05-12 04:51:55 +0000199 [this](StringExtractorGDBRemote packet, Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 bool &interrupt, bool &quit) {
201 quit = true;
202 return this->Handle_k(packet);
203 });
Tamas Berghammere13c2732015-02-11 10:29:30 +0000204}
205
Zachary Turner97206d52017-05-12 04:51:55 +0000206Status
207GDBRemoteCommunicationServerLLGS::SetLaunchArguments(const char *const args[],
208 int argc) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 if ((argc < 1) || !args || !args[0] || !args[0][0])
Zachary Turner97206d52017-05-12 04:51:55 +0000210 return Status("%s: no process command line specified to launch",
211 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
Zachary Turner97206d52017-05-12 04:51:55 +0000214 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000215}
216
Zachary Turner97206d52017-05-12 04:51:55 +0000217Status
218GDBRemoteCommunicationServerLLGS::SetLaunchFlags(unsigned int launch_flags) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219 m_process_launch_info.GetFlags().Set(launch_flags);
Zachary Turner97206d52017-05-12 04:51:55 +0000220 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000221}
222
Zachary Turner97206d52017-05-12 04:51:55 +0000223Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226 if (!m_process_launch_info.GetArguments().GetArgumentCount())
Zachary Turner97206d52017-05-12 04:51:55 +0000227 return Status("%s: no process command line specified to launch",
228 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 const bool should_forward_stdio =
231 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
232 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
233 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
234 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
235 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000236
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 const bool default_to_use_pty = true;
238 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 {
241 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
Pavel Labath82abefa2017-07-18 09:24:48 +0000242 assert(!m_debugged_process_up && "lldb-server creating debugged "
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 "process but one already exists");
Pavel Labath96e600f2017-07-07 11:02:19 +0000244 auto process_or =
245 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
246 if (!process_or) {
247 Status status(process_or.takeError());
248 llvm::errs() << llvm::formatv(
249 "failed to launch executable `{0}`: {1}",
250 m_process_launch_info.GetArguments().GetArgumentAtIndex(0), status);
251 return status;
252 }
Pavel Labath82abefa2017-07-18 09:24:48 +0000253 m_debugged_process_up = std::move(*process_or);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
257 // as needed.
258 // llgs local-process debugging may specify PTY paths, which will make these
259 // file actions non-null
260 // process launch -i/e/o will also make these file actions non-null
261 // nullptr means that the traffic is expected to flow over gdb-remote protocol
262 if (should_forward_stdio) {
263 // nullptr means it's not redirected to file or pty (in case of LLGS local)
264 // at least one of stdio will be transferred pty<->gdb-remote
265 // we need to give the pty master handle to this object to read and/or write
Pavel Labath82abefa2017-07-18 09:24:48 +0000266 LLDB_LOG(log,
267 "pid = {0}: setting up stdout/stderr redirection via $O "
268 "gdb-remote commands",
269 m_debugged_process_up->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 // Setup stdout/stderr mapping from inferior to $O
Pavel Labath82abefa2017-07-18 09:24:48 +0000272 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 if (terminal_fd >= 0) {
274 if (log)
275 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
276 "inferior STDIO fd to %d",
277 __FUNCTION__, terminal_fd);
Pavel Labath96e600f2017-07-07 11:02:19 +0000278 Status status = SetSTDIOFileDescriptor(terminal_fd);
279 if (status.Fail())
280 return status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281 } else {
282 if (log)
283 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
284 "inferior STDIO since terminal fd reported as %d",
285 __FUNCTION__, terminal_fd);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000286 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000287 } else {
Pavel Labath82abefa2017-07-18 09:24:48 +0000288 LLDB_LOG(log,
289 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
290 "will communicate over client-provided file descriptors",
291 m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292 }
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 printf("Launched '%s' as process %" PRIu64 "...\n",
295 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
Pavel Labath82abefa2017-07-18 09:24:48 +0000296 m_debugged_process_up->GetID());
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000297
Pavel Labath96e600f2017-07-07 11:02:19 +0000298 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000299}
300
Zachary Turner97206d52017-05-12 04:51:55 +0000301Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
303 if (log)
304 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
305 __FUNCTION__, pid);
306
307 // Before we try to attach, make sure we aren't already monitoring something
308 // else.
Pavel Labath82abefa2017-07-18 09:24:48 +0000309 if (m_debugged_process_up &&
310 m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID)
Zachary Turner97206d52017-05-12 04:51:55 +0000311 return Status("cannot attach to a process %" PRIu64
312 " when another process with pid %" PRIu64
313 " is being debugged.",
Pavel Labath82abefa2017-07-18 09:24:48 +0000314 pid, m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315
316 // Try to attach.
Pavel Labath96e600f2017-07-07 11:02:19 +0000317 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
318 if (!process_or) {
319 Status status(process_or.takeError());
320 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
321 status);
322 return status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 }
Pavel Labath82abefa2017-07-18 09:24:48 +0000324 m_debugged_process_up = std::move(*process_or);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325
326 // Setup stdout/stderr mapping from inferior.
Pavel Labath82abefa2017-07-18 09:24:48 +0000327 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 if (terminal_fd >= 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000329 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
331 "inferior STDIO fd to %d",
332 __FUNCTION__, terminal_fd);
Pavel Labath96e600f2017-07-07 11:02:19 +0000333 Status status = SetSTDIOFileDescriptor(terminal_fd);
334 if (status.Fail())
335 return status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 } else {
337 if (log)
338 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
339 "inferior STDIO since terminal fd reported as %d",
340 __FUNCTION__, terminal_fd);
341 }
342
343 printf("Attached to process %" PRIu64 "...\n", pid);
Pavel Labath96e600f2017-07-07 11:02:19 +0000344 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345}
346
347void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
348 NativeProcessProtocol *process) {
349 assert(process && "process cannot be NULL");
350 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
351 if (log) {
352 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
353 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
354 __FUNCTION__, process->GetID(),
355 StateAsCString(process->GetState()));
356 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000357}
358
359GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360GDBRemoteCommunicationServerLLGS::SendWResponse(
361 NativeProcessProtocol *process) {
362 assert(process && "process cannot be NULL");
363 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000364
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 // send W notification
Pavel Labath3508fc82017-06-19 12:47:50 +0000366 auto wait_status = process->GetExitStatus();
367 if (!wait_status) {
368 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
369 process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 StreamGDBRemote response;
372 response.PutChar('E');
373 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
374 return SendPacketNoLock(response.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375 }
Pavel Labath3508fc82017-06-19 12:47:50 +0000376
377 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
378 *wait_status);
379
380 StreamGDBRemote response;
381 response.Format("{0:g}", *wait_status);
382 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000383}
384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385static void AppendHexValue(StreamString &response, const uint8_t *buf,
386 uint32_t buf_size, bool swap) {
387 int64_t i;
388 if (swap) {
389 for (i = buf_size - 1; i >= 0; i--)
390 response.PutHex8(buf[i]);
391 } else {
392 for (i = 0; i < buf_size; i++)
393 response.PutHex8(buf[i]);
394 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000395}
396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397static void WriteRegisterValueInHexFixedWidth(
398 StreamString &response, NativeRegisterContextSP &reg_ctx_sp,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000399 const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
400 lldb::ByteOrder byte_order) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 RegisterValue reg_value;
402 if (!reg_value_p) {
Zachary Turner97206d52017-05-12 04:51:55 +0000403 Status error = reg_ctx_sp->ReadRegister(&reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 if (error.Success())
405 reg_value_p = &reg_value;
406 // else log.
407 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 if (reg_value_p) {
410 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
Pavel Labathe0a5b572017-01-20 14:17:16 +0000411 reg_value_p->GetByteSize(),
412 byte_order == lldb::eByteOrderLittle);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 } else {
414 // Zero-out any unreadable values.
415 if (reg_info.byte_size > 0) {
416 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
417 AppendHexValue(response, zeros.data(), zeros.size(), false);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000418 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000420}
421
Pavel Labathe0a5b572017-01-20 14:17:16 +0000422static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath4a4bb122015-07-16 14:14:35 +0000424
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
426 if (!reg_ctx_sp)
427 return nullptr;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000428
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000430
431#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 // Expedite all registers in the first register set (i.e. should be GPRs) that
433 // are not contained in other registers.
434 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
435 if (!reg_set_p)
436 return nullptr;
437 for (const uint32_t *reg_num_p = reg_set_p->registers;
438 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
439 uint32_t reg_num = *reg_num_p;
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000440#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 // Expedite only a couple of registers until we figure out why sending
442 // registers is
443 // expensive.
444 static const uint32_t k_expedited_registers[] = {
445 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
446 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
Pavel Labathc4645bb2015-10-26 16:25:28 +0000447
Pavel Labathe0a5b572017-01-20 14:17:16 +0000448 for (const uint32_t *generic_reg_p = k_expedited_registers;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
450 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
451 eRegisterKindGeneric, *generic_reg_p);
452 if (reg_num == LLDB_INVALID_REGNUM)
453 continue; // Target does not support the given register.
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000454#endif
455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 const RegisterInfo *const reg_info_p =
457 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
458 if (reg_info_p == nullptr) {
459 if (log)
460 log->Printf(
461 "%s failed to get register info for register index %" PRIu32,
462 __FUNCTION__, reg_num);
463 continue;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000464 }
465
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466 if (reg_info_p->value_regs != nullptr)
467 continue; // Only expedite registers that are not contained in other
468 // registers.
Pavel Labath4a4bb122015-07-16 14:14:35 +0000469
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000471 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472 if (error.Fail()) {
473 if (log)
474 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
Pavel Labath05569f62015-07-23 09:09:29 +0000475 __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
477 reg_num, error.AsCString());
478 continue;
Pavel Labath05569f62015-07-23 09:09:29 +0000479 }
480
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481 StreamString stream;
482 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000483 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484
485 register_object_sp->SetObject(
486 llvm::to_string(reg_num),
487 std::make_shared<JSONString>(stream.GetString()));
488 }
489
490 return register_object_sp;
Pavel Labath05569f62015-07-23 09:09:29 +0000491}
492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493static const char *GetStopReasonString(StopReason stop_reason) {
494 switch (stop_reason) {
495 case eStopReasonTrace:
496 return "trace";
497 case eStopReasonBreakpoint:
498 return "breakpoint";
499 case eStopReasonWatchpoint:
500 return "watchpoint";
501 case eStopReasonSignal:
502 return "signal";
503 case eStopReasonException:
504 return "exception";
505 case eStopReasonExec:
506 return "exec";
507 case eStopReasonInstrumentation:
508 case eStopReasonInvalid:
509 case eStopReasonPlanComplete:
510 case eStopReasonThreadExiting:
511 case eStopReasonNone:
512 break; // ignored
513 }
514 return nullptr;
515}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000516
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
518 bool abridged) {
519 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000520
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000522
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 // Ensure we can get info on the given thread.
524 uint32_t thread_idx = 0;
525 for (NativeThreadProtocolSP thread_sp;
526 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
527 ++thread_idx) {
528
529 lldb::tid_t tid = thread_sp->GetID();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000530
531 // Grab the reason this thread stopped.
532 struct ThreadStopInfo tid_stop_info;
533 std::string description;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 if (!thread_sp->GetStopReason(tid_stop_info, description))
535 return nullptr;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000536
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537 const int signum = tid_stop_info.details.signal.signo;
538 if (log) {
539 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
540 " tid %" PRIu64
541 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
542 __FUNCTION__, process.GetID(), tid, signum,
543 tid_stop_info.reason, tid_stop_info.details.exception.type);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000544 }
545
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
547 threads_array_sp->AppendObject(thread_obj_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000548
Pavel Labathe0a5b572017-01-20 14:17:16 +0000549 if (!abridged) {
550 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
551 thread_obj_sp->SetObject("registers", registers_sp);
552 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
555 if (signum != 0)
556 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 const std::string thread_name = thread_sp->GetName();
559 if (!thread_name.empty())
560 thread_obj_sp->SetObject("name",
561 std::make_shared<JSONString>(thread_name));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000562
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
564 thread_obj_sp->SetObject("reason",
565 std::make_shared<JSONString>(stop_reason_str));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000566
567 if (!description.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 thread_obj_sp->SetObject("description",
569 std::make_shared<JSONString>(description));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 if ((tid_stop_info.reason == eStopReasonException) &&
572 tid_stop_info.details.exception.type) {
573 thread_obj_sp->SetObject(
574 "metype",
575 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
576
577 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
578 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
579 ++i) {
580 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
581 tid_stop_info.details.exception.data[i]));
582 }
583 thread_obj_sp->SetObject("medata", medata_array_sp);
584 }
585
586 // TODO: Expedite interesting regions of inferior memory
587 }
588
589 return threads_array_sp;
590}
591
592GDBRemoteCommunication::PacketResult
593GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
594 lldb::tid_t tid) {
595 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
596
597 // Ensure we have a debugged process.
Pavel Labath82abefa2017-07-18 09:24:48 +0000598 if (!m_debugged_process_up ||
599 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 return SendErrorResponse(50);
601
Pavel Labath82abefa2017-07-18 09:24:48 +0000602 LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
603 m_debugged_process_up->GetID(), tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604
605 // Ensure we can get info on the given thread.
Pavel Labath82abefa2017-07-18 09:24:48 +0000606 NativeThreadProtocolSP thread_sp(m_debugged_process_up->GetThreadByID(tid));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 if (!thread_sp)
608 return SendErrorResponse(51);
609
610 // Grab the reason this thread stopped.
611 struct ThreadStopInfo tid_stop_info;
612 std::string description;
613 if (!thread_sp->GetStopReason(tid_stop_info, description))
614 return SendErrorResponse(52);
615
616 // FIXME implement register handling for exec'd inferiors.
617 // if (tid_stop_info.reason == eStopReasonExec)
618 // {
619 // const bool force = true;
620 // InitializeRegisters(force);
621 // }
622
623 StreamString response;
624 // Output the T packet with the thread
625 response.PutChar('T');
626 int signum = tid_stop_info.details.signal.signo;
Pavel Labath82abefa2017-07-18 09:24:48 +0000627 LLDB_LOG(
628 log,
629 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
630 m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
631 tid_stop_info.details.exception.type);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632
633 // Print the signal number.
634 response.PutHex8(signum & 0xff);
635
636 // Include the tid.
637 response.Printf("thread:%" PRIx64 ";", tid);
638
639 // Include the thread name if there is one.
640 const std::string thread_name = thread_sp->GetName();
641 if (!thread_name.empty()) {
642 size_t thread_name_len = thread_name.length();
643
644 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
645 response.PutCString("name:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000646 response.PutCString(thread_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 } else {
648 // The thread name contains special chars, send as hex bytes.
649 response.PutCString("hexname:");
650 response.PutCStringAsRawHex8(thread_name.c_str());
651 }
652 response.PutChar(';');
653 }
654
655 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
656 // will send all thread IDs back in the "threads" key whose value is
657 // a list of hex thread IDs separated by commas:
658 // "threads:10a,10b,10c;"
659 // This will save the debugger from having to send a pair of qfThreadInfo
660 // and qsThreadInfo packets, but it also might take a lot of room in the
661 // stop reply packet, so it must be enabled only on systems where there
662 // are no limits on packet lengths.
663 if (m_list_threads_in_stop_reply) {
664 response.PutCString("threads:");
665
666 uint32_t thread_index = 0;
667 NativeThreadProtocolSP listed_thread_sp;
668 for (listed_thread_sp =
Pavel Labath82abefa2017-07-18 09:24:48 +0000669 m_debugged_process_up->GetThreadAtIndex(thread_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 listed_thread_sp; ++thread_index,
Pavel Labath82abefa2017-07-18 09:24:48 +0000671 listed_thread_sp = m_debugged_process_up->GetThreadAtIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 thread_index)) {
673 if (thread_index > 0)
674 response.PutChar(',');
675 response.Printf("%" PRIx64, listed_thread_sp->GetID());
676 }
677 response.PutChar(';');
678
679 // Include JSON info that describes the stop reason for any threads
680 // that actually have stop reasons. We use the new "jstopinfo" key
681 // whose values is hex ascii JSON that contains the thread IDs
682 // thread stop info only for threads that have stop reasons. Only send
683 // this if we have more than one thread otherwise this packet has all
684 // the info it needs.
685 if (thread_index > 0) {
686 const bool threads_with_valid_stop_info_only = true;
687 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
Pavel Labath82abefa2017-07-18 09:24:48 +0000688 *m_debugged_process_up, threads_with_valid_stop_info_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 if (threads_info_sp) {
690 response.PutCString("jstopinfo:");
691 StreamString unescaped_response;
692 threads_info_sp->Write(unescaped_response);
693 response.PutCStringAsRawHex8(unescaped_response.GetData());
694 response.PutChar(';');
Pavel Labath82abefa2017-07-18 09:24:48 +0000695 } else
696 LLDB_LOG(log, "failed to prepare a jstopinfo field for pid {0}",
697 m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 }
Pavel Labathe0a5b572017-01-20 14:17:16 +0000699
700 uint32_t i = 0;
701 response.PutCString("thread-pcs");
702 char delimiter = ':';
703 for (NativeThreadProtocolSP thread_sp;
Pavel Labath82abefa2017-07-18 09:24:48 +0000704 (thread_sp = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
Pavel Labathe0a5b572017-01-20 14:17:16 +0000705 ++i) {
706 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
707 if (!reg_ctx_sp)
708 continue;
709
710 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
711 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
712 const RegisterInfo *const reg_info_p =
713 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
714
715 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000716 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Pavel Labathe0a5b572017-01-20 14:17:16 +0000717 if (error.Fail()) {
718 if (log)
719 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
720 __FUNCTION__,
721 reg_info_p->name ? reg_info_p->name
722 : "<unnamed-register>",
723 reg_to_read, error.AsCString());
724 continue;
725 }
726
727 response.PutChar(delimiter);
728 delimiter = ',';
729 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
730 &reg_value, endian::InlHostByteOrder());
731 }
732
733 response.PutChar(';');
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 }
735
736 //
737 // Expedite registers.
738 //
739
740 // Grab the register context.
741 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
742 if (reg_ctx_sp) {
743 // Expedite all registers in the first register set (i.e. should be GPRs)
744 // that are not contained in other registers.
745 const RegisterSet *reg_set_p;
746 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
747 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
748 if (log)
749 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
750 "from set '%s' (registers set count: %zu)",
751 __FUNCTION__,
752 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
753 reg_set_p->num_registers);
754
755 for (const uint32_t *reg_num_p = reg_set_p->registers;
756 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
757 const RegisterInfo *const reg_info_p =
758 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
759 if (reg_info_p == nullptr) {
760 if (log)
761 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
762 "register info for register set '%s', register index "
763 "%" PRIu32,
764 __FUNCTION__,
765 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
766 *reg_num_p);
767 } else if (reg_info_p->value_regs == nullptr) {
768 // Only expediate registers that are not contained in other registers.
769 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000770 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 if (error.Success()) {
772 response.Printf("%.02x:", *reg_num_p);
773 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000774 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 response.PutChar(';');
776 } else {
777 if (log)
778 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
779 "register '%s' index %" PRIu32 ": %s",
780 __FUNCTION__, reg_info_p->name ? reg_info_p->name
781 : "<unnamed-register>",
782 *reg_num_p, error.AsCString());
783 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000784 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000785 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000786 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000788
Kate Stoneb9c1b512016-09-06 20:57:50 +0000789 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
790 if (reason_str != nullptr) {
791 response.Printf("reason:%s;", reason_str);
792 }
793
794 if (!description.empty()) {
795 // Description may contains special chars, send as hex bytes.
796 response.PutCString("description:");
797 response.PutCStringAsRawHex8(description.c_str());
798 response.PutChar(';');
799 } else if ((tid_stop_info.reason == eStopReasonException) &&
800 tid_stop_info.details.exception.type) {
801 response.PutCString("metype:");
802 response.PutHex64(tid_stop_info.details.exception.type);
803 response.PutCString(";mecount:");
804 response.PutHex32(tid_stop_info.details.exception.data_count);
805 response.PutChar(';');
806
807 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
808 response.PutCString("medata:");
809 response.PutHex64(tid_stop_info.details.exception.data[i]);
810 response.PutChar(';');
811 }
812 }
813
814 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000815}
816
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
818 NativeProcessProtocol *process) {
819 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000820
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
822 if (log)
823 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
824
825 PacketResult result = SendStopReasonForState(StateType::eStateExited);
826 if (result != PacketResult::Success) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000827 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
829 "notification for PID %" PRIu64 ", state: eStateExited",
830 __FUNCTION__, process->GetID());
831 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000832
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 // Close the pipe to the inferior terminal i/o if we launched it
834 // and set one up.
835 MaybeCloseInferiorTerminalConnection();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000836
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837 // We are ready to exit the debug monitor.
838 m_exit_now = true;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000839}
840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
842 NativeProcessProtocol *process) {
843 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000844
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
846 if (log)
847 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000848
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 // Send the stop reason unless this is the stop after the
850 // launch or attach.
851 switch (m_inferior_prev_state) {
852 case eStateLaunching:
853 case eStateAttaching:
854 // Don't send anything per debugserver behavior.
855 break;
856 default:
857 // In all other cases, send the stop reason.
858 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
859 if (result != PacketResult::Success) {
860 if (log)
861 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
862 "notification for PID %" PRIu64 ", state: eStateExited",
863 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000864 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 break;
866 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000867}
868
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
870 NativeProcessProtocol *process, lldb::StateType state) {
871 assert(process && "process cannot be NULL");
872 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
873 if (log) {
874 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
875 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
876 __FUNCTION__, process->GetID(), StateAsCString(state));
877 }
878
879 switch (state) {
880 case StateType::eStateRunning:
881 StartSTDIOForwarding();
882 break;
883
884 case StateType::eStateStopped:
885 // Make sure we get all of the pending stdout/stderr from the inferior
886 // and send it to the lldb host before we send the state change
887 // notification
888 SendProcessOutput();
889 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
890 // does not
891 // interfere with our protocol.
892 StopSTDIOForwarding();
893 HandleInferiorState_Stopped(process);
894 break;
895
896 case StateType::eStateExited:
897 // Same as above
898 SendProcessOutput();
899 StopSTDIOForwarding();
900 HandleInferiorState_Exited(process);
901 break;
902
903 default:
904 if (log) {
905 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
906 "change for pid %" PRIu64 ", new state: %s",
907 __FUNCTION__, process->GetID(), StateAsCString(state));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000908 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 break;
910 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000911
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 // Remember the previous state reported to us.
913 m_inferior_prev_state = state;
914}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000915
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
917 ClearProcessSpecificData();
918}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000919
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
921 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
922
923 if (!m_handshake_completed) {
924 if (!HandshakeWithClient()) {
925 if (log)
926 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
927 "client failed, exiting",
928 __FUNCTION__);
929 m_mainloop.RequestTermination();
930 return;
931 }
932 m_handshake_completed = true;
933 }
934
935 bool interrupt = false;
936 bool done = false;
Zachary Turner97206d52017-05-12 04:51:55 +0000937 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000938 while (true) {
Pavel Labath1eff73c2016-11-24 10:54:49 +0000939 const PacketResult result = GetPacketAndSendResponse(
940 std::chrono::microseconds(0), error, interrupt, done);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 if (result == PacketResult::ErrorReplyTimeout)
942 break; // No more packets in the queue
943
944 if ((result != PacketResult::Success)) {
945 if (log)
946 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
947 "failed: %s",
948 __FUNCTION__, error.AsCString());
949 m_mainloop.RequestTermination();
950 break;
951 }
952 }
953}
954
Zachary Turner97206d52017-05-12 04:51:55 +0000955Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 std::unique_ptr<Connection> &&connection) {
957 IOObjectSP read_object_sp = connection->GetReadObject();
958 GDBRemoteCommunicationServer::SetConnection(connection.release());
959
Zachary Turner97206d52017-05-12 04:51:55 +0000960 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 m_network_handle_up = m_mainloop.RegisterReadObject(
962 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
963 error);
964 return error;
965}
966
967GDBRemoteCommunication::PacketResult
968GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
969 uint32_t len) {
970 if ((buffer == nullptr) || (len == 0)) {
971 // Nothing to send.
972 return PacketResult::Success;
973 }
974
975 StreamString response;
976 response.PutChar('O');
977 response.PutBytesAsRawHex8(buffer, len);
978
979 return SendPacketNoLock(response.GetString());
980}
981
Zachary Turner97206d52017-05-12 04:51:55 +0000982Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
983 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984
985 // Set up the reading/handling of process I/O
986 std::unique_ptr<ConnectionFileDescriptor> conn_up(
987 new ConnectionFileDescriptor(fd, true));
988 if (!conn_up) {
989 error.SetErrorString("failed to create ConnectionFileDescriptor");
990 return error;
991 }
992
993 m_stdio_communication.SetCloseOnEOF(false);
994 m_stdio_communication.SetConnection(conn_up.release());
995 if (!m_stdio_communication.IsConnected()) {
996 error.SetErrorString(
997 "failed to set connection for inferior I/O communication");
998 return error;
999 }
1000
Zachary Turner97206d52017-05-12 04:51:55 +00001001 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002}
1003
1004void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1005 // Don't forward if not connected (e.g. when attaching).
1006 if (!m_stdio_communication.IsConnected())
1007 return;
1008
Zachary Turner97206d52017-05-12 04:51:55 +00001009 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 lldbassert(!m_stdio_handle_up);
1011 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1012 m_stdio_communication.GetConnection()->GetReadObject(),
1013 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1014
1015 if (!m_stdio_handle_up) {
1016 // Not much we can do about the failure. Log it and continue without
1017 // forwarding.
1018 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1019 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1020 "forwarding: %s",
1021 __FUNCTION__, error.AsCString());
1022 }
1023}
1024
1025void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1026 m_stdio_handle_up.reset();
1027}
1028
1029void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1030 char buffer[1024];
1031 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00001032 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 while (true) {
Pavel Labathc4063ee2016-11-25 11:58:44 +00001034 size_t bytes_read = m_stdio_communication.Read(
1035 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 switch (status) {
1037 case eConnectionStatusSuccess:
1038 SendONotification(buffer, bytes_read);
1039 break;
1040 case eConnectionStatusLostConnection:
1041 case eConnectionStatusEndOfFile:
1042 case eConnectionStatusError:
1043 case eConnectionStatusNoConnection:
1044 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1045 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1046 "forwarding as communication returned status %d (error: "
1047 "%s)",
1048 __FUNCTION__, status, error.AsCString());
1049 m_stdio_handle_up.reset();
1050 return;
1051
1052 case eConnectionStatusInterrupted:
1053 case eConnectionStatusTimedOut:
1054 return;
1055 }
1056 }
1057}
1058
1059GDBRemoteCommunication::PacketResult
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001060GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1061 StringExtractorGDBRemote &packet) {
1062 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1063 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001064 if (!m_debugged_process_up ||
1065 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001066 return SendErrorResponse(68);
1067
1068 if (!packet.ConsumeFront("jTraceStart:"))
1069 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1070
1071 TraceOptions options;
1072 uint64_t type = std::numeric_limits<uint64_t>::max();
1073 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1074 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1075 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1076
1077 auto json_object = StructuredData::ParseJSON(packet.Peek());
1078
1079 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001080 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001081 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1082
1083 auto json_dict = json_object->GetAsDictionary();
1084
Pavel Labath4c950232017-05-26 13:53:39 +00001085 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001086 options.setMetaDataBufferSize(metabuffersize);
1087
Pavel Labath4c950232017-05-26 13:53:39 +00001088 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001089 options.setTraceBufferSize(buffersize);
1090
Pavel Labath4c950232017-05-26 13:53:39 +00001091 json_dict->GetValueForKeyAsInteger("type", type);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001092 options.setType(static_cast<lldb::TraceType>(type));
1093
Pavel Labath4c950232017-05-26 13:53:39 +00001094 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001095 options.setThreadID(tid);
1096
1097 StructuredData::ObjectSP custom_params_sp =
1098 json_dict->GetValueForKey("params");
1099 if (custom_params_sp &&
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001100 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001101 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1102
1103 options.setTraceParams(
1104 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1105
1106 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1107 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1108 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1109 type);
1110 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1111 }
1112
1113 Status error;
1114 lldb::user_id_t uid = LLDB_INVALID_UID;
Pavel Labath82abefa2017-07-18 09:24:48 +00001115 uid = m_debugged_process_up->StartTrace(options, error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001116 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1117 if (error.Fail())
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001118 return SendErrorResponse(error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001119
1120 StreamGDBRemote response;
1121 response.Printf("%" PRIx64, uid);
1122 return SendPacketNoLock(response.GetString());
1123}
1124
1125GDBRemoteCommunication::PacketResult
1126GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1127 StringExtractorGDBRemote &packet) {
1128 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001129 if (!m_debugged_process_up ||
1130 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001131 return SendErrorResponse(68);
1132
1133 if (!packet.ConsumeFront("jTraceStop:"))
1134 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1135
1136 lldb::user_id_t uid = LLDB_INVALID_UID;
1137 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1138
1139 auto json_object = StructuredData::ParseJSON(packet.Peek());
1140
1141 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001142 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001143 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1144
1145 auto json_dict = json_object->GetAsDictionary();
1146
Pavel Labath4c950232017-05-26 13:53:39 +00001147 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001148 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1149
Pavel Labath4c950232017-05-26 13:53:39 +00001150 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001151
Pavel Labath82abefa2017-07-18 09:24:48 +00001152 Status error = m_debugged_process_up->StopTrace(uid, tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001153
1154 if (error.Fail())
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001155 return SendErrorResponse(error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001156
1157 return SendOKResponse();
1158}
1159
1160GDBRemoteCommunication::PacketResult
1161GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1162 StringExtractorGDBRemote &packet) {
1163
1164 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001165 if (!m_debugged_process_up ||
1166 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001167 return SendErrorResponse(68);
1168
1169 if (!packet.ConsumeFront("jTraceConfigRead:"))
1170 return SendIllFormedResponse(packet,
1171 "jTraceConfigRead: Ill formed packet ");
1172
1173 lldb::user_id_t uid = LLDB_INVALID_UID;
1174 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1175
1176 auto json_object = StructuredData::ParseJSON(packet.Peek());
1177
1178 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001179 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001180 return SendIllFormedResponse(packet,
1181 "jTraceConfigRead: Ill formed packet ");
1182
1183 auto json_dict = json_object->GetAsDictionary();
1184
Pavel Labath4c950232017-05-26 13:53:39 +00001185 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001186 return SendIllFormedResponse(packet,
1187 "jTraceConfigRead: Ill formed packet ");
1188
Pavel Labath4c950232017-05-26 13:53:39 +00001189 json_dict->GetValueForKeyAsInteger("threadid", threadid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001190
1191 TraceOptions options;
1192 StreamGDBRemote response;
1193
1194 options.setThreadID(threadid);
Pavel Labath82abefa2017-07-18 09:24:48 +00001195 Status error = m_debugged_process_up->GetTraceConfig(uid, options);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001196
1197 if (error.Fail())
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001198 return SendErrorResponse(error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001199
1200 StreamGDBRemote escaped_response;
1201 StructuredData::Dictionary json_packet;
1202
1203 json_packet.AddIntegerItem("type", options.getType());
1204 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1205 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1206
1207 StructuredData::DictionarySP custom_params = options.getTraceParams();
1208 if (custom_params)
1209 json_packet.AddItem("params", custom_params);
1210
1211 StreamString json_string;
1212 json_packet.Dump(json_string, false);
1213 escaped_response.PutEscapedBytes(json_string.GetData(),
1214 json_string.GetSize());
1215 return SendPacketNoLock(escaped_response.GetString());
1216}
1217
1218GDBRemoteCommunication::PacketResult
1219GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1220 StringExtractorGDBRemote &packet) {
1221
1222 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001223 if (!m_debugged_process_up ||
1224 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001225 return SendErrorResponse(68);
1226
1227 enum PacketType { MetaData, BufferData };
1228 PacketType tracetype = MetaData;
1229
1230 if (packet.ConsumeFront("jTraceBufferRead:"))
1231 tracetype = BufferData;
1232 else if (packet.ConsumeFront("jTraceMetaRead:"))
1233 tracetype = MetaData;
1234 else {
1235 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1236 }
1237
1238 lldb::user_id_t uid = LLDB_INVALID_UID;
1239
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001240 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001241 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001242 uint64_t offset = std::numeric_limits<uint64_t>::max();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001243
1244 auto json_object = StructuredData::ParseJSON(packet.Peek());
1245
1246 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001247 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001248 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1249
1250 auto json_dict = json_object->GetAsDictionary();
1251
Pavel Labath4c950232017-05-26 13:53:39 +00001252 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1253 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1254 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001255 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1256
Pavel Labath4c950232017-05-26 13:53:39 +00001257 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001258
1259 // Allocate the response buffer.
Ravitheja Addepally0e62a122017-05-26 14:26:14 +00001260 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1261 if (!buffer)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001262 return SendErrorResponse(0x78);
1263
1264 StreamGDBRemote response;
1265 Status error;
Ravitheja Addepally0e62a122017-05-26 14:26:14 +00001266 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001267
1268 if (tracetype == BufferData)
Pavel Labath82abefa2017-07-18 09:24:48 +00001269 error = m_debugged_process_up->GetData(uid, tid, buf, offset);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001270 else if (tracetype == MetaData)
Pavel Labath82abefa2017-07-18 09:24:48 +00001271 error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001272
1273 if (error.Fail())
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001274 return SendErrorResponse(error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001275
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001276 for (auto i : buf)
1277 response.PutHex8(i);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001278
1279 StreamGDBRemote escaped_response;
1280 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1281 return SendPacketNoLock(escaped_response.GetString());
1282}
1283
1284GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1286 StringExtractorGDBRemote &packet) {
1287 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001288 if (!m_debugged_process_up ||
1289 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 return SendErrorResponse(68);
1291
Pavel Labath82abefa2017-07-18 09:24:48 +00001292 lldb::pid_t pid = m_debugged_process_up->GetID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293
1294 if (pid == LLDB_INVALID_PROCESS_ID)
1295 return SendErrorResponse(1);
1296
1297 ProcessInstanceInfo proc_info;
1298 if (!Host::GetProcessInfo(pid, proc_info))
1299 return SendErrorResponse(1);
1300
1301 StreamString response;
1302 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1303 return SendPacketNoLock(response.GetString());
1304}
1305
1306GDBRemoteCommunication::PacketResult
1307GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1308 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001309 if (!m_debugged_process_up ||
1310 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001311 return SendErrorResponse(68);
1312
1313 // Make sure we set the current thread so g and p packets return
1314 // the data the gdb will expect.
Pavel Labath82abefa2017-07-18 09:24:48 +00001315 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 SetCurrentThreadID(tid);
1317
Pavel Labath82abefa2017-07-18 09:24:48 +00001318 NativeThreadProtocolSP thread_sp = m_debugged_process_up->GetCurrentThread();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319 if (!thread_sp)
1320 return SendErrorResponse(69);
1321
1322 StreamString response;
1323 response.Printf("QC%" PRIx64, thread_sp->GetID());
1324
1325 return SendPacketNoLock(response.GetString());
1326}
1327
1328GDBRemoteCommunication::PacketResult
1329GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1330 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1331
1332 StopSTDIOForwarding();
1333
Pavel Labath82abefa2017-07-18 09:24:48 +00001334 if (!m_debugged_process_up) {
1335 LLDB_LOG(log, "No debugged process found.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 return PacketResult::Success;
1337 }
1338
Pavel Labath82abefa2017-07-18 09:24:48 +00001339 Status error = m_debugged_process_up->Kill();
1340 if (error.Fail())
1341 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1342 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343
1344 // No OK response for kill packet.
1345 // return SendOKResponse ();
1346 return PacketResult::Success;
1347}
1348
1349GDBRemoteCommunication::PacketResult
1350GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1351 StringExtractorGDBRemote &packet) {
1352 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1353 if (packet.GetU32(0))
1354 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1355 else
1356 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1357 return SendOKResponse();
1358}
1359
1360GDBRemoteCommunication::PacketResult
1361GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1362 StringExtractorGDBRemote &packet) {
1363 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1364 std::string path;
1365 packet.GetHexByteString(path);
1366 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1367 return SendOKResponse();
1368}
1369
1370GDBRemoteCommunication::PacketResult
1371GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1372 StringExtractorGDBRemote &packet) {
1373 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1374 if (working_dir) {
1375 StreamString response;
1376 response.PutCStringAsRawHex8(working_dir.GetCString());
1377 return SendPacketNoLock(response.GetString());
1378 }
1379
1380 return SendErrorResponse(14);
1381}
1382
1383GDBRemoteCommunication::PacketResult
1384GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1385 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1386 if (log)
1387 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1388
1389 // Ensure we have a native process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001390 if (!m_debugged_process_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001391 if (log)
1392 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1393 "shared pointer",
1394 __FUNCTION__);
1395 return SendErrorResponse(0x36);
1396 }
1397
1398 // Pull out the signal number.
1399 packet.SetFilePos(::strlen("C"));
1400 if (packet.GetBytesLeft() < 1) {
1401 // Shouldn't be using a C without a signal.
1402 return SendIllFormedResponse(packet, "C packet specified without signal.");
1403 }
1404 const uint32_t signo =
1405 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1406 if (signo == std::numeric_limits<uint32_t>::max())
1407 return SendIllFormedResponse(packet, "failed to parse signal number");
1408
1409 // Handle optional continue address.
1410 if (packet.GetBytesLeft() > 0) {
1411 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1412 if (*packet.Peek() == ';')
1413 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1414 else
1415 return SendIllFormedResponse(
1416 packet, "unexpected content after $C{signal-number}");
1417 }
1418
1419 ResumeActionList resume_actions(StateType::eStateRunning, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00001420 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421
1422 // We have two branches: what to do if a continue thread is specified (in
1423 // which case we target
1424 // sending the signal to that thread), or when we don't have a continue thread
1425 // set (in which
1426 // case we send a signal to the process).
1427
1428 // TODO discuss with Greg Clayton, make sure this makes sense.
1429
1430 lldb::tid_t signal_tid = GetContinueThreadID();
1431 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1432 // The resume action for the continue thread (or all threads if a continue
1433 // thread is not set).
1434 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1435 static_cast<int>(signo)};
1436
1437 // Add the action for the continue thread (or all threads when the continue
1438 // thread isn't present).
1439 resume_actions.Append(action);
1440 } else {
1441 // Send the signal to the process since we weren't targeting a specific
1442 // continue thread with the signal.
Pavel Labath82abefa2017-07-18 09:24:48 +00001443 error = m_debugged_process_up->Signal(signo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001445 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1446 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447
1448 return SendErrorResponse(0x52);
1449 }
1450 }
1451
1452 // Resume the threads.
Pavel Labath82abefa2017-07-18 09:24:48 +00001453 error = m_debugged_process_up->Resume(resume_actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001455 LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1456 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001457
1458 return SendErrorResponse(0x38);
1459 }
1460
1461 // Don't send an "OK" packet; response is the stopped/exited message.
1462 return PacketResult::Success;
1463}
1464
1465GDBRemoteCommunication::PacketResult
1466GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1467 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1468 if (log)
1469 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1470
1471 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1472
1473 // For now just support all continue.
1474 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1475 if (has_continue_address) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001476 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1477 packet.Peek());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001478 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1479 }
1480
1481 // Ensure we have a native process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001482 if (!m_debugged_process_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483 if (log)
1484 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1485 "shared pointer",
1486 __FUNCTION__);
1487 return SendErrorResponse(0x36);
1488 }
1489
1490 // Build the ResumeActionList
1491 ResumeActionList actions(StateType::eStateRunning, 0);
1492
Pavel Labath82abefa2017-07-18 09:24:48 +00001493 Status error = m_debugged_process_up->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001494 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001495 LLDB_LOG(log, "c failed for process {0}: {1}",
1496 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001497 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1498 }
1499
Pavel Labath82abefa2017-07-18 09:24:48 +00001500 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001501 // No response required from continue.
1502 return PacketResult::Success;
1503}
1504
1505GDBRemoteCommunication::PacketResult
1506GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1507 StringExtractorGDBRemote &packet) {
1508 StreamString response;
1509 response.Printf("vCont;c;C;s;S");
1510
1511 return SendPacketNoLock(response.GetString());
1512}
1513
1514GDBRemoteCommunication::PacketResult
1515GDBRemoteCommunicationServerLLGS::Handle_vCont(
1516 StringExtractorGDBRemote &packet) {
1517 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1518 if (log)
1519 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1520 __FUNCTION__);
1521
1522 packet.SetFilePos(::strlen("vCont"));
1523
1524 if (packet.GetBytesLeft() == 0) {
1525 if (log)
1526 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1527 "vCont package",
1528 __FUNCTION__);
1529 return SendIllFormedResponse(packet, "Missing action from vCont package");
1530 }
1531
1532 // Check if this is all continue (no options or ";c").
1533 if (::strcmp(packet.Peek(), ";c") == 0) {
1534 // Move past the ';', then do a simple 'c'.
1535 packet.SetFilePos(packet.GetFilePos() + 1);
1536 return Handle_c(packet);
1537 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1538 // Move past the ';', then do a simple 's'.
1539 packet.SetFilePos(packet.GetFilePos() + 1);
1540 return Handle_s(packet);
1541 }
1542
1543 // Ensure we have a native process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001544 if (!m_debugged_process_up) {
1545 LLDB_LOG(log, "no debugged process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546 return SendErrorResponse(0x36);
1547 }
1548
1549 ResumeActionList thread_actions;
1550
1551 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1552 // Skip the semi-colon.
1553 packet.GetChar();
1554
1555 // Build up the thread action.
1556 ResumeAction thread_action;
1557 thread_action.tid = LLDB_INVALID_THREAD_ID;
1558 thread_action.state = eStateInvalid;
1559 thread_action.signal = 0;
1560
1561 const char action = packet.GetChar();
1562 switch (action) {
1563 case 'C':
1564 thread_action.signal = packet.GetHexMaxU32(false, 0);
1565 if (thread_action.signal == 0)
1566 return SendIllFormedResponse(
1567 packet, "Could not parse signal in vCont packet C action");
1568 LLVM_FALLTHROUGH;
1569
1570 case 'c':
1571 // Continue
1572 thread_action.state = eStateRunning;
1573 break;
1574
1575 case 'S':
1576 thread_action.signal = packet.GetHexMaxU32(false, 0);
1577 if (thread_action.signal == 0)
1578 return SendIllFormedResponse(
1579 packet, "Could not parse signal in vCont packet S action");
1580 LLVM_FALLTHROUGH;
1581
1582 case 's':
1583 // Step
1584 thread_action.state = eStateStepping;
1585 break;
Pavel Labathabadc222015-11-27 13:33:29 +00001586
Tamas Berghammere13c2732015-02-11 10:29:30 +00001587 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001588 return SendIllFormedResponse(packet, "Unsupported vCont action");
1589 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00001590 }
1591
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592 // Parse out optional :{thread-id} value.
1593 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1594 // Consume the separator.
1595 packet.GetChar();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001596
Kate Stoneb9c1b512016-09-06 20:57:50 +00001597 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1598 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1599 return SendIllFormedResponse(
1600 packet, "Could not parse thread number in vCont packet");
Pavel Labath77dc9562015-07-13 10:44:55 +00001601 }
1602
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603 thread_actions.Append(thread_action);
1604 }
Pavel Labath77dc9562015-07-13 10:44:55 +00001605
Pavel Labath82abefa2017-07-18 09:24:48 +00001606 Status error = m_debugged_process_up->Resume(thread_actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001608 LLDB_LOG(log, "vCont failed for process {0}: {1}",
1609 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001610 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1611 }
1612
Pavel Labath82abefa2017-07-18 09:24:48 +00001613 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614 // No response required from vCont.
1615 return PacketResult::Success;
Pavel Labath77dc9562015-07-13 10:44:55 +00001616}
1617
Kate Stoneb9c1b512016-09-06 20:57:50 +00001618void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1619 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath82abefa2017-07-18 09:24:48 +00001620 LLDB_LOG(log, "setting current thread id to {0}", tid);
Pavel Labath77dc9562015-07-13 10:44:55 +00001621
Kate Stoneb9c1b512016-09-06 20:57:50 +00001622 m_current_tid = tid;
Pavel Labath82abefa2017-07-18 09:24:48 +00001623 if (m_debugged_process_up)
1624 m_debugged_process_up->SetCurrentThreadID(m_current_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625}
1626
1627void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1628 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath82abefa2017-07-18 09:24:48 +00001629 LLDB_LOG(log, "setting continue thread id to {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001630
1631 m_continue_tid = tid;
Pavel Labath77dc9562015-07-13 10:44:55 +00001632}
1633
Tamas Berghammere13c2732015-02-11 10:29:30 +00001634GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001635GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1636 StringExtractorGDBRemote &packet) {
1637 // Handle the $? gdbremote command.
Tamas Berghammere13c2732015-02-11 10:29:30 +00001638
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639 // If no process, indicate error
Pavel Labath82abefa2017-07-18 09:24:48 +00001640 if (!m_debugged_process_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001641 return SendErrorResponse(02);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001642
Pavel Labath82abefa2017-07-18 09:24:48 +00001643 return SendStopReasonForState(m_debugged_process_up->GetState());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001644}
1645
1646GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001647GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1648 lldb::StateType process_state) {
1649 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00001650
Kate Stoneb9c1b512016-09-06 20:57:50 +00001651 switch (process_state) {
1652 case eStateAttaching:
1653 case eStateLaunching:
1654 case eStateRunning:
1655 case eStateStepping:
1656 case eStateDetached:
1657 // NOTE: gdb protocol doc looks like it should return $OK
1658 // when everything is running (i.e. no stopped result).
1659 return PacketResult::Success; // Ignore
Tamas Berghammere13c2732015-02-11 10:29:30 +00001660
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661 case eStateSuspended:
1662 case eStateStopped:
1663 case eStateCrashed: {
Pavel Labath82abefa2017-07-18 09:24:48 +00001664 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001665 // Make sure we set the current thread so g and p packets return
1666 // the data the gdb will expect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001667 SetCurrentThreadID(tid);
1668 return SendStopReplyPacketForThread(tid);
1669 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001670
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671 case eStateInvalid:
1672 case eStateUnloaded:
1673 case eStateExited:
Pavel Labath82abefa2017-07-18 09:24:48 +00001674 return SendWResponse(m_debugged_process_up.get());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001675
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676 default:
Pavel Labath82abefa2017-07-18 09:24:48 +00001677 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1678 m_debugged_process_up->GetID(), process_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001679 break;
1680 }
Pavel Labath424b2012015-07-28 09:06:56 +00001681
Kate Stoneb9c1b512016-09-06 20:57:50 +00001682 return SendErrorResponse(0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001683}
1684
1685GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001686GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1687 StringExtractorGDBRemote &packet) {
1688 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001689 if (!m_debugged_process_up ||
1690 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001692
Kate Stoneb9c1b512016-09-06 20:57:50 +00001693 // Ensure we have a thread.
Pavel Labath82abefa2017-07-18 09:24:48 +00001694 NativeThreadProtocolSP thread_sp(m_debugged_process_up->GetThreadAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001695 if (!thread_sp)
1696 return SendErrorResponse(69);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001697
Kate Stoneb9c1b512016-09-06 20:57:50 +00001698 // Get the register context for the first thread.
1699 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1700 if (!reg_context_sp)
1701 return SendErrorResponse(69);
1702
1703 // Parse out the register number from the request.
1704 packet.SetFilePos(strlen("qRegisterInfo"));
1705 const uint32_t reg_index =
1706 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1707 if (reg_index == std::numeric_limits<uint32_t>::max())
1708 return SendErrorResponse(69);
1709
1710 // Return the end of registers response if we've iterated one past the end of
1711 // the register set.
1712 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1713 return SendErrorResponse(69);
1714
1715 const RegisterInfo *reg_info =
1716 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1717 if (!reg_info)
1718 return SendErrorResponse(69);
1719
1720 // Build the reginfos response.
1721 StreamGDBRemote response;
1722
1723 response.PutCString("name:");
1724 response.PutCString(reg_info->name);
1725 response.PutChar(';');
1726
1727 if (reg_info->alt_name && reg_info->alt_name[0]) {
1728 response.PutCString("alt-name:");
1729 response.PutCString(reg_info->alt_name);
1730 response.PutChar(';');
1731 }
1732
1733 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1734 reg_info->byte_size * 8, reg_info->byte_offset);
1735
1736 switch (reg_info->encoding) {
1737 case eEncodingUint:
1738 response.PutCString("encoding:uint;");
1739 break;
1740 case eEncodingSint:
1741 response.PutCString("encoding:sint;");
1742 break;
1743 case eEncodingIEEE754:
1744 response.PutCString("encoding:ieee754;");
1745 break;
1746 case eEncodingVector:
1747 response.PutCString("encoding:vector;");
1748 break;
1749 default:
1750 break;
1751 }
1752
1753 switch (reg_info->format) {
1754 case eFormatBinary:
1755 response.PutCString("format:binary;");
1756 break;
1757 case eFormatDecimal:
1758 response.PutCString("format:decimal;");
1759 break;
1760 case eFormatHex:
1761 response.PutCString("format:hex;");
1762 break;
1763 case eFormatFloat:
1764 response.PutCString("format:float;");
1765 break;
1766 case eFormatVectorOfSInt8:
1767 response.PutCString("format:vector-sint8;");
1768 break;
1769 case eFormatVectorOfUInt8:
1770 response.PutCString("format:vector-uint8;");
1771 break;
1772 case eFormatVectorOfSInt16:
1773 response.PutCString("format:vector-sint16;");
1774 break;
1775 case eFormatVectorOfUInt16:
1776 response.PutCString("format:vector-uint16;");
1777 break;
1778 case eFormatVectorOfSInt32:
1779 response.PutCString("format:vector-sint32;");
1780 break;
1781 case eFormatVectorOfUInt32:
1782 response.PutCString("format:vector-uint32;");
1783 break;
1784 case eFormatVectorOfFloat32:
1785 response.PutCString("format:vector-float32;");
1786 break;
Valentina Giusticda0ae42016-09-08 14:16:45 +00001787 case eFormatVectorOfUInt64:
1788 response.PutCString("format:vector-uint64;");
1789 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001790 case eFormatVectorOfUInt128:
1791 response.PutCString("format:vector-uint128;");
1792 break;
1793 default:
1794 break;
1795 };
1796
1797 const char *const register_set_name =
1798 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1799 if (register_set_name) {
1800 response.PutCString("set:");
1801 response.PutCString(register_set_name);
1802 response.PutChar(';');
1803 }
1804
1805 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1806 LLDB_INVALID_REGNUM)
1807 response.Printf("ehframe:%" PRIu32 ";",
1808 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1809
1810 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1811 response.Printf("dwarf:%" PRIu32 ";",
1812 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1813
1814 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1815 case LLDB_REGNUM_GENERIC_PC:
1816 response.PutCString("generic:pc;");
1817 break;
1818 case LLDB_REGNUM_GENERIC_SP:
1819 response.PutCString("generic:sp;");
1820 break;
1821 case LLDB_REGNUM_GENERIC_FP:
1822 response.PutCString("generic:fp;");
1823 break;
1824 case LLDB_REGNUM_GENERIC_RA:
1825 response.PutCString("generic:ra;");
1826 break;
1827 case LLDB_REGNUM_GENERIC_FLAGS:
1828 response.PutCString("generic:flags;");
1829 break;
1830 case LLDB_REGNUM_GENERIC_ARG1:
1831 response.PutCString("generic:arg1;");
1832 break;
1833 case LLDB_REGNUM_GENERIC_ARG2:
1834 response.PutCString("generic:arg2;");
1835 break;
1836 case LLDB_REGNUM_GENERIC_ARG3:
1837 response.PutCString("generic:arg3;");
1838 break;
1839 case LLDB_REGNUM_GENERIC_ARG4:
1840 response.PutCString("generic:arg4;");
1841 break;
1842 case LLDB_REGNUM_GENERIC_ARG5:
1843 response.PutCString("generic:arg5;");
1844 break;
1845 case LLDB_REGNUM_GENERIC_ARG6:
1846 response.PutCString("generic:arg6;");
1847 break;
1848 case LLDB_REGNUM_GENERIC_ARG7:
1849 response.PutCString("generic:arg7;");
1850 break;
1851 case LLDB_REGNUM_GENERIC_ARG8:
1852 response.PutCString("generic:arg8;");
1853 break;
1854 default:
1855 break;
1856 }
1857
1858 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1859 response.PutCString("container-regs:");
1860 int i = 0;
1861 for (const uint32_t *reg_num = reg_info->value_regs;
1862 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1863 if (i > 0)
1864 response.PutChar(',');
1865 response.Printf("%" PRIx32, *reg_num);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001866 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001867 response.PutChar(';');
1868 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001869
Kate Stoneb9c1b512016-09-06 20:57:50 +00001870 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1871 response.PutCString("invalidate-regs:");
1872 int i = 0;
1873 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1874 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1875 if (i > 0)
1876 response.PutChar(',');
1877 response.Printf("%" PRIx32, *reg_num);
1878 }
1879 response.PutChar(';');
1880 }
1881
1882 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1883 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1884 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1885 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1886 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1887 response.PutChar(';');
1888 }
1889 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001890}
1891
1892GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001893GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1894 StringExtractorGDBRemote &packet) {
1895 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1896
1897 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001898 if (!m_debugged_process_up ||
1899 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
1900 LLDB_LOG(log, "no process ({0}), returning OK",
1901 m_debugged_process_up ? "invalid process id"
1902 : "null m_debugged_process_up");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 return SendOKResponse();
1904 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001905
Kate Stoneb9c1b512016-09-06 20:57:50 +00001906 StreamGDBRemote response;
1907 response.PutChar('m');
1908
Pavel Labath82abefa2017-07-18 09:24:48 +00001909 LLDB_LOG(log, "starting thread iteration");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001910 NativeThreadProtocolSP thread_sp;
1911 uint32_t thread_index;
1912 for (thread_index = 0,
Pavel Labath82abefa2017-07-18 09:24:48 +00001913 thread_sp = m_debugged_process_up->GetThreadAtIndex(thread_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001914 thread_sp; ++thread_index,
Pavel Labath82abefa2017-07-18 09:24:48 +00001915 thread_sp = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
1916 LLDB_LOG(log, "iterated thread {0}({1}, tid={2})", thread_index,
1917 thread_sp ? "is not null" : "null",
1918 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919 if (thread_index > 0)
1920 response.PutChar(',');
1921 response.Printf("%" PRIx64, thread_sp->GetID());
1922 }
1923
Pavel Labath82abefa2017-07-18 09:24:48 +00001924 LLDB_LOG(log, "finished thread iteration");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925 return SendPacketNoLock(response.GetString());
1926}
1927
1928GDBRemoteCommunication::PacketResult
1929GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1930 StringExtractorGDBRemote &packet) {
1931 // FIXME for now we return the full thread list in the initial packet and
1932 // always do nothing here.
1933 return SendPacketNoLock("l");
1934}
1935
1936GDBRemoteCommunication::PacketResult
1937GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1938 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1939
1940 // Parse out the register number from the request.
1941 packet.SetFilePos(strlen("p"));
1942 const uint32_t reg_index =
1943 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1944 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1945 if (log)
1946 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1947 "parse register number from request \"%s\"",
1948 __FUNCTION__, packet.GetStringRef().c_str());
1949 return SendErrorResponse(0x15);
1950 }
1951
1952 // Get the thread to use.
1953 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
1954 if (!thread_sp) {
1955 if (log)
1956 log->Printf(
1957 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
1958 __FUNCTION__);
1959 return SendErrorResponse(0x15);
1960 }
1961
1962 // Get the thread's register context.
1963 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1964 if (!reg_context_sp) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001965 LLDB_LOG(
1966 log,
1967 "pid {0} tid {1} failed, no register context available for the thread",
1968 m_debugged_process_up->GetID(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001969 return SendErrorResponse(0x15);
1970 }
1971
1972 // Return the end of registers response if we've iterated one past the end of
1973 // the register set.
1974 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
1975 if (log)
1976 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1977 "register %" PRIu32 " beyond register count %" PRIu32,
1978 __FUNCTION__, reg_index,
1979 reg_context_sp->GetUserRegisterCount());
1980 return SendErrorResponse(0x15);
1981 }
1982
1983 const RegisterInfo *reg_info =
1984 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1985 if (!reg_info) {
1986 if (log)
1987 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1988 "register %" PRIu32 " returned NULL",
1989 __FUNCTION__, reg_index);
1990 return SendErrorResponse(0x15);
1991 }
1992
1993 // Build the reginfos response.
1994 StreamGDBRemote response;
1995
1996 // Retrieve the value
1997 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +00001998 Status error = reg_context_sp->ReadRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001999 if (error.Fail()) {
2000 if (log)
2001 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
2002 "requested register %" PRIu32 " (%s) failed: %s",
2003 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2004 return SendErrorResponse(0x15);
2005 }
2006
2007 const uint8_t *const data =
2008 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
2009 if (!data) {
2010 if (log)
2011 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
2012 "bytes from requested register %" PRIu32,
2013 __FUNCTION__, reg_index);
2014 return SendErrorResponse(0x15);
2015 }
2016
2017 // FIXME flip as needed to get data in big/little endian format for this host.
2018 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2019 response.PutHex8(data[i]);
2020
2021 return SendPacketNoLock(response.GetString());
2022}
2023
2024GDBRemoteCommunication::PacketResult
2025GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2026 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2027
2028 // Ensure there is more content.
2029 if (packet.GetBytesLeft() < 1)
2030 return SendIllFormedResponse(packet, "Empty P packet");
2031
2032 // Parse out the register number from the request.
2033 packet.SetFilePos(strlen("P"));
2034 const uint32_t reg_index =
2035 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2036 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2037 if (log)
2038 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2039 "parse register number from request \"%s\"",
2040 __FUNCTION__, packet.GetStringRef().c_str());
2041 return SendErrorResponse(0x29);
2042 }
2043
2044 // Note debugserver would send an E30 here.
2045 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2046 return SendIllFormedResponse(
2047 packet, "P packet missing '=' char after register number");
2048
2049 // Get process architecture.
2050 ArchSpec process_arch;
Pavel Labath82abefa2017-07-18 09:24:48 +00002051 if (!m_debugged_process_up ||
2052 !m_debugged_process_up->GetArchitecture(process_arch)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002053 if (log)
2054 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
2055 "inferior architecture",
2056 __FUNCTION__);
2057 return SendErrorResponse(0x49);
2058 }
2059
2060 // Parse out the value.
2061 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2062 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2063
2064 // Get the thread to use.
2065 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2066 if (!thread_sp) {
2067 if (log)
2068 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2069 "available (thread index 0)",
2070 __FUNCTION__);
2071 return SendErrorResponse(0x28);
2072 }
2073
2074 // Get the thread's register context.
2075 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2076 if (!reg_context_sp) {
2077 if (log)
2078 log->Printf(
2079 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2080 " failed, no register context available for the thread",
Pavel Labath82abefa2017-07-18 09:24:48 +00002081 __FUNCTION__, m_debugged_process_up->GetID(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002082 return SendErrorResponse(0x15);
2083 }
2084
2085 const RegisterInfo *reg_info =
2086 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2087 if (!reg_info) {
2088 if (log)
2089 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2090 "register %" PRIu32 " returned NULL",
2091 __FUNCTION__, reg_index);
2092 return SendErrorResponse(0x48);
2093 }
2094
2095 // Return the end of registers response if we've iterated one past the end of
2096 // the register set.
2097 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2098 if (log)
2099 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2100 "register %" PRIu32 " beyond register count %" PRIu32,
2101 __FUNCTION__, reg_index,
2102 reg_context_sp->GetUserRegisterCount());
2103 return SendErrorResponse(0x47);
2104 }
2105
2106 // The dwarf expression are evaluate on host site
2107 // which may cause register size to change
2108 // Hence the reg_size may not be same as reg_info->bytes_size
2109 if ((reg_size != reg_info->byte_size) &&
2110 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2111 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2112 }
2113
2114 // Build the reginfos response.
2115 StreamGDBRemote response;
2116
2117 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
Zachary Turner97206d52017-05-12 04:51:55 +00002118 Status error = reg_context_sp->WriteRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002119 if (error.Fail()) {
2120 if (log)
2121 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2122 "requested register %" PRIu32 " (%s) failed: %s",
2123 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2124 return SendErrorResponse(0x32);
2125 }
2126
2127 return SendOKResponse();
2128}
2129
2130GDBRemoteCommunication::PacketResult
2131GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2132 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2133
2134 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002135 if (!m_debugged_process_up ||
2136 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002137 if (log)
2138 log->Printf(
2139 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2140 __FUNCTION__);
2141 return SendErrorResponse(0x15);
2142 }
2143
2144 // Parse out which variant of $H is requested.
2145 packet.SetFilePos(strlen("H"));
2146 if (packet.GetBytesLeft() < 1) {
2147 if (log)
2148 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2149 "missing {g,c} variant",
2150 __FUNCTION__);
2151 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2152 }
2153
2154 const char h_variant = packet.GetChar();
2155 switch (h_variant) {
2156 case 'g':
2157 break;
2158
2159 case 'c':
2160 break;
2161
2162 default:
2163 if (log)
2164 log->Printf(
2165 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2166 __FUNCTION__, h_variant);
2167 return SendIllFormedResponse(packet,
2168 "H variant unsupported, should be c or g");
2169 }
2170
2171 // Parse out the thread number.
2172 // FIXME return a parse success/fail value. All values are valid here.
2173 const lldb::tid_t tid =
2174 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2175
2176 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2177 // (any thread).
2178 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002179 NativeThreadProtocolSP thread_sp(m_debugged_process_up->GetThreadByID(tid));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180 if (!thread_sp) {
2181 if (log)
2182 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2183 " not found",
2184 __FUNCTION__, tid);
2185 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002186 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002187 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002188
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189 // Now switch the given thread type.
2190 switch (h_variant) {
2191 case 'g':
2192 SetCurrentThreadID(tid);
2193 break;
2194
2195 case 'c':
2196 SetContinueThreadID(tid);
2197 break;
2198
2199 default:
2200 assert(false && "unsupported $H variant - shouldn't get here");
2201 return SendIllFormedResponse(packet,
2202 "H variant unsupported, should be c or g");
2203 }
2204
2205 return SendOKResponse();
2206}
2207
2208GDBRemoteCommunication::PacketResult
2209GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2210 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2211
2212 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002213 if (!m_debugged_process_up ||
2214 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215 if (log)
2216 log->Printf(
2217 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2218 __FUNCTION__);
2219 return SendErrorResponse(0x15);
2220 }
2221
2222 packet.SetFilePos(::strlen("I"));
2223 uint8_t tmp[4096];
2224 for (;;) {
2225 size_t read = packet.GetHexBytesAvail(tmp);
2226 if (read == 0) {
2227 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002228 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229 // write directly to stdin *this might block if stdin buffer is full*
2230 // TODO: enqueue this block in circular buffer and send window size to
2231 // remote host
2232 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00002233 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 m_stdio_communication.Write(tmp, read, status, &error);
2235 if (error.Fail()) {
2236 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002237 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002239
Kate Stoneb9c1b512016-09-06 20:57:50 +00002240 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002241}
2242
2243GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2245 StringExtractorGDBRemote &packet) {
2246 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2247
2248 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002249 if (!m_debugged_process_up ||
2250 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2251 LLDB_LOG(log, "failed, no process available");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002252 return SendErrorResponse(0x15);
2253 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002254
Kate Stoneb9c1b512016-09-06 20:57:50 +00002255 // Interrupt the process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002256 Status error = m_debugged_process_up->Interrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002258 LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
2259 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002260 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2261 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002262
Pavel Labath82abefa2017-07-18 09:24:48 +00002263 LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002264
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 // No response required from stop all.
2266 return PacketResult::Success;
2267}
Tamas Berghammere13c2732015-02-11 10:29:30 +00002268
Kate Stoneb9c1b512016-09-06 20:57:50 +00002269GDBRemoteCommunication::PacketResult
2270GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2271 StringExtractorGDBRemote &packet) {
2272 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002273
Pavel Labath82abefa2017-07-18 09:24:48 +00002274 if (!m_debugged_process_up ||
2275 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002276 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002277 log->Printf(
2278 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2279 __FUNCTION__);
2280 return SendErrorResponse(0x15);
2281 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002282
Kate Stoneb9c1b512016-09-06 20:57:50 +00002283 // Parse out the memory address.
2284 packet.SetFilePos(strlen("m"));
2285 if (packet.GetBytesLeft() < 1)
2286 return SendIllFormedResponse(packet, "Too short m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002287
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288 // Read the address. Punting on validation.
2289 // FIXME replace with Hex U64 read with no default value that fails on failed
2290 // read.
2291 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002292
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293 // Validate comma.
2294 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2295 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002296
Kate Stoneb9c1b512016-09-06 20:57:50 +00002297 // Get # bytes to read.
2298 if (packet.GetBytesLeft() < 1)
2299 return SendIllFormedResponse(packet, "Length missing in m packet");
2300
2301 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2302 if (byte_count == 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002303 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002304 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2305 "zero-length packet",
2306 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002307 return SendOKResponse();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002308 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002309
Kate Stoneb9c1b512016-09-06 20:57:50 +00002310 // Allocate the response buffer.
2311 std::string buf(byte_count, '\0');
2312 if (buf.empty())
2313 return SendErrorResponse(0x78);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002314
Kate Stoneb9c1b512016-09-06 20:57:50 +00002315 // Retrieve the process memory.
2316 size_t bytes_read = 0;
Pavel Labath82abefa2017-07-18 09:24:48 +00002317 Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002318 read_addr, &buf[0], byte_count, bytes_read);
2319 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002320 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002321 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2322 " mem 0x%" PRIx64 ": failed to read. Error: %s",
Pavel Labath82abefa2017-07-18 09:24:48 +00002323 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 error.AsCString());
2325 return SendErrorResponse(0x08);
2326 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002327
Kate Stoneb9c1b512016-09-06 20:57:50 +00002328 if (bytes_read == 0) {
2329 if (log)
2330 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2331 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
Pavel Labath82abefa2017-07-18 09:24:48 +00002332 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002333 byte_count);
2334 return SendErrorResponse(0x08);
2335 }
2336
2337 StreamGDBRemote response;
2338 packet.SetFilePos(0);
2339 char kind = packet.GetChar('?');
2340 if (kind == 'x')
2341 response.PutEscapedBytes(buf.data(), byte_count);
2342 else {
2343 assert(kind == 'm');
2344 for (size_t i = 0; i < bytes_read; ++i)
2345 response.PutHex8(buf[i]);
2346 }
2347
2348 return SendPacketNoLock(response.GetString());
2349}
2350
2351GDBRemoteCommunication::PacketResult
2352GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2353 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2354
Pavel Labath82abefa2017-07-18 09:24:48 +00002355 if (!m_debugged_process_up ||
2356 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357 if (log)
2358 log->Printf(
2359 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2360 __FUNCTION__);
2361 return SendErrorResponse(0x15);
2362 }
2363
2364 // Parse out the memory address.
2365 packet.SetFilePos(strlen("M"));
2366 if (packet.GetBytesLeft() < 1)
2367 return SendIllFormedResponse(packet, "Too short M packet");
2368
2369 // Read the address. Punting on validation.
2370 // FIXME replace with Hex U64 read with no default value that fails on failed
2371 // read.
2372 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2373
2374 // Validate comma.
2375 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2376 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2377
2378 // Get # bytes to read.
2379 if (packet.GetBytesLeft() < 1)
2380 return SendIllFormedResponse(packet, "Length missing in M packet");
2381
2382 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2383 if (byte_count == 0) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002384 LLDB_LOG(log, "nothing to write: zero-length packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002385 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386 }
2387
2388 // Validate colon.
2389 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2390 return SendIllFormedResponse(
2391 packet, "Comma sep missing in M packet after byte length");
2392
2393 // Allocate the conversion buffer.
2394 std::vector<uint8_t> buf(byte_count, 0);
2395 if (buf.empty())
2396 return SendErrorResponse(0x78);
2397
2398 // Convert the hex memory write contents to bytes.
2399 StreamGDBRemote response;
2400 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2401 if (convert_count != byte_count) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002402 LLDB_LOG(log,
2403 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2404 "to convert.",
2405 m_debugged_process_up->GetID(), write_addr, byte_count,
2406 convert_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 return SendIllFormedResponse(packet, "M content byte length specified did "
2408 "not match hex-encoded content "
2409 "length");
2410 }
2411
2412 // Write the process memory.
2413 size_t bytes_written = 0;
Pavel Labath82abefa2017-07-18 09:24:48 +00002414 Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
Zachary Turner97206d52017-05-12 04:51:55 +00002415 byte_count, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002417 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2418 m_debugged_process_up->GetID(), write_addr, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419 return SendErrorResponse(0x09);
2420 }
2421
2422 if (bytes_written == 0) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002423 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2424 m_debugged_process_up->GetID(), write_addr, byte_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002425 return SendErrorResponse(0x09);
2426 }
2427
2428 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002429}
2430
2431GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002432GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2433 StringExtractorGDBRemote &packet) {
2434 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002435
Kate Stoneb9c1b512016-09-06 20:57:50 +00002436 // Currently only the NativeProcessProtocol knows if it can handle a
2437 // qMemoryRegionInfoSupported
2438 // request, but we're not guaranteed to be attached to a process. For now
2439 // we'll assume the
2440 // client only asks this when a process is being debugged.
Tamas Berghammere13c2732015-02-11 10:29:30 +00002441
Kate Stoneb9c1b512016-09-06 20:57:50 +00002442 // Ensure we have a process running; otherwise, we can't figure this out
2443 // since we won't have a NativeProcessProtocol.
Pavel Labath82abefa2017-07-18 09:24:48 +00002444 if (!m_debugged_process_up ||
2445 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002446 if (log)
2447 log->Printf(
2448 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2449 __FUNCTION__);
2450 return SendErrorResponse(0x15);
2451 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002452
Kate Stoneb9c1b512016-09-06 20:57:50 +00002453 // Test if we can get any region back when asking for the region around NULL.
2454 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002455 const Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00002456 m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002457 if (error.Fail()) {
2458 // We don't support memory region info collection for this
2459 // NativeProcessProtocol.
2460 return SendUnimplementedResponse("");
2461 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002462
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002464}
2465
2466GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2468 StringExtractorGDBRemote &packet) {
2469 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002470
Kate Stoneb9c1b512016-09-06 20:57:50 +00002471 // Ensure we have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002472 if (!m_debugged_process_up ||
2473 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474 if (log)
2475 log->Printf(
2476 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2477 __FUNCTION__);
2478 return SendErrorResponse(0x15);
2479 }
2480
2481 // Parse out the memory address.
2482 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2483 if (packet.GetBytesLeft() < 1)
2484 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2485
2486 // Read the address. Punting on validation.
2487 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2488
2489 StreamGDBRemote response;
2490
2491 // Get the memory region info for the target address.
2492 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002493 const Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00002494 m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002495 if (error.Fail()) {
2496 // Return the error message.
2497
2498 response.PutCString("error:");
2499 response.PutCStringAsRawHex8(error.AsCString());
2500 response.PutChar(';');
2501 } else {
2502 // Range start and size.
2503 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2504 region_info.GetRange().GetRangeBase(),
2505 region_info.GetRange().GetByteSize());
2506
2507 // Permissions.
2508 if (region_info.GetReadable() || region_info.GetWritable() ||
2509 region_info.GetExecutable()) {
2510 // Write permissions info.
2511 response.PutCString("permissions:");
2512
2513 if (region_info.GetReadable())
2514 response.PutChar('r');
2515 if (region_info.GetWritable())
2516 response.PutChar('w');
2517 if (region_info.GetExecutable())
2518 response.PutChar('x');
2519
2520 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002521 }
2522
Kate Stoneb9c1b512016-09-06 20:57:50 +00002523 // Name
2524 ConstString name = region_info.GetName();
2525 if (name) {
2526 response.PutCString("name:");
2527 response.PutCStringAsRawHex8(name.AsCString());
2528 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002529 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002531
Kate Stoneb9c1b512016-09-06 20:57:50 +00002532 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002533}
2534
2535GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2537 // Ensure we have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002538 if (!m_debugged_process_up ||
2539 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002540 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002541 LLDB_LOG(log, "failed, no process available");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002542 return SendErrorResponse(0x15);
2543 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002544
Kate Stoneb9c1b512016-09-06 20:57:50 +00002545 // Parse out software or hardware breakpoint or watchpoint requested.
2546 packet.SetFilePos(strlen("Z"));
2547 if (packet.GetBytesLeft() < 1)
2548 return SendIllFormedResponse(
2549 packet, "Too short Z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002550
Kate Stoneb9c1b512016-09-06 20:57:50 +00002551 bool want_breakpoint = true;
2552 bool want_hardware = false;
2553 uint32_t watch_flags = 0;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002554
Kate Stoneb9c1b512016-09-06 20:57:50 +00002555 const GDBStoppointType stoppoint_type =
2556 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2557 switch (stoppoint_type) {
2558 case eBreakpointSoftware:
2559 want_hardware = false;
2560 want_breakpoint = true;
2561 break;
2562 case eBreakpointHardware:
2563 want_hardware = true;
2564 want_breakpoint = true;
2565 break;
2566 case eWatchpointWrite:
2567 watch_flags = 1;
2568 want_hardware = true;
2569 want_breakpoint = false;
2570 break;
2571 case eWatchpointRead:
2572 watch_flags = 2;
2573 want_hardware = true;
2574 want_breakpoint = false;
2575 break;
2576 case eWatchpointReadWrite:
2577 watch_flags = 3;
2578 want_hardware = true;
2579 want_breakpoint = false;
2580 break;
2581 case eStoppointInvalid:
2582 return SendIllFormedResponse(
2583 packet, "Z packet had invalid software/hardware specifier");
2584 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002585
Kate Stoneb9c1b512016-09-06 20:57:50 +00002586 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2587 return SendIllFormedResponse(
2588 packet, "Malformed Z packet, expecting comma after stoppoint type");
2589
2590 // Parse out the stoppoint address.
2591 if (packet.GetBytesLeft() < 1)
2592 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2593 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2594
2595 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2596 return SendIllFormedResponse(
2597 packet, "Malformed Z packet, expecting comma after address");
2598
2599 // Parse out the stoppoint size (i.e. size hint for opcode size).
2600 const uint32_t size =
2601 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2602 if (size == std::numeric_limits<uint32_t>::max())
2603 return SendIllFormedResponse(
2604 packet, "Malformed Z packet, failed to parse size argument");
2605
2606 if (want_breakpoint) {
2607 // Try to set the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002608 const Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00002609 m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002610 if (error.Success())
2611 return SendOKResponse();
2612 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002613 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2614 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002615 return SendErrorResponse(0x09);
2616 } else {
2617 // Try to set the watchpoint.
Pavel Labath82abefa2017-07-18 09:24:48 +00002618 const Status error = m_debugged_process_up->SetWatchpoint(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002619 addr, size, watch_flags, want_hardware);
2620 if (error.Success())
2621 return SendOKResponse();
2622 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002623 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2624 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002625 return SendErrorResponse(0x09);
2626 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002627}
2628
2629GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002630GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2631 // Ensure we have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002632 if (!m_debugged_process_up ||
2633 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002635 LLDB_LOG(log, "failed, no process available");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002636 return SendErrorResponse(0x15);
2637 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002638
Kate Stoneb9c1b512016-09-06 20:57:50 +00002639 // Parse out software or hardware breakpoint or watchpoint requested.
2640 packet.SetFilePos(strlen("z"));
2641 if (packet.GetBytesLeft() < 1)
2642 return SendIllFormedResponse(
2643 packet, "Too short z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002644
Kate Stoneb9c1b512016-09-06 20:57:50 +00002645 bool want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002646 bool want_hardware = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002647
Kate Stoneb9c1b512016-09-06 20:57:50 +00002648 const GDBStoppointType stoppoint_type =
2649 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2650 switch (stoppoint_type) {
2651 case eBreakpointHardware:
2652 want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002653 want_hardware = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654 break;
2655 case eBreakpointSoftware:
2656 want_breakpoint = true;
2657 break;
2658 case eWatchpointWrite:
2659 want_breakpoint = false;
2660 break;
2661 case eWatchpointRead:
2662 want_breakpoint = false;
2663 break;
2664 case eWatchpointReadWrite:
2665 want_breakpoint = false;
2666 break;
2667 default:
2668 return SendIllFormedResponse(
2669 packet, "z packet had invalid software/hardware specifier");
2670 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002671
Kate Stoneb9c1b512016-09-06 20:57:50 +00002672 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2673 return SendIllFormedResponse(
2674 packet, "Malformed z packet, expecting comma after stoppoint type");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002675
Kate Stoneb9c1b512016-09-06 20:57:50 +00002676 // Parse out the stoppoint address.
2677 if (packet.GetBytesLeft() < 1)
2678 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2679 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002680
Kate Stoneb9c1b512016-09-06 20:57:50 +00002681 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2682 return SendIllFormedResponse(
2683 packet, "Malformed z packet, expecting comma after address");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002684
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685 /*
2686 // Parse out the stoppoint size (i.e. size hint for opcode size).
2687 const uint32_t size = packet.GetHexMaxU32 (false,
2688 std::numeric_limits<uint32_t>::max ());
2689 if (size == std::numeric_limits<uint32_t>::max ())
2690 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2691 size argument");
2692 */
Tamas Berghammere13c2732015-02-11 10:29:30 +00002693
Kate Stoneb9c1b512016-09-06 20:57:50 +00002694 if (want_breakpoint) {
2695 // Try to clear the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002696 const Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00002697 m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002698 if (error.Success())
2699 return SendOKResponse();
2700 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002701 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2702 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703 return SendErrorResponse(0x09);
2704 } else {
2705 // Try to clear the watchpoint.
Pavel Labath82abefa2017-07-18 09:24:48 +00002706 const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002707 if (error.Success())
2708 return SendOKResponse();
2709 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002710 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2711 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712 return SendErrorResponse(0x09);
2713 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002714}
2715
2716GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002717GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2718 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002719
Kate Stoneb9c1b512016-09-06 20:57:50 +00002720 // Ensure we have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002721 if (!m_debugged_process_up ||
2722 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723 if (log)
2724 log->Printf(
2725 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2726 __FUNCTION__);
2727 return SendErrorResponse(0x32);
2728 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002729
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 // We first try to use a continue thread id. If any one or any all set, use
2731 // the current thread.
2732 // Bail out if we don't have a thread id.
2733 lldb::tid_t tid = GetContinueThreadID();
2734 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2735 tid = GetCurrentThreadID();
2736 if (tid == LLDB_INVALID_THREAD_ID)
2737 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002738
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739 // Double check that we have such a thread.
2740 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
Pavel Labath82abefa2017-07-18 09:24:48 +00002741 NativeThreadProtocolSP thread_sp = m_debugged_process_up->GetThreadByID(tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742 if (!thread_sp || thread_sp->GetID() != tid)
2743 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002744
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745 // Create the step action for the given thread.
2746 ResumeAction action = {tid, eStateStepping, 0};
Tamas Berghammere13c2732015-02-11 10:29:30 +00002747
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 // Setup the actions list.
2749 ResumeActionList actions;
2750 actions.Append(action);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002751
Kate Stoneb9c1b512016-09-06 20:57:50 +00002752 // All other threads stop while we're single stepping a thread.
2753 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
Pavel Labath82abefa2017-07-18 09:24:48 +00002754 Status error = m_debugged_process_up->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002755 if (error.Fail()) {
2756 if (log)
2757 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2758 " tid %" PRIu64 " Resume() failed with error: %s",
Pavel Labath82abefa2017-07-18 09:24:48 +00002759 __FUNCTION__, m_debugged_process_up->GetID(), tid,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 error.AsCString());
2761 return SendErrorResponse(0x49);
2762 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002763
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 // No response here - the stop or exit will come from the resulting action.
2765 return PacketResult::Success;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002766}
2767
2768GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002769GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2770 StringExtractorGDBRemote &packet) {
2771// *BSD impls should be able to do this too.
Kamil Rytarowskic93408a2017-03-21 17:27:59 +00002772#if defined(__linux__) || defined(__NetBSD__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002774
Kate Stoneb9c1b512016-09-06 20:57:50 +00002775 // Parse out the offset.
2776 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2777 if (packet.GetBytesLeft() < 1)
2778 return SendIllFormedResponse(packet,
2779 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002780
Kate Stoneb9c1b512016-09-06 20:57:50 +00002781 const uint64_t auxv_offset =
2782 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2783 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2784 return SendIllFormedResponse(packet,
2785 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002786
Kate Stoneb9c1b512016-09-06 20:57:50 +00002787 // Parse out comma.
2788 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2789 return SendIllFormedResponse(
2790 packet, "qXfer:auxv:read:: packet missing comma after offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002791
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 // Parse out the length.
2793 const uint64_t auxv_length =
2794 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2795 if (auxv_length == std::numeric_limits<uint64_t>::max())
2796 return SendIllFormedResponse(packet,
2797 "qXfer:auxv:read:: packet missing length");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002798
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 // Grab the auxv data if we need it.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002800 if (!m_active_auxv_buffer_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 // Make sure we have a valid process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002802 if (!m_debugged_process_up ||
2803 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 if (log)
2805 log->Printf(
2806 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2807 __FUNCTION__);
2808 return SendErrorResponse(0x10);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002809 }
2810
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811 // Grab the auxv data.
Pavel Labath82abefa2017-07-18 09:24:48 +00002812 auto buffer_or_error = m_debugged_process_up->GetAuxvData();
Pavel Labathb7f0f452017-03-17 11:08:40 +00002813 if (!buffer_or_error) {
2814 std::error_code ec = buffer_or_error.getError();
2815 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2816 return SendErrorResponse(ec.value());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002817 }
Pavel Labathb7f0f452017-03-17 11:08:40 +00002818 m_active_auxv_buffer_up = std::move(*buffer_or_error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002819 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002820
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 StreamGDBRemote response;
2822 bool done_with_buffer = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002823
Pavel Labathb7f0f452017-03-17 11:08:40 +00002824 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2825 if (auxv_offset >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 // We have nothing left to send. Mark the buffer as complete.
2827 response.PutChar('l');
2828 done_with_buffer = true;
2829 } else {
2830 // Figure out how many bytes are available starting at the given offset.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002831 buffer = buffer.drop_front(auxv_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002832
2833 // Mark the response type according to whether we're reading the remainder
2834 // of the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002835 if (auxv_length >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836 // There will be nothing left to read after this
2837 response.PutChar('l');
2838 done_with_buffer = true;
2839 } else {
2840 // There will still be bytes to read after this request.
2841 response.PutChar('m');
Pavel Labathb7f0f452017-03-17 11:08:40 +00002842 buffer = buffer.take_front(auxv_length);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002843 }
2844
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 // Now write the data in encoded binary form.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002846 response.PutEscapedBytes(buffer.data(), buffer.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002848
Kate Stoneb9c1b512016-09-06 20:57:50 +00002849 if (done_with_buffer)
Pavel Labathb7f0f452017-03-17 11:08:40 +00002850 m_active_auxv_buffer_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002851
2852 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002853#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854 return SendUnimplementedResponse("not implemented on this platform");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002855#endif
2856}
2857
2858GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2860 StringExtractorGDBRemote &packet) {
2861 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002862
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863 // Move past packet name.
2864 packet.SetFilePos(strlen("QSaveRegisterState"));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002865
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 // Get the thread to use.
2867 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2868 if (!thread_sp) {
2869 if (m_thread_suffix_supported)
2870 return SendIllFormedResponse(
2871 packet, "No thread specified in QSaveRegisterState packet");
2872 else
2873 return SendIllFormedResponse(packet,
2874 "No thread was is set with the Hg packet");
2875 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002876
Kate Stoneb9c1b512016-09-06 20:57:50 +00002877 // Grab the register context for the thread.
2878 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2879 if (!reg_context_sp) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002880 LLDB_LOG(
2881 log,
2882 "pid {0} tid {1} failed, no register context available for the thread",
2883 m_debugged_process_up->GetID(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002884 return SendErrorResponse(0x15);
2885 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002886
Kate Stoneb9c1b512016-09-06 20:57:50 +00002887 // Save registers to a buffer.
2888 DataBufferSP register_data_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00002889 Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002891 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
2892 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002893 return SendErrorResponse(0x75);
2894 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002895
Kate Stoneb9c1b512016-09-06 20:57:50 +00002896 // Allocate a new save id.
2897 const uint32_t save_id = GetNextSavedRegistersID();
2898 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2899 "GetNextRegisterSaveID() returned an existing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002900
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 // Save the register data buffer under the save id.
2902 {
2903 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2904 m_saved_registers_map[save_id] = register_data_sp;
2905 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002906
Kate Stoneb9c1b512016-09-06 20:57:50 +00002907 // Write the response.
2908 StreamGDBRemote response;
2909 response.Printf("%" PRIu32, save_id);
2910 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002911}
2912
2913GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002914GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
2915 StringExtractorGDBRemote &packet) {
2916 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002917
Kate Stoneb9c1b512016-09-06 20:57:50 +00002918 // Parse out save id.
2919 packet.SetFilePos(strlen("QRestoreRegisterState:"));
2920 if (packet.GetBytesLeft() < 1)
2921 return SendIllFormedResponse(
2922 packet, "QRestoreRegisterState packet missing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002923
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 const uint32_t save_id = packet.GetU32(0);
2925 if (save_id == 0) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002926 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
2927 "expecting decimal uint32_t");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002928 return SendErrorResponse(0x76);
2929 }
2930
2931 // Get the thread to use.
2932 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2933 if (!thread_sp) {
2934 if (m_thread_suffix_supported)
2935 return SendIllFormedResponse(
2936 packet, "No thread specified in QRestoreRegisterState packet");
2937 else
2938 return SendIllFormedResponse(packet,
2939 "No thread was is set with the Hg packet");
2940 }
2941
2942 // Grab the register context for the thread.
2943 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2944 if (!reg_context_sp) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002945 LLDB_LOG(
2946 log,
2947 "pid {0} tid {1} failed, no register context available for the thread",
2948 m_debugged_process_up->GetID(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002949 return SendErrorResponse(0x15);
2950 }
2951
2952 // Retrieve register state buffer, then remove from the list.
2953 DataBufferSP register_data_sp;
2954 {
2955 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2956
2957 // Find the register set buffer for the given save id.
2958 auto it = m_saved_registers_map.find(save_id);
2959 if (it == m_saved_registers_map.end()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002960 LLDB_LOG(log,
2961 "pid {0} does not have a register set save buffer for id {1}",
2962 m_debugged_process_up->GetID(), save_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002963 return SendErrorResponse(0x77);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002964 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002965 register_data_sp = it->second;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002966
Kate Stoneb9c1b512016-09-06 20:57:50 +00002967 // Remove it from the map.
2968 m_saved_registers_map.erase(it);
2969 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002970
Zachary Turner97206d52017-05-12 04:51:55 +00002971 Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002972 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002973 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
2974 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 return SendErrorResponse(0x77);
2976 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002977
Kate Stoneb9c1b512016-09-06 20:57:50 +00002978 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002979}
2980
2981GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982GDBRemoteCommunicationServerLLGS::Handle_vAttach(
2983 StringExtractorGDBRemote &packet) {
2984 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002985
Kate Stoneb9c1b512016-09-06 20:57:50 +00002986 // Consume the ';' after vAttach.
2987 packet.SetFilePos(strlen("vAttach"));
2988 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2989 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002990
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 // Grab the PID to which we will attach (assume hex encoding).
2992 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2993 if (pid == LLDB_INVALID_PROCESS_ID)
2994 return SendIllFormedResponse(packet,
2995 "vAttach failed to parse the process id");
2996
2997 // Attempt to attach.
2998 if (log)
2999 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3000 "pid %" PRIu64,
3001 __FUNCTION__, pid);
3002
Zachary Turner97206d52017-05-12 04:51:55 +00003003 Status error = AttachToProcess(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003004
3005 if (error.Fail()) {
3006 if (log)
3007 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3008 "pid %" PRIu64 ": %s\n",
3009 __FUNCTION__, pid, error.AsCString());
3010 return SendErrorResponse(0x01);
3011 }
3012
3013 // Notify we attached by sending a stop packet.
Pavel Labath82abefa2017-07-18 09:24:48 +00003014 return SendStopReasonForState(m_debugged_process_up->GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015}
3016
3017GDBRemoteCommunication::PacketResult
3018GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3019 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3020
3021 StopSTDIOForwarding();
3022
3023 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003024 if (!m_debugged_process_up ||
3025 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 if (log)
3027 log->Printf(
3028 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3029 __FUNCTION__);
3030 return SendErrorResponse(0x15);
3031 }
3032
3033 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3034
3035 // Consume the ';' after D.
3036 packet.SetFilePos(1);
3037 if (packet.GetBytesLeft()) {
3038 if (packet.GetChar() != ';')
3039 return SendIllFormedResponse(packet, "D missing expected ';'");
3040
3041 // Grab the PID from which we will detach (assume hex encoding).
3042 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003043 if (pid == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003044 return SendIllFormedResponse(packet, "D failed to parse the process id");
3045 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003046
Pavel Labath82abefa2017-07-18 09:24:48 +00003047 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 return SendIllFormedResponse(packet, "Invalid pid");
3049 }
3050
Pavel Labath82abefa2017-07-18 09:24:48 +00003051 const Status error = m_debugged_process_up->Detach();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003052 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003053 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003054 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3055 "pid %" PRIu64 ": %s\n",
Pavel Labath82abefa2017-07-18 09:24:48 +00003056 __FUNCTION__, m_debugged_process_up->GetID(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003057 error.AsCString());
3058 return SendErrorResponse(0x01);
3059 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003060
Kate Stoneb9c1b512016-09-06 20:57:50 +00003061 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003062}
3063
3064GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003065GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3066 StringExtractorGDBRemote &packet) {
3067 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003068
Kate Stoneb9c1b512016-09-06 20:57:50 +00003069 packet.SetFilePos(strlen("qThreadStopInfo"));
3070 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3071 if (tid == LLDB_INVALID_THREAD_ID) {
Pavel Labath4a4bb122015-07-16 14:14:35 +00003072 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003073 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3074 "parse thread id from request \"%s\"",
3075 __FUNCTION__, packet.GetStringRef().c_str());
3076 return SendErrorResponse(0x15);
3077 }
3078 return SendStopReplyPacketForThread(tid);
3079}
3080
3081GDBRemoteCommunication::PacketResult
3082GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3083 StringExtractorGDBRemote &) {
3084 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3085
3086 // Ensure we have a debugged process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003087 if (!m_debugged_process_up ||
3088 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +00003089 return SendErrorResponse(50);
Pavel Labath82abefa2017-07-18 09:24:48 +00003090 LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
Pavel Labath4a4bb122015-07-16 14:14:35 +00003091
Kate Stoneb9c1b512016-09-06 20:57:50 +00003092 StreamString response;
3093 const bool threads_with_valid_stop_info_only = false;
3094 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
Pavel Labath82abefa2017-07-18 09:24:48 +00003095 *m_debugged_process_up, threads_with_valid_stop_info_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096 if (!threads_array_sp) {
Pavel Labath82abefa2017-07-18 09:24:48 +00003097 LLDB_LOG(log, "failed to prepare a packet for pid {0}",
3098 m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 return SendErrorResponse(52);
3100 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00003101
Kate Stoneb9c1b512016-09-06 20:57:50 +00003102 threads_array_sp->Write(response);
3103 StreamGDBRemote escaped_response;
3104 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3105 return SendPacketNoLock(escaped_response.GetString());
Pavel Labath4a4bb122015-07-16 14:14:35 +00003106}
3107
3108GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003109GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3110 StringExtractorGDBRemote &packet) {
3111 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003112 if (!m_debugged_process_up ||
3113 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003114 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003115
Kate Stoneb9c1b512016-09-06 20:57:50 +00003116 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3117 if (packet.GetBytesLeft() == 0)
3118 return SendOKResponse();
3119 if (packet.GetChar() != ':')
3120 return SendErrorResponse(67);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003121
Pavel Labath82abefa2017-07-18 09:24:48 +00003122 auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003123
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124 StreamGDBRemote response;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003125 if (hw_debug_cap == llvm::None)
3126 response.Printf("num:0;");
3127 else
3128 response.Printf("num:%d;", hw_debug_cap->second);
3129
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003131}
3132
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003133GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3135 StringExtractorGDBRemote &packet) {
3136 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003137 if (!m_debugged_process_up ||
3138 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 return SendErrorResponse(67);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003140
Kate Stoneb9c1b512016-09-06 20:57:50 +00003141 packet.SetFilePos(strlen("qFileLoadAddress:"));
3142 if (packet.GetBytesLeft() == 0)
3143 return SendErrorResponse(68);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003144
Kate Stoneb9c1b512016-09-06 20:57:50 +00003145 std::string file_name;
3146 packet.GetHexByteString(file_name);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003147
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00003149 Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00003150 m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003151 if (error.Fail())
3152 return SendErrorResponse(69);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003153
Kate Stoneb9c1b512016-09-06 20:57:50 +00003154 if (file_load_address == LLDB_INVALID_ADDRESS)
3155 return SendErrorResponse(1); // File not loaded
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003156
Kate Stoneb9c1b512016-09-06 20:57:50 +00003157 StreamGDBRemote response;
3158 response.PutHex64(file_load_address);
3159 return SendPacketNoLock(response.GetString());
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003160}
3161
Pavel Labath4a705e72017-02-24 09:29:14 +00003162GDBRemoteCommunication::PacketResult
3163GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3164 StringExtractorGDBRemote &packet) {
3165 std::vector<int> signals;
3166 packet.SetFilePos(strlen("QPassSignals:"));
3167
3168 // Read sequence of hex signal numbers divided by a semicolon and
3169 // optionally spaces.
3170 while (packet.GetBytesLeft() > 0) {
3171 int signal = packet.GetS32(-1, 16);
3172 if (signal < 0)
3173 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3174 signals.push_back(signal);
3175
3176 packet.SkipSpaces();
3177 char separator = packet.GetChar();
3178 if (separator == '\0')
3179 break; // End of string
3180 if (separator != ';')
3181 return SendIllFormedResponse(packet, "Invalid separator,"
3182 " expected semicolon.");
3183 }
3184
3185 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003186 if (!m_debugged_process_up)
Pavel Labath4a705e72017-02-24 09:29:14 +00003187 return SendErrorResponse(68);
3188
Pavel Labath82abefa2017-07-18 09:24:48 +00003189 Status error = m_debugged_process_up->IgnoreSignals(signals);
Pavel Labath4a705e72017-02-24 09:29:14 +00003190 if (error.Fail())
3191 return SendErrorResponse(69);
3192
3193 return SendOKResponse();
3194}
3195
Kate Stoneb9c1b512016-09-06 20:57:50 +00003196void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3197 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003198
Kate Stoneb9c1b512016-09-06 20:57:50 +00003199 // Tell the stdio connection to shut down.
3200 if (m_stdio_communication.IsConnected()) {
3201 auto connection = m_stdio_communication.GetConnection();
3202 if (connection) {
Zachary Turner97206d52017-05-12 04:51:55 +00003203 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003204 connection->Disconnect(&error);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003205
Kate Stoneb9c1b512016-09-06 20:57:50 +00003206 if (error.Success()) {
3207 if (log)
3208 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3209 "terminal stdio - SUCCESS",
3210 __FUNCTION__);
3211 } else {
3212 if (log)
3213 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3214 "terminal stdio - FAIL: %s",
3215 __FUNCTION__, error.AsCString());
3216 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003217 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003218 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003219}
3220
Kate Stoneb9c1b512016-09-06 20:57:50 +00003221NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3222 StringExtractorGDBRemote &packet) {
3223 NativeThreadProtocolSP thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003224
Kate Stoneb9c1b512016-09-06 20:57:50 +00003225 // We have no thread if we don't have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003226 if (!m_debugged_process_up ||
3227 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
Tamas Berghammere13c2732015-02-11 10:29:30 +00003228 return thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003229
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230 // If the client hasn't asked for thread suffix support, there will not be a
3231 // thread suffix.
3232 // Use the current thread in that case.
3233 if (!m_thread_suffix_supported) {
3234 const lldb::tid_t current_tid = GetCurrentThreadID();
3235 if (current_tid == LLDB_INVALID_THREAD_ID)
3236 return thread_sp;
3237 else if (current_tid == 0) {
3238 // Pick a thread.
Pavel Labath82abefa2017-07-18 09:24:48 +00003239 return m_debugged_process_up->GetThreadAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003240 } else
Pavel Labath82abefa2017-07-18 09:24:48 +00003241 return m_debugged_process_up->GetThreadByID(current_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003242 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003243
Kate Stoneb9c1b512016-09-06 20:57:50 +00003244 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003245
Kate Stoneb9c1b512016-09-06 20:57:50 +00003246 // Parse out the ';'.
3247 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003248 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003249 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3250 "error: expected ';' prior to start of thread suffix: packet "
3251 "contents = '%s'",
3252 __FUNCTION__, packet.GetStringRef().c_str());
3253 return thread_sp;
3254 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003255
Kate Stoneb9c1b512016-09-06 20:57:50 +00003256 if (!packet.GetBytesLeft())
3257 return thread_sp;
3258
3259 // Parse out thread: portion.
3260 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3261 if (log)
3262 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3263 "error: expected 'thread:' but not found, packet contents = "
3264 "'%s'",
3265 __FUNCTION__, packet.GetStringRef().c_str());
3266 return thread_sp;
3267 }
3268 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3269 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3270 if (tid != 0)
Pavel Labath82abefa2017-07-18 09:24:48 +00003271 return m_debugged_process_up->GetThreadByID(tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003272
3273 return thread_sp;
3274}
3275
3276lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3277 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3278 // Use whatever the debug process says is the current thread id
3279 // since the protocol either didn't specify or specified we want
3280 // any/all threads marked as the current thread.
Pavel Labath82abefa2017-07-18 09:24:48 +00003281 if (!m_debugged_process_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003282 return LLDB_INVALID_THREAD_ID;
Pavel Labath82abefa2017-07-18 09:24:48 +00003283 return m_debugged_process_up->GetCurrentThreadID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003284 }
3285 // Use the specific current thread id set by the gdb remote protocol.
3286 return m_current_tid;
3287}
3288
3289uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3290 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3291 return m_next_saved_registers_id++;
3292}
3293
3294void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
Pavel Labathb7f0f452017-03-17 11:08:40 +00003295 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003296
Pavel Labathb7f0f452017-03-17 11:08:40 +00003297 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3298 m_active_auxv_buffer_up.reset();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003299}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003300
3301FileSpec
Kate Stoneb9c1b512016-09-06 20:57:50 +00003302GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3303 const ArchSpec &arch) {
Pavel Labath82abefa2017-07-18 09:24:48 +00003304 if (m_debugged_process_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003305 FileSpec file_spec;
Pavel Labath82abefa2017-07-18 09:24:48 +00003306 if (m_debugged_process_up
Kate Stoneb9c1b512016-09-06 20:57:50 +00003307 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3308 .Success()) {
3309 if (file_spec.Exists())
3310 return file_spec;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003311 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003312 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003313
Kate Stoneb9c1b512016-09-06 20:57:50 +00003314 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003315}