1 //===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include <cerrno>
10
11 #include "lldb/Host/Config.h"
12
13
14 #include <chrono>
15 #include <cstring>
16 #include <limits>
17 #include <thread>
18
19 #include "GDBRemoteCommunicationServerLLGS.h"
20 #include "lldb/Host/ConnectionFileDescriptor.h"
21 #include "lldb/Host/Debug.h"
22 #include "lldb/Host/File.h"
23 #include "lldb/Host/FileAction.h"
24 #include "lldb/Host/FileSystem.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/HostInfo.h"
27 #include "lldb/Host/PosixApi.h"
28 #include "lldb/Host/Socket.h"
29 #include "lldb/Host/common/NativeProcessProtocol.h"
30 #include "lldb/Host/common/NativeRegisterContext.h"
31 #include "lldb/Host/common/NativeThreadProtocol.h"
32 #include "lldb/Target/MemoryRegionInfo.h"
33 #include "lldb/Utility/Args.h"
34 #include "lldb/Utility/DataBuffer.h"
35 #include "lldb/Utility/Endian.h"
36 #include "lldb/Utility/GDBRemote.h"
37 #include "lldb/Utility/LLDBAssert.h"
38 #include "lldb/Utility/LLDBLog.h"
39 #include "lldb/Utility/Log.h"
40 #include "lldb/Utility/RegisterValue.h"
41 #include "lldb/Utility/State.h"
42 #include "lldb/Utility/StreamString.h"
43 #include "lldb/Utility/UnimplementedError.h"
44 #include "lldb/Utility/UriParser.h"
45 #include "llvm/ADT/Triple.h"
46 #include "llvm/Support/JSON.h"
47 #include "llvm/Support/ScopedPrinter.h"
48
49 #include "ProcessGDBRemote.h"
50 #include "ProcessGDBRemoteLog.h"
51 #include "lldb/Utility/StringExtractorGDBRemote.h"
52
53 using namespace lldb;
54 using namespace lldb_private;
55 using namespace lldb_private::process_gdb_remote;
56 using namespace llvm;
57
58 // GDBRemote Errors
59
60 namespace {
61 enum GDBRemoteServerError {
62 // Set to the first unused error number in literal form below
63 eErrorFirst = 29,
64 eErrorNoProcess = eErrorFirst,
65 eErrorResume,
66 eErrorExitStatus
67 };
68 }
69
70 // GDBRemoteCommunicationServerLLGS constructor
GDBRemoteCommunicationServerLLGS(MainLoop & mainloop,const NativeProcessProtocol::Factory & process_factory)71 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
72 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
73 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
74 "gdb-remote.server.rx_packet"),
75 m_mainloop(mainloop), m_process_factory(process_factory),
76 m_current_process(nullptr), m_continue_process(nullptr),
77 m_stdio_communication("process.stdio") {
78 RegisterPacketHandlers();
79 }
80
RegisterPacketHandlers()81 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
82 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
83 &GDBRemoteCommunicationServerLLGS::Handle_C);
84 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
85 &GDBRemoteCommunicationServerLLGS::Handle_c);
86 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
87 &GDBRemoteCommunicationServerLLGS::Handle_D);
88 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
89 &GDBRemoteCommunicationServerLLGS::Handle_H);
90 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
91 &GDBRemoteCommunicationServerLLGS::Handle_I);
92 RegisterMemberFunctionHandler(
93 StringExtractorGDBRemote::eServerPacketType_interrupt,
94 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
95 RegisterMemberFunctionHandler(
96 StringExtractorGDBRemote::eServerPacketType_m,
97 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
98 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
99 &GDBRemoteCommunicationServerLLGS::Handle_M);
100 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M,
101 &GDBRemoteCommunicationServerLLGS::Handle__M);
102 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m,
103 &GDBRemoteCommunicationServerLLGS::Handle__m);
104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
105 &GDBRemoteCommunicationServerLLGS::Handle_p);
106 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
107 &GDBRemoteCommunicationServerLLGS::Handle_P);
108 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
109 &GDBRemoteCommunicationServerLLGS::Handle_qC);
110 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_T,
111 &GDBRemoteCommunicationServerLLGS::Handle_T);
112 RegisterMemberFunctionHandler(
113 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
114 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
115 RegisterMemberFunctionHandler(
116 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
117 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
118 RegisterMemberFunctionHandler(
119 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
120 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
121 RegisterMemberFunctionHandler(
122 StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported,
123 &GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported);
124 RegisterMemberFunctionHandler(
125 StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply,
126 &GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply);
127 RegisterMemberFunctionHandler(
128 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
129 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
130 RegisterMemberFunctionHandler(
131 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
132 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
133 RegisterMemberFunctionHandler(
134 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
135 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
136 RegisterMemberFunctionHandler(
137 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
138 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
139 RegisterMemberFunctionHandler(
140 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
141 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
142 RegisterMemberFunctionHandler(
143 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
144 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
145 RegisterMemberFunctionHandler(
146 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
147 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
148 RegisterMemberFunctionHandler(
149 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
150 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
151 RegisterMemberFunctionHandler(
152 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
153 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
154 RegisterMemberFunctionHandler(
155 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
156 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
157 RegisterMemberFunctionHandler(
158 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
159 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
160 RegisterMemberFunctionHandler(
161 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
162 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
163 RegisterMemberFunctionHandler(
164 StringExtractorGDBRemote::eServerPacketType_qXfer,
165 &GDBRemoteCommunicationServerLLGS::Handle_qXfer);
166 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
167 &GDBRemoteCommunicationServerLLGS::Handle_s);
168 RegisterMemberFunctionHandler(
169 StringExtractorGDBRemote::eServerPacketType_stop_reason,
170 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
171 RegisterMemberFunctionHandler(
172 StringExtractorGDBRemote::eServerPacketType_vAttach,
173 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
174 RegisterMemberFunctionHandler(
175 StringExtractorGDBRemote::eServerPacketType_vAttachWait,
176 &GDBRemoteCommunicationServerLLGS::Handle_vAttachWait);
177 RegisterMemberFunctionHandler(
178 StringExtractorGDBRemote::eServerPacketType_qVAttachOrWaitSupported,
179 &GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported);
180 RegisterMemberFunctionHandler(
181 StringExtractorGDBRemote::eServerPacketType_vAttachOrWait,
182 &GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait);
183 RegisterMemberFunctionHandler(
184 StringExtractorGDBRemote::eServerPacketType_vCont,
185 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
186 RegisterMemberFunctionHandler(
187 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
188 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
189 RegisterMemberFunctionHandler(
190 StringExtractorGDBRemote::eServerPacketType_vRun,
191 &GDBRemoteCommunicationServerLLGS::Handle_vRun);
192 RegisterMemberFunctionHandler(
193 StringExtractorGDBRemote::eServerPacketType_x,
194 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
195 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
196 &GDBRemoteCommunicationServerLLGS::Handle_Z);
197 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
198 &GDBRemoteCommunicationServerLLGS::Handle_z);
199 RegisterMemberFunctionHandler(
200 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
201 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
202
203 RegisterMemberFunctionHandler(
204 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupported,
205 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported);
206 RegisterMemberFunctionHandler(
207 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStart,
208 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart);
209 RegisterMemberFunctionHandler(
210 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStop,
211 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop);
212 RegisterMemberFunctionHandler(
213 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetState,
214 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState);
215 RegisterMemberFunctionHandler(
216 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetBinaryData,
217 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData);
218
219 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,
220 &GDBRemoteCommunicationServerLLGS::Handle_g);
221
222 RegisterMemberFunctionHandler(
223 StringExtractorGDBRemote::eServerPacketType_qMemTags,
224 &GDBRemoteCommunicationServerLLGS::Handle_qMemTags);
225
226 RegisterMemberFunctionHandler(
227 StringExtractorGDBRemote::eServerPacketType_QMemTags,
228 &GDBRemoteCommunicationServerLLGS::Handle_QMemTags);
229
230 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
231 [this](StringExtractorGDBRemote packet, Status &error,
232 bool &interrupt, bool &quit) {
233 quit = true;
234 return this->Handle_k(packet);
235 });
236
237 RegisterMemberFunctionHandler(
238 StringExtractorGDBRemote::eServerPacketType_vKill,
239 &GDBRemoteCommunicationServerLLGS::Handle_vKill);
240
241 RegisterMemberFunctionHandler(
242 StringExtractorGDBRemote::eServerPacketType_qLLDBSaveCore,
243 &GDBRemoteCommunicationServerLLGS::Handle_qSaveCore);
244
245 RegisterMemberFunctionHandler(
246 StringExtractorGDBRemote::eServerPacketType_QNonStop,
247 &GDBRemoteCommunicationServerLLGS::Handle_QNonStop);
248 RegisterMemberFunctionHandler(
249 StringExtractorGDBRemote::eServerPacketType_vStdio,
250 &GDBRemoteCommunicationServerLLGS::Handle_vStdio);
251 RegisterMemberFunctionHandler(
252 StringExtractorGDBRemote::eServerPacketType_vStopped,
253 &GDBRemoteCommunicationServerLLGS::Handle_vStopped);
254 RegisterMemberFunctionHandler(
255 StringExtractorGDBRemote::eServerPacketType_vCtrlC,
256 &GDBRemoteCommunicationServerLLGS::Handle_vCtrlC);
257 }
258
SetLaunchInfo(const ProcessLaunchInfo & info)259 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
260 m_process_launch_info = info;
261 }
262
LaunchProcess()263 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
264 Log *log = GetLog(LLDBLog::Process);
265
266 if (!m_process_launch_info.GetArguments().GetArgumentCount())
267 return Status("%s: no process command line specified to launch",
268 __FUNCTION__);
269
270 const bool should_forward_stdio =
271 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
272 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
273 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
274 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
275 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
276
277 if (should_forward_stdio) {
278 // Temporarily relax the following for Windows until we can take advantage
279 // of the recently added pty support. This doesn't really affect the use of
280 // lldb-server on Windows.
281 #if !defined(_WIN32)
282 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
283 return Status(std::move(Err));
284 #endif
285 }
286
287 {
288 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
289 assert(m_debugged_processes.empty() && "lldb-server creating debugged "
290 "process but one already exists");
291 auto process_or =
292 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
293 if (!process_or)
294 return Status(process_or.takeError());
295 m_continue_process = m_current_process = process_or->get();
296 m_debugged_processes.emplace(
297 m_current_process->GetID(),
298 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
299 }
300
301 SetEnabledExtensions(*m_current_process);
302
303 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
304 // needed. llgs local-process debugging may specify PTY paths, which will
305 // make these file actions non-null process launch -i/e/o will also make
306 // these file actions non-null nullptr means that the traffic is expected to
307 // flow over gdb-remote protocol
308 if (should_forward_stdio) {
309 // nullptr means it's not redirected to file or pty (in case of LLGS local)
310 // at least one of stdio will be transferred pty<->gdb-remote we need to
311 // give the pty primary handle to this object to read and/or write
312 LLDB_LOG(log,
313 "pid = {0}: setting up stdout/stderr redirection via $O "
314 "gdb-remote commands",
315 m_current_process->GetID());
316
317 // Setup stdout/stderr mapping from inferior to $O
318 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
319 if (terminal_fd >= 0) {
320 LLDB_LOGF(log,
321 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
322 "inferior STDIO fd to %d",
323 __FUNCTION__, terminal_fd);
324 Status status = SetSTDIOFileDescriptor(terminal_fd);
325 if (status.Fail())
326 return status;
327 } else {
328 LLDB_LOGF(log,
329 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
330 "inferior STDIO since terminal fd reported as %d",
331 __FUNCTION__, terminal_fd);
332 }
333 } else {
334 LLDB_LOG(log,
335 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
336 "will communicate over client-provided file descriptors",
337 m_current_process->GetID());
338 }
339
340 printf("Launched '%s' as process %" PRIu64 "...\n",
341 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
342 m_current_process->GetID());
343
344 return Status();
345 }
346
AttachToProcess(lldb::pid_t pid)347 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
348 Log *log = GetLog(LLDBLog::Process);
349 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
350 __FUNCTION__, pid);
351
352 // Before we try to attach, make sure we aren't already monitoring something
353 // else.
354 if (!m_debugged_processes.empty())
355 return Status("cannot attach to process %" PRIu64
356 " when another process with pid %" PRIu64
357 " is being debugged.",
358 pid, m_current_process->GetID());
359
360 // Try to attach.
361 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
362 if (!process_or) {
363 Status status(process_or.takeError());
364 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid,
365 status);
366 return status;
367 }
368 m_continue_process = m_current_process = process_or->get();
369 m_debugged_processes.emplace(
370 m_current_process->GetID(),
371 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
372 SetEnabledExtensions(*m_current_process);
373
374 // Setup stdout/stderr mapping from inferior.
375 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
376 if (terminal_fd >= 0) {
377 LLDB_LOGF(log,
378 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
379 "inferior STDIO fd to %d",
380 __FUNCTION__, terminal_fd);
381 Status status = SetSTDIOFileDescriptor(terminal_fd);
382 if (status.Fail())
383 return status;
384 } else {
385 LLDB_LOGF(log,
386 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
387 "inferior STDIO since terminal fd reported as %d",
388 __FUNCTION__, terminal_fd);
389 }
390
391 printf("Attached to process %" PRIu64 "...\n", pid);
392 return Status();
393 }
394
AttachWaitProcess(llvm::StringRef process_name,bool include_existing)395 Status GDBRemoteCommunicationServerLLGS::AttachWaitProcess(
396 llvm::StringRef process_name, bool include_existing) {
397 Log *log = GetLog(LLDBLog::Process);
398
399 std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);
400
401 // Create the matcher used to search the process list.
402 ProcessInstanceInfoList exclusion_list;
403 ProcessInstanceInfoMatch match_info;
404 match_info.GetProcessInfo().GetExecutableFile().SetFile(
405 process_name, llvm::sys::path::Style::native);
406 match_info.SetNameMatchType(NameMatch::Equals);
407
408 if (include_existing) {
409 LLDB_LOG(log, "including existing processes in search");
410 } else {
411 // Create the excluded process list before polling begins.
412 Host::FindProcesses(match_info, exclusion_list);
413 LLDB_LOG(log, "placed '{0}' processes in the exclusion list.",
414 exclusion_list.size());
415 }
416
417 LLDB_LOG(log, "waiting for '{0}' to appear", process_name);
418
419 auto is_in_exclusion_list =
420 [&exclusion_list](const ProcessInstanceInfo &info) {
421 for (auto &excluded : exclusion_list) {
422 if (excluded.GetProcessID() == info.GetProcessID())
423 return true;
424 }
425 return false;
426 };
427
428 ProcessInstanceInfoList loop_process_list;
429 while (true) {
430 loop_process_list.clear();
431 if (Host::FindProcesses(match_info, loop_process_list)) {
432 // Remove all the elements that are in the exclusion list.
433 llvm::erase_if(loop_process_list, is_in_exclusion_list);
434
435 // One match! We found the desired process.
436 if (loop_process_list.size() == 1) {
437 auto matching_process_pid = loop_process_list[0].GetProcessID();
438 LLDB_LOG(log, "found pid {0}", matching_process_pid);
439 return AttachToProcess(matching_process_pid);
440 }
441
442 // Multiple matches! Return an error reporting the PIDs we found.
443 if (loop_process_list.size() > 1) {
444 StreamString error_stream;
445 error_stream.Format(
446 "Multiple executables with name: '{0}' found. Pids: ",
447 process_name);
448 for (size_t i = 0; i < loop_process_list.size() - 1; ++i) {
449 error_stream.Format("{0}, ", loop_process_list[i].GetProcessID());
450 }
451 error_stream.Format("{0}.", loop_process_list.back().GetProcessID());
452
453 Status error;
454 error.SetErrorString(error_stream.GetString());
455 return error;
456 }
457 }
458 // No matches, we have not found the process. Sleep until next poll.
459 LLDB_LOG(log, "sleep {0} seconds", polling_interval);
460 std::this_thread::sleep_for(polling_interval);
461 }
462 }
463
InitializeDelegate(NativeProcessProtocol * process)464 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
465 NativeProcessProtocol *process) {
466 assert(process && "process cannot be NULL");
467 Log *log = GetLog(LLDBLog::Process);
468 if (log) {
469 LLDB_LOGF(log,
470 "GDBRemoteCommunicationServerLLGS::%s called with "
471 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
472 __FUNCTION__, process->GetID(),
473 StateAsCString(process->GetState()));
474 }
475 }
476
477 GDBRemoteCommunication::PacketResult
SendWResponse(NativeProcessProtocol * process)478 GDBRemoteCommunicationServerLLGS::SendWResponse(
479 NativeProcessProtocol *process) {
480 assert(process && "process cannot be NULL");
481 Log *log = GetLog(LLDBLog::Process);
482
483 // send W notification
484 auto wait_status = process->GetExitStatus();
485 if (!wait_status) {
486 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
487 process->GetID());
488
489 StreamGDBRemote response;
490 response.PutChar('E');
491 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
492 return SendPacketNoLock(response.GetString());
493 }
494
495 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
496 *wait_status);
497
498 // If the process was killed through vKill, return "OK".
499 if (bool(m_debugged_processes.at(process->GetID()).flags &
500 DebuggedProcess::Flag::vkilled))
501 return SendOKResponse();
502
503 StreamGDBRemote response;
504 response.Format("{0:g}", *wait_status);
505 if (bool(m_extensions_supported &
506 NativeProcessProtocol::Extension::multiprocess))
507 response.Format(";process:{0:x-}", process->GetID());
508 if (m_non_stop)
509 return SendNotificationPacketNoLock("Stop", m_stop_notification_queue,
510 response.GetString());
511 return SendPacketNoLock(response.GetString());
512 }
513
AppendHexValue(StreamString & response,const uint8_t * buf,uint32_t buf_size,bool swap)514 static void AppendHexValue(StreamString &response, const uint8_t *buf,
515 uint32_t buf_size, bool swap) {
516 int64_t i;
517 if (swap) {
518 for (i = buf_size - 1; i >= 0; i--)
519 response.PutHex8(buf[i]);
520 } else {
521 for (i = 0; i < buf_size; i++)
522 response.PutHex8(buf[i]);
523 }
524 }
525
GetEncodingNameOrEmpty(const RegisterInfo & reg_info)526 static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) {
527 switch (reg_info.encoding) {
528 case eEncodingUint:
529 return "uint";
530 case eEncodingSint:
531 return "sint";
532 case eEncodingIEEE754:
533 return "ieee754";
534 case eEncodingVector:
535 return "vector";
536 default:
537 return "";
538 }
539 }
540
GetFormatNameOrEmpty(const RegisterInfo & reg_info)541 static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) {
542 switch (reg_info.format) {
543 case eFormatBinary:
544 return "binary";
545 case eFormatDecimal:
546 return "decimal";
547 case eFormatHex:
548 return "hex";
549 case eFormatFloat:
550 return "float";
551 case eFormatVectorOfSInt8:
552 return "vector-sint8";
553 case eFormatVectorOfUInt8:
554 return "vector-uint8";
555 case eFormatVectorOfSInt16:
556 return "vector-sint16";
557 case eFormatVectorOfUInt16:
558 return "vector-uint16";
559 case eFormatVectorOfSInt32:
560 return "vector-sint32";
561 case eFormatVectorOfUInt32:
562 return "vector-uint32";
563 case eFormatVectorOfFloat32:
564 return "vector-float32";
565 case eFormatVectorOfUInt64:
566 return "vector-uint64";
567 case eFormatVectorOfUInt128:
568 return "vector-uint128";
569 default:
570 return "";
571 };
572 }
573
GetKindGenericOrEmpty(const RegisterInfo & reg_info)574 static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) {
575 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
576 case LLDB_REGNUM_GENERIC_PC:
577 return "pc";
578 case LLDB_REGNUM_GENERIC_SP:
579 return "sp";
580 case LLDB_REGNUM_GENERIC_FP:
581 return "fp";
582 case LLDB_REGNUM_GENERIC_RA:
583 return "ra";
584 case LLDB_REGNUM_GENERIC_FLAGS:
585 return "flags";
586 case LLDB_REGNUM_GENERIC_ARG1:
587 return "arg1";
588 case LLDB_REGNUM_GENERIC_ARG2:
589 return "arg2";
590 case LLDB_REGNUM_GENERIC_ARG3:
591 return "arg3";
592 case LLDB_REGNUM_GENERIC_ARG4:
593 return "arg4";
594 case LLDB_REGNUM_GENERIC_ARG5:
595 return "arg5";
596 case LLDB_REGNUM_GENERIC_ARG6:
597 return "arg6";
598 case LLDB_REGNUM_GENERIC_ARG7:
599 return "arg7";
600 case LLDB_REGNUM_GENERIC_ARG8:
601 return "arg8";
602 default:
603 return "";
604 }
605 }
606
CollectRegNums(const uint32_t * reg_num,StreamString & response,bool usehex)607 static void CollectRegNums(const uint32_t *reg_num, StreamString &response,
608 bool usehex) {
609 for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
610 if (i > 0)
611 response.PutChar(',');
612 if (usehex)
613 response.Printf("%" PRIx32, *reg_num);
614 else
615 response.Printf("%" PRIu32, *reg_num);
616 }
617 }
618
WriteRegisterValueInHexFixedWidth(StreamString & response,NativeRegisterContext & reg_ctx,const RegisterInfo & reg_info,const RegisterValue * reg_value_p,lldb::ByteOrder byte_order)619 static void WriteRegisterValueInHexFixedWidth(
620 StreamString &response, NativeRegisterContext ®_ctx,
621 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
622 lldb::ByteOrder byte_order) {
623 RegisterValue reg_value;
624 if (!reg_value_p) {
625 Status error = reg_ctx.ReadRegister(®_info, reg_value);
626 if (error.Success())
627 reg_value_p = ®_value;
628 // else log.
629 }
630
631 if (reg_value_p) {
632 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
633 reg_value_p->GetByteSize(),
634 byte_order == lldb::eByteOrderLittle);
635 } else {
636 // Zero-out any unreadable values.
637 if (reg_info.byte_size > 0) {
638 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
639 AppendHexValue(response, zeros.data(), zeros.size(), false);
640 }
641 }
642 }
643
644 static llvm::Optional<json::Object>
GetRegistersAsJSON(NativeThreadProtocol & thread)645 GetRegistersAsJSON(NativeThreadProtocol &thread) {
646 Log *log = GetLog(LLDBLog::Thread);
647
648 NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
649
650 json::Object register_object;
651
652 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
653 const auto expedited_regs =
654 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
655 #else
656 const auto expedited_regs =
657 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal);
658 #endif
659 if (expedited_regs.empty())
660 return llvm::None;
661
662 for (auto ®_num : expedited_regs) {
663 const RegisterInfo *const reg_info_p =
664 reg_ctx.GetRegisterInfoAtIndex(reg_num);
665 if (reg_info_p == nullptr) {
666 LLDB_LOGF(log,
667 "%s failed to get register info for register index %" PRIu32,
668 __FUNCTION__, reg_num);
669 continue;
670 }
671
672 if (reg_info_p->value_regs != nullptr)
673 continue; // Only expedite registers that are not contained in other
674 // registers.
675
676 RegisterValue reg_value;
677 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
678 if (error.Fail()) {
679 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
680 __FUNCTION__,
681 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
682 reg_num, error.AsCString());
683 continue;
684 }
685
686 StreamString stream;
687 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
688 ®_value, lldb::eByteOrderBig);
689
690 register_object.try_emplace(llvm::to_string(reg_num),
691 stream.GetString().str());
692 }
693
694 return register_object;
695 }
696
GetStopReasonString(StopReason stop_reason)697 static const char *GetStopReasonString(StopReason stop_reason) {
698 switch (stop_reason) {
699 case eStopReasonTrace:
700 return "trace";
701 case eStopReasonBreakpoint:
702 return "breakpoint";
703 case eStopReasonWatchpoint:
704 return "watchpoint";
705 case eStopReasonSignal:
706 return "signal";
707 case eStopReasonException:
708 return "exception";
709 case eStopReasonExec:
710 return "exec";
711 case eStopReasonProcessorTrace:
712 return "processor trace";
713 case eStopReasonFork:
714 return "fork";
715 case eStopReasonVFork:
716 return "vfork";
717 case eStopReasonVForkDone:
718 return "vforkdone";
719 case eStopReasonInstrumentation:
720 case eStopReasonInvalid:
721 case eStopReasonPlanComplete:
722 case eStopReasonThreadExiting:
723 case eStopReasonNone:
724 break; // ignored
725 }
726 return nullptr;
727 }
728
729 static llvm::Expected<json::Array>
GetJSONThreadsInfo(NativeProcessProtocol & process,bool abridged)730 GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {
731 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
732
733 json::Array threads_array;
734
735 // Ensure we can get info on the given thread.
736 for (NativeThreadProtocol &thread : process.Threads()) {
737 lldb::tid_t tid = thread.GetID();
738 // Grab the reason this thread stopped.
739 struct ThreadStopInfo tid_stop_info;
740 std::string description;
741 if (!thread.GetStopReason(tid_stop_info, description))
742 return llvm::make_error<llvm::StringError>(
743 "failed to get stop reason", llvm::inconvertibleErrorCode());
744
745 const int signum = tid_stop_info.signo;
746 if (log) {
747 LLDB_LOGF(log,
748 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
749 " tid %" PRIu64
750 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
751 __FUNCTION__, process.GetID(), tid, signum,
752 tid_stop_info.reason, tid_stop_info.details.exception.type);
753 }
754
755 json::Object thread_obj;
756
757 if (!abridged) {
758 if (llvm::Optional<json::Object> registers = GetRegistersAsJSON(thread))
759 thread_obj.try_emplace("registers", std::move(*registers));
760 }
761
762 thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
763
764 if (signum != 0)
765 thread_obj.try_emplace("signal", signum);
766
767 const std::string thread_name = thread.GetName();
768 if (!thread_name.empty())
769 thread_obj.try_emplace("name", thread_name);
770
771 const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
772 if (stop_reason)
773 thread_obj.try_emplace("reason", stop_reason);
774
775 if (!description.empty())
776 thread_obj.try_emplace("description", description);
777
778 if ((tid_stop_info.reason == eStopReasonException) &&
779 tid_stop_info.details.exception.type) {
780 thread_obj.try_emplace(
781 "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
782
783 json::Array medata_array;
784 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
785 ++i) {
786 medata_array.push_back(
787 static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
788 }
789 thread_obj.try_emplace("medata", std::move(medata_array));
790 }
791 threads_array.push_back(std::move(thread_obj));
792 }
793 return threads_array;
794 }
795
796 StreamString
PrepareStopReplyPacketForThread(NativeThreadProtocol & thread)797 GDBRemoteCommunicationServerLLGS::PrepareStopReplyPacketForThread(
798 NativeThreadProtocol &thread) {
799 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
800
801 NativeProcessProtocol &process = thread.GetProcess();
802
803 LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(),
804 thread.GetID());
805
806 // Grab the reason this thread stopped.
807 StreamString response;
808 struct ThreadStopInfo tid_stop_info;
809 std::string description;
810 if (!thread.GetStopReason(tid_stop_info, description))
811 return response;
812
813 // FIXME implement register handling for exec'd inferiors.
814 // if (tid_stop_info.reason == eStopReasonExec) {
815 // const bool force = true;
816 // InitializeRegisters(force);
817 // }
818
819 // Output the T packet with the thread
820 response.PutChar('T');
821 int signum = tid_stop_info.signo;
822 LLDB_LOG(
823 log,
824 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
825 process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason),
826 tid_stop_info.details.exception.type);
827
828 // Print the signal number.
829 response.PutHex8(signum & 0xff);
830
831 // Include the (pid and) tid.
832 response.PutCString("thread:");
833 AppendThreadIDToResponse(response, process.GetID(), thread.GetID());
834 response.PutChar(';');
835
836 // Include the thread name if there is one.
837 const std::string thread_name = thread.GetName();
838 if (!thread_name.empty()) {
839 size_t thread_name_len = thread_name.length();
840
841 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
842 response.PutCString("name:");
843 response.PutCString(thread_name);
844 } else {
845 // The thread name contains special chars, send as hex bytes.
846 response.PutCString("hexname:");
847 response.PutStringAsRawHex8(thread_name);
848 }
849 response.PutChar(';');
850 }
851
852 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
853 // send all thread IDs back in the "threads" key whose value is a list of hex
854 // thread IDs separated by commas:
855 // "threads:10a,10b,10c;"
856 // This will save the debugger from having to send a pair of qfThreadInfo and
857 // qsThreadInfo packets, but it also might take a lot of room in the stop
858 // reply packet, so it must be enabled only on systems where there are no
859 // limits on packet lengths.
860 if (m_list_threads_in_stop_reply) {
861 response.PutCString("threads:");
862
863 uint32_t thread_num = 0;
864 for (NativeThreadProtocol &listed_thread : process.Threads()) {
865 if (thread_num > 0)
866 response.PutChar(',');
867 response.Printf("%" PRIx64, listed_thread.GetID());
868 ++thread_num;
869 }
870 response.PutChar(';');
871
872 // Include JSON info that describes the stop reason for any threads that
873 // actually have stop reasons. We use the new "jstopinfo" key whose values
874 // is hex ascii JSON that contains the thread IDs thread stop info only for
875 // threads that have stop reasons. Only send this if we have more than one
876 // thread otherwise this packet has all the info it needs.
877 if (thread_num > 1) {
878 const bool threads_with_valid_stop_info_only = true;
879 llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
880 *m_current_process, threads_with_valid_stop_info_only);
881 if (threads_info) {
882 response.PutCString("jstopinfo:");
883 StreamString unescaped_response;
884 unescaped_response.AsRawOstream() << std::move(*threads_info);
885 response.PutStringAsRawHex8(unescaped_response.GetData());
886 response.PutChar(';');
887 } else {
888 LLDB_LOG_ERROR(log, threads_info.takeError(),
889 "failed to prepare a jstopinfo field for pid {1}: {0}",
890 process.GetID());
891 }
892 }
893
894 response.PutCString("thread-pcs");
895 char delimiter = ':';
896 for (NativeThreadProtocol &thread : process.Threads()) {
897 NativeRegisterContext ®_ctx = thread.GetRegisterContext();
898
899 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
900 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
901 const RegisterInfo *const reg_info_p =
902 reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
903
904 RegisterValue reg_value;
905 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
906 if (error.Fail()) {
907 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
908 __FUNCTION__,
909 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
910 reg_to_read, error.AsCString());
911 continue;
912 }
913
914 response.PutChar(delimiter);
915 delimiter = ',';
916 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
917 ®_value, endian::InlHostByteOrder());
918 }
919
920 response.PutChar(';');
921 }
922
923 //
924 // Expedite registers.
925 //
926
927 // Grab the register context.
928 NativeRegisterContext ®_ctx = thread.GetRegisterContext();
929 const auto expedited_regs =
930 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
931
932 for (auto ®_num : expedited_regs) {
933 const RegisterInfo *const reg_info_p =
934 reg_ctx.GetRegisterInfoAtIndex(reg_num);
935 // Only expediate registers that are not contained in other registers.
936 if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) {
937 RegisterValue reg_value;
938 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
939 if (error.Success()) {
940 response.Printf("%.02x:", reg_num);
941 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
942 ®_value, lldb::eByteOrderBig);
943 response.PutChar(';');
944 } else {
945 LLDB_LOGF(log,
946 "GDBRemoteCommunicationServerLLGS::%s failed to read "
947 "register '%s' index %" PRIu32 ": %s",
948 __FUNCTION__,
949 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
950 reg_num, error.AsCString());
951 }
952 }
953 }
954
955 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
956 if (reason_str != nullptr) {
957 response.Printf("reason:%s;", reason_str);
958 }
959
960 if (!description.empty()) {
961 // Description may contains special chars, send as hex bytes.
962 response.PutCString("description:");
963 response.PutStringAsRawHex8(description);
964 response.PutChar(';');
965 } else if ((tid_stop_info.reason == eStopReasonException) &&
966 tid_stop_info.details.exception.type) {
967 response.PutCString("metype:");
968 response.PutHex64(tid_stop_info.details.exception.type);
969 response.PutCString(";mecount:");
970 response.PutHex32(tid_stop_info.details.exception.data_count);
971 response.PutChar(';');
972
973 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
974 response.PutCString("medata:");
975 response.PutHex64(tid_stop_info.details.exception.data[i]);
976 response.PutChar(';');
977 }
978 }
979
980 // Include child process PID/TID for forks.
981 if (tid_stop_info.reason == eStopReasonFork ||
982 tid_stop_info.reason == eStopReasonVFork) {
983 assert(bool(m_extensions_supported &
984 NativeProcessProtocol::Extension::multiprocess));
985 if (tid_stop_info.reason == eStopReasonFork)
986 assert(bool(m_extensions_supported &
987 NativeProcessProtocol::Extension::fork));
988 if (tid_stop_info.reason == eStopReasonVFork)
989 assert(bool(m_extensions_supported &
990 NativeProcessProtocol::Extension::vfork));
991 response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str,
992 tid_stop_info.details.fork.child_pid,
993 tid_stop_info.details.fork.child_tid);
994 }
995
996 return response;
997 }
998
999 GDBRemoteCommunication::PacketResult
SendStopReplyPacketForThread(NativeProcessProtocol & process,lldb::tid_t tid,bool force_synchronous)1000 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
1001 NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) {
1002 // Ensure we can get info on the given thread.
1003 NativeThreadProtocol *thread = process.GetThreadByID(tid);
1004 if (!thread)
1005 return SendErrorResponse(51);
1006
1007 StreamString response = PrepareStopReplyPacketForThread(*thread);
1008 if (response.Empty())
1009 return SendErrorResponse(42);
1010
1011 if (m_non_stop && !force_synchronous) {
1012 PacketResult ret = SendNotificationPacketNoLock(
1013 "Stop", m_stop_notification_queue, response.GetString());
1014 // Queue notification events for the remaining threads.
1015 EnqueueStopReplyPackets(tid);
1016 return ret;
1017 }
1018
1019 return SendPacketNoLock(response.GetString());
1020 }
1021
EnqueueStopReplyPackets(lldb::tid_t thread_to_skip)1022 void GDBRemoteCommunicationServerLLGS::EnqueueStopReplyPackets(
1023 lldb::tid_t thread_to_skip) {
1024 if (!m_non_stop)
1025 return;
1026
1027 for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) {
1028 if (listed_thread.GetID() != thread_to_skip) {
1029 StreamString stop_reply = PrepareStopReplyPacketForThread(listed_thread);
1030 if (!stop_reply.Empty())
1031 m_stop_notification_queue.push_back(stop_reply.GetString().str());
1032 }
1033 }
1034 }
1035
HandleInferiorState_Exited(NativeProcessProtocol * process)1036 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
1037 NativeProcessProtocol *process) {
1038 assert(process && "process cannot be NULL");
1039
1040 Log *log = GetLog(LLDBLog::Process);
1041 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1042
1043 PacketResult result = SendStopReasonForState(
1044 *process, StateType::eStateExited, /*force_synchronous=*/false);
1045 if (result != PacketResult::Success) {
1046 LLDB_LOGF(log,
1047 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1048 "notification for PID %" PRIu64 ", state: eStateExited",
1049 __FUNCTION__, process->GetID());
1050 }
1051
1052 if (m_current_process == process)
1053 m_current_process = nullptr;
1054 if (m_continue_process == process)
1055 m_continue_process = nullptr;
1056
1057 lldb::pid_t pid = process->GetID();
1058 m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) {
1059 auto find_it = m_debugged_processes.find(pid);
1060 assert(find_it != m_debugged_processes.end());
1061 bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled);
1062 m_debugged_processes.erase(find_it);
1063 // Terminate the main loop only if vKill has not been used.
1064 // When running in non-stop mode, wait for the vStopped to clear
1065 // the notification queue.
1066 if (m_debugged_processes.empty() && !m_non_stop && !vkilled) {
1067 // Close the pipe to the inferior terminal i/o if we launched it and set
1068 // one up.
1069 MaybeCloseInferiorTerminalConnection();
1070
1071 // We are ready to exit the debug monitor.
1072 m_exit_now = true;
1073 loop.RequestTermination();
1074 }
1075 });
1076 }
1077
HandleInferiorState_Stopped(NativeProcessProtocol * process)1078 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
1079 NativeProcessProtocol *process) {
1080 assert(process && "process cannot be NULL");
1081
1082 Log *log = GetLog(LLDBLog::Process);
1083 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1084
1085 PacketResult result = SendStopReasonForState(
1086 *process, StateType::eStateStopped, /*force_synchronous=*/false);
1087 if (result != PacketResult::Success) {
1088 LLDB_LOGF(log,
1089 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1090 "notification for PID %" PRIu64 ", state: eStateExited",
1091 __FUNCTION__, process->GetID());
1092 }
1093 }
1094
ProcessStateChanged(NativeProcessProtocol * process,lldb::StateType state)1095 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
1096 NativeProcessProtocol *process, lldb::StateType state) {
1097 assert(process && "process cannot be NULL");
1098 Log *log = GetLog(LLDBLog::Process);
1099 if (log) {
1100 LLDB_LOGF(log,
1101 "GDBRemoteCommunicationServerLLGS::%s called with "
1102 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
1103 __FUNCTION__, process->GetID(), StateAsCString(state));
1104 }
1105
1106 switch (state) {
1107 case StateType::eStateRunning:
1108 break;
1109
1110 case StateType::eStateStopped:
1111 // Make sure we get all of the pending stdout/stderr from the inferior and
1112 // send it to the lldb host before we send the state change notification
1113 SendProcessOutput();
1114 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
1115 // does not interfere with our protocol.
1116 if (!m_non_stop)
1117 StopSTDIOForwarding();
1118 HandleInferiorState_Stopped(process);
1119 break;
1120
1121 case StateType::eStateExited:
1122 // Same as above
1123 SendProcessOutput();
1124 if (!m_non_stop)
1125 StopSTDIOForwarding();
1126 HandleInferiorState_Exited(process);
1127 break;
1128
1129 default:
1130 if (log) {
1131 LLDB_LOGF(log,
1132 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
1133 "change for pid %" PRIu64 ", new state: %s",
1134 __FUNCTION__, process->GetID(), StateAsCString(state));
1135 }
1136 break;
1137 }
1138 }
1139
DidExec(NativeProcessProtocol * process)1140 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
1141 ClearProcessSpecificData();
1142 }
1143
NewSubprocess(NativeProcessProtocol * parent_process,std::unique_ptr<NativeProcessProtocol> child_process)1144 void GDBRemoteCommunicationServerLLGS::NewSubprocess(
1145 NativeProcessProtocol *parent_process,
1146 std::unique_ptr<NativeProcessProtocol> child_process) {
1147 lldb::pid_t child_pid = child_process->GetID();
1148 assert(child_pid != LLDB_INVALID_PROCESS_ID);
1149 assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end());
1150 m_debugged_processes.emplace(
1151 child_pid,
1152 DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}});
1153 }
1154
DataAvailableCallback()1155 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
1156 Log *log = GetLog(GDBRLog::Comm);
1157
1158 bool interrupt = false;
1159 bool done = false;
1160 Status error;
1161 while (true) {
1162 const PacketResult result = GetPacketAndSendResponse(
1163 std::chrono::microseconds(0), error, interrupt, done);
1164 if (result == PacketResult::ErrorReplyTimeout)
1165 break; // No more packets in the queue
1166
1167 if ((result != PacketResult::Success)) {
1168 LLDB_LOGF(log,
1169 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1170 "failed: %s",
1171 __FUNCTION__, error.AsCString());
1172 m_mainloop.RequestTermination();
1173 break;
1174 }
1175 }
1176 }
1177
InitializeConnection(std::unique_ptr<Connection> connection)1178 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
1179 std::unique_ptr<Connection> connection) {
1180 IOObjectSP read_object_sp = connection->GetReadObject();
1181 GDBRemoteCommunicationServer::SetConnection(std::move(connection));
1182
1183 Status error;
1184 m_network_handle_up = m_mainloop.RegisterReadObject(
1185 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1186 error);
1187 return error;
1188 }
1189
1190 GDBRemoteCommunication::PacketResult
SendONotification(const char * buffer,uint32_t len)1191 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1192 uint32_t len) {
1193 if ((buffer == nullptr) || (len == 0)) {
1194 // Nothing to send.
1195 return PacketResult::Success;
1196 }
1197
1198 StreamString response;
1199 response.PutChar('O');
1200 response.PutBytesAsRawHex8(buffer, len);
1201
1202 if (m_non_stop)
1203 return SendNotificationPacketNoLock("Stdio", m_stdio_notification_queue,
1204 response.GetString());
1205 return SendPacketNoLock(response.GetString());
1206 }
1207
SetSTDIOFileDescriptor(int fd)1208 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1209 Status error;
1210
1211 // Set up the reading/handling of process I/O
1212 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1213 new ConnectionFileDescriptor(fd, true));
1214 if (!conn_up) {
1215 error.SetErrorString("failed to create ConnectionFileDescriptor");
1216 return error;
1217 }
1218
1219 m_stdio_communication.SetCloseOnEOF(false);
1220 m_stdio_communication.SetConnection(std::move(conn_up));
1221 if (!m_stdio_communication.IsConnected()) {
1222 error.SetErrorString(
1223 "failed to set connection for inferior I/O communication");
1224 return error;
1225 }
1226
1227 return Status();
1228 }
1229
StartSTDIOForwarding()1230 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1231 // Don't forward if not connected (e.g. when attaching).
1232 if (!m_stdio_communication.IsConnected())
1233 return;
1234
1235 Status error;
1236 assert(!m_stdio_handle_up);
1237 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1238 m_stdio_communication.GetConnection()->GetReadObject(),
1239 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1240
1241 if (!m_stdio_handle_up) {
1242 // Not much we can do about the failure. Log it and continue without
1243 // forwarding.
1244 if (Log *log = GetLog(LLDBLog::Process))
1245 LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error);
1246 }
1247 }
1248
StopSTDIOForwarding()1249 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1250 m_stdio_handle_up.reset();
1251 }
1252
SendProcessOutput()1253 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1254 char buffer[1024];
1255 ConnectionStatus status;
1256 Status error;
1257 while (true) {
1258 size_t bytes_read = m_stdio_communication.Read(
1259 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1260 switch (status) {
1261 case eConnectionStatusSuccess:
1262 SendONotification(buffer, bytes_read);
1263 break;
1264 case eConnectionStatusLostConnection:
1265 case eConnectionStatusEndOfFile:
1266 case eConnectionStatusError:
1267 case eConnectionStatusNoConnection:
1268 if (Log *log = GetLog(LLDBLog::Process))
1269 LLDB_LOGF(log,
1270 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1271 "forwarding as communication returned status %d (error: "
1272 "%s)",
1273 __FUNCTION__, status, error.AsCString());
1274 m_stdio_handle_up.reset();
1275 return;
1276
1277 case eConnectionStatusInterrupted:
1278 case eConnectionStatusTimedOut:
1279 return;
1280 }
1281 }
1282 }
1283
1284 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceSupported(StringExtractorGDBRemote & packet)1285 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported(
1286 StringExtractorGDBRemote &packet) {
1287
1288 // Fail if we don't have a current process.
1289 if (!m_current_process ||
1290 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1291 return SendErrorResponse(Status("Process not running."));
1292
1293 return SendJSONResponse(m_current_process->TraceSupported());
1294 }
1295
1296 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceStop(StringExtractorGDBRemote & packet)1297 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop(
1298 StringExtractorGDBRemote &packet) {
1299 // Fail if we don't have a current process.
1300 if (!m_current_process ||
1301 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1302 return SendErrorResponse(Status("Process not running."));
1303
1304 packet.ConsumeFront("jLLDBTraceStop:");
1305 Expected<TraceStopRequest> stop_request =
1306 json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");
1307 if (!stop_request)
1308 return SendErrorResponse(stop_request.takeError());
1309
1310 if (Error err = m_current_process->TraceStop(*stop_request))
1311 return SendErrorResponse(std::move(err));
1312
1313 return SendOKResponse();
1314 }
1315
1316 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceStart(StringExtractorGDBRemote & packet)1317 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart(
1318 StringExtractorGDBRemote &packet) {
1319
1320 // Fail if we don't have a current process.
1321 if (!m_current_process ||
1322 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1323 return SendErrorResponse(Status("Process not running."));
1324
1325 packet.ConsumeFront("jLLDBTraceStart:");
1326 Expected<TraceStartRequest> request =
1327 json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");
1328 if (!request)
1329 return SendErrorResponse(request.takeError());
1330
1331 if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))
1332 return SendErrorResponse(std::move(err));
1333
1334 return SendOKResponse();
1335 }
1336
1337 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceGetState(StringExtractorGDBRemote & packet)1338 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState(
1339 StringExtractorGDBRemote &packet) {
1340
1341 // Fail if we don't have a current process.
1342 if (!m_current_process ||
1343 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1344 return SendErrorResponse(Status("Process not running."));
1345
1346 packet.ConsumeFront("jLLDBTraceGetState:");
1347 Expected<TraceGetStateRequest> request =
1348 json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");
1349 if (!request)
1350 return SendErrorResponse(request.takeError());
1351
1352 return SendJSONResponse(m_current_process->TraceGetState(request->type));
1353 }
1354
1355 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceGetBinaryData(StringExtractorGDBRemote & packet)1356 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData(
1357 StringExtractorGDBRemote &packet) {
1358
1359 // Fail if we don't have a current process.
1360 if (!m_current_process ||
1361 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1362 return SendErrorResponse(Status("Process not running."));
1363
1364 packet.ConsumeFront("jLLDBTraceGetBinaryData:");
1365 llvm::Expected<TraceGetBinaryDataRequest> request =
1366 llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),
1367 "TraceGetBinaryDataRequest");
1368 if (!request)
1369 return SendErrorResponse(Status(request.takeError()));
1370
1371 if (Expected<std::vector<uint8_t>> bytes =
1372 m_current_process->TraceGetBinaryData(*request)) {
1373 StreamGDBRemote response;
1374 response.PutEscapedBytes(bytes->data(), bytes->size());
1375 return SendPacketNoLock(response.GetString());
1376 } else
1377 return SendErrorResponse(bytes.takeError());
1378 }
1379
1380 GDBRemoteCommunication::PacketResult
Handle_qProcessInfo(StringExtractorGDBRemote & packet)1381 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1382 StringExtractorGDBRemote &packet) {
1383 // Fail if we don't have a current process.
1384 if (!m_current_process ||
1385 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1386 return SendErrorResponse(68);
1387
1388 lldb::pid_t pid = m_current_process->GetID();
1389
1390 if (pid == LLDB_INVALID_PROCESS_ID)
1391 return SendErrorResponse(1);
1392
1393 ProcessInstanceInfo proc_info;
1394 if (!Host::GetProcessInfo(pid, proc_info))
1395 return SendErrorResponse(1);
1396
1397 StreamString response;
1398 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1399 return SendPacketNoLock(response.GetString());
1400 }
1401
1402 GDBRemoteCommunication::PacketResult
Handle_qC(StringExtractorGDBRemote & packet)1403 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1404 // Fail if we don't have a current process.
1405 if (!m_current_process ||
1406 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1407 return SendErrorResponse(68);
1408
1409 // Make sure we set the current thread so g and p packets return the data the
1410 // gdb will expect.
1411 lldb::tid_t tid = m_current_process->GetCurrentThreadID();
1412 SetCurrentThreadID(tid);
1413
1414 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1415 if (!thread)
1416 return SendErrorResponse(69);
1417
1418 StreamString response;
1419 response.PutCString("QC");
1420 AppendThreadIDToResponse(response, m_current_process->GetID(),
1421 thread->GetID());
1422
1423 return SendPacketNoLock(response.GetString());
1424 }
1425
1426 GDBRemoteCommunication::PacketResult
Handle_k(StringExtractorGDBRemote & packet)1427 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1428 Log *log = GetLog(LLDBLog::Process);
1429
1430 if (!m_non_stop)
1431 StopSTDIOForwarding();
1432
1433 if (m_debugged_processes.empty()) {
1434 LLDB_LOG(log, "No debugged process found.");
1435 return PacketResult::Success;
1436 }
1437
1438 for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end();
1439 ++it) {
1440 LLDB_LOG(log, "Killing process {0}", it->first);
1441 Status error = it->second.process_up->Kill();
1442 if (error.Fail())
1443 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first,
1444 error);
1445 }
1446
1447 // The response to kill packet is undefined per the spec. LLDB
1448 // follows the same rules as for continue packets, i.e. no response
1449 // in all-stop mode, and "OK" in non-stop mode; in both cases this
1450 // is followed by the actual stop reason.
1451 return SendContinueSuccessResponse();
1452 }
1453
1454 GDBRemoteCommunication::PacketResult
Handle_vKill(StringExtractorGDBRemote & packet)1455 GDBRemoteCommunicationServerLLGS::Handle_vKill(
1456 StringExtractorGDBRemote &packet) {
1457 if (!m_non_stop)
1458 StopSTDIOForwarding();
1459
1460 packet.SetFilePos(6); // vKill;
1461 uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
1462 if (pid == LLDB_INVALID_PROCESS_ID)
1463 return SendIllFormedResponse(packet,
1464 "vKill failed to parse the process id");
1465
1466 auto it = m_debugged_processes.find(pid);
1467 if (it == m_debugged_processes.end())
1468 return SendErrorResponse(42);
1469
1470 Status error = it->second.process_up->Kill();
1471 if (error.Fail())
1472 return SendErrorResponse(error.ToError());
1473
1474 // OK response is sent when the process dies.
1475 it->second.flags |= DebuggedProcess::Flag::vkilled;
1476 return PacketResult::Success;
1477 }
1478
1479 GDBRemoteCommunication::PacketResult
Handle_QSetDisableASLR(StringExtractorGDBRemote & packet)1480 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1481 StringExtractorGDBRemote &packet) {
1482 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1483 if (packet.GetU32(0))
1484 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1485 else
1486 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1487 return SendOKResponse();
1488 }
1489
1490 GDBRemoteCommunication::PacketResult
Handle_QSetWorkingDir(StringExtractorGDBRemote & packet)1491 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1492 StringExtractorGDBRemote &packet) {
1493 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1494 std::string path;
1495 packet.GetHexByteString(path);
1496 m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1497 return SendOKResponse();
1498 }
1499
1500 GDBRemoteCommunication::PacketResult
Handle_qGetWorkingDir(StringExtractorGDBRemote & packet)1501 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1502 StringExtractorGDBRemote &packet) {
1503 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1504 if (working_dir) {
1505 StreamString response;
1506 response.PutStringAsRawHex8(working_dir.GetCString());
1507 return SendPacketNoLock(response.GetString());
1508 }
1509
1510 return SendErrorResponse(14);
1511 }
1512
1513 GDBRemoteCommunication::PacketResult
Handle_QThreadSuffixSupported(StringExtractorGDBRemote & packet)1514 GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported(
1515 StringExtractorGDBRemote &packet) {
1516 m_thread_suffix_supported = true;
1517 return SendOKResponse();
1518 }
1519
1520 GDBRemoteCommunication::PacketResult
Handle_QListThreadsInStopReply(StringExtractorGDBRemote & packet)1521 GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply(
1522 StringExtractorGDBRemote &packet) {
1523 m_list_threads_in_stop_reply = true;
1524 return SendOKResponse();
1525 }
1526
1527 GDBRemoteCommunication::PacketResult
ResumeProcess(NativeProcessProtocol & process,const ResumeActionList & actions)1528 GDBRemoteCommunicationServerLLGS::ResumeProcess(
1529 NativeProcessProtocol &process, const ResumeActionList &actions) {
1530 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1531
1532 // In non-stop protocol mode, the process could be running already.
1533 // We do not support resuming threads independently, so just error out.
1534 if (!process.CanResume()) {
1535 LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(),
1536 process.GetState());
1537 return SendErrorResponse(0x37);
1538 }
1539
1540 Status error = process.Resume(actions);
1541 if (error.Fail()) {
1542 LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error);
1543 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1544 }
1545
1546 LLDB_LOG(log, "process {0} resumed", process.GetID());
1547
1548 return PacketResult::Success;
1549 }
1550
1551 GDBRemoteCommunication::PacketResult
Handle_C(StringExtractorGDBRemote & packet)1552 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1553 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1554 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1555
1556 // Ensure we have a native process.
1557 if (!m_continue_process) {
1558 LLDB_LOGF(log,
1559 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1560 "shared pointer",
1561 __FUNCTION__);
1562 return SendErrorResponse(0x36);
1563 }
1564
1565 // Pull out the signal number.
1566 packet.SetFilePos(::strlen("C"));
1567 if (packet.GetBytesLeft() < 1) {
1568 // Shouldn't be using a C without a signal.
1569 return SendIllFormedResponse(packet, "C packet specified without signal.");
1570 }
1571 const uint32_t signo =
1572 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1573 if (signo == std::numeric_limits<uint32_t>::max())
1574 return SendIllFormedResponse(packet, "failed to parse signal number");
1575
1576 // Handle optional continue address.
1577 if (packet.GetBytesLeft() > 0) {
1578 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1579 if (*packet.Peek() == ';')
1580 return SendUnimplementedResponse(packet.GetStringRef().data());
1581 else
1582 return SendIllFormedResponse(
1583 packet, "unexpected content after $C{signal-number}");
1584 }
1585
1586 // In non-stop protocol mode, the process could be running already.
1587 // We do not support resuming threads independently, so just error out.
1588 if (!m_continue_process->CanResume()) {
1589 LLDB_LOG(log, "process cannot be resumed (state={0})",
1590 m_continue_process->GetState());
1591 return SendErrorResponse(0x37);
1592 }
1593
1594 ResumeActionList resume_actions(StateType::eStateRunning,
1595 LLDB_INVALID_SIGNAL_NUMBER);
1596 Status error;
1597
1598 // We have two branches: what to do if a continue thread is specified (in
1599 // which case we target sending the signal to that thread), or when we don't
1600 // have a continue thread set (in which case we send a signal to the
1601 // process).
1602
1603 // TODO discuss with Greg Clayton, make sure this makes sense.
1604
1605 lldb::tid_t signal_tid = GetContinueThreadID();
1606 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1607 // The resume action for the continue thread (or all threads if a continue
1608 // thread is not set).
1609 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1610 static_cast<int>(signo)};
1611
1612 // Add the action for the continue thread (or all threads when the continue
1613 // thread isn't present).
1614 resume_actions.Append(action);
1615 } else {
1616 // Send the signal to the process since we weren't targeting a specific
1617 // continue thread with the signal.
1618 error = m_continue_process->Signal(signo);
1619 if (error.Fail()) {
1620 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1621 m_continue_process->GetID(), error);
1622
1623 return SendErrorResponse(0x52);
1624 }
1625 }
1626
1627 // NB: this checks CanResume() twice but using a single code path for
1628 // resuming still seems worth it.
1629 PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions);
1630 if (resume_res != PacketResult::Success)
1631 return resume_res;
1632
1633 // Don't send an "OK" packet, except in non-stop mode;
1634 // otherwise, the response is the stopped/exited message.
1635 return SendContinueSuccessResponse();
1636 }
1637
1638 GDBRemoteCommunication::PacketResult
Handle_c(StringExtractorGDBRemote & packet)1639 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1640 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1641 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1642
1643 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1644
1645 // For now just support all continue.
1646 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1647 if (has_continue_address) {
1648 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1649 packet.Peek());
1650 return SendUnimplementedResponse(packet.GetStringRef().data());
1651 }
1652
1653 // Ensure we have a native process.
1654 if (!m_continue_process) {
1655 LLDB_LOGF(log,
1656 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1657 "shared pointer",
1658 __FUNCTION__);
1659 return SendErrorResponse(0x36);
1660 }
1661
1662 // Build the ResumeActionList
1663 ResumeActionList actions(StateType::eStateRunning,
1664 LLDB_INVALID_SIGNAL_NUMBER);
1665
1666 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
1667 if (resume_res != PacketResult::Success)
1668 return resume_res;
1669
1670 return SendContinueSuccessResponse();
1671 }
1672
1673 GDBRemoteCommunication::PacketResult
Handle_vCont_actions(StringExtractorGDBRemote & packet)1674 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1675 StringExtractorGDBRemote &packet) {
1676 StreamString response;
1677 response.Printf("vCont;c;C;s;S;t");
1678
1679 return SendPacketNoLock(response.GetString());
1680 }
1681
ResumeActionListStopsAllThreads(ResumeActionList & actions)1682 static bool ResumeActionListStopsAllThreads(ResumeActionList &actions) {
1683 // We're doing a stop-all if and only if our only action is a "t" for all
1684 // threads.
1685 if (const ResumeAction *default_action =
1686 actions.GetActionForThread(LLDB_INVALID_THREAD_ID, false)) {
1687 if (default_action->state == eStateSuspended && actions.GetSize() == 1)
1688 return true;
1689 }
1690
1691 return false;
1692 }
1693
1694 GDBRemoteCommunication::PacketResult
Handle_vCont(StringExtractorGDBRemote & packet)1695 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1696 StringExtractorGDBRemote &packet) {
1697 Log *log = GetLog(LLDBLog::Process);
1698 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1699 __FUNCTION__);
1700
1701 packet.SetFilePos(::strlen("vCont"));
1702
1703 if (packet.GetBytesLeft() == 0) {
1704 LLDB_LOGF(log,
1705 "GDBRemoteCommunicationServerLLGS::%s missing action from "
1706 "vCont package",
1707 __FUNCTION__);
1708 return SendIllFormedResponse(packet, "Missing action from vCont package");
1709 }
1710
1711 if (::strcmp(packet.Peek(), ";s") == 0) {
1712 // Move past the ';', then do a simple 's'.
1713 packet.SetFilePos(packet.GetFilePos() + 1);
1714 return Handle_s(packet);
1715 }
1716
1717 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;
1718
1719 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1720 // Skip the semi-colon.
1721 packet.GetChar();
1722
1723 // Build up the thread action.
1724 ResumeAction thread_action;
1725 thread_action.tid = LLDB_INVALID_THREAD_ID;
1726 thread_action.state = eStateInvalid;
1727 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1728
1729 const char action = packet.GetChar();
1730 switch (action) {
1731 case 'C':
1732 thread_action.signal = packet.GetHexMaxU32(false, 0);
1733 if (thread_action.signal == 0)
1734 return SendIllFormedResponse(
1735 packet, "Could not parse signal in vCont packet C action");
1736 LLVM_FALLTHROUGH;
1737
1738 case 'c':
1739 // Continue
1740 thread_action.state = eStateRunning;
1741 break;
1742
1743 case 'S':
1744 thread_action.signal = packet.GetHexMaxU32(false, 0);
1745 if (thread_action.signal == 0)
1746 return SendIllFormedResponse(
1747 packet, "Could not parse signal in vCont packet S action");
1748 LLVM_FALLTHROUGH;
1749
1750 case 's':
1751 // Step
1752 thread_action.state = eStateStepping;
1753 break;
1754
1755 case 't':
1756 // Stop
1757 thread_action.state = eStateSuspended;
1758 break;
1759
1760 default:
1761 return SendIllFormedResponse(packet, "Unsupported vCont action");
1762 break;
1763 }
1764
1765 lldb::pid_t pid = StringExtractorGDBRemote::AllProcesses;
1766 lldb::tid_t tid = StringExtractorGDBRemote::AllThreads;
1767
1768 // Parse out optional :{thread-id} value.
1769 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1770 // Consume the separator.
1771 packet.GetChar();
1772
1773 auto pid_tid = packet.GetPidTid(StringExtractorGDBRemote::AllProcesses);
1774 if (!pid_tid)
1775 return SendIllFormedResponse(packet, "Malformed thread-id");
1776
1777 pid = pid_tid->first;
1778 tid = pid_tid->second;
1779 }
1780
1781 if (thread_action.state == eStateSuspended &&
1782 tid != StringExtractorGDBRemote::AllThreads) {
1783 return SendIllFormedResponse(
1784 packet, "'t' action not supported for individual threads");
1785 }
1786
1787 if (pid == StringExtractorGDBRemote::AllProcesses) {
1788 if (m_debugged_processes.size() > 1)
1789 return SendIllFormedResponse(
1790 packet, "Resuming multiple processes not supported yet");
1791 if (!m_continue_process) {
1792 LLDB_LOG(log, "no debugged process");
1793 return SendErrorResponse(0x36);
1794 }
1795 pid = m_continue_process->GetID();
1796 }
1797
1798 if (tid == StringExtractorGDBRemote::AllThreads)
1799 tid = LLDB_INVALID_THREAD_ID;
1800
1801 thread_action.tid = tid;
1802
1803 thread_actions[pid].Append(thread_action);
1804 }
1805
1806 assert(thread_actions.size() >= 1);
1807 if (thread_actions.size() > 1)
1808 return SendIllFormedResponse(
1809 packet, "Resuming multiple processes not supported yet");
1810
1811 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {
1812 auto process_it = m_debugged_processes.find(x.first);
1813 if (process_it == m_debugged_processes.end()) {
1814 LLDB_LOG(log, "vCont failed for process {0}: process not debugged",
1815 x.first);
1816 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1817 }
1818
1819 // There are four possible scenarios here. These are:
1820 // 1. vCont on a stopped process that resumes at least one thread.
1821 // In this case, we call Resume().
1822 // 2. vCont on a stopped process that leaves all threads suspended.
1823 // A no-op.
1824 // 3. vCont on a running process that requests suspending all
1825 // running threads. In this case, we call Interrupt().
1826 // 4. vCont on a running process that requests suspending a subset
1827 // of running threads or resuming a subset of suspended threads.
1828 // Since we do not support full nonstop mode, this is unsupported
1829 // and we return an error.
1830
1831 assert(process_it->second.process_up);
1832 if (ResumeActionListStopsAllThreads(x.second)) {
1833 if (process_it->second.process_up->IsRunning()) {
1834 assert(m_non_stop);
1835
1836 Status error = process_it->second.process_up->Interrupt();
1837 if (error.Fail()) {
1838 LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first,
1839 error);
1840 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1841 }
1842
1843 LLDB_LOG(log, "halted process {0}", x.first);
1844
1845 // hack to avoid enabling stdio forwarding after stop
1846 // TODO: remove this when we improve stdio forwarding for nonstop
1847 assert(thread_actions.size() == 1);
1848 return SendOKResponse();
1849 }
1850 } else {
1851 PacketResult resume_res =
1852 ResumeProcess(*process_it->second.process_up, x.second);
1853 if (resume_res != PacketResult::Success)
1854 return resume_res;
1855 }
1856 }
1857
1858 return SendContinueSuccessResponse();
1859 }
1860
SetCurrentThreadID(lldb::tid_t tid)1861 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1862 Log *log = GetLog(LLDBLog::Thread);
1863 LLDB_LOG(log, "setting current thread id to {0}", tid);
1864
1865 m_current_tid = tid;
1866 if (m_current_process)
1867 m_current_process->SetCurrentThreadID(m_current_tid);
1868 }
1869
SetContinueThreadID(lldb::tid_t tid)1870 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1871 Log *log = GetLog(LLDBLog::Thread);
1872 LLDB_LOG(log, "setting continue thread id to {0}", tid);
1873
1874 m_continue_tid = tid;
1875 }
1876
1877 GDBRemoteCommunication::PacketResult
Handle_stop_reason(StringExtractorGDBRemote & packet)1878 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1879 StringExtractorGDBRemote &packet) {
1880 // Handle the $? gdbremote command.
1881
1882 if (m_non_stop) {
1883 // Clear the notification queue first, except for pending exit
1884 // notifications.
1885 llvm::erase_if(m_stop_notification_queue, [](const std::string &x) {
1886 return x.front() != 'W' && x.front() != 'X';
1887 });
1888
1889 if (m_current_process) {
1890 // Queue stop reply packets for all active threads. Start with
1891 // the current thread (for clients that don't actually support multiple
1892 // stop reasons).
1893 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1894 if (thread) {
1895 StreamString stop_reply = PrepareStopReplyPacketForThread(*thread);
1896 if (!stop_reply.Empty())
1897 m_stop_notification_queue.push_back(stop_reply.GetString().str());
1898 }
1899 EnqueueStopReplyPackets(thread ? thread->GetID()
1900 : LLDB_INVALID_THREAD_ID);
1901 }
1902
1903 // If the notification queue is empty (i.e. everything is running), send OK.
1904 if (m_stop_notification_queue.empty())
1905 return SendOKResponse();
1906
1907 // Send the first item from the new notification queue synchronously.
1908 return SendPacketNoLock(m_stop_notification_queue.front());
1909 }
1910
1911 // If no process, indicate error
1912 if (!m_current_process)
1913 return SendErrorResponse(02);
1914
1915 return SendStopReasonForState(*m_current_process,
1916 m_current_process->GetState(),
1917 /*force_synchronous=*/true);
1918 }
1919
1920 GDBRemoteCommunication::PacketResult
SendStopReasonForState(NativeProcessProtocol & process,lldb::StateType process_state,bool force_synchronous)1921 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1922 NativeProcessProtocol &process, lldb::StateType process_state,
1923 bool force_synchronous) {
1924 Log *log = GetLog(LLDBLog::Process);
1925
1926 if (m_disabling_non_stop) {
1927 // Check if we are waiting for any more processes to stop. If we are,
1928 // do not send the OK response yet.
1929 for (const auto &it : m_debugged_processes) {
1930 if (it.second.process_up->IsRunning())
1931 return PacketResult::Success;
1932 }
1933
1934 // If all expected processes were stopped after a QNonStop:0 request,
1935 // send the OK response.
1936 m_disabling_non_stop = false;
1937 return SendOKResponse();
1938 }
1939
1940 switch (process_state) {
1941 case eStateAttaching:
1942 case eStateLaunching:
1943 case eStateRunning:
1944 case eStateStepping:
1945 case eStateDetached:
1946 // NOTE: gdb protocol doc looks like it should return $OK
1947 // when everything is running (i.e. no stopped result).
1948 return PacketResult::Success; // Ignore
1949
1950 case eStateSuspended:
1951 case eStateStopped:
1952 case eStateCrashed: {
1953 lldb::tid_t tid = process.GetCurrentThreadID();
1954 // Make sure we set the current thread so g and p packets return the data
1955 // the gdb will expect.
1956 SetCurrentThreadID(tid);
1957 return SendStopReplyPacketForThread(process, tid, force_synchronous);
1958 }
1959
1960 case eStateInvalid:
1961 case eStateUnloaded:
1962 case eStateExited:
1963 return SendWResponse(&process);
1964
1965 default:
1966 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1967 process.GetID(), process_state);
1968 break;
1969 }
1970
1971 return SendErrorResponse(0);
1972 }
1973
1974 GDBRemoteCommunication::PacketResult
Handle_qRegisterInfo(StringExtractorGDBRemote & packet)1975 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1976 StringExtractorGDBRemote &packet) {
1977 // Fail if we don't have a current process.
1978 if (!m_current_process ||
1979 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1980 return SendErrorResponse(68);
1981
1982 // Ensure we have a thread.
1983 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
1984 if (!thread)
1985 return SendErrorResponse(69);
1986
1987 // Get the register context for the first thread.
1988 NativeRegisterContext ®_context = thread->GetRegisterContext();
1989
1990 // Parse out the register number from the request.
1991 packet.SetFilePos(strlen("qRegisterInfo"));
1992 const uint32_t reg_index =
1993 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1994 if (reg_index == std::numeric_limits<uint32_t>::max())
1995 return SendErrorResponse(69);
1996
1997 // Return the end of registers response if we've iterated one past the end of
1998 // the register set.
1999 if (reg_index >= reg_context.GetUserRegisterCount())
2000 return SendErrorResponse(69);
2001
2002 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2003 if (!reg_info)
2004 return SendErrorResponse(69);
2005
2006 // Build the reginfos response.
2007 StreamGDBRemote response;
2008
2009 response.PutCString("name:");
2010 response.PutCString(reg_info->name);
2011 response.PutChar(';');
2012
2013 if (reg_info->alt_name && reg_info->alt_name[0]) {
2014 response.PutCString("alt-name:");
2015 response.PutCString(reg_info->alt_name);
2016 response.PutChar(';');
2017 }
2018
2019 response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);
2020
2021 if (!reg_context.RegisterOffsetIsDynamic())
2022 response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);
2023
2024 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2025 if (!encoding.empty())
2026 response << "encoding:" << encoding << ';';
2027
2028 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2029 if (!format.empty())
2030 response << "format:" << format << ';';
2031
2032 const char *const register_set_name =
2033 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2034 if (register_set_name)
2035 response << "set:" << register_set_name << ';';
2036
2037 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
2038 LLDB_INVALID_REGNUM)
2039 response.Printf("ehframe:%" PRIu32 ";",
2040 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
2041
2042 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
2043 response.Printf("dwarf:%" PRIu32 ";",
2044 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2045
2046 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2047 if (!kind_generic.empty())
2048 response << "generic:" << kind_generic << ';';
2049
2050 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2051 response.PutCString("container-regs:");
2052 CollectRegNums(reg_info->value_regs, response, true);
2053 response.PutChar(';');
2054 }
2055
2056 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2057 response.PutCString("invalidate-regs:");
2058 CollectRegNums(reg_info->invalidate_regs, response, true);
2059 response.PutChar(';');
2060 }
2061
2062 return SendPacketNoLock(response.GetString());
2063 }
2064
AddProcessThreads(StreamGDBRemote & response,NativeProcessProtocol & process,bool & had_any)2065 void GDBRemoteCommunicationServerLLGS::AddProcessThreads(
2066 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {
2067 Log *log = GetLog(LLDBLog::Thread);
2068
2069 lldb::pid_t pid = process.GetID();
2070 if (pid == LLDB_INVALID_PROCESS_ID)
2071 return;
2072
2073 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());
2074 for (NativeThreadProtocol &thread : process.Threads()) {
2075 LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());
2076 response.PutChar(had_any ? ',' : 'm');
2077 AppendThreadIDToResponse(response, pid, thread.GetID());
2078 had_any = true;
2079 }
2080 }
2081
2082 GDBRemoteCommunication::PacketResult
Handle_qfThreadInfo(StringExtractorGDBRemote & packet)2083 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
2084 StringExtractorGDBRemote &packet) {
2085 assert(m_debugged_processes.size() == 1 ||
2086 bool(m_extensions_supported &
2087 NativeProcessProtocol::Extension::multiprocess));
2088
2089 bool had_any = false;
2090 StreamGDBRemote response;
2091
2092 for (auto &pid_ptr : m_debugged_processes)
2093 AddProcessThreads(response, *pid_ptr.second.process_up, had_any);
2094
2095 if (!had_any)
2096 return SendOKResponse();
2097 return SendPacketNoLock(response.GetString());
2098 }
2099
2100 GDBRemoteCommunication::PacketResult
Handle_qsThreadInfo(StringExtractorGDBRemote & packet)2101 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
2102 StringExtractorGDBRemote &packet) {
2103 // FIXME for now we return the full thread list in the initial packet and
2104 // always do nothing here.
2105 return SendPacketNoLock("l");
2106 }
2107
2108 GDBRemoteCommunication::PacketResult
Handle_g(StringExtractorGDBRemote & packet)2109 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
2110 Log *log = GetLog(LLDBLog::Thread);
2111
2112 // Move past packet name.
2113 packet.SetFilePos(strlen("g"));
2114
2115 // Get the thread to use.
2116 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2117 if (!thread) {
2118 LLDB_LOG(log, "failed, no thread available");
2119 return SendErrorResponse(0x15);
2120 }
2121
2122 // Get the thread's register context.
2123 NativeRegisterContext ®_ctx = thread->GetRegisterContext();
2124
2125 std::vector<uint8_t> regs_buffer;
2126 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
2127 ++reg_num) {
2128 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
2129
2130 if (reg_info == nullptr) {
2131 LLDB_LOG(log, "failed to get register info for register index {0}",
2132 reg_num);
2133 return SendErrorResponse(0x15);
2134 }
2135
2136 if (reg_info->value_regs != nullptr)
2137 continue; // skip registers that are contained in other registers
2138
2139 RegisterValue reg_value;
2140 Status error = reg_ctx.ReadRegister(reg_info, reg_value);
2141 if (error.Fail()) {
2142 LLDB_LOG(log, "failed to read register at index {0}", reg_num);
2143 return SendErrorResponse(0x15);
2144 }
2145
2146 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2147 // Resize the buffer to guarantee it can store the register offsetted
2148 // data.
2149 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2150
2151 // Copy the register offsetted data to the buffer.
2152 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
2153 reg_info->byte_size);
2154 }
2155
2156 // Write the response.
2157 StreamGDBRemote response;
2158 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
2159
2160 return SendPacketNoLock(response.GetString());
2161 }
2162
2163 GDBRemoteCommunication::PacketResult
Handle_p(StringExtractorGDBRemote & packet)2164 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2165 Log *log = GetLog(LLDBLog::Thread);
2166
2167 // Parse out the register number from the request.
2168 packet.SetFilePos(strlen("p"));
2169 const uint32_t reg_index =
2170 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2171 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2172 LLDB_LOGF(log,
2173 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2174 "parse register number from request \"%s\"",
2175 __FUNCTION__, packet.GetStringRef().data());
2176 return SendErrorResponse(0x15);
2177 }
2178
2179 // Get the thread to use.
2180 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2181 if (!thread) {
2182 LLDB_LOG(log, "failed, no thread available");
2183 return SendErrorResponse(0x15);
2184 }
2185
2186 // Get the thread's register context.
2187 NativeRegisterContext ®_context = thread->GetRegisterContext();
2188
2189 // Return the end of registers response if we've iterated one past the end of
2190 // the register set.
2191 if (reg_index >= reg_context.GetUserRegisterCount()) {
2192 LLDB_LOGF(log,
2193 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2194 "register %" PRIu32 " beyond register count %" PRIu32,
2195 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2196 return SendErrorResponse(0x15);
2197 }
2198
2199 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2200 if (!reg_info) {
2201 LLDB_LOGF(log,
2202 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2203 "register %" PRIu32 " returned NULL",
2204 __FUNCTION__, reg_index);
2205 return SendErrorResponse(0x15);
2206 }
2207
2208 // Build the reginfos response.
2209 StreamGDBRemote response;
2210
2211 // Retrieve the value
2212 RegisterValue reg_value;
2213 Status error = reg_context.ReadRegister(reg_info, reg_value);
2214 if (error.Fail()) {
2215 LLDB_LOGF(log,
2216 "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2217 "requested register %" PRIu32 " (%s) failed: %s",
2218 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2219 return SendErrorResponse(0x15);
2220 }
2221
2222 const uint8_t *const data =
2223 static_cast<const uint8_t *>(reg_value.GetBytes());
2224 if (!data) {
2225 LLDB_LOGF(log,
2226 "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2227 "bytes from requested register %" PRIu32,
2228 __FUNCTION__, reg_index);
2229 return SendErrorResponse(0x15);
2230 }
2231
2232 // FIXME flip as needed to get data in big/little endian format for this host.
2233 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2234 response.PutHex8(data[i]);
2235
2236 return SendPacketNoLock(response.GetString());
2237 }
2238
2239 GDBRemoteCommunication::PacketResult
Handle_P(StringExtractorGDBRemote & packet)2240 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2241 Log *log = GetLog(LLDBLog::Thread);
2242
2243 // Ensure there is more content.
2244 if (packet.GetBytesLeft() < 1)
2245 return SendIllFormedResponse(packet, "Empty P packet");
2246
2247 // Parse out the register number from the request.
2248 packet.SetFilePos(strlen("P"));
2249 const uint32_t reg_index =
2250 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2251 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2252 LLDB_LOGF(log,
2253 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2254 "parse register number from request \"%s\"",
2255 __FUNCTION__, packet.GetStringRef().data());
2256 return SendErrorResponse(0x29);
2257 }
2258
2259 // Note debugserver would send an E30 here.
2260 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2261 return SendIllFormedResponse(
2262 packet, "P packet missing '=' char after register number");
2263
2264 // Parse out the value.
2265 uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize];
2266 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2267
2268 // Get the thread to use.
2269 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2270 if (!thread) {
2271 LLDB_LOGF(log,
2272 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2273 "available (thread index 0)",
2274 __FUNCTION__);
2275 return SendErrorResponse(0x28);
2276 }
2277
2278 // Get the thread's register context.
2279 NativeRegisterContext ®_context = thread->GetRegisterContext();
2280 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2281 if (!reg_info) {
2282 LLDB_LOGF(log,
2283 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2284 "register %" PRIu32 " returned NULL",
2285 __FUNCTION__, reg_index);
2286 return SendErrorResponse(0x48);
2287 }
2288
2289 // Return the end of registers response if we've iterated one past the end of
2290 // the register set.
2291 if (reg_index >= reg_context.GetUserRegisterCount()) {
2292 LLDB_LOGF(log,
2293 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2294 "register %" PRIu32 " beyond register count %" PRIu32,
2295 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2296 return SendErrorResponse(0x47);
2297 }
2298
2299 if (reg_size != reg_info->byte_size)
2300 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2301
2302 // Build the reginfos response.
2303 StreamGDBRemote response;
2304
2305 RegisterValue reg_value(makeArrayRef(reg_bytes, reg_size),
2306 m_current_process->GetArchitecture().GetByteOrder());
2307 Status error = reg_context.WriteRegister(reg_info, reg_value);
2308 if (error.Fail()) {
2309 LLDB_LOGF(log,
2310 "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2311 "requested register %" PRIu32 " (%s) failed: %s",
2312 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2313 return SendErrorResponse(0x32);
2314 }
2315
2316 return SendOKResponse();
2317 }
2318
2319 GDBRemoteCommunication::PacketResult
Handle_H(StringExtractorGDBRemote & packet)2320 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2321 Log *log = GetLog(LLDBLog::Thread);
2322
2323 // Parse out which variant of $H is requested.
2324 packet.SetFilePos(strlen("H"));
2325 if (packet.GetBytesLeft() < 1) {
2326 LLDB_LOGF(log,
2327 "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2328 "missing {g,c} variant",
2329 __FUNCTION__);
2330 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2331 }
2332
2333 const char h_variant = packet.GetChar();
2334 NativeProcessProtocol *default_process;
2335 switch (h_variant) {
2336 case 'g':
2337 default_process = m_current_process;
2338 break;
2339
2340 case 'c':
2341 default_process = m_continue_process;
2342 break;
2343
2344 default:
2345 LLDB_LOGF(
2346 log,
2347 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2348 __FUNCTION__, h_variant);
2349 return SendIllFormedResponse(packet,
2350 "H variant unsupported, should be c or g");
2351 }
2352
2353 // Parse out the thread number.
2354 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2355 : LLDB_INVALID_PROCESS_ID);
2356 if (!pid_tid)
2357 return SendErrorResponse(llvm::make_error<StringError>(
2358 inconvertibleErrorCode(), "Malformed thread-id"));
2359
2360 lldb::pid_t pid = pid_tid->first;
2361 lldb::tid_t tid = pid_tid->second;
2362
2363 if (pid == StringExtractorGDBRemote::AllProcesses)
2364 return SendUnimplementedResponse("Selecting all processes not supported");
2365 if (pid == LLDB_INVALID_PROCESS_ID)
2366 return SendErrorResponse(llvm::make_error<StringError>(
2367 inconvertibleErrorCode(), "No current process and no PID provided"));
2368
2369 // Check the process ID and find respective process instance.
2370 auto new_process_it = m_debugged_processes.find(pid);
2371 if (new_process_it == m_debugged_processes.end())
2372 return SendErrorResponse(llvm::make_error<StringError>(
2373 inconvertibleErrorCode(),
2374 llvm::formatv("No process with PID {0} debugged", pid)));
2375
2376 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2377 // (any thread).
2378 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2379 NativeThreadProtocol *thread =
2380 new_process_it->second.process_up->GetThreadByID(tid);
2381 if (!thread) {
2382 LLDB_LOGF(log,
2383 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2384 " not found",
2385 __FUNCTION__, tid);
2386 return SendErrorResponse(0x15);
2387 }
2388 }
2389
2390 // Now switch the given process and thread type.
2391 switch (h_variant) {
2392 case 'g':
2393 m_current_process = new_process_it->second.process_up.get();
2394 SetCurrentThreadID(tid);
2395 break;
2396
2397 case 'c':
2398 m_continue_process = new_process_it->second.process_up.get();
2399 SetContinueThreadID(tid);
2400 break;
2401
2402 default:
2403 assert(false && "unsupported $H variant - shouldn't get here");
2404 return SendIllFormedResponse(packet,
2405 "H variant unsupported, should be c or g");
2406 }
2407
2408 return SendOKResponse();
2409 }
2410
2411 GDBRemoteCommunication::PacketResult
Handle_I(StringExtractorGDBRemote & packet)2412 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2413 Log *log = GetLog(LLDBLog::Thread);
2414
2415 // Fail if we don't have a current process.
2416 if (!m_current_process ||
2417 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2418 LLDB_LOGF(
2419 log,
2420 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2421 __FUNCTION__);
2422 return SendErrorResponse(0x15);
2423 }
2424
2425 packet.SetFilePos(::strlen("I"));
2426 uint8_t tmp[4096];
2427 for (;;) {
2428 size_t read = packet.GetHexBytesAvail(tmp);
2429 if (read == 0) {
2430 break;
2431 }
2432 // write directly to stdin *this might block if stdin buffer is full*
2433 // TODO: enqueue this block in circular buffer and send window size to
2434 // remote host
2435 ConnectionStatus status;
2436 Status error;
2437 m_stdio_communication.Write(tmp, read, status, &error);
2438 if (error.Fail()) {
2439 return SendErrorResponse(0x15);
2440 }
2441 }
2442
2443 return SendOKResponse();
2444 }
2445
2446 GDBRemoteCommunication::PacketResult
Handle_interrupt(StringExtractorGDBRemote & packet)2447 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2448 StringExtractorGDBRemote &packet) {
2449 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
2450
2451 // Fail if we don't have a current process.
2452 if (!m_current_process ||
2453 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2454 LLDB_LOG(log, "failed, no process available");
2455 return SendErrorResponse(0x15);
2456 }
2457
2458 // Interrupt the process.
2459 Status error = m_current_process->Interrupt();
2460 if (error.Fail()) {
2461 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
2462 error);
2463 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2464 }
2465
2466 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2467
2468 // No response required from stop all.
2469 return PacketResult::Success;
2470 }
2471
2472 GDBRemoteCommunication::PacketResult
Handle_memory_read(StringExtractorGDBRemote & packet)2473 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2474 StringExtractorGDBRemote &packet) {
2475 Log *log = GetLog(LLDBLog::Process);
2476
2477 if (!m_current_process ||
2478 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2479 LLDB_LOGF(
2480 log,
2481 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2482 __FUNCTION__);
2483 return SendErrorResponse(0x15);
2484 }
2485
2486 // Parse out the memory address.
2487 packet.SetFilePos(strlen("m"));
2488 if (packet.GetBytesLeft() < 1)
2489 return SendIllFormedResponse(packet, "Too short m packet");
2490
2491 // Read the address. Punting on validation.
2492 // FIXME replace with Hex U64 read with no default value that fails on failed
2493 // read.
2494 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2495
2496 // Validate comma.
2497 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2498 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2499
2500 // Get # bytes to read.
2501 if (packet.GetBytesLeft() < 1)
2502 return SendIllFormedResponse(packet, "Length missing in m packet");
2503
2504 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2505 if (byte_count == 0) {
2506 LLDB_LOGF(log,
2507 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2508 "zero-length packet",
2509 __FUNCTION__);
2510 return SendOKResponse();
2511 }
2512
2513 // Allocate the response buffer.
2514 std::string buf(byte_count, '\0');
2515 if (buf.empty())
2516 return SendErrorResponse(0x78);
2517
2518 // Retrieve the process memory.
2519 size_t bytes_read = 0;
2520 Status error = m_current_process->ReadMemoryWithoutTrap(
2521 read_addr, &buf[0], byte_count, bytes_read);
2522 if (error.Fail()) {
2523 LLDB_LOGF(log,
2524 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2525 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2526 __FUNCTION__, m_current_process->GetID(), read_addr,
2527 error.AsCString());
2528 return SendErrorResponse(0x08);
2529 }
2530
2531 if (bytes_read == 0) {
2532 LLDB_LOGF(log,
2533 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2534 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2535 __FUNCTION__, m_current_process->GetID(), read_addr, byte_count);
2536 return SendErrorResponse(0x08);
2537 }
2538
2539 StreamGDBRemote response;
2540 packet.SetFilePos(0);
2541 char kind = packet.GetChar('?');
2542 if (kind == 'x')
2543 response.PutEscapedBytes(buf.data(), byte_count);
2544 else {
2545 assert(kind == 'm');
2546 for (size_t i = 0; i < bytes_read; ++i)
2547 response.PutHex8(buf[i]);
2548 }
2549
2550 return SendPacketNoLock(response.GetString());
2551 }
2552
2553 GDBRemoteCommunication::PacketResult
Handle__M(StringExtractorGDBRemote & packet)2554 GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) {
2555 Log *log = GetLog(LLDBLog::Process);
2556
2557 if (!m_current_process ||
2558 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2559 LLDB_LOGF(
2560 log,
2561 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2562 __FUNCTION__);
2563 return SendErrorResponse(0x15);
2564 }
2565
2566 // Parse out the memory address.
2567 packet.SetFilePos(strlen("_M"));
2568 if (packet.GetBytesLeft() < 1)
2569 return SendIllFormedResponse(packet, "Too short _M packet");
2570
2571 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2572 if (size == LLDB_INVALID_ADDRESS)
2573 return SendIllFormedResponse(packet, "Address not valid");
2574 if (packet.GetChar() != ',')
2575 return SendIllFormedResponse(packet, "Bad packet");
2576 Permissions perms = {};
2577 while (packet.GetBytesLeft() > 0) {
2578 switch (packet.GetChar()) {
2579 case 'r':
2580 perms |= ePermissionsReadable;
2581 break;
2582 case 'w':
2583 perms |= ePermissionsWritable;
2584 break;
2585 case 'x':
2586 perms |= ePermissionsExecutable;
2587 break;
2588 default:
2589 return SendIllFormedResponse(packet, "Bad permissions");
2590 }
2591 }
2592
2593 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
2594 if (!addr)
2595 return SendErrorResponse(addr.takeError());
2596
2597 StreamGDBRemote response;
2598 response.PutHex64(*addr);
2599 return SendPacketNoLock(response.GetString());
2600 }
2601
2602 GDBRemoteCommunication::PacketResult
Handle__m(StringExtractorGDBRemote & packet)2603 GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) {
2604 Log *log = GetLog(LLDBLog::Process);
2605
2606 if (!m_current_process ||
2607 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2608 LLDB_LOGF(
2609 log,
2610 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2611 __FUNCTION__);
2612 return SendErrorResponse(0x15);
2613 }
2614
2615 // Parse out the memory address.
2616 packet.SetFilePos(strlen("_m"));
2617 if (packet.GetBytesLeft() < 1)
2618 return SendIllFormedResponse(packet, "Too short m packet");
2619
2620 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2621 if (addr == LLDB_INVALID_ADDRESS)
2622 return SendIllFormedResponse(packet, "Address not valid");
2623
2624 if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
2625 return SendErrorResponse(std::move(Err));
2626
2627 return SendOKResponse();
2628 }
2629
2630 GDBRemoteCommunication::PacketResult
Handle_M(StringExtractorGDBRemote & packet)2631 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2632 Log *log = GetLog(LLDBLog::Process);
2633
2634 if (!m_current_process ||
2635 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2636 LLDB_LOGF(
2637 log,
2638 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2639 __FUNCTION__);
2640 return SendErrorResponse(0x15);
2641 }
2642
2643 // Parse out the memory address.
2644 packet.SetFilePos(strlen("M"));
2645 if (packet.GetBytesLeft() < 1)
2646 return SendIllFormedResponse(packet, "Too short M packet");
2647
2648 // Read the address. Punting on validation.
2649 // FIXME replace with Hex U64 read with no default value that fails on failed
2650 // read.
2651 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2652
2653 // Validate comma.
2654 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2655 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2656
2657 // Get # bytes to read.
2658 if (packet.GetBytesLeft() < 1)
2659 return SendIllFormedResponse(packet, "Length missing in M packet");
2660
2661 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2662 if (byte_count == 0) {
2663 LLDB_LOG(log, "nothing to write: zero-length packet");
2664 return PacketResult::Success;
2665 }
2666
2667 // Validate colon.
2668 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2669 return SendIllFormedResponse(
2670 packet, "Comma sep missing in M packet after byte length");
2671
2672 // Allocate the conversion buffer.
2673 std::vector<uint8_t> buf(byte_count, 0);
2674 if (buf.empty())
2675 return SendErrorResponse(0x78);
2676
2677 // Convert the hex memory write contents to bytes.
2678 StreamGDBRemote response;
2679 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2680 if (convert_count != byte_count) {
2681 LLDB_LOG(log,
2682 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2683 "to convert.",
2684 m_current_process->GetID(), write_addr, byte_count, convert_count);
2685 return SendIllFormedResponse(packet, "M content byte length specified did "
2686 "not match hex-encoded content "
2687 "length");
2688 }
2689
2690 // Write the process memory.
2691 size_t bytes_written = 0;
2692 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2693 bytes_written);
2694 if (error.Fail()) {
2695 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2696 m_current_process->GetID(), write_addr, error);
2697 return SendErrorResponse(0x09);
2698 }
2699
2700 if (bytes_written == 0) {
2701 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2702 m_current_process->GetID(), write_addr, byte_count);
2703 return SendErrorResponse(0x09);
2704 }
2705
2706 return SendOKResponse();
2707 }
2708
2709 GDBRemoteCommunication::PacketResult
Handle_qMemoryRegionInfoSupported(StringExtractorGDBRemote & packet)2710 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2711 StringExtractorGDBRemote &packet) {
2712 Log *log = GetLog(LLDBLog::Process);
2713
2714 // Currently only the NativeProcessProtocol knows if it can handle a
2715 // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2716 // attached to a process. For now we'll assume the client only asks this
2717 // when a process is being debugged.
2718
2719 // Ensure we have a process running; otherwise, we can't figure this out
2720 // since we won't have a NativeProcessProtocol.
2721 if (!m_current_process ||
2722 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2723 LLDB_LOGF(
2724 log,
2725 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2726 __FUNCTION__);
2727 return SendErrorResponse(0x15);
2728 }
2729
2730 // Test if we can get any region back when asking for the region around NULL.
2731 MemoryRegionInfo region_info;
2732 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2733 if (error.Fail()) {
2734 // We don't support memory region info collection for this
2735 // NativeProcessProtocol.
2736 return SendUnimplementedResponse("");
2737 }
2738
2739 return SendOKResponse();
2740 }
2741
2742 GDBRemoteCommunication::PacketResult
Handle_qMemoryRegionInfo(StringExtractorGDBRemote & packet)2743 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2744 StringExtractorGDBRemote &packet) {
2745 Log *log = GetLog(LLDBLog::Process);
2746
2747 // Ensure we have a process.
2748 if (!m_current_process ||
2749 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2750 LLDB_LOGF(
2751 log,
2752 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2753 __FUNCTION__);
2754 return SendErrorResponse(0x15);
2755 }
2756
2757 // Parse out the memory address.
2758 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2759 if (packet.GetBytesLeft() < 1)
2760 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2761
2762 // Read the address. Punting on validation.
2763 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2764
2765 StreamGDBRemote response;
2766
2767 // Get the memory region info for the target address.
2768 MemoryRegionInfo region_info;
2769 const Status error =
2770 m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2771 if (error.Fail()) {
2772 // Return the error message.
2773
2774 response.PutCString("error:");
2775 response.PutStringAsRawHex8(error.AsCString());
2776 response.PutChar(';');
2777 } else {
2778 // Range start and size.
2779 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2780 region_info.GetRange().GetRangeBase(),
2781 region_info.GetRange().GetByteSize());
2782
2783 // Permissions.
2784 if (region_info.GetReadable() || region_info.GetWritable() ||
2785 region_info.GetExecutable()) {
2786 // Write permissions info.
2787 response.PutCString("permissions:");
2788
2789 if (region_info.GetReadable())
2790 response.PutChar('r');
2791 if (region_info.GetWritable())
2792 response.PutChar('w');
2793 if (region_info.GetExecutable())
2794 response.PutChar('x');
2795
2796 response.PutChar(';');
2797 }
2798
2799 // Flags
2800 MemoryRegionInfo::OptionalBool memory_tagged =
2801 region_info.GetMemoryTagged();
2802 if (memory_tagged != MemoryRegionInfo::eDontKnow) {
2803 response.PutCString("flags:");
2804 if (memory_tagged == MemoryRegionInfo::eYes) {
2805 response.PutCString("mt");
2806 }
2807 response.PutChar(';');
2808 }
2809
2810 // Name
2811 ConstString name = region_info.GetName();
2812 if (name) {
2813 response.PutCString("name:");
2814 response.PutStringAsRawHex8(name.GetStringRef());
2815 response.PutChar(';');
2816 }
2817 }
2818
2819 return SendPacketNoLock(response.GetString());
2820 }
2821
2822 GDBRemoteCommunication::PacketResult
Handle_Z(StringExtractorGDBRemote & packet)2823 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2824 // Ensure we have a process.
2825 if (!m_current_process ||
2826 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2827 Log *log = GetLog(LLDBLog::Process);
2828 LLDB_LOG(log, "failed, no process available");
2829 return SendErrorResponse(0x15);
2830 }
2831
2832 // Parse out software or hardware breakpoint or watchpoint requested.
2833 packet.SetFilePos(strlen("Z"));
2834 if (packet.GetBytesLeft() < 1)
2835 return SendIllFormedResponse(
2836 packet, "Too short Z packet, missing software/hardware specifier");
2837
2838 bool want_breakpoint = true;
2839 bool want_hardware = false;
2840 uint32_t watch_flags = 0;
2841
2842 const GDBStoppointType stoppoint_type =
2843 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2844 switch (stoppoint_type) {
2845 case eBreakpointSoftware:
2846 want_hardware = false;
2847 want_breakpoint = true;
2848 break;
2849 case eBreakpointHardware:
2850 want_hardware = true;
2851 want_breakpoint = true;
2852 break;
2853 case eWatchpointWrite:
2854 watch_flags = 1;
2855 want_hardware = true;
2856 want_breakpoint = false;
2857 break;
2858 case eWatchpointRead:
2859 watch_flags = 2;
2860 want_hardware = true;
2861 want_breakpoint = false;
2862 break;
2863 case eWatchpointReadWrite:
2864 watch_flags = 3;
2865 want_hardware = true;
2866 want_breakpoint = false;
2867 break;
2868 case eStoppointInvalid:
2869 return SendIllFormedResponse(
2870 packet, "Z packet had invalid software/hardware specifier");
2871 }
2872
2873 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2874 return SendIllFormedResponse(
2875 packet, "Malformed Z packet, expecting comma after stoppoint type");
2876
2877 // Parse out the stoppoint address.
2878 if (packet.GetBytesLeft() < 1)
2879 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2880 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2881
2882 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2883 return SendIllFormedResponse(
2884 packet, "Malformed Z packet, expecting comma after address");
2885
2886 // Parse out the stoppoint size (i.e. size hint for opcode size).
2887 const uint32_t size =
2888 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2889 if (size == std::numeric_limits<uint32_t>::max())
2890 return SendIllFormedResponse(
2891 packet, "Malformed Z packet, failed to parse size argument");
2892
2893 if (want_breakpoint) {
2894 // Try to set the breakpoint.
2895 const Status error =
2896 m_current_process->SetBreakpoint(addr, size, want_hardware);
2897 if (error.Success())
2898 return SendOKResponse();
2899 Log *log = GetLog(LLDBLog::Breakpoints);
2900 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2901 m_current_process->GetID(), error);
2902 return SendErrorResponse(0x09);
2903 } else {
2904 // Try to set the watchpoint.
2905 const Status error = m_current_process->SetWatchpoint(
2906 addr, size, watch_flags, want_hardware);
2907 if (error.Success())
2908 return SendOKResponse();
2909 Log *log = GetLog(LLDBLog::Watchpoints);
2910 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2911 m_current_process->GetID(), error);
2912 return SendErrorResponse(0x09);
2913 }
2914 }
2915
2916 GDBRemoteCommunication::PacketResult
Handle_z(StringExtractorGDBRemote & packet)2917 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2918 // Ensure we have a process.
2919 if (!m_current_process ||
2920 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2921 Log *log = GetLog(LLDBLog::Process);
2922 LLDB_LOG(log, "failed, no process available");
2923 return SendErrorResponse(0x15);
2924 }
2925
2926 // Parse out software or hardware breakpoint or watchpoint requested.
2927 packet.SetFilePos(strlen("z"));
2928 if (packet.GetBytesLeft() < 1)
2929 return SendIllFormedResponse(
2930 packet, "Too short z packet, missing software/hardware specifier");
2931
2932 bool want_breakpoint = true;
2933 bool want_hardware = false;
2934
2935 const GDBStoppointType stoppoint_type =
2936 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2937 switch (stoppoint_type) {
2938 case eBreakpointHardware:
2939 want_breakpoint = true;
2940 want_hardware = true;
2941 break;
2942 case eBreakpointSoftware:
2943 want_breakpoint = true;
2944 break;
2945 case eWatchpointWrite:
2946 want_breakpoint = false;
2947 break;
2948 case eWatchpointRead:
2949 want_breakpoint = false;
2950 break;
2951 case eWatchpointReadWrite:
2952 want_breakpoint = false;
2953 break;
2954 default:
2955 return SendIllFormedResponse(
2956 packet, "z packet had invalid software/hardware specifier");
2957 }
2958
2959 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2960 return SendIllFormedResponse(
2961 packet, "Malformed z packet, expecting comma after stoppoint type");
2962
2963 // Parse out the stoppoint address.
2964 if (packet.GetBytesLeft() < 1)
2965 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2966 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2967
2968 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2969 return SendIllFormedResponse(
2970 packet, "Malformed z packet, expecting comma after address");
2971
2972 /*
2973 // Parse out the stoppoint size (i.e. size hint for opcode size).
2974 const uint32_t size = packet.GetHexMaxU32 (false,
2975 std::numeric_limits<uint32_t>::max ());
2976 if (size == std::numeric_limits<uint32_t>::max ())
2977 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2978 size argument");
2979 */
2980
2981 if (want_breakpoint) {
2982 // Try to clear the breakpoint.
2983 const Status error =
2984 m_current_process->RemoveBreakpoint(addr, want_hardware);
2985 if (error.Success())
2986 return SendOKResponse();
2987 Log *log = GetLog(LLDBLog::Breakpoints);
2988 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2989 m_current_process->GetID(), error);
2990 return SendErrorResponse(0x09);
2991 } else {
2992 // Try to clear the watchpoint.
2993 const Status error = m_current_process->RemoveWatchpoint(addr);
2994 if (error.Success())
2995 return SendOKResponse();
2996 Log *log = GetLog(LLDBLog::Watchpoints);
2997 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2998 m_current_process->GetID(), error);
2999 return SendErrorResponse(0x09);
3000 }
3001 }
3002
3003 GDBRemoteCommunication::PacketResult
Handle_s(StringExtractorGDBRemote & packet)3004 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
3005 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3006
3007 // Ensure we have a process.
3008 if (!m_continue_process ||
3009 (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3010 LLDB_LOGF(
3011 log,
3012 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3013 __FUNCTION__);
3014 return SendErrorResponse(0x32);
3015 }
3016
3017 // We first try to use a continue thread id. If any one or any all set, use
3018 // the current thread. Bail out if we don't have a thread id.
3019 lldb::tid_t tid = GetContinueThreadID();
3020 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3021 tid = GetCurrentThreadID();
3022 if (tid == LLDB_INVALID_THREAD_ID)
3023 return SendErrorResponse(0x33);
3024
3025 // Double check that we have such a thread.
3026 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3027 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);
3028 if (!thread)
3029 return SendErrorResponse(0x33);
3030
3031 // Create the step action for the given thread.
3032 ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
3033
3034 // Setup the actions list.
3035 ResumeActionList actions;
3036 actions.Append(action);
3037
3038 // All other threads stop while we're single stepping a thread.
3039 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3040
3041 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
3042 if (resume_res != PacketResult::Success)
3043 return resume_res;
3044
3045 // No response here, unless in non-stop mode.
3046 // Otherwise, the stop or exit will come from the resulting action.
3047 return SendContinueSuccessResponse();
3048 }
3049
3050 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
BuildTargetXml()3051 GDBRemoteCommunicationServerLLGS::BuildTargetXml() {
3052 // Ensure we have a thread.
3053 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
3054 if (!thread)
3055 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3056 "No thread available");
3057
3058 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3059 // Get the register context for the first thread.
3060 NativeRegisterContext ®_context = thread->GetRegisterContext();
3061
3062 StreamString response;
3063
3064 response.Printf("<?xml version=\"1.0\"?>");
3065 response.Printf("<target version=\"1.0\">");
3066
3067 response.Printf("<architecture>%s</architecture>",
3068 m_current_process->GetArchitecture()
3069 .GetTriple()
3070 .getArchName()
3071 .str()
3072 .c_str());
3073
3074 response.Printf("<feature>");
3075
3076 const int registers_count = reg_context.GetUserRegisterCount();
3077 for (int reg_index = 0; reg_index < registers_count; reg_index++) {
3078 const RegisterInfo *reg_info =
3079 reg_context.GetRegisterInfoAtIndex(reg_index);
3080
3081 if (!reg_info) {
3082 LLDB_LOGF(log,
3083 "%s failed to get register info for register index %" PRIu32,
3084 "target.xml", reg_index);
3085 continue;
3086 }
3087
3088 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" regnum=\"%d\" ",
3089 reg_info->name, reg_info->byte_size * 8, reg_index);
3090
3091 if (!reg_context.RegisterOffsetIsDynamic())
3092 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
3093
3094 if (reg_info->alt_name && reg_info->alt_name[0])
3095 response.Printf("altname=\"%s\" ", reg_info->alt_name);
3096
3097 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
3098 if (!encoding.empty())
3099 response << "encoding=\"" << encoding << "\" ";
3100
3101 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
3102 if (!format.empty())
3103 response << "format=\"" << format << "\" ";
3104
3105 const char *const register_set_name =
3106 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
3107 if (register_set_name)
3108 response << "group=\"" << register_set_name << "\" ";
3109
3110 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
3111 LLDB_INVALID_REGNUM)
3112 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
3113 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
3114
3115 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3116 LLDB_INVALID_REGNUM)
3117 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
3118 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3119
3120 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
3121 if (!kind_generic.empty())
3122 response << "generic=\"" << kind_generic << "\" ";
3123
3124 if (reg_info->value_regs &&
3125 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
3126 response.PutCString("value_regnums=\"");
3127 CollectRegNums(reg_info->value_regs, response, false);
3128 response.Printf("\" ");
3129 }
3130
3131 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3132 response.PutCString("invalidate_regnums=\"");
3133 CollectRegNums(reg_info->invalidate_regs, response, false);
3134 response.Printf("\" ");
3135 }
3136
3137 response.Printf("/>");
3138 }
3139
3140 response.Printf("</feature>");
3141 response.Printf("</target>");
3142 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
3143 }
3144
3145 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
ReadXferObject(llvm::StringRef object,llvm::StringRef annex)3146 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
3147 llvm::StringRef annex) {
3148 // Make sure we have a valid process.
3149 if (!m_current_process ||
3150 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3151 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3152 "No process available");
3153 }
3154
3155 if (object == "auxv") {
3156 // Grab the auxv data.
3157 auto buffer_or_error = m_current_process->GetAuxvData();
3158 if (!buffer_or_error)
3159 return llvm::errorCodeToError(buffer_or_error.getError());
3160 return std::move(*buffer_or_error);
3161 }
3162
3163 if (object == "siginfo") {
3164 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
3165 if (!thread)
3166 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3167 "no current thread");
3168
3169 auto buffer_or_error = thread->GetSiginfo();
3170 if (!buffer_or_error)
3171 return buffer_or_error.takeError();
3172 return std::move(*buffer_or_error);
3173 }
3174
3175 if (object == "libraries-svr4") {
3176 auto library_list = m_current_process->GetLoadedSVR4Libraries();
3177 if (!library_list)
3178 return library_list.takeError();
3179
3180 StreamString response;
3181 response.Printf("<library-list-svr4 version=\"1.0\">");
3182 for (auto const &library : *library_list) {
3183 response.Printf("<library name=\"%s\" ",
3184 XMLEncodeAttributeValue(library.name.c_str()).c_str());
3185 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
3186 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
3187 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
3188 }
3189 response.Printf("</library-list-svr4>");
3190 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3191 }
3192
3193 if (object == "features" && annex == "target.xml")
3194 return BuildTargetXml();
3195
3196 return llvm::make_error<UnimplementedError>();
3197 }
3198
3199 GDBRemoteCommunication::PacketResult
Handle_qXfer(StringExtractorGDBRemote & packet)3200 GDBRemoteCommunicationServerLLGS::Handle_qXfer(
3201 StringExtractorGDBRemote &packet) {
3202 SmallVector<StringRef, 5> fields;
3203 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
3204 StringRef(packet.GetStringRef()).split(fields, ':', 4);
3205 if (fields.size() != 5)
3206 return SendIllFormedResponse(packet, "malformed qXfer packet");
3207 StringRef &xfer_object = fields[1];
3208 StringRef &xfer_action = fields[2];
3209 StringRef &xfer_annex = fields[3];
3210 StringExtractor offset_data(fields[4]);
3211 if (xfer_action != "read")
3212 return SendUnimplementedResponse("qXfer action not supported");
3213 // Parse offset.
3214 const uint64_t xfer_offset =
3215 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3216 if (xfer_offset == std::numeric_limits<uint64_t>::max())
3217 return SendIllFormedResponse(packet, "qXfer packet missing offset");
3218 // Parse out comma.
3219 if (offset_data.GetChar() != ',')
3220 return SendIllFormedResponse(packet,
3221 "qXfer packet missing comma after offset");
3222 // Parse out the length.
3223 const uint64_t xfer_length =
3224 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3225 if (xfer_length == std::numeric_limits<uint64_t>::max())
3226 return SendIllFormedResponse(packet, "qXfer packet missing length");
3227
3228 // Get a previously constructed buffer if it exists or create it now.
3229 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3230 auto buffer_it = m_xfer_buffer_map.find(buffer_key);
3231 if (buffer_it == m_xfer_buffer_map.end()) {
3232 auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
3233 if (!buffer_up)
3234 return SendErrorResponse(buffer_up.takeError());
3235 buffer_it = m_xfer_buffer_map
3236 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3237 .first;
3238 }
3239
3240 // Send back the response
3241 StreamGDBRemote response;
3242 bool done_with_buffer = false;
3243 llvm::StringRef buffer = buffer_it->second->getBuffer();
3244 if (xfer_offset >= buffer.size()) {
3245 // We have nothing left to send. Mark the buffer as complete.
3246 response.PutChar('l');
3247 done_with_buffer = true;
3248 } else {
3249 // Figure out how many bytes are available starting at the given offset.
3250 buffer = buffer.drop_front(xfer_offset);
3251 // Mark the response type according to whether we're reading the remainder
3252 // of the data.
3253 if (xfer_length >= buffer.size()) {
3254 // There will be nothing left to read after this
3255 response.PutChar('l');
3256 done_with_buffer = true;
3257 } else {
3258 // There will still be bytes to read after this request.
3259 response.PutChar('m');
3260 buffer = buffer.take_front(xfer_length);
3261 }
3262 // Now write the data in encoded binary form.
3263 response.PutEscapedBytes(buffer.data(), buffer.size());
3264 }
3265
3266 if (done_with_buffer)
3267 m_xfer_buffer_map.erase(buffer_it);
3268
3269 return SendPacketNoLock(response.GetString());
3270 }
3271
3272 GDBRemoteCommunication::PacketResult
Handle_QSaveRegisterState(StringExtractorGDBRemote & packet)3273 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
3274 StringExtractorGDBRemote &packet) {
3275 Log *log = GetLog(LLDBLog::Thread);
3276
3277 // Move past packet name.
3278 packet.SetFilePos(strlen("QSaveRegisterState"));
3279
3280 // Get the thread to use.
3281 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3282 if (!thread) {
3283 if (m_thread_suffix_supported)
3284 return SendIllFormedResponse(
3285 packet, "No thread specified in QSaveRegisterState packet");
3286 else
3287 return SendIllFormedResponse(packet,
3288 "No thread was is set with the Hg packet");
3289 }
3290
3291 // Grab the register context for the thread.
3292 NativeRegisterContext& reg_context = thread->GetRegisterContext();
3293
3294 // Save registers to a buffer.
3295 WritableDataBufferSP register_data_sp;
3296 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3297 if (error.Fail()) {
3298 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3299 m_current_process->GetID(), error);
3300 return SendErrorResponse(0x75);
3301 }
3302
3303 // Allocate a new save id.
3304 const uint32_t save_id = GetNextSavedRegistersID();
3305 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3306 "GetNextRegisterSaveID() returned an existing register save id");
3307
3308 // Save the register data buffer under the save id.
3309 {
3310 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3311 m_saved_registers_map[save_id] = register_data_sp;
3312 }
3313
3314 // Write the response.
3315 StreamGDBRemote response;
3316 response.Printf("%" PRIu32, save_id);
3317 return SendPacketNoLock(response.GetString());
3318 }
3319
3320 GDBRemoteCommunication::PacketResult
Handle_QRestoreRegisterState(StringExtractorGDBRemote & packet)3321 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3322 StringExtractorGDBRemote &packet) {
3323 Log *log = GetLog(LLDBLog::Thread);
3324
3325 // Parse out save id.
3326 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3327 if (packet.GetBytesLeft() < 1)
3328 return SendIllFormedResponse(
3329 packet, "QRestoreRegisterState packet missing register save id");
3330
3331 const uint32_t save_id = packet.GetU32(0);
3332 if (save_id == 0) {
3333 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3334 "expecting decimal uint32_t");
3335 return SendErrorResponse(0x76);
3336 }
3337
3338 // Get the thread to use.
3339 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3340 if (!thread) {
3341 if (m_thread_suffix_supported)
3342 return SendIllFormedResponse(
3343 packet, "No thread specified in QRestoreRegisterState packet");
3344 else
3345 return SendIllFormedResponse(packet,
3346 "No thread was is set with the Hg packet");
3347 }
3348
3349 // Grab the register context for the thread.
3350 NativeRegisterContext ®_context = thread->GetRegisterContext();
3351
3352 // Retrieve register state buffer, then remove from the list.
3353 DataBufferSP register_data_sp;
3354 {
3355 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3356
3357 // Find the register set buffer for the given save id.
3358 auto it = m_saved_registers_map.find(save_id);
3359 if (it == m_saved_registers_map.end()) {
3360 LLDB_LOG(log,
3361 "pid {0} does not have a register set save buffer for id {1}",
3362 m_current_process->GetID(), save_id);
3363 return SendErrorResponse(0x77);
3364 }
3365 register_data_sp = it->second;
3366
3367 // Remove it from the map.
3368 m_saved_registers_map.erase(it);
3369 }
3370
3371 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3372 if (error.Fail()) {
3373 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3374 m_current_process->GetID(), error);
3375 return SendErrorResponse(0x77);
3376 }
3377
3378 return SendOKResponse();
3379 }
3380
3381 GDBRemoteCommunication::PacketResult
Handle_vAttach(StringExtractorGDBRemote & packet)3382 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3383 StringExtractorGDBRemote &packet) {
3384 Log *log = GetLog(LLDBLog::Process);
3385
3386 // Consume the ';' after vAttach.
3387 packet.SetFilePos(strlen("vAttach"));
3388 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3389 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3390
3391 // Grab the PID to which we will attach (assume hex encoding).
3392 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3393 if (pid == LLDB_INVALID_PROCESS_ID)
3394 return SendIllFormedResponse(packet,
3395 "vAttach failed to parse the process id");
3396
3397 // Attempt to attach.
3398 LLDB_LOGF(log,
3399 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3400 "pid %" PRIu64,
3401 __FUNCTION__, pid);
3402
3403 Status error = AttachToProcess(pid);
3404
3405 if (error.Fail()) {
3406 LLDB_LOGF(log,
3407 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3408 "pid %" PRIu64 ": %s\n",
3409 __FUNCTION__, pid, error.AsCString());
3410 return SendErrorResponse(error);
3411 }
3412
3413 // Notify we attached by sending a stop packet.
3414 assert(m_current_process);
3415 return SendStopReasonForState(*m_current_process,
3416 m_current_process->GetState(),
3417 /*force_synchronous=*/false);
3418 }
3419
3420 GDBRemoteCommunication::PacketResult
Handle_vAttachWait(StringExtractorGDBRemote & packet)3421 GDBRemoteCommunicationServerLLGS::Handle_vAttachWait(
3422 StringExtractorGDBRemote &packet) {
3423 Log *log = GetLog(LLDBLog::Process);
3424
3425 // Consume the ';' after the identifier.
3426 packet.SetFilePos(strlen("vAttachWait"));
3427
3428 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3429 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
3430
3431 // Allocate the buffer for the process name from vAttachWait.
3432 std::string process_name;
3433 if (!packet.GetHexByteString(process_name))
3434 return SendIllFormedResponse(packet,
3435 "vAttachWait failed to parse process name");
3436
3437 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3438
3439 Status error = AttachWaitProcess(process_name, false);
3440 if (error.Fail()) {
3441 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3442 error);
3443 return SendErrorResponse(error);
3444 }
3445
3446 // Notify we attached by sending a stop packet.
3447 assert(m_current_process);
3448 return SendStopReasonForState(*m_current_process,
3449 m_current_process->GetState(),
3450 /*force_synchronous=*/false);
3451 }
3452
3453 GDBRemoteCommunication::PacketResult
Handle_qVAttachOrWaitSupported(StringExtractorGDBRemote & packet)3454 GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported(
3455 StringExtractorGDBRemote &packet) {
3456 return SendOKResponse();
3457 }
3458
3459 GDBRemoteCommunication::PacketResult
Handle_vAttachOrWait(StringExtractorGDBRemote & packet)3460 GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait(
3461 StringExtractorGDBRemote &packet) {
3462 Log *log = GetLog(LLDBLog::Process);
3463
3464 // Consume the ';' after the identifier.
3465 packet.SetFilePos(strlen("vAttachOrWait"));
3466
3467 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3468 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
3469
3470 // Allocate the buffer for the process name from vAttachWait.
3471 std::string process_name;
3472 if (!packet.GetHexByteString(process_name))
3473 return SendIllFormedResponse(packet,
3474 "vAttachOrWait failed to parse process name");
3475
3476 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3477
3478 Status error = AttachWaitProcess(process_name, true);
3479 if (error.Fail()) {
3480 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3481 error);
3482 return SendErrorResponse(error);
3483 }
3484
3485 // Notify we attached by sending a stop packet.
3486 assert(m_current_process);
3487 return SendStopReasonForState(*m_current_process,
3488 m_current_process->GetState(),
3489 /*force_synchronous=*/false);
3490 }
3491
3492 GDBRemoteCommunication::PacketResult
Handle_vRun(StringExtractorGDBRemote & packet)3493 GDBRemoteCommunicationServerLLGS::Handle_vRun(
3494 StringExtractorGDBRemote &packet) {
3495 Log *log = GetLog(LLDBLog::Process);
3496
3497 llvm::StringRef s = packet.GetStringRef();
3498 if (!s.consume_front("vRun;"))
3499 return SendErrorResponse(8);
3500
3501 llvm::SmallVector<llvm::StringRef, 16> argv;
3502 s.split(argv, ';');
3503
3504 for (llvm::StringRef hex_arg : argv) {
3505 StringExtractor arg_ext{hex_arg};
3506 std::string arg;
3507 arg_ext.GetHexByteString(arg);
3508 m_process_launch_info.GetArguments().AppendArgument(arg);
3509 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3510 arg.c_str());
3511 }
3512
3513 if (!argv.empty()) {
3514 m_process_launch_info.GetExecutableFile().SetFile(
3515 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);
3516 m_process_launch_error = LaunchProcess();
3517 if (m_process_launch_error.Success()) {
3518 assert(m_current_process);
3519 return SendStopReasonForState(*m_current_process,
3520 m_current_process->GetState(),
3521 /*force_synchronous=*/true);
3522 }
3523 LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error);
3524 }
3525 return SendErrorResponse(8);
3526 }
3527
3528 GDBRemoteCommunication::PacketResult
Handle_D(StringExtractorGDBRemote & packet)3529 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3530 Log *log = GetLog(LLDBLog::Process);
3531 if (!m_non_stop)
3532 StopSTDIOForwarding();
3533
3534 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3535
3536 // Consume the ';' after D.
3537 packet.SetFilePos(1);
3538 if (packet.GetBytesLeft()) {
3539 if (packet.GetChar() != ';')
3540 return SendIllFormedResponse(packet, "D missing expected ';'");
3541
3542 // Grab the PID from which we will detach (assume hex encoding).
3543 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3544 if (pid == LLDB_INVALID_PROCESS_ID)
3545 return SendIllFormedResponse(packet, "D failed to parse the process id");
3546 }
3547
3548 // Detach forked children if their PID was specified *or* no PID was requested
3549 // (i.e. detach-all packet).
3550 llvm::Error detach_error = llvm::Error::success();
3551 bool detached = false;
3552 for (auto it = m_debugged_processes.begin();
3553 it != m_debugged_processes.end();) {
3554 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
3555 LLDB_LOGF(log,
3556 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3557 __FUNCTION__, it->first);
3558 if (llvm::Error e = it->second.process_up->Detach().ToError())
3559 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3560 else {
3561 if (it->second.process_up.get() == m_current_process)
3562 m_current_process = nullptr;
3563 if (it->second.process_up.get() == m_continue_process)
3564 m_continue_process = nullptr;
3565 it = m_debugged_processes.erase(it);
3566 detached = true;
3567 continue;
3568 }
3569 }
3570 ++it;
3571 }
3572
3573 if (detach_error)
3574 return SendErrorResponse(std::move(detach_error));
3575 if (!detached)
3576 return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid));
3577 return SendOKResponse();
3578 }
3579
3580 GDBRemoteCommunication::PacketResult
Handle_qThreadStopInfo(StringExtractorGDBRemote & packet)3581 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3582 StringExtractorGDBRemote &packet) {
3583 Log *log = GetLog(LLDBLog::Thread);
3584
3585 if (!m_current_process ||
3586 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3587 return SendErrorResponse(50);
3588
3589 packet.SetFilePos(strlen("qThreadStopInfo"));
3590 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3591 if (tid == LLDB_INVALID_THREAD_ID) {
3592 LLDB_LOGF(log,
3593 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3594 "parse thread id from request \"%s\"",
3595 __FUNCTION__, packet.GetStringRef().data());
3596 return SendErrorResponse(0x15);
3597 }
3598 return SendStopReplyPacketForThread(*m_current_process, tid,
3599 /*force_synchronous=*/true);
3600 }
3601
3602 GDBRemoteCommunication::PacketResult
Handle_jThreadsInfo(StringExtractorGDBRemote &)3603 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3604 StringExtractorGDBRemote &) {
3605 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3606
3607 // Ensure we have a debugged process.
3608 if (!m_current_process ||
3609 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3610 return SendErrorResponse(50);
3611 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
3612
3613 StreamString response;
3614 const bool threads_with_valid_stop_info_only = false;
3615 llvm::Expected<json::Value> threads_info =
3616 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
3617 if (!threads_info) {
3618 LLDB_LOG_ERROR(log, threads_info.takeError(),
3619 "failed to prepare a packet for pid {1}: {0}",
3620 m_current_process->GetID());
3621 return SendErrorResponse(52);
3622 }
3623
3624 response.AsRawOstream() << *threads_info;
3625 StreamGDBRemote escaped_response;
3626 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3627 return SendPacketNoLock(escaped_response.GetString());
3628 }
3629
3630 GDBRemoteCommunication::PacketResult
Handle_qWatchpointSupportInfo(StringExtractorGDBRemote & packet)3631 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3632 StringExtractorGDBRemote &packet) {
3633 // Fail if we don't have a current process.
3634 if (!m_current_process ||
3635 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3636 return SendErrorResponse(68);
3637
3638 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3639 if (packet.GetBytesLeft() == 0)
3640 return SendOKResponse();
3641 if (packet.GetChar() != ':')
3642 return SendErrorResponse(67);
3643
3644 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
3645
3646 StreamGDBRemote response;
3647 if (hw_debug_cap == llvm::None)
3648 response.Printf("num:0;");
3649 else
3650 response.Printf("num:%d;", hw_debug_cap->second);
3651
3652 return SendPacketNoLock(response.GetString());
3653 }
3654
3655 GDBRemoteCommunication::PacketResult
Handle_qFileLoadAddress(StringExtractorGDBRemote & packet)3656 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3657 StringExtractorGDBRemote &packet) {
3658 // Fail if we don't have a current process.
3659 if (!m_current_process ||
3660 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3661 return SendErrorResponse(67);
3662
3663 packet.SetFilePos(strlen("qFileLoadAddress:"));
3664 if (packet.GetBytesLeft() == 0)
3665 return SendErrorResponse(68);
3666
3667 std::string file_name;
3668 packet.GetHexByteString(file_name);
3669
3670 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3671 Status error =
3672 m_current_process->GetFileLoadAddress(file_name, file_load_address);
3673 if (error.Fail())
3674 return SendErrorResponse(69);
3675
3676 if (file_load_address == LLDB_INVALID_ADDRESS)
3677 return SendErrorResponse(1); // File not loaded
3678
3679 StreamGDBRemote response;
3680 response.PutHex64(file_load_address);
3681 return SendPacketNoLock(response.GetString());
3682 }
3683
3684 GDBRemoteCommunication::PacketResult
Handle_QPassSignals(StringExtractorGDBRemote & packet)3685 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3686 StringExtractorGDBRemote &packet) {
3687 std::vector<int> signals;
3688 packet.SetFilePos(strlen("QPassSignals:"));
3689
3690 // Read sequence of hex signal numbers divided by a semicolon and optionally
3691 // spaces.
3692 while (packet.GetBytesLeft() > 0) {
3693 int signal = packet.GetS32(-1, 16);
3694 if (signal < 0)
3695 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3696 signals.push_back(signal);
3697
3698 packet.SkipSpaces();
3699 char separator = packet.GetChar();
3700 if (separator == '\0')
3701 break; // End of string
3702 if (separator != ';')
3703 return SendIllFormedResponse(packet, "Invalid separator,"
3704 " expected semicolon.");
3705 }
3706
3707 // Fail if we don't have a current process.
3708 if (!m_current_process)
3709 return SendErrorResponse(68);
3710
3711 Status error = m_current_process->IgnoreSignals(signals);
3712 if (error.Fail())
3713 return SendErrorResponse(69);
3714
3715 return SendOKResponse();
3716 }
3717
3718 GDBRemoteCommunication::PacketResult
Handle_qMemTags(StringExtractorGDBRemote & packet)3719 GDBRemoteCommunicationServerLLGS::Handle_qMemTags(
3720 StringExtractorGDBRemote &packet) {
3721 Log *log = GetLog(LLDBLog::Process);
3722
3723 // Ensure we have a process.
3724 if (!m_current_process ||
3725 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3726 LLDB_LOGF(
3727 log,
3728 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3729 __FUNCTION__);
3730 return SendErrorResponse(1);
3731 }
3732
3733 // We are expecting
3734 // qMemTags:<hex address>,<hex length>:<hex type>
3735
3736 // Address
3737 packet.SetFilePos(strlen("qMemTags:"));
3738 const char *current_char = packet.Peek();
3739 if (!current_char || *current_char == ',')
3740 return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
3741 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3742
3743 // Length
3744 char previous_char = packet.GetChar();
3745 current_char = packet.Peek();
3746 // If we don't have a separator or the length field is empty
3747 if (previous_char != ',' || (current_char && *current_char == ':'))
3748 return SendIllFormedResponse(packet,
3749 "Invalid addr,length pair in qMemTags packet");
3750
3751 if (packet.GetBytesLeft() < 1)
3752 return SendIllFormedResponse(
3753 packet, "Too short qMemtags: packet (looking for length)");
3754 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3755
3756 // Type
3757 const char *invalid_type_err = "Invalid type field in qMemTags: packet";
3758 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3759 return SendIllFormedResponse(packet, invalid_type_err);
3760
3761 // Type is a signed integer but packed into the packet as its raw bytes.
3762 // However, our GetU64 uses strtoull which allows +/-. We do not want this.
3763 const char *first_type_char = packet.Peek();
3764 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3765 return SendIllFormedResponse(packet, invalid_type_err);
3766
3767 // Extract type as unsigned then cast to signed.
3768 // Using a uint64_t here so that we have some value outside of the 32 bit
3769 // range to use as the invalid return value.
3770 uint64_t raw_type =
3771 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3772
3773 if ( // Make sure the cast below would be valid
3774 raw_type > std::numeric_limits<uint32_t>::max() ||
3775 // To catch inputs like "123aardvark" that will parse but clearly aren't
3776 // valid in this case.
3777 packet.GetBytesLeft()) {
3778 return SendIllFormedResponse(packet, invalid_type_err);
3779 }
3780
3781 // First narrow to 32 bits otherwise the copy into type would take
3782 // the wrong 4 bytes on big endian.
3783 uint32_t raw_type_32 = raw_type;
3784 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3785
3786 StreamGDBRemote response;
3787 std::vector<uint8_t> tags;
3788 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
3789 if (error.Fail())
3790 return SendErrorResponse(1);
3791
3792 // This m is here in case we want to support multi part replies in the future.
3793 // In the same manner as qfThreadInfo/qsThreadInfo.
3794 response.PutChar('m');
3795 response.PutBytesAsRawHex8(tags.data(), tags.size());
3796 return SendPacketNoLock(response.GetString());
3797 }
3798
3799 GDBRemoteCommunication::PacketResult
Handle_QMemTags(StringExtractorGDBRemote & packet)3800 GDBRemoteCommunicationServerLLGS::Handle_QMemTags(
3801 StringExtractorGDBRemote &packet) {
3802 Log *log = GetLog(LLDBLog::Process);
3803
3804 // Ensure we have a process.
3805 if (!m_current_process ||
3806 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3807 LLDB_LOGF(
3808 log,
3809 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3810 __FUNCTION__);
3811 return SendErrorResponse(1);
3812 }
3813
3814 // We are expecting
3815 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
3816
3817 // Address
3818 packet.SetFilePos(strlen("QMemTags:"));
3819 const char *current_char = packet.Peek();
3820 if (!current_char || *current_char == ',')
3821 return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
3822 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3823
3824 // Length
3825 char previous_char = packet.GetChar();
3826 current_char = packet.Peek();
3827 // If we don't have a separator or the length field is empty
3828 if (previous_char != ',' || (current_char && *current_char == ':'))
3829 return SendIllFormedResponse(packet,
3830 "Invalid addr,length pair in QMemTags packet");
3831
3832 if (packet.GetBytesLeft() < 1)
3833 return SendIllFormedResponse(
3834 packet, "Too short QMemtags: packet (looking for length)");
3835 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3836
3837 // Type
3838 const char *invalid_type_err = "Invalid type field in QMemTags: packet";
3839 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3840 return SendIllFormedResponse(packet, invalid_type_err);
3841
3842 // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
3843 const char *first_type_char = packet.Peek();
3844 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3845 return SendIllFormedResponse(packet, invalid_type_err);
3846
3847 // The type is a signed integer but is in the packet as its raw bytes.
3848 // So parse first as unsigned then cast to signed later.
3849 // We extract to 64 bit, even though we only expect 32, so that we've
3850 // got some invalid value we can check for.
3851 uint64_t raw_type =
3852 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3853 if (raw_type > std::numeric_limits<uint32_t>::max())
3854 return SendIllFormedResponse(packet, invalid_type_err);
3855
3856 // First narrow to 32 bits. Otherwise the copy below would get the wrong
3857 // 4 bytes on big endian.
3858 uint32_t raw_type_32 = raw_type;
3859 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3860
3861 // Tag data
3862 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3863 return SendIllFormedResponse(packet,
3864 "Missing tag data in QMemTags: packet");
3865
3866 // Must be 2 chars per byte
3867 const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
3868 if (packet.GetBytesLeft() % 2)
3869 return SendIllFormedResponse(packet, invalid_data_err);
3870
3871 // This is bytes here and is unpacked into target specific tags later
3872 // We cannot assume that number of bytes == length here because the server
3873 // can repeat tags to fill a given range.
3874 std::vector<uint8_t> tag_data;
3875 // Zero length writes will not have any tag data
3876 // (but we pass them on because it will still check that tagging is enabled)
3877 if (packet.GetBytesLeft()) {
3878 size_t byte_count = packet.GetBytesLeft() / 2;
3879 tag_data.resize(byte_count);
3880 size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
3881 if (converted_bytes != byte_count) {
3882 return SendIllFormedResponse(packet, invalid_data_err);
3883 }
3884 }
3885
3886 Status status =
3887 m_current_process->WriteMemoryTags(type, addr, length, tag_data);
3888 return status.Success() ? SendOKResponse() : SendErrorResponse(1);
3889 }
3890
3891 GDBRemoteCommunication::PacketResult
Handle_qSaveCore(StringExtractorGDBRemote & packet)3892 GDBRemoteCommunicationServerLLGS::Handle_qSaveCore(
3893 StringExtractorGDBRemote &packet) {
3894 // Fail if we don't have a current process.
3895 if (!m_current_process ||
3896 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3897 return SendErrorResponse(Status("Process not running."));
3898
3899 std::string path_hint;
3900
3901 StringRef packet_str{packet.GetStringRef()};
3902 assert(packet_str.startswith("qSaveCore"));
3903 if (packet_str.consume_front("qSaveCore;")) {
3904 for (auto x : llvm::split(packet_str, ';')) {
3905 if (x.consume_front("path-hint:"))
3906 StringExtractor(x).GetHexByteString(path_hint);
3907 else
3908 return SendErrorResponse(Status("Unsupported qSaveCore option"));
3909 }
3910 }
3911
3912 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);
3913 if (!ret)
3914 return SendErrorResponse(ret.takeError());
3915
3916 StreamString response;
3917 response.PutCString("core-path:");
3918 response.PutStringAsRawHex8(ret.get());
3919 return SendPacketNoLock(response.GetString());
3920 }
3921
3922 GDBRemoteCommunication::PacketResult
Handle_QNonStop(StringExtractorGDBRemote & packet)3923 GDBRemoteCommunicationServerLLGS::Handle_QNonStop(
3924 StringExtractorGDBRemote &packet) {
3925 Log *log = GetLog(LLDBLog::Process);
3926
3927 StringRef packet_str{packet.GetStringRef()};
3928 assert(packet_str.startswith("QNonStop:"));
3929 packet_str.consume_front("QNonStop:");
3930 if (packet_str == "0") {
3931 if (m_non_stop)
3932 StopSTDIOForwarding();
3933 for (auto &process_it : m_debugged_processes) {
3934 if (process_it.second.process_up->IsRunning()) {
3935 assert(m_non_stop);
3936 Status error = process_it.second.process_up->Interrupt();
3937 if (error.Fail()) {
3938 LLDB_LOG(log,
3939 "while disabling nonstop, failed to halt process {0}: {1}",
3940 process_it.first, error);
3941 return SendErrorResponse(0x41);
3942 }
3943 // we must not send stop reasons after QNonStop
3944 m_disabling_non_stop = true;
3945 }
3946 }
3947 m_stdio_notification_queue.clear();
3948 m_stop_notification_queue.clear();
3949 m_non_stop = false;
3950 // If we are stopping anything, defer sending the OK response until we're
3951 // done.
3952 if (m_disabling_non_stop)
3953 return PacketResult::Success;
3954 } else if (packet_str == "1") {
3955 if (!m_non_stop)
3956 StartSTDIOForwarding();
3957 m_non_stop = true;
3958 } else
3959 return SendErrorResponse(Status("Invalid QNonStop packet"));
3960 return SendOKResponse();
3961 }
3962
3963 GDBRemoteCommunication::PacketResult
HandleNotificationAck(std::deque<std::string> & queue)3964 GDBRemoteCommunicationServerLLGS::HandleNotificationAck(
3965 std::deque<std::string> &queue) {
3966 // Per the protocol, the first message put into the queue is sent
3967 // immediately. However, it remains the queue until the client ACKs it --
3968 // then we pop it and send the next message. The process repeats until
3969 // the last message in the queue is ACK-ed, in which case the packet sends
3970 // an OK response.
3971 if (queue.empty())
3972 return SendErrorResponse(Status("No pending notification to ack"));
3973 queue.pop_front();
3974 if (!queue.empty())
3975 return SendPacketNoLock(queue.front());
3976 return SendOKResponse();
3977 }
3978
3979 GDBRemoteCommunication::PacketResult
Handle_vStdio(StringExtractorGDBRemote & packet)3980 GDBRemoteCommunicationServerLLGS::Handle_vStdio(
3981 StringExtractorGDBRemote &packet) {
3982 return HandleNotificationAck(m_stdio_notification_queue);
3983 }
3984
3985 GDBRemoteCommunication::PacketResult
Handle_vStopped(StringExtractorGDBRemote & packet)3986 GDBRemoteCommunicationServerLLGS::Handle_vStopped(
3987 StringExtractorGDBRemote &packet) {
3988 PacketResult ret = HandleNotificationAck(m_stop_notification_queue);
3989 // If this was the last notification and all the processes exited,
3990 // terminate the server.
3991 if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {
3992 m_exit_now = true;
3993 m_mainloop.RequestTermination();
3994 }
3995 return ret;
3996 }
3997
3998 GDBRemoteCommunication::PacketResult
Handle_vCtrlC(StringExtractorGDBRemote & packet)3999 GDBRemoteCommunicationServerLLGS::Handle_vCtrlC(
4000 StringExtractorGDBRemote &packet) {
4001 if (!m_non_stop)
4002 return SendErrorResponse(Status("vCtrl is only valid in non-stop mode"));
4003
4004 PacketResult interrupt_res = Handle_interrupt(packet);
4005 // If interrupting the process failed, pass the result through.
4006 if (interrupt_res != PacketResult::Success)
4007 return interrupt_res;
4008 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).
4009 return SendOKResponse();
4010 }
4011
4012 GDBRemoteCommunication::PacketResult
Handle_T(StringExtractorGDBRemote & packet)4013 GDBRemoteCommunicationServerLLGS::Handle_T(StringExtractorGDBRemote &packet) {
4014 packet.SetFilePos(strlen("T"));
4015 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()
4016 : LLDB_INVALID_PROCESS_ID);
4017 if (!pid_tid)
4018 return SendErrorResponse(llvm::make_error<StringError>(
4019 inconvertibleErrorCode(), "Malformed thread-id"));
4020
4021 lldb::pid_t pid = pid_tid->first;
4022 lldb::tid_t tid = pid_tid->second;
4023
4024 // Technically, this would also be caught by the PID check but let's be more
4025 // explicit about the error.
4026 if (pid == LLDB_INVALID_PROCESS_ID)
4027 return SendErrorResponse(llvm::make_error<StringError>(
4028 inconvertibleErrorCode(), "No current process and no PID provided"));
4029
4030 // Check the process ID and find respective process instance.
4031 auto new_process_it = m_debugged_processes.find(pid);
4032 if (new_process_it == m_debugged_processes.end())
4033 return SendErrorResponse(1);
4034
4035 // Check the thread ID
4036 if (!new_process_it->second.process_up->GetThreadByID(tid))
4037 return SendErrorResponse(2);
4038
4039 return SendOKResponse();
4040 }
4041
MaybeCloseInferiorTerminalConnection()4042 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
4043 Log *log = GetLog(LLDBLog::Process);
4044
4045 // Tell the stdio connection to shut down.
4046 if (m_stdio_communication.IsConnected()) {
4047 auto connection = m_stdio_communication.GetConnection();
4048 if (connection) {
4049 Status error;
4050 connection->Disconnect(&error);
4051
4052 if (error.Success()) {
4053 LLDB_LOGF(log,
4054 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4055 "terminal stdio - SUCCESS",
4056 __FUNCTION__);
4057 } else {
4058 LLDB_LOGF(log,
4059 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4060 "terminal stdio - FAIL: %s",
4061 __FUNCTION__, error.AsCString());
4062 }
4063 }
4064 }
4065 }
4066
GetThreadFromSuffix(StringExtractorGDBRemote & packet)4067 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
4068 StringExtractorGDBRemote &packet) {
4069 // We have no thread if we don't have a process.
4070 if (!m_current_process ||
4071 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
4072 return nullptr;
4073
4074 // If the client hasn't asked for thread suffix support, there will not be a
4075 // thread suffix. Use the current thread in that case.
4076 if (!m_thread_suffix_supported) {
4077 const lldb::tid_t current_tid = GetCurrentThreadID();
4078 if (current_tid == LLDB_INVALID_THREAD_ID)
4079 return nullptr;
4080 else if (current_tid == 0) {
4081 // Pick a thread.
4082 return m_current_process->GetThreadAtIndex(0);
4083 } else
4084 return m_current_process->GetThreadByID(current_tid);
4085 }
4086
4087 Log *log = GetLog(LLDBLog::Thread);
4088
4089 // Parse out the ';'.
4090 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
4091 LLDB_LOGF(log,
4092 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4093 "error: expected ';' prior to start of thread suffix: packet "
4094 "contents = '%s'",
4095 __FUNCTION__, packet.GetStringRef().data());
4096 return nullptr;
4097 }
4098
4099 if (!packet.GetBytesLeft())
4100 return nullptr;
4101
4102 // Parse out thread: portion.
4103 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
4104 LLDB_LOGF(log,
4105 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4106 "error: expected 'thread:' but not found, packet contents = "
4107 "'%s'",
4108 __FUNCTION__, packet.GetStringRef().data());
4109 return nullptr;
4110 }
4111 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
4112 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4113 if (tid != 0)
4114 return m_current_process->GetThreadByID(tid);
4115
4116 return nullptr;
4117 }
4118
GetCurrentThreadID() const4119 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
4120 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
4121 // Use whatever the debug process says is the current thread id since the
4122 // protocol either didn't specify or specified we want any/all threads
4123 // marked as the current thread.
4124 if (!m_current_process)
4125 return LLDB_INVALID_THREAD_ID;
4126 return m_current_process->GetCurrentThreadID();
4127 }
4128 // Use the specific current thread id set by the gdb remote protocol.
4129 return m_current_tid;
4130 }
4131
GetNextSavedRegistersID()4132 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
4133 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
4134 return m_next_saved_registers_id++;
4135 }
4136
ClearProcessSpecificData()4137 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
4138 Log *log = GetLog(LLDBLog::Process);
4139
4140 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
4141 m_xfer_buffer_map.clear();
4142 }
4143
4144 FileSpec
FindModuleFile(const std::string & module_path,const ArchSpec & arch)4145 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
4146 const ArchSpec &arch) {
4147 if (m_current_process) {
4148 FileSpec file_spec;
4149 if (m_current_process
4150 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4151 .Success()) {
4152 if (FileSystem::Instance().Exists(file_spec))
4153 return file_spec;
4154 }
4155 }
4156
4157 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
4158 }
4159
XMLEncodeAttributeValue(llvm::StringRef value)4160 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
4161 llvm::StringRef value) {
4162 std::string result;
4163 for (const char &c : value) {
4164 switch (c) {
4165 case '\'':
4166 result += "'";
4167 break;
4168 case '"':
4169 result += """;
4170 break;
4171 case '<':
4172 result += "<";
4173 break;
4174 case '>':
4175 result += ">";
4176 break;
4177 default:
4178 result += c;
4179 break;
4180 }
4181 }
4182 return result;
4183 }
4184
HandleFeatures(const llvm::ArrayRef<llvm::StringRef> client_features)4185 std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures(
4186 const llvm::ArrayRef<llvm::StringRef> client_features) {
4187 std::vector<std::string> ret =
4188 GDBRemoteCommunicationServerCommon::HandleFeatures(client_features);
4189 ret.insert(ret.end(), {
4190 "QThreadSuffixSupported+",
4191 "QListThreadsInStopReply+",
4192 "qXfer:features:read+",
4193 "QNonStop+",
4194 });
4195
4196 // report server-only features
4197 using Extension = NativeProcessProtocol::Extension;
4198 Extension plugin_features = m_process_factory.GetSupportedExtensions();
4199 if (bool(plugin_features & Extension::pass_signals))
4200 ret.push_back("QPassSignals+");
4201 if (bool(plugin_features & Extension::auxv))
4202 ret.push_back("qXfer:auxv:read+");
4203 if (bool(plugin_features & Extension::libraries_svr4))
4204 ret.push_back("qXfer:libraries-svr4:read+");
4205 if (bool(plugin_features & Extension::siginfo_read))
4206 ret.push_back("qXfer:siginfo:read+");
4207 if (bool(plugin_features & Extension::memory_tagging))
4208 ret.push_back("memory-tagging+");
4209 if (bool(plugin_features & Extension::savecore))
4210 ret.push_back("qSaveCore+");
4211
4212 // check for client features
4213 m_extensions_supported = {};
4214 for (llvm::StringRef x : client_features)
4215 m_extensions_supported |=
4216 llvm::StringSwitch<Extension>(x)
4217 .Case("multiprocess+", Extension::multiprocess)
4218 .Case("fork-events+", Extension::fork)
4219 .Case("vfork-events+", Extension::vfork)
4220 .Default({});
4221
4222 m_extensions_supported &= plugin_features;
4223
4224 // fork & vfork require multiprocess
4225 if (!bool(m_extensions_supported & Extension::multiprocess))
4226 m_extensions_supported &= ~(Extension::fork | Extension::vfork);
4227
4228 // report only if actually supported
4229 if (bool(m_extensions_supported & Extension::multiprocess))
4230 ret.push_back("multiprocess+");
4231 if (bool(m_extensions_supported & Extension::fork))
4232 ret.push_back("fork-events+");
4233 if (bool(m_extensions_supported & Extension::vfork))
4234 ret.push_back("vfork-events+");
4235
4236 for (auto &x : m_debugged_processes)
4237 SetEnabledExtensions(*x.second.process_up);
4238 return ret;
4239 }
4240
SetEnabledExtensions(NativeProcessProtocol & process)4241 void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions(
4242 NativeProcessProtocol &process) {
4243 NativeProcessProtocol::Extension flags = m_extensions_supported;
4244 assert(!bool(flags & ~m_process_factory.GetSupportedExtensions()));
4245 process.SetEnabledExtensions(flags);
4246 }
4247
4248 GDBRemoteCommunication::PacketResult
SendContinueSuccessResponse()4249 GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() {
4250 if (m_non_stop)
4251 return SendOKResponse();
4252 StartSTDIOForwarding();
4253 return PacketResult::Success;
4254 }
4255
AppendThreadIDToResponse(Stream & response,lldb::pid_t pid,lldb::tid_t tid)4256 void GDBRemoteCommunicationServerLLGS::AppendThreadIDToResponse(
4257 Stream &response, lldb::pid_t pid, lldb::tid_t tid) {
4258 if (bool(m_extensions_supported &
4259 NativeProcessProtocol::Extension::multiprocess))
4260 response.Format("p{0:x-}.", pid);
4261 response.Format("{0:x-}", tid);
4262 }
4263
4264 std::string
LLGSArgToURL(llvm::StringRef url_arg,bool reverse_connect)4265 lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg,
4266 bool reverse_connect) {
4267 // Try parsing the argument as URL.
4268 if (llvm::Optional<URI> url = URI::Parse(url_arg)) {
4269 if (reverse_connect)
4270 return url_arg.str();
4271
4272 // Translate the scheme from LLGS notation to ConnectionFileDescriptor.
4273 // If the scheme doesn't match any, pass it through to support using CFD
4274 // schemes directly.
4275 std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4276 .Case("tcp", "listen")
4277 .Case("unix", "unix-accept")
4278 .Case("unix-abstract", "unix-abstract-accept")
4279 .Default(url->scheme.str());
4280 llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4281 return new_url;
4282 }
4283
4284 std::string host_port = url_arg.str();
4285 // If host_and_port starts with ':', default the host to be "localhost" and
4286 // expect the remainder to be the port.
4287 if (url_arg.startswith(":"))
4288 host_port.insert(0, "localhost");
4289
4290 // Try parsing the (preprocessed) argument as host:port pair.
4291 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))
4292 return (reverse_connect ? "connect://" : "listen://") + host_port;
4293
4294 // If none of the above applied, interpret the argument as UNIX socket path.
4295 return (reverse_connect ? "unix-connect://" : "unix-accept://") +
4296 url_arg.str();
4297 }
4298