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