Debian Codegraph @

gdbserver/server.cc

raw
1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2025 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 #include "gdbthread.h"
20 #include "gdbsupport/agent.h"
21 #include "notif.h"
22 #include "tdesc.h"
23 #include "gdbsupport/rsp-low.h"
24 #include "gdbsupport/signals-state-save-restore.h"
25 #include <ctype.h>
26 #include <unistd.h>
27 #if HAVE_SIGNAL_H
28 #include <signal.h>
29 #endif
30 #include "gdbsupport/gdb_vecs.h"
31 #include "gdbsupport/gdb_wait.h"
32 #include "gdbsupport/btrace-common.h"
33 #include "gdbsupport/filestuff.h"
34 #include "tracepoint.h"
35 #include "dll.h"
36 #include "hostio.h"
37 #include <vector>
38 #include "gdbsupport/unordered_map.h"
39 #include "gdbsupport/common-inferior.h"
40 #include "gdbsupport/job-control.h"
41 #include "gdbsupport/environ.h"
42 #include "filenames.h"
43 #include "gdbsupport/pathstuff.h"
44 #ifdef USE_XML
45 #include "xml-builtin.h"
46 #endif
47
48 #include "gdbsupport/selftest.h"
49 #include "gdbsupport/scope-exit.h"
50 #include "gdbsupport/gdb_select.h"
51 #include "gdbsupport/scoped_restore.h"
52 #include "gdbsupport/search.h"
53 #include "gdbsupport/gdb_argv_vec.h"
54 #include "gdbsupport/remote-args.h"
55
56 #include <getopt.h>
57
58 /* PBUFSIZ must also be at least as big as IPA_CMD_BUF_SIZE, because
59 the client state data is passed directly to some agent
60 functions. */
61 static_assert (PBUFSIZ >= IPA_CMD_BUF_SIZE);
62
63 #define require_running_or_return(BUF) \
64 if (!target_running ()) \
65 { \
66 write_enn (BUF); \
67 return; \
68 }
69
70 #define require_running_or_break(BUF) \
71 if (!target_running ()) \
72 { \
73 write_enn (BUF); \
74 break; \
75 }
76
77 /* The environment to pass to the inferior when creating it. */
78
79 static gdb_environ our_environ;
80
81 bool server_waiting;
82
83 static bool extended_protocol;
84 static bool response_needed;
85 static bool exit_requested;
86
87 /* --once: Exit after the first connection has closed. */
88 bool run_once;
89
90 /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
91 static bool report_no_resumed;
92
93 /* The event loop checks this to decide whether to continue accepting
94 events. */
95 static bool keep_processing_events = true;
96
97 bool non_stop;
98
99 static struct {
100 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
101 binary if needed. */
102 void set (const char *path)
103 {
104 m_path = path;
105
106 /* Make sure we're using the absolute path of the inferior when
107 creating it. */
108 if (!contains_dir_separator (m_path.c_str ()))
109 {
110 int reg_file_errno;
111
112 /* Check if the file is in our CWD. If it is, then we prefix
113 its name with CURRENT_DIRECTORY. Otherwise, we leave the
114 name as-is because we'll try searching for it in $PATH. */
115 if (is_regular_file (m_path.c_str (), &reg_file_errno))
116 m_path = gdb_abspath (m_path);
117 }
118 }
119
120 /* Return the PROGRAM_PATH. */
121 const char *get ()
122 { return m_path.empty () ? nullptr : m_path.c_str (); }
123
124 private:
125 /* The program name, adjusted if needed. */
126 std::string m_path;
127 } program_path;
128
129 /* All program arguments are merged into a single string. */
130
131 static std::string program_args;
132
133 static std::string wrapper_argv;
134
135 /* The PID of the originally created or attached inferior. Used to
136 send signals to the process when GDB sends us an asynchronous interrupt
137 (user hitting Control-C in the client), and to wait for the child to exit
138 when no longer debugging it. */
139
140 unsigned long signal_pid;
141
142 /* Set if you want to disable optional thread related packets support
143 in gdbserver, for the sake of testing GDB against stubs that don't
144 support them. */
145 bool disable_packet_vCont;
146 bool disable_packet_vCont_step;
147 bool disable_packet_Tthread;
148 bool disable_packet_qC;
149 bool disable_packet_qfThreadInfo;
150 bool disable_packet_T;
151
152 static unsigned char *mem_buf;
153
154 /* A sub-class of 'struct notif_event' for stop, holding information
155 relative to a single stop reply. We keep a queue of these to
156 push to GDB in non-stop mode. */
157
158 struct vstop_notif : public notif_event
159 {
160 /* Thread or process that got the event. */
161 ptid_t ptid;
162
163 /* Event info. */
164 struct target_waitstatus status;
165 };
166
167 /* The current btrace configuration. This is gdbserver's mirror of GDB's
168 btrace configuration. */
169 static struct btrace_config current_btrace_conf;
170
171 /* The client remote protocol state. */
172
173 static client_state g_client_state;
174
175 client_state &
176 get_client_state ()
177 {
178 client_state &cs = g_client_state;
179 return cs;
180 }
181
182
183 /* Put a stop reply to the stop reply queue. */
184
185 static void
186 queue_stop_reply (ptid_t ptid, const target_waitstatus &status)
187 {
188 struct vstop_notif *new_notif = new struct vstop_notif;
189
190 new_notif->ptid = ptid;
191 new_notif->status = status;
192
193 notif_event_enque (&notif_stop, new_notif);
194 }
195
196 static bool
197 remove_all_on_match_ptid (struct notif_event *event, ptid_t filter_ptid)
198 {
199 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
200
201 return vstop_event->ptid.matches (filter_ptid);
202 }
203
204 /* See server.h. */
205
206 void
207 discard_queued_stop_replies (ptid_t ptid)
208 {
209 std::list<notif_event *>::iterator iter, next, end;
210 end = notif_stop.queue.end ();
211 for (iter = notif_stop.queue.begin (); iter != end; iter = next)
212 {
213 next = iter;
214 ++next;
215
216 if (iter == notif_stop.queue.begin ())
217 {
218 /* The head of the list contains the notification that was
219 already sent to GDB. So we can't remove it, otherwise
220 when GDB sends the vStopped, it would ack the _next_
221 notification, which hadn't been sent yet! */
222 continue;
223 }
224
225 if (remove_all_on_match_ptid (*iter, ptid))
226 {
227 delete *iter;
228 notif_stop.queue.erase (iter);
229 }
230 }
231 }
232
233 static void
234 vstop_notif_reply (struct notif_event *event, char *own_buf)
235 {
236 struct vstop_notif *vstop = (struct vstop_notif *) event;
237
238 prepare_resume_reply (own_buf, vstop->ptid, vstop->status);
239 }
240
241 /* Helper for in_queued_stop_replies. */
242
243 static bool
244 in_queued_stop_replies_ptid (struct notif_event *event, ptid_t filter_ptid)
245 {
246 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
247
248 if (vstop_event->ptid.matches (filter_ptid))
249 return true;
250
251 /* Don't resume fork children that GDB does not know about yet. */
252 if ((vstop_event->status.kind () == TARGET_WAITKIND_FORKED
253 || vstop_event->status.kind () == TARGET_WAITKIND_VFORKED
254 || vstop_event->status.kind () == TARGET_WAITKIND_THREAD_CLONED)
255 && vstop_event->status.child_ptid ().matches (filter_ptid))
256 return true;
257
258 return false;
259 }
260
261 /* See server.h. */
262
263 int
264 in_queued_stop_replies (ptid_t ptid)
265 {
266 for (notif_event *event : notif_stop.queue)
267 {
268 if (in_queued_stop_replies_ptid (event, ptid))
269 return true;
270 }
271
272 return false;
273 }
274
275 struct notif_server notif_stop =
276 {
277 "vStopped", "Stop", {}, vstop_notif_reply,
278 };
279
280 static int
281 target_running (void)
282 {
283 return get_first_thread () != NULL;
284 }
285
286 /* See gdbsupport/common-inferior.h. */
287
288 const char *
289 get_exec_wrapper ()
290 {
291 return !wrapper_argv.empty () ? wrapper_argv.c_str () : NULL;
292 }
293
294 /* See server.h. */
295
296 gdb_environ *
297 get_environ ()
298 {
299 return &our_environ;
300 }
301
302 static int
303 attach_inferior (int pid)
304 {
305 client_state &cs = get_client_state ();
306 /* myattach should return -1 if attaching is unsupported,
307 0 if it succeeded, and call error() otherwise. */
308
309 if (find_process_pid (pid) != nullptr)
310 error ("Already attached to process %d\n", pid);
311
312 if (myattach (pid) != 0)
313 return -1;
314
315 fprintf (stderr, "Attached; pid = %d\n", pid);
316 fflush (stderr);
317
318 /* FIXME - It may be that we should get the SIGNAL_PID from the
319 attach function, so that it can be the main thread instead of
320 whichever we were told to attach to. */
321 signal_pid = pid;
322
323 if (!non_stop)
324 {
325 cs.last_ptid = mywait (ptid_t (pid), &cs.last_status, 0, 0);
326
327 /* GDB knows to ignore the first SIGSTOP after attaching to a running
328 process using the "attach" command, but this is different; it's
329 just using "target remote". Pretend it's just starting up. */
330 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED
331 && cs.last_status.sig () == GDB_SIGNAL_STOP)
332 cs.last_status.set_stopped (GDB_SIGNAL_TRAP);
333
334 current_thread->last_resume_kind = resume_stop;
335 current_thread->last_status = cs.last_status;
336 }
337
338 return 0;
339 }
340
341 /* Decode a qXfer read request. Return 0 if everything looks OK,
342 or -1 otherwise. */
343
344 static int
345 decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
346 {
347 /* After the read marker and annex, qXfer looks like a
348 traditional 'm' packet. */
349 decode_m_packet (buf, ofs, len);
350
351 return 0;
352 }
353
354 static int
355 decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
356 {
357 /* Extract and NUL-terminate the object. */
358 *object = buf;
359 while (*buf && *buf != ':')
360 buf++;
361 if (*buf == '\0')
362 return -1;
363 *buf++ = 0;
364
365 /* Extract and NUL-terminate the read/write action. */
366 *rw = buf;
367 while (*buf && *buf != ':')
368 buf++;
369 if (*buf == '\0')
370 return -1;
371 *buf++ = 0;
372
373 /* Extract and NUL-terminate the annex. */
374 *annex = buf;
375 while (*buf && *buf != ':')
376 buf++;
377 if (*buf == '\0')
378 return -1;
379 *buf++ = 0;
380
381 *offset = buf;
382 return 0;
383 }
384
385 /* Write the response to a successful qXfer read. Returns the
386 length of the (binary) data stored in BUF, corresponding
387 to as much of DATA/LEN as we could fit. IS_MORE controls
388 the first character of the response. */
389 static int
390 write_qxfer_response (char *buf, const gdb_byte *data, int len, int is_more)
391 {
392 int out_len;
393
394 if (is_more)
395 buf[0] = 'm';
396 else
397 buf[0] = 'l';
398
399 return remote_escape_output (data, len, 1, (unsigned char *) buf + 1,
400 &out_len, PBUFSIZ - 2) + 1;
401 }
402
403 /* Handle btrace enabling in BTS format. */
404
405 static void
406 handle_btrace_enable_bts (thread_info *thread)
407 {
408 if (thread->btrace != NULL)
409 error (_("Btrace already enabled."));
410
411 current_btrace_conf.format = BTRACE_FORMAT_BTS;
412 thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
413 }
414
415 /* Handle btrace enabling in Intel Processor Trace format. */
416
417 static void
418 handle_btrace_enable_pt (thread_info *thread)
419 {
420 if (thread->btrace != NULL)
421 error (_("Btrace already enabled."));
422
423 current_btrace_conf.format = BTRACE_FORMAT_PT;
424 thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
425 }
426
427 /* Handle btrace disabling. */
428
429 static void
430 handle_btrace_disable (thread_info *thread)
431 {
432
433 if (thread->btrace == NULL)
434 error (_("Branch tracing not enabled."));
435
436 if (target_disable_btrace (thread->btrace) != 0)
437 error (_("Could not disable branch tracing."));
438
439 thread->btrace = NULL;
440 }
441
442 /* Handle the "Qbtrace" packet. */
443
444 static int
445 handle_btrace_general_set (char *own_buf)
446 {
447 client_state &cs = get_client_state ();
448 thread_info *thread;
449 char *op;
450
451 if (!startswith (own_buf, "Qbtrace:"))
452 return 0;
453
454 op = own_buf + strlen ("Qbtrace:");
455
456 if (cs.general_thread == null_ptid
457 || cs.general_thread == minus_one_ptid)
458 {
459 strcpy (own_buf, "E.Must select a single thread.");
460 return -1;
461 }
462
463 thread = find_thread_ptid (cs.general_thread);
464 if (thread == NULL)
465 {
466 strcpy (own_buf, "E.No such thread.");
467 return -1;
468 }
469
470 try
471 {
472 if (strcmp (op, "bts") == 0)
473 handle_btrace_enable_bts (thread);
474 else if (strcmp (op, "pt") == 0)
475 handle_btrace_enable_pt (thread);
476 else if (strcmp (op, "off") == 0)
477 handle_btrace_disable (thread);
478 else
479 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
480
481 write_ok (own_buf);
482 }
483 catch (const gdb_exception_error &exception)
484 {
485 sprintf (own_buf, "E.%s", exception.what ());
486 }
487
488 return 1;
489 }
490
491 /* Handle the "Qbtrace-conf" packet. */
492
493 static int
494 handle_btrace_conf_general_set (char *own_buf)
495 {
496 client_state &cs = get_client_state ();
497 thread_info *thread;
498 char *op;
499
500 if (!startswith (own_buf, "Qbtrace-conf:"))
501 return 0;
502
503 op = own_buf + strlen ("Qbtrace-conf:");
504
505 if (cs.general_thread == null_ptid
506 || cs.general_thread == minus_one_ptid)
507 {
508 strcpy (own_buf, "E.Must select a single thread.");
509 return -1;
510 }
511
512 thread = find_thread_ptid (cs.general_thread);
513 if (thread == NULL)
514 {
515 strcpy (own_buf, "E.No such thread.");
516 return -1;
517 }
518
519 if (startswith (op, "bts:size="))
520 {
521 unsigned long size;
522 char *endp = NULL;
523
524 errno = 0;
525 size = strtoul (op + strlen ("bts:size="), &endp, 16);
526 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
527 {
528 strcpy (own_buf, "E.Bad size value.");
529 return -1;
530 }
531
532 current_btrace_conf.bts.size = (unsigned int) size;
533 }
534 else if (strncmp (op, "pt:size=", strlen ("pt:size=")) == 0)
535 {
536 unsigned long size;
537 char *endp = NULL;
538
539 errno = 0;
540 size = strtoul (op + strlen ("pt:size="), &endp, 16);
541 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
542 {
543 strcpy (own_buf, "E.Bad size value.");
544 return -1;
545 }
546
547 current_btrace_conf.pt.size = (unsigned int) size;
548 }
549 else if (strncmp (op, "pt:ptwrite=", strlen ("pt:ptwrite=")) == 0)
550 {
551 op += strlen ("pt:ptwrite=");
552 if (strncmp (op, "\"yes\"", strlen ("\"yes\"")) == 0)
553 current_btrace_conf.pt.ptwrite = true;
554 else if (strncmp (op, "\"no\"", strlen ("\"no\"")) == 0)
555 current_btrace_conf.pt.ptwrite = false;
556 else
557 {
558 strcpy (own_buf, "E.Bad ptwrite value.");
559 return -1;
560 }
561 }
562 else if (strncmp (op, "pt:event-tracing=", strlen ("pt:event-tracing=")) == 0)
563 {
564 op += strlen ("pt:event-tracing=");
565 if (strncmp (op, "\"yes\"", strlen ("\"yes\"")) == 0)
566 current_btrace_conf.pt.event_tracing = true;
567 else if (strncmp (op, "\"no\"", strlen ("\"no\"")) == 0)
568 current_btrace_conf.pt.event_tracing = false;
569 else
570 {
571 strcpy (own_buf, "E.Bad event-tracing value.");
572 return -1;
573 }
574 }
575 else
576 {
577 strcpy (own_buf, "E.Bad Qbtrace configuration option.");
578 return -1;
579 }
580
581 write_ok (own_buf);
582 return 1;
583 }
584
585 /* Create the qMemTags packet reply given TAGS.
586
587 Returns true if parsing succeeded and false otherwise. */
588
589 static bool
590 create_fetch_memtags_reply (char *reply, const gdb::byte_vector &tags)
591 {
592 /* It is an error to pass a zero-sized tag vector. */
593 gdb_assert (tags.size () != 0);
594
595 std::string packet ("m");
596
597 /* Write the tag data. */
598 packet += bin2hex (tags.data (), tags.size ());
599
600 /* Check if the reply is too big for the packet to handle. */
601 if (PBUFSIZ < packet.size ())
602 return false;
603
604 strcpy (reply, packet.c_str ());
605 return true;
606 }
607
608 /* Parse the QMemTags request into ADDR, LEN and TAGS.
609
610 Returns true if parsing succeeded and false otherwise. */
611
612 static bool
613 parse_store_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
614 gdb::byte_vector &tags, int *type)
615 {
616 gdb_assert (startswith (request, "QMemTags:"));
617
618 const char *p = request + strlen ("QMemTags:");
619
620 /* Read address and length. */
621 unsigned int length = 0;
622 p = decode_m_packet_params (p, addr, &length, ':');
623 *len = length;
624
625 /* Read the tag type. */
626 ULONGEST tag_type = 0;
627 p = unpack_varlen_hex (p, &tag_type);
628 *type = (int) tag_type;
629
630 /* Make sure there is a colon after the type. */
631 if (*p != ':')
632 return false;
633
634 /* Skip the colon. */
635 p++;
636
637 /* Read the tag data. */
638 tags = hex2bin (p);
639
640 return true;
641 }
642
643 /* Parse thread options starting at *P and return them. On exit,
644 advance *P past the options. */
645
646 static gdb_thread_options
647 parse_gdb_thread_options (const char **p)
648 {
649 ULONGEST options = 0;
650 *p = unpack_varlen_hex (*p, &options);
651 return (gdb_thread_option) options;
652 }
653
654 /* Handle all of the extended 'Q' packets. */
655
656 static void
657 handle_general_set (char *own_buf)
658 {
659 client_state &cs = get_client_state ();
660 if (startswith (own_buf, "QPassSignals:"))
661 {
662 int numsigs = (int) GDB_SIGNAL_LAST, i;
663 const char *p = own_buf + strlen ("QPassSignals:");
664 CORE_ADDR cursig;
665
666 p = decode_address_to_semicolon (&cursig, p);
667 for (i = 0; i < numsigs; i++)
668 {
669 if (i == cursig)
670 {
671 cs.pass_signals[i] = 1;
672 if (*p == '\0')
673 /* Keep looping, to clear the remaining signals. */
674 cursig = -1;
675 else
676 p = decode_address_to_semicolon (&cursig, p);
677 }
678 else
679 cs.pass_signals[i] = 0;
680 }
681 strcpy (own_buf, "OK");
682 return;
683 }
684
685 if (startswith (own_buf, "QProgramSignals:"))
686 {
687 int numsigs = (int) GDB_SIGNAL_LAST, i;
688 const char *p = own_buf + strlen ("QProgramSignals:");
689 CORE_ADDR cursig;
690
691 cs.program_signals_p = 1;
692
693 p = decode_address_to_semicolon (&cursig, p);
694 for (i = 0; i < numsigs; i++)
695 {
696 if (i == cursig)
697 {
698 cs.program_signals[i] = 1;
699 if (*p == '\0')
700 /* Keep looping, to clear the remaining signals. */
701 cursig = -1;
702 else
703 p = decode_address_to_semicolon (&cursig, p);
704 }
705 else
706 cs.program_signals[i] = 0;
707 }
708 strcpy (own_buf, "OK");
709 return;
710 }
711
712 if (startswith (own_buf, "QCatchSyscalls:"))
713 {
714 const char *p = own_buf + sizeof ("QCatchSyscalls:") - 1;
715 int enabled = -1;
716 CORE_ADDR sysno;
717 struct process_info *process;
718
719 if (!target_running () || !target_supports_catch_syscall ())
720 {
721 write_enn (own_buf);
722 return;
723 }
724
725 if (strcmp (p, "0") == 0)
726 enabled = 0;
727 else if (p[0] == '1' && (p[1] == ';' || p[1] == '\0'))
728 enabled = 1;
729 else
730 {
731 fprintf (stderr, "Unknown catch-syscalls mode requested: %s\n",
732 own_buf);
733 write_enn (own_buf);
734 return;
735 }
736
737 process = current_process ();
738 process->syscalls_to_catch.clear ();
739
740 if (enabled)
741 {
742 p += 1;
743 if (*p == ';')
744 {
745 p += 1;
746 while (*p != '\0')
747 {
748 p = decode_address_to_semicolon (&sysno, p);
749 process->syscalls_to_catch.push_back (sysno);
750 }
751 }
752 else
753 process->syscalls_to_catch.push_back (ANY_SYSCALL);
754 }
755
756 write_ok (own_buf);
757 return;
758 }
759
760 if (strcmp (own_buf, "QEnvironmentReset") == 0)
761 {
762 our_environ = gdb_environ::from_host_environ ();
763
764 write_ok (own_buf);
765 return;
766 }
767
768 if (startswith (own_buf, "QEnvironmentHexEncoded:"))
769 {
770 const char *p = own_buf + sizeof ("QEnvironmentHexEncoded:") - 1;
771 /* The final form of the environment variable. FINAL_VAR will
772 hold the 'VAR=VALUE' format. */
773 std::string final_var = hex2str (p);
774 std::string var_name, var_value;
775
776 remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p);
777 remote_debug_printf ("[Environment variable to be set: '%s']",
778 final_var.c_str ());
779
780 size_t pos = final_var.find ('=');
781 if (pos == std::string::npos)
782 {
783 warning (_("Unexpected format for environment variable: '%s'"),
784 final_var.c_str ());
785 write_enn (own_buf);
786 return;
787 }
788
789 var_name = final_var.substr (0, pos);
790 var_value = final_var.substr (pos + 1, std::string::npos);
791
792 our_environ.set (var_name.c_str (), var_value.c_str ());
793
794 write_ok (own_buf);
795 return;
796 }
797
798 if (startswith (own_buf, "QEnvironmentUnset:"))
799 {
800 const char *p = own_buf + sizeof ("QEnvironmentUnset:") - 1;
801 std::string varname = hex2str (p);
802
803 remote_debug_printf ("[QEnvironmentUnset received '%s']", p);
804 remote_debug_printf ("[Environment variable to be unset: '%s']",
805 varname.c_str ());
806
807 our_environ.unset (varname.c_str ());
808
809 write_ok (own_buf);
810 return;
811 }
812
813 if (strcmp (own_buf, "QStartNoAckMode") == 0)
814 {
815 remote_debug_printf ("[noack mode enabled]");
816
817 cs.noack_mode = 1;
818 write_ok (own_buf);
819 return;
820 }
821
822 if (startswith (own_buf, "QNonStop:"))
823 {
824 char *mode = own_buf + 9;
825 int req = -1;
826 const char *req_str;
827
828 if (strcmp (mode, "0") == 0)
829 req = 0;
830 else if (strcmp (mode, "1") == 0)
831 req = 1;
832 else
833 {
834 /* We don't know what this mode is, so complain to
835 GDB. */
836 fprintf (stderr, "Unknown non-stop mode requested: %s\n",
837 own_buf);
838 write_enn (own_buf);
839 return;
840 }
841
842 req_str = req ? "non-stop" : "all-stop";
843 if (the_target->start_non_stop (req == 1) != 0)
844 {
845 fprintf (stderr, "Setting %s mode failed\n", req_str);
846 write_enn (own_buf);
847 return;
848 }
849
850 non_stop = (req != 0);
851
852 remote_debug_printf ("[%s mode enabled]", req_str);
853
854 write_ok (own_buf);
855 return;
856 }
857
858 if (startswith (own_buf, "QDisableRandomization:"))
859 {
860 char *packet = own_buf + strlen ("QDisableRandomization:");
861 ULONGEST setting;
862
863 unpack_varlen_hex (packet, &setting);
864 cs.disable_randomization = setting;
865
866 remote_debug_printf (cs.disable_randomization
867 ? "[address space randomization disabled]"
868 : "[address space randomization enabled]");
869
870 write_ok (own_buf);
871 return;
872 }
873
874 if (target_supports_tracepoints ()
875 && handle_tracepoint_general_set (own_buf))
876 return;
877
878 if (startswith (own_buf, "QAgent:"))
879 {
880 char *mode = own_buf + strlen ("QAgent:");
881 int req = 0;
882
883 if (strcmp (mode, "0") == 0)
884 req = 0;
885 else if (strcmp (mode, "1") == 0)
886 req = 1;
887 else
888 {
889 /* We don't know what this value is, so complain to GDB. */
890 sprintf (own_buf, "E.Unknown QAgent value");
891 return;
892 }
893
894 /* Update the flag. */
895 use_agent = req;
896 remote_debug_printf ("[%s agent]", req ? "Enable" : "Disable");
897 write_ok (own_buf);
898 return;
899 }
900
901 if (handle_btrace_general_set (own_buf))
902 return;
903
904 if (handle_btrace_conf_general_set (own_buf))
905 return;
906
907 if (startswith (own_buf, "QThreadEvents:"))
908 {
909 char *mode = own_buf + strlen ("QThreadEvents:");
910 enum tribool req = TRIBOOL_UNKNOWN;
911
912 if (strcmp (mode, "0") == 0)
913 req = TRIBOOL_FALSE;
914 else if (strcmp (mode, "1") == 0)
915 req = TRIBOOL_TRUE;
916 else
917 {
918 /* We don't know what this mode is, so complain to GDB. */
919 std::string err
920 = string_printf ("E.Unknown thread-events mode requested: %s\n",
921 mode);
922 strcpy (own_buf, err.c_str ());
923 return;
924 }
925
926 cs.report_thread_events = (req == TRIBOOL_TRUE);
927
928 remote_debug_printf ("[thread events are now %s]\n",
929 cs.report_thread_events ? "enabled" : "disabled");
930
931 write_ok (own_buf);
932 return;
933 }
934
935 if (startswith (own_buf, "QThreadOptions;"))
936 {
937 const char *p = own_buf + strlen ("QThreadOptions");
938
939 gdb_thread_options supported_options = target_supported_thread_options ();
940 if (supported_options == 0)
941 {
942 /* Something went wrong -- we don't support any option, but
943 GDB sent the packet anyway. */
944 write_enn (own_buf);
945 return;
946 }
947
948 /* We could store the options directly in thread->thread_options
949 without this map, but that would mean that a QThreadOptions
950 packet with a wildcard like "QThreadOptions;0;3:TID" would
951 result in the debug logs showing:
952
953 [options for TID are now 0x0]
954 [options for TID are now 0x3]
955
956 It's nicer if we only print the final options for each TID,
957 and if we only print about it if the options changed compared
958 to the options that were previously set on the thread. */
959 gdb::unordered_map<thread_info *, gdb_thread_options> set_options;
960
961 while (*p != '\0')
962 {
963 if (p[0] != ';')
964 {
965 write_enn (own_buf);
966 return;
967 }
968 p++;
969
970 /* Read the options. */
971
972 gdb_thread_options options = parse_gdb_thread_options (&p);
973
974 if ((options & ~supported_options) != 0)
975 {
976 /* GDB asked for an unknown or unsupported option, so
977 error out. */
978 std::string err
979 = string_printf ("E.Unknown thread options requested: %s\n",
980 to_string (options).c_str ());
981 strcpy (own_buf, err.c_str ());
982 return;
983 }
984
985 ptid_t ptid;
986
987 if (p[0] == ';' || p[0] == '\0')
988 ptid = minus_one_ptid;
989 else if (p[0] == ':')
990 {
991 const char *q;
992
993 ptid = read_ptid (p + 1, &q);
994
995 if (p == q)
996 {
997 write_enn (own_buf);
998 return;
999 }
1000 p = q;
1001 if (p[0] != ';' && p[0] != '\0')
1002 {
1003 write_enn (own_buf);
1004 return;
1005 }
1006 }
1007 else
1008 {
1009 write_enn (own_buf);
1010 return;
1011 }
1012
1013 /* Convert PID.-1 => PID.0 for ptid.matches. */
1014 if (ptid.lwp () == -1)
1015 ptid = ptid_t (ptid.pid ());
1016
1017 for_each_thread ([&] (thread_info *thread)
1018 {
1019 if (thread->id.matches (ptid))
1020 set_options[thread] = options;
1021 });
1022 }
1023
1024 for (const auto &[thread, options] : set_options)
1025 if (thread->thread_options != options)
1026 {
1027 threads_debug_printf ("[options for %s are now %s]\n",
1028 target_pid_to_str (thread->id).c_str (),
1029 to_string (options).c_str ());
1030
1031 thread->thread_options = options;
1032 }
1033
1034 write_ok (own_buf);
1035 return;
1036 }
1037
1038 if (startswith (own_buf, "QStartupWithShell:"))
1039 {
1040 const char *value = own_buf + strlen ("QStartupWithShell:");
1041
1042 if (strcmp (value, "1") == 0)
1043 startup_with_shell = true;
1044 else if (strcmp (value, "0") == 0)
1045 startup_with_shell = false;
1046 else
1047 {
1048 /* Unknown value. */
1049 fprintf (stderr, "Unknown value to startup-with-shell: %s\n",
1050 own_buf);
1051 write_enn (own_buf);
1052 return;
1053 }
1054
1055 remote_debug_printf ("[Inferior will %s started with shell]",
1056 startup_with_shell ? "be" : "not be");
1057
1058 write_ok (own_buf);
1059 return;
1060 }
1061
1062 if (startswith (own_buf, "QSetWorkingDir:"))
1063 {
1064 const char *p = own_buf + strlen ("QSetWorkingDir:");
1065
1066 if (*p != '\0')
1067 {
1068 std::string path = hex2str (p);
1069
1070 remote_debug_printf ("[Set the inferior's current directory to %s]",
1071 path.c_str ());
1072
1073 set_inferior_cwd (std::move (path));
1074 }
1075 else
1076 {
1077 /* An empty argument means that we should clear out any
1078 previously set cwd for the inferior. */
1079 set_inferior_cwd ("");
1080
1081 remote_debug_printf ("[Unset the inferior's current directory; will "
1082 "use gdbserver's cwd]");
1083 }
1084 write_ok (own_buf);
1085
1086 return;
1087 }
1088
1089
1090 /* Handle store memory tags packets. */
1091 if (startswith (own_buf, "QMemTags:")
1092 && target_supports_memory_tagging ())
1093 {
1094 gdb::byte_vector tags;
1095 CORE_ADDR addr = 0;
1096 size_t len = 0;
1097 int type = 0;
1098
1099 require_running_or_return (own_buf);
1100
1101 bool ret = parse_store_memtags_request (own_buf, &addr, &len, tags,
1102 &type);
1103
1104 if (ret)
1105 ret = the_target->store_memtags (addr, len, tags, type);
1106
1107 if (!ret)
1108 write_enn (own_buf);
1109 else
1110 write_ok (own_buf);
1111
1112 return;
1113 }
1114
1115 /* Otherwise we didn't know what packet it was. Say we didn't
1116 understand it. */
1117 own_buf[0] = 0;
1118 }
1119
1120 static const char *
1121 get_features_xml (const char *annex)
1122 {
1123 const struct target_desc *desc = current_target_desc ();
1124
1125 /* `desc->xmltarget' defines what to return when looking for the
1126 "target.xml" file. Its contents can either be verbatim XML code
1127 (prefixed with a '@') or else the name of the actual XML file to
1128 be used in place of "target.xml".
1129
1130 This variable is set up from the auto-generated
1131 init_registers_... routine for the current target. */
1132
1133 if (strcmp (annex, "target.xml") == 0)
1134 {
1135 const char *ret = tdesc_get_features_xml (desc);
1136
1137 if (*ret == '@')
1138 return ret + 1;
1139 else
1140 annex = ret;
1141 }
1142
1143 #ifdef USE_XML
1144 {
1145 int i;
1146
1147 /* Look for the annex. */
1148 for (i = 0; xml_builtin[i][0] != NULL; i++)
1149 if (strcmp (annex, xml_builtin[i][0]) == 0)
1150 break;
1151
1152 if (xml_builtin[i][0] != NULL)
1153 return xml_builtin[i][1];
1154 }
1155 #endif
1156
1157 return NULL;
1158 }
1159
1160 static void
1161 monitor_show_help (void)
1162 {
1163 monitor_output ("The following monitor commands are supported:\n");
1164 monitor_output (" set debug on\n");
1165 monitor_output (" Enable general debugging messages\n");
1166 monitor_output (" set debug off\n");
1167 monitor_output (" Disable all debugging messages\n");
1168 monitor_output (" set debug COMPONENT <off|on>\n");
1169 monitor_output (" Enable debugging messages for COMPONENT, which is\n");
1170 monitor_output (" one of: all, threads, remote, event-loop.\n");
1171 monitor_output (" set debug-hw-points <0|1>\n");
1172 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1173 monitor_output (" set debug-format option1[,option2,...]\n");
1174 monitor_output (" Add additional information to debugging messages\n");
1175 monitor_output (" Options: all, none, timestamp\n");
1176 monitor_output (" exit\n");
1177 monitor_output (" Quit GDBserver\n");
1178 }
1179
1180 /* Read trace frame or inferior memory. Returns the number of bytes
1181 actually read, zero when no further transfer is possible, and -1 on
1182 error. Return of a positive value smaller than LEN does not
1183 indicate there's no more to be read, only the end of the transfer.
1184 E.g., when GDB reads memory from a traceframe, a first request may
1185 be served from a memory block that does not cover the whole request
1186 length. A following request gets the rest served from either
1187 another block (of the same traceframe) or from the read-only
1188 regions. */
1189
1190 static int
1191 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1192 {
1193 client_state &cs = get_client_state ();
1194 int res;
1195
1196 if (cs.current_traceframe >= 0)
1197 {
1198 ULONGEST nbytes;
1199 ULONGEST length = len;
1200
1201 if (traceframe_read_mem (cs.current_traceframe,
1202 memaddr, myaddr, len, &nbytes))
1203 return -1;
1204 /* Data read from trace buffer, we're done. */
1205 if (nbytes > 0)
1206 return nbytes;
1207 if (!in_readonly_region (memaddr, length))
1208 return -1;
1209 /* Otherwise we have a valid readonly case, fall through. */
1210 /* (assume no half-trace half-real blocks for now) */
1211 }
1212
1213 if (set_desired_process ())
1214 res = read_inferior_memory (memaddr, myaddr, len);
1215 else
1216 res = 1;
1217
1218 return res == 0 ? len : -1;
1219 }
1220
1221 /* Write trace frame or inferior memory. Actually, writing to trace
1222 frames is forbidden. */
1223
1224 static int
1225 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
1226 {
1227 client_state &cs = get_client_state ();
1228 if (cs.current_traceframe >= 0)
1229 return EIO;
1230 else
1231 {
1232 int ret;
1233
1234 if (set_desired_process ())
1235 ret = target_write_memory (memaddr, myaddr, len);
1236 else
1237 ret = EIO;
1238 return ret;
1239 }
1240 }
1241
1242 /* Handle qSearch:memory packets. */
1243
1244 static void
1245 handle_search_memory (char *own_buf, int packet_len)
1246 {
1247 CORE_ADDR start_addr;
1248 CORE_ADDR search_space_len;
1249 gdb_byte *pattern;
1250 unsigned int pattern_len;
1251 int found;
1252 CORE_ADDR found_addr;
1253 int cmd_name_len = sizeof ("qSearch:memory:") - 1;
1254
1255 pattern = (gdb_byte *) malloc (packet_len);
1256 if (pattern == NULL)
1257 error ("Unable to allocate memory to perform the search");
1258
1259 if (decode_search_memory_packet (own_buf + cmd_name_len,
1260 packet_len - cmd_name_len,
1261 &start_addr, &search_space_len,
1262 pattern, &pattern_len) < 0)
1263 {
1264 free (pattern);
1265 error ("Error in parsing qSearch:memory packet");
1266 }
1267
1268 auto read_memory = [] (CORE_ADDR addr, gdb_byte *result, size_t len)
1269 {
1270 return gdb_read_memory (addr, result, len) == len;
1271 };
1272
1273 found = simple_search_memory (read_memory, start_addr, search_space_len,
1274 pattern, pattern_len, &found_addr);
1275
1276 if (found > 0)
1277 sprintf (own_buf, "1,%lx", (long) found_addr);
1278 else if (found == 0)
1279 strcpy (own_buf, "0");
1280 else
1281 strcpy (own_buf, "E00");
1282
1283 free (pattern);
1284 }
1285
1286 /* Handle the "D" packet. */
1287
1288 static void
1289 handle_detach (char *own_buf)
1290 {
1291 client_state &cs = get_client_state ();
1292
1293 process_info *process;
1294
1295 if (cs.multi_process)
1296 {
1297 /* skip 'D;' */
1298 int pid = strtol (&own_buf[2], NULL, 16);
1299
1300 process = find_process_pid (pid);
1301 }
1302 else
1303 process = current_process ();
1304
1305 if (process == NULL)
1306 {
1307 write_enn (own_buf);
1308 return;
1309 }
1310
1311 if ((tracing && disconnected_tracing) || any_persistent_commands (process))
1312 {
1313 if (tracing && disconnected_tracing)
1314 fprintf (stderr,
1315 "Disconnected tracing in effect, "
1316 "leaving gdbserver attached to the process\n");
1317
1318 if (any_persistent_commands (process))
1319 fprintf (stderr,
1320 "Persistent commands are present, "
1321 "leaving gdbserver attached to the process\n");
1322
1323 /* Make sure we're in non-stop/async mode, so we we can both
1324 wait for an async socket accept, and handle async target
1325 events simultaneously. There's also no point either in
1326 having the target stop all threads, when we're going to
1327 pass signals down without informing GDB. */
1328 if (!non_stop)
1329 {
1330 threads_debug_printf ("Forcing non-stop mode");
1331
1332 non_stop = true;
1333 the_target->start_non_stop (true);
1334 }
1335
1336 process->gdb_detached = 1;
1337
1338 /* Detaching implicitly resumes all threads. */
1339 target_continue_no_signal (minus_one_ptid);
1340
1341 write_ok (own_buf);
1342 return;
1343 }
1344
1345 fprintf (stderr, "Detaching from process %d\n", process->pid);
1346 stop_tracing ();
1347
1348 /* We'll need this after PROCESS has been destroyed. */
1349 int pid = process->pid;
1350
1351 /* If this process has an unreported fork child, that child is not known to
1352 GDB, so GDB won't take care of detaching it. We must do it here.
1353
1354 Here, we specifically don't want to use "safe iteration", as detaching
1355 another process might delete the next thread in the iteration, which is
1356 the one saved by the safe iterator. We will never delete the currently
1357 iterated on thread, so standard iteration should be safe. */
1358 for (thread_info &thread : process->thread_list ())
1359 {
1360 /* Only threads that have a pending fork event. */
1361 target_waitkind kind;
1362 thread_info *child = target_thread_pending_child (&thread, &kind);
1363 if (child == nullptr || kind == TARGET_WAITKIND_THREAD_CLONED)
1364 continue;
1365
1366 process_info *fork_child_process = child->process ();
1367 int fork_child_pid = fork_child_process->pid;
1368
1369 if (detach_inferior (fork_child_process) != 0)
1370 warning (_("Failed to detach fork child %s, child of %s"),
1371 target_pid_to_str (ptid_t (fork_child_pid)).c_str (),
1372 target_pid_to_str (thread.id).c_str ());
1373 }
1374
1375 if (detach_inferior (process) != 0)
1376 write_enn (own_buf);
1377 else
1378 {
1379 discard_queued_stop_replies (ptid_t (pid));
1380 write_ok (own_buf);
1381
1382 if (extended_protocol || target_running ())
1383 {
1384 /* There is still at least one inferior remaining or
1385 we are in extended mode, so don't terminate gdbserver,
1386 and instead treat this like a normal program exit. */
1387 cs.last_status.set_exited (0);
1388 cs.last_ptid = ptid_t (pid);
1389
1390 switch_to_thread (nullptr);
1391 }
1392 else
1393 {
1394 putpkt (own_buf);
1395 remote_close ();
1396
1397 /* If we are attached, then we can exit. Otherwise, we
1398 need to hang around doing nothing, until the child is
1399 gone. */
1400 join_inferior (pid);
1401 exit (0);
1402 }
1403 }
1404 }
1405
1406 /* Parse options to --debug-format= and "monitor set debug-format".
1407 ARG is the text after "--debug-format=" or "monitor set debug-format".
1408 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1409 This triggers calls to monitor_output.
1410 The result is an empty string if all options were parsed ok, otherwise an
1411 error message which the caller must free.
1412
1413 N.B. These commands affect all debug format settings, they are not
1414 cumulative. If a format is not specified, it is turned off.
1415 However, we don't go to extra trouble with things like
1416 "monitor set debug-format all,none,timestamp".
1417 Instead we just parse them one at a time, in order.
1418
1419 The syntax for "monitor set debug" we support here is not identical
1420 to gdb's "set debug foo on|off" because we also use this function to
1421 parse "--debug-format=foo,bar". */
1422
1423 static std::string
1424 parse_debug_format_options (const char *arg, int is_monitor)
1425 {
1426 /* First turn all debug format options off. */
1427 debug_timestamp = 0;
1428
1429 /* First remove leading spaces, for "monitor set debug-format". */
1430 while (isspace (*arg))
1431 ++arg;
1432
1433 std::vector<gdb::unique_xmalloc_ptr<char>> options
1434 = delim_string_to_char_ptr_vec (arg, ',');
1435
1436 for (const gdb::unique_xmalloc_ptr<char> &option : options)
1437 {
1438 if (strcmp (option.get (), "all") == 0)
1439 {
1440 debug_timestamp = 1;
1441 if (is_monitor)
1442 monitor_output ("All extra debug format options enabled.\n");
1443 }
1444 else if (strcmp (option.get (), "none") == 0)
1445 {
1446 debug_timestamp = 0;
1447 if (is_monitor)
1448 monitor_output ("All extra debug format options disabled.\n");
1449 }
1450 else if (strcmp (option.get (), "timestamp") == 0)
1451 {
1452 debug_timestamp = 1;
1453 if (is_monitor)
1454 monitor_output ("Timestamps will be added to debug output.\n");
1455 }
1456 else if (*option == '\0')
1457 {
1458 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1459 continue;
1460 }
1461 else
1462 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1463 option.get ());
1464 }
1465
1466 return std::string ();
1467 }
1468
1469 /* A wrapper to enable, or disable a debug flag. These are debug flags
1470 that control the debug output from gdbserver, that developers might
1471 want, this is not something most end users will need. */
1472
1473 struct debug_opt
1474 {
1475 /* NAME is the name of this debug option, this should be a simple string
1476 containing no whitespace, starting with a letter from isalpha(), and
1477 contain only isalnum() characters and '_' underscore and '-' hyphen.
1478
1479 SETTER is a callback function used to set the debug variable. This
1480 callback will be passed true to enable the debug setting, or false to
1481 disable the debug setting. */
1482 debug_opt (const char *name, std::function<void (bool)> setter)
1483 : m_name (name),
1484 m_setter (setter)
1485 {
1486 gdb_assert (isalpha (*name));
1487 }
1488
1489 /* Called to enable or disable the debug setting. */
1490 void set (bool enable) const
1491 {
1492 m_setter (enable);
1493 }
1494
1495 /* Return the name of this debug option. */
1496 const char *name () const
1497 { return m_name; }
1498
1499 private:
1500 /* The name of this debug option. */
1501 const char *m_name;
1502
1503 /* The callback to update the debug setting. */
1504 std::function<void (bool)> m_setter;
1505 };
1506
1507 /* The set of all debug options that gdbserver supports. These are the
1508 options that can be passed to the command line '--debug=...' flag, or to
1509 the monitor command 'monitor set debug ...'. */
1510
1511 static std::vector<debug_opt> all_debug_opt {
1512 {"threads", [] (bool enable)
1513 {
1514 debug_threads = enable;
1515 }},
1516 {"remote", [] (bool enable)
1517 {
1518 remote_debug = enable;
1519 }},
1520 {"event-loop", [] (bool enable)
1521 {
1522 debug_event_loop = (enable ? debug_event_loop_kind::ALL
1523 : debug_event_loop_kind::OFF);
1524 }}
1525 };
1526
1527 /* Parse the options to --debug=...
1528
1529 OPTIONS is the string of debug components which should be enabled (or
1530 disabled), and must not be nullptr. An empty OPTIONS string is valid,
1531 in which case a default set of debug components will be enabled.
1532
1533 An unknown, or otherwise invalid debug component will result in an
1534 exception being thrown.
1535
1536 OPTIONS can consist of multiple debug component names separated by a
1537 comma. Debugging for each component will be turned on. The special
1538 component 'all' can be used to enable debugging for all components.
1539
1540 A component can also be prefixed with '-' to disable debugging of that
1541 component, so a user might use: '--debug=all,-remote', to enable all
1542 debugging, except for the remote (protocol) component. Components are
1543 processed left to write in the OPTIONS list. */
1544
1545 static void
1546 parse_debug_options (const char *options)
1547 {
1548 gdb_assert (options != nullptr);
1549
1550 /* Empty options means the "default" set. This exists mostly for
1551 backwards compatibility with gdbserver's legacy behavior. */
1552 if (*options == '\0')
1553 options = "+threads";
1554
1555 while (*options != '\0')
1556 {
1557 const char *end = strchrnul (options, ',');
1558
1559 bool enable = *options != '-';
1560 if (*options == '-' || *options == '+')
1561 ++options;
1562
1563 std::string opt (options, end - options);
1564
1565 if (opt.size () == 0)
1566 error ("invalid empty debug option");
1567
1568 bool is_opt_all = opt == "all";
1569
1570 bool found = false;
1571 for (const auto &debug_opt : all_debug_opt)
1572 if (is_opt_all || opt == debug_opt.name ())
1573 {
1574 debug_opt.set (enable);
1575 found = true;
1576 if (!is_opt_all)
1577 break;
1578 }
1579
1580 if (!found)
1581 error ("unknown debug option '%s'", opt.c_str ());
1582
1583 options = (*end == ',') ? end + 1 : end;
1584 }
1585 }
1586
1587 /* Called from the 'monitor' command handler, to handle general 'set debug'
1588 monitor commands with one of the formats:
1589
1590 set debug COMPONENT VALUE
1591 set debug VALUE
1592
1593 In both of these command formats VALUE can be 'on', 'off', '1', or '0'
1594 with 1/0 being equivalent to on/off respectively.
1595
1596 In the no-COMPONENT version of the command, if VALUE is 'on' (or '1')
1597 then the component 'threads' is assumed, this is for backward
1598 compatibility, but maybe in the future we might find a better "default"
1599 set of debug flags to enable.
1600
1601 In the no-COMPONENT version of the command, if VALUE is 'off' (or '0')
1602 then all debugging is turned off.
1603
1604 Otherwise, COMPONENT must be one of the known debug components, and that
1605 component is either enabled or disabled as appropriate.
1606
1607 The string MON contains either 'COMPONENT VALUE' or just the 'VALUE' for
1608 the second command format, the 'set debug ' has been stripped off
1609 already.
1610
1611 Return a string containing an error message if something goes wrong,
1612 this error can be returned as part of the monitor command output. If
1613 everything goes correctly then the debug global will have been updated,
1614 and an empty string is returned. */
1615
1616 static std::string
1617 handle_general_monitor_debug (const char *mon)
1618 {
1619 mon = skip_spaces (mon);
1620
1621 if (*mon == '\0')
1622 return "No debug component name found.\n";
1623
1624 /* Find the first word within MON. This is either the component name,
1625 or the value if no component has been given. */
1626 const char *end = skip_to_space (mon);
1627 std::string component (mon, end - mon);
1628 if (component.find (',') != component.npos || component[0] == '-'
1629 || component[0] == '+')
1630 return "Invalid character found in debug component name.\n";
1631
1632 /* In ACTION_STR we create a string that will be passed to the
1633 parse_debug_options string. This will be either '+COMPONENT' or
1634 '-COMPONENT' depending on whether we want to enable or disable
1635 COMPONENT. */
1636 std::string action_str;
1637
1638 /* If parse_debug_options succeeds, then MSG will be returned to the user
1639 as the output of the monitor command. */
1640 std::string msg;
1641
1642 /* Check for 'set debug off', this disables all debug output. */
1643 if (component == "0" || component == "off")
1644 {
1645 if (*skip_spaces (end) != '\0')
1646 return string_printf
1647 ("Junk '%s' found at end of 'set debug %s' command.\n",
1648 skip_spaces (end), std::string (mon, end - mon).c_str ());
1649
1650 action_str = "-all";
1651 msg = "All debug output disabled.\n";
1652 }
1653 /* Check for 'set debug on', this disables a general set of debug. */
1654 else if (component == "1" || component == "on")
1655 {
1656 if (*skip_spaces (end) != '\0')
1657 return string_printf
1658 ("Junk '%s' found at end of 'set debug %s' command.\n",
1659 skip_spaces (end), std::string (mon, end - mon).c_str ());
1660
1661 action_str = "+threads";
1662 msg = "General debug output enabled.\n";
1663 }
1664 /* Otherwise we should have 'set debug COMPONENT VALUE'. Extract the two
1665 parts and validate. */
1666 else
1667 {
1668 /* Figure out the value the user passed. */
1669 const char *value_start = skip_spaces (end);
1670 if (*value_start == '\0')
1671 return string_printf ("Missing value for 'set debug %s' command.\n",
1672 mon);
1673
1674 const char *after_value = skip_to_space (value_start);
1675 if (*skip_spaces (after_value) != '\0')
1676 return string_printf
1677 ("Junk '%s' found at end of 'set debug %s' command.\n",
1678 skip_spaces (after_value),
1679 std::string (mon, after_value - mon).c_str ());
1680
1681 std::string value (value_start, after_value - value_start);
1682
1683 /* Check VALUE to see if we are enabling, or disabling. */
1684 bool enable;
1685 if (value == "0" || value == "off")
1686 enable = false;
1687 else if (value == "1" || value == "on")
1688 enable = true;
1689 else
1690 return string_printf ("Invalid value '%s' for 'set debug %s'.\n",
1691 value.c_str (),
1692 std::string (mon, end - mon).c_str ());
1693
1694 action_str = std::string (enable ? "+" : "-") + component;
1695 msg = string_printf ("Debug output for '%s' %s.\n", component.c_str (),
1696 enable ? "enabled" : "disabled");
1697 }
1698
1699 gdb_assert (!msg.empty ());
1700 gdb_assert (!action_str.empty ());
1701
1702 try
1703 {
1704 parse_debug_options (action_str.c_str ());
1705 monitor_output (msg.c_str ());
1706 }
1707 catch (const gdb_exception_error &exception)
1708 {
1709 return string_printf ("Error: %s\n", exception.what ());
1710 }
1711
1712 return {};
1713 }
1714
1715 /* Handle monitor commands not handled by target-specific handlers. */
1716
1717 static void
1718 handle_monitor_command (char *mon, char *own_buf)
1719 {
1720 if (startswith (mon, "set debug "))
1721 {
1722 std::string error_msg
1723 = handle_general_monitor_debug (mon + sizeof ("set debug ") - 1);
1724
1725 if (!error_msg.empty ())
1726 {
1727 monitor_output (error_msg.c_str ());
1728 monitor_show_help ();
1729 write_enn (own_buf);
1730 }
1731 }
1732 else if (strcmp (mon, "set debug-hw-points 1") == 0)
1733 {
1734 show_debug_regs = 1;
1735 monitor_output ("H/W point debugging output enabled.\n");
1736 }
1737 else if (strcmp (mon, "set debug-hw-points 0") == 0)
1738 {
1739 show_debug_regs = 0;
1740 monitor_output ("H/W point debugging output disabled.\n");
1741 }
1742 else if (startswith (mon, "set debug-format "))
1743 {
1744 std::string error_msg
1745 = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
1746 1);
1747
1748 if (!error_msg.empty ())
1749 {
1750 monitor_output (error_msg.c_str ());
1751 monitor_show_help ();
1752 write_enn (own_buf);
1753 }
1754 }
1755 else if (strcmp (mon, "set debug-file") == 0)
1756 debug_set_output (nullptr);
1757 else if (startswith (mon, "set debug-file "))
1758 debug_set_output (mon + sizeof ("set debug-file ") - 1);
1759 else if (strcmp (mon, "help") == 0)
1760 monitor_show_help ();
1761 else if (strcmp (mon, "exit") == 0)
1762 exit_requested = true;
1763 else
1764 {
1765 monitor_output ("Unknown monitor command.\n\n");
1766 monitor_show_help ();
1767 write_enn (own_buf);
1768 }
1769 }
1770
1771 /* Associates a callback with each supported qXfer'able object. */
1772
1773 struct qxfer
1774 {
1775 /* The object this handler handles. */
1776 const char *object;
1777
1778 /* Request that the target transfer up to LEN 8-bit bytes of the
1779 target's OBJECT. The OFFSET, for a seekable object, specifies
1780 the starting point. The ANNEX can be used to provide additional
1781 data-specific information to the target.
1782
1783 Return the number of bytes actually transferred, zero when no
1784 further transfer is possible, -1 on error, -2 when the transfer
1785 is not supported, and -3 on a verbose error message that should
1786 be preserved. Return of a positive value smaller than LEN does
1787 not indicate the end of the object, only the end of the transfer.
1788
1789 One, and only one, of readbuf or writebuf must be non-NULL. */
1790 int (*xfer) (const char *annex,
1791 gdb_byte *readbuf, const gdb_byte *writebuf,
1792 ULONGEST offset, LONGEST len);
1793 };
1794
1795 /* Handle qXfer:auxv:read. */
1796
1797 static int
1798 handle_qxfer_auxv (const char *annex,
1799 gdb_byte *readbuf, const gdb_byte *writebuf,
1800 ULONGEST offset, LONGEST len)
1801 {
1802 if (!the_target->supports_read_auxv () || writebuf != NULL)
1803 return -2;
1804
1805 if (annex[0] != '\0' || current_thread == NULL)
1806 return -1;
1807
1808 return the_target->read_auxv (current_thread->id.pid (), offset, readbuf,
1809 len);
1810 }
1811
1812 /* Handle qXfer:exec-file:read. */
1813
1814 static int
1815 handle_qxfer_exec_file (const char *annex,
1816 gdb_byte *readbuf, const gdb_byte *writebuf,
1817 ULONGEST offset, LONGEST len)
1818 {
1819 ULONGEST pid;
1820 int total_len;
1821
1822 if (!the_target->supports_pid_to_exec_file () || writebuf != NULL)
1823 return -2;
1824
1825 if (annex[0] == '\0')
1826 {
1827 if (current_thread == NULL)
1828 return -1;
1829
1830 pid = current_thread->id.pid ();
1831 }
1832 else
1833 {
1834 annex = unpack_varlen_hex (annex, &pid);
1835 if (annex[0] != '\0')
1836 return -1;
1837 }
1838
1839 if (pid <= 0)
1840 return -1;
1841
1842 const char *file = the_target->pid_to_exec_file (pid);
1843 if (file == NULL)
1844 return -1;
1845
1846 total_len = strlen (file);
1847
1848 if (offset > total_len)
1849 return -1;
1850
1851 if (offset + len > total_len)
1852 len = total_len - offset;
1853
1854 memcpy (readbuf, file + offset, len);
1855 return len;
1856 }
1857
1858 /* Handle qXfer:features:read. */
1859
1860 static int
1861 handle_qxfer_features (const char *annex,
1862 gdb_byte *readbuf, const gdb_byte *writebuf,
1863 ULONGEST offset, LONGEST len)
1864 {
1865 const char *document;
1866 size_t total_len;
1867
1868 if (writebuf != NULL)
1869 return -2;
1870
1871 if (!target_running ())
1872 return -1;
1873
1874 /* Grab the correct annex. */
1875 document = get_features_xml (annex);
1876 if (document == NULL)
1877 return -1;
1878
1879 total_len = strlen (document);
1880
1881 if (offset > total_len)
1882 return -1;
1883
1884 if (offset + len > total_len)
1885 len = total_len - offset;
1886
1887 memcpy (readbuf, document + offset, len);
1888 return len;
1889 }
1890
1891 /* Handle qXfer:libraries:read. */
1892
1893 static int
1894 handle_qxfer_libraries (const char *annex,
1895 gdb_byte *readbuf, const gdb_byte *writebuf,
1896 ULONGEST offset, LONGEST len)
1897 {
1898 if (writebuf != NULL)
1899 return -2;
1900
1901 if (annex[0] != '\0' || current_thread == NULL)
1902 return -1;
1903
1904 std::string document = "<library-list version=\"1.0\">\n";
1905
1906 process_info *proc = current_process ();
1907 for (const dll_info &dll : proc->all_dlls)
1908 document += string_printf
1909 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1910 dll.name.c_str (), paddress (dll.base_addr));
1911
1912 document += "</library-list>\n";
1913
1914 if (offset > document.length ())
1915 return -1;
1916
1917 if (offset + len > document.length ())
1918 len = document.length () - offset;
1919
1920 memcpy (readbuf, &document[offset], len);
1921
1922 return len;
1923 }
1924
1925 /* Handle qXfer:libraries-svr4:read. */
1926
1927 static int
1928 handle_qxfer_libraries_svr4 (const char *annex,
1929 gdb_byte *readbuf, const gdb_byte *writebuf,
1930 ULONGEST offset, LONGEST len)
1931 {
1932 if (writebuf != NULL)
1933 return -2;
1934
1935 if (current_thread == NULL
1936 || !the_target->supports_qxfer_libraries_svr4 ())
1937 return -1;
1938
1939 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf,
1940 offset, len);
1941 }
1942
1943 /* Handle qXfer:osadata:read. */
1944
1945 static int
1946 handle_qxfer_osdata (const char *annex,
1947 gdb_byte *readbuf, const gdb_byte *writebuf,
1948 ULONGEST offset, LONGEST len)
1949 {
1950 if (!the_target->supports_qxfer_osdata () || writebuf != NULL)
1951 return -2;
1952
1953 return the_target->qxfer_osdata (annex, readbuf, NULL, offset, len);
1954 }
1955
1956 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1957
1958 static int
1959 handle_qxfer_siginfo (const char *annex,
1960 gdb_byte *readbuf, const gdb_byte *writebuf,
1961 ULONGEST offset, LONGEST len)
1962 {
1963 if (!the_target->supports_qxfer_siginfo ())
1964 return -2;
1965
1966 if (annex[0] != '\0' || current_thread == NULL)
1967 return -1;
1968
1969 return the_target->qxfer_siginfo (annex, readbuf, writebuf, offset, len);
1970 }
1971
1972 /* Helper for handle_qxfer_threads_proper.
1973 Emit the XML to describe the thread of INF. */
1974
1975 static void
1976 handle_qxfer_threads_worker (thread_info *thread, std::string *buffer)
1977 {
1978 ptid_t ptid = thread->id;
1979 char ptid_s[100];
1980 int core = target_core_of_thread (ptid);
1981 char core_s[21];
1982 const char *name = target_thread_name (ptid);
1983 std::string id_str = target_thread_id_str (thread);
1984 int handle_len;
1985 gdb_byte *handle;
1986 bool handle_status = target_thread_handle (ptid, &handle, &handle_len);
1987
1988 /* If this is a (v)fork/clone child (has a (v)fork/clone parent),
1989 GDB does not yet know about this thread, and must not know about
1990 it until it gets the corresponding (v)fork/clone event. Exclude
1991 this thread from the list. */
1992 if (target_thread_pending_parent (thread) != nullptr)
1993 return;
1994
1995 write_ptid (ptid_s, ptid);
1996
1997 string_xml_appendf (*buffer, "<thread id=\"%s\"", ptid_s);
1998
1999 if (core != -1)
2000 {
2001 sprintf (core_s, "%d", core);
2002 string_xml_appendf (*buffer, " core=\"%s\"", core_s);
2003 }
2004
2005 if (name != NULL)
2006 string_xml_appendf (*buffer, " name=\"%s\"", name);
2007
2008 if (!id_str.empty ())
2009 string_xml_appendf (*buffer, " id_str=\"%s\"", id_str.c_str ());
2010
2011 if (handle_status)
2012 {
2013 char *handle_s = (char *) alloca (handle_len * 2 + 1);
2014 bin2hex (handle, handle_s, handle_len);
2015 string_xml_appendf (*buffer, " handle=\"%s\"", handle_s);
2016 }
2017
2018 string_xml_appendf (*buffer, "/>\n");
2019 }
2020
2021 /* Helper for handle_qxfer_threads. Return true on success, false
2022 otherwise. */
2023
2024 static bool
2025 handle_qxfer_threads_proper (std::string *buffer)
2026 {
2027 *buffer += "<threads>\n";
2028
2029 /* The target may need to access memory and registers (e.g. via
2030 libthread_db) to fetch thread properties. Even if don't need to
2031 stop threads to access memory, we still will need to be able to
2032 access registers, and other ptrace accesses like
2033 PTRACE_GET_THREAD_AREA that require a paused thread. Pause all
2034 threads here, so that we pause each thread at most once for all
2035 accesses. */
2036 if (non_stop)
2037 target_pause_all (true);
2038
2039 for_each_thread ([&] (thread_info *thread)
2040 {
2041 handle_qxfer_threads_worker (thread, buffer);
2042 });
2043
2044 if (non_stop)
2045 target_unpause_all (true);
2046
2047 *buffer += "</threads>\n";
2048 return true;
2049 }
2050
2051 /* Handle qXfer:threads:read. */
2052
2053 static int
2054 handle_qxfer_threads (const char *annex,
2055 gdb_byte *readbuf, const gdb_byte *writebuf,
2056 ULONGEST offset, LONGEST len)
2057 {
2058 static std::string result;
2059
2060 if (writebuf != NULL)
2061 return -2;
2062
2063 if (annex[0] != '\0')
2064 return -1;
2065
2066 if (offset == 0)
2067 {
2068 /* When asked for data at offset 0, generate everything and store into
2069 'result'. Successive reads will be served off 'result'. */
2070 result.clear ();
2071
2072 bool res = handle_qxfer_threads_proper (&result);
2073
2074 if (!res)
2075 return -1;
2076 }
2077
2078 if (offset >= result.length ())
2079 {
2080 /* We're out of data. */
2081 result.clear ();
2082 return 0;
2083 }
2084
2085 if (len > result.length () - offset)
2086 len = result.length () - offset;
2087
2088 memcpy (readbuf, result.c_str () + offset, len);
2089
2090 return len;
2091 }
2092
2093 /* Handle qXfer:traceframe-info:read. */
2094
2095 static int
2096 handle_qxfer_traceframe_info (const char *annex,
2097 gdb_byte *readbuf, const gdb_byte *writebuf,
2098 ULONGEST offset, LONGEST len)
2099 {
2100 client_state &cs = get_client_state ();
2101 static std::string result;
2102
2103 if (writebuf != NULL)
2104 return -2;
2105
2106 if (!target_running () || annex[0] != '\0' || cs.current_traceframe == -1)
2107 return -1;
2108
2109 if (offset == 0)
2110 {
2111 /* When asked for data at offset 0, generate everything and
2112 store into 'result'. Successive reads will be served off
2113 'result'. */
2114 result.clear ();
2115
2116 traceframe_read_info (cs.current_traceframe, &result);
2117 }
2118
2119 if (offset >= result.length ())
2120 {
2121 /* We're out of data. */
2122 result.clear ();
2123 return 0;
2124 }
2125
2126 if (len > result.length () - offset)
2127 len = result.length () - offset;
2128
2129 memcpy (readbuf, result.c_str () + offset, len);
2130 return len;
2131 }
2132
2133 /* Handle qXfer:fdpic:read. */
2134
2135 static int
2136 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
2137 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
2138 {
2139 if (!the_target->supports_read_loadmap ())
2140 return -2;
2141
2142 if (current_thread == NULL)
2143 return -1;
2144
2145 return the_target->read_loadmap (annex, offset, readbuf, len);
2146 }
2147
2148 /* Handle qXfer:btrace:read. */
2149
2150 static int
2151 handle_qxfer_btrace (const char *annex,
2152 gdb_byte *readbuf, const gdb_byte *writebuf,
2153 ULONGEST offset, LONGEST len)
2154 {
2155 client_state &cs = get_client_state ();
2156 static std::string cache;
2157 thread_info *thread;
2158 enum btrace_read_type type;
2159 int result;
2160
2161 if (writebuf != NULL)
2162 return -2;
2163
2164 if (cs.general_thread == null_ptid
2165 || cs.general_thread == minus_one_ptid)
2166 {
2167 strcpy (cs.own_buf, "E.Must select a single thread.");
2168 return -3;
2169 }
2170
2171 thread = find_thread_ptid (cs.general_thread);
2172 if (thread == NULL)
2173 {
2174 strcpy (cs.own_buf, "E.No such thread.");
2175 return -3;
2176 }
2177
2178 if (thread->btrace == NULL)
2179 {
2180 strcpy (cs.own_buf, "E.Btrace not enabled.");
2181 return -3;
2182 }
2183
2184 if (strcmp (annex, "all") == 0)
2185 type = BTRACE_READ_ALL;
2186 else if (strcmp (annex, "new") == 0)
2187 type = BTRACE_READ_NEW;
2188 else if (strcmp (annex, "delta") == 0)
2189 type = BTRACE_READ_DELTA;
2190 else
2191 {
2192 strcpy (cs.own_buf, "E.Bad annex.");
2193 return -3;
2194 }
2195
2196 if (offset == 0)
2197 {
2198 cache.clear ();
2199
2200 try
2201 {
2202 result = target_read_btrace (thread->btrace, &cache, type);
2203 if (result != 0)
2204 memcpy (cs.own_buf, cache.c_str (), cache.length ());
2205 }
2206 catch (const gdb_exception_error &exception)
2207 {
2208 sprintf (cs.own_buf, "E.%s", exception.what ());
2209 result = -1;
2210 }
2211
2212 if (result != 0)
2213 return -3;
2214 }
2215 else if (offset > cache.length ())
2216 {
2217 cache.clear ();
2218 return -3;
2219 }
2220
2221 if (len > cache.length () - offset)
2222 len = cache.length () - offset;
2223
2224 memcpy (readbuf, cache.c_str () + offset, len);
2225
2226 return len;
2227 }
2228
2229 /* Handle qXfer:btrace-conf:read. */
2230
2231 static int
2232 handle_qxfer_btrace_conf (const char *annex,
2233 gdb_byte *readbuf, const gdb_byte *writebuf,
2234 ULONGEST offset, LONGEST len)
2235 {
2236 client_state &cs = get_client_state ();
2237 static std::string cache;
2238 thread_info *thread;
2239 int result;
2240
2241 if (writebuf != NULL)
2242 return -2;
2243
2244 if (annex[0] != '\0')
2245 return -1;
2246
2247 if (cs.general_thread == null_ptid
2248 || cs.general_thread == minus_one_ptid)
2249 {
2250 strcpy (cs.own_buf, "E.Must select a single thread.");
2251 return -3;
2252 }
2253
2254 thread = find_thread_ptid (cs.general_thread);
2255 if (thread == NULL)
2256 {
2257 strcpy (cs.own_buf, "E.No such thread.");
2258 return -3;
2259 }
2260
2261 if (thread->btrace == NULL)
2262 {
2263 strcpy (cs.own_buf, "E.Btrace not enabled.");
2264 return -3;
2265 }
2266
2267 if (offset == 0)
2268 {
2269 cache.clear ();
2270
2271 try
2272 {
2273 result = target_read_btrace_conf (thread->btrace, &cache);
2274 if (result != 0)
2275 memcpy (cs.own_buf, cache.c_str (), cache.length ());
2276 }
2277 catch (const gdb_exception_error &exception)
2278 {
2279 sprintf (cs.own_buf, "E.%s", exception.what ());
2280 result = -1;
2281 }
2282
2283 if (result != 0)
2284 return -3;
2285 }
2286 else if (offset > cache.length ())
2287 {
2288 cache.clear ();
2289 return -3;
2290 }
2291
2292 if (len > cache.length () - offset)
2293 len = cache.length () - offset;
2294
2295 memcpy (readbuf, cache.c_str () + offset, len);
2296
2297 return len;
2298 }
2299
2300 static const struct qxfer qxfer_packets[] =
2301 {
2302 { "auxv", handle_qxfer_auxv },
2303 { "btrace", handle_qxfer_btrace },
2304 { "btrace-conf", handle_qxfer_btrace_conf },
2305 { "exec-file", handle_qxfer_exec_file},
2306 { "fdpic", handle_qxfer_fdpic},
2307 { "features", handle_qxfer_features },
2308 { "libraries", handle_qxfer_libraries },
2309 { "libraries-svr4", handle_qxfer_libraries_svr4 },
2310 { "osdata", handle_qxfer_osdata },
2311 { "siginfo", handle_qxfer_siginfo },
2312 { "threads", handle_qxfer_threads },
2313 { "traceframe-info", handle_qxfer_traceframe_info },
2314 };
2315
2316 static int
2317 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
2318 {
2319 int i;
2320 char *object;
2321 char *rw;
2322 char *annex;
2323 char *offset;
2324
2325 if (!startswith (own_buf, "qXfer:"))
2326 return 0;
2327
2328 /* Grab the object, r/w and annex. */
2329 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
2330 {
2331 write_enn (own_buf);
2332 return 1;
2333 }
2334
2335 for (i = 0;
2336 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
2337 i++)
2338 {
2339 const struct qxfer *q = &qxfer_packets[i];
2340
2341 if (strcmp (object, q->object) == 0)
2342 {
2343 if (strcmp (rw, "read") == 0)
2344 {
2345 unsigned char *data;
2346 int n;
2347 CORE_ADDR ofs;
2348 unsigned int len;
2349
2350 /* Grab the offset and length. */
2351 if (decode_xfer_read (offset, &ofs, &len) < 0)
2352 {
2353 write_enn (own_buf);
2354 return 1;
2355 }
2356
2357 /* Read one extra byte, as an indicator of whether there is
2358 more. */
2359 if (len > PBUFSIZ - 2)
2360 len = PBUFSIZ - 2;
2361 data = (unsigned char *) malloc (len + 1);
2362 if (data == NULL)
2363 {
2364 write_enn (own_buf);
2365 return 1;
2366 }
2367 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
2368 if (n == -2)
2369 {
2370 free (data);
2371 return 0;
2372 }
2373 else if (n == -3)
2374 {
2375 /* Preserve error message. */
2376 }
2377 else if (n < 0)
2378 write_enn (own_buf);
2379 else if (n > len)
2380 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
2381 else
2382 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
2383
2384 free (data);
2385 return 1;
2386 }
2387 else if (strcmp (rw, "write") == 0)
2388 {
2389 int n;
2390 unsigned int len;
2391 CORE_ADDR ofs;
2392 unsigned char *data;
2393
2394 strcpy (own_buf, "E00");
2395 data = (unsigned char *) malloc (packet_len - (offset - own_buf));
2396 if (data == NULL)
2397 {
2398 write_enn (own_buf);
2399 return 1;
2400 }
2401 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
2402 &ofs, &len, data) < 0)
2403 {
2404 free (data);
2405 write_enn (own_buf);
2406 return 1;
2407 }
2408
2409 n = (*q->xfer) (annex, NULL, data, ofs, len);
2410 if (n == -2)
2411 {
2412 free (data);
2413 return 0;
2414 }
2415 else if (n == -3)
2416 {
2417 /* Preserve error message. */
2418 }
2419 else if (n < 0)
2420 write_enn (own_buf);
2421 else
2422 sprintf (own_buf, "%x", n);
2423
2424 free (data);
2425 return 1;
2426 }
2427
2428 return 0;
2429 }
2430 }
2431
2432 return 0;
2433 }
2434
2435 /* Compute 32 bit CRC from inferior memory.
2436
2437 On success, return 32 bit CRC.
2438 On failure, return (unsigned long long) -1. */
2439
2440 static unsigned long long
2441 crc32 (CORE_ADDR base, int len, unsigned int crc)
2442 {
2443 while (len--)
2444 {
2445 unsigned char byte = 0;
2446
2447 /* Return failure if memory read fails. */
2448 if (read_inferior_memory (base, &byte, 1) != 0)
2449 return (unsigned long long) -1;
2450
2451 crc = xcrc32 (&byte, 1, crc);
2452 base++;
2453 }
2454 return (unsigned long long) crc;
2455 }
2456
2457 /* Parse the qMemTags packet request into ADDR and LEN. */
2458
2459 static void
2460 parse_fetch_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
2461 int *type)
2462 {
2463 gdb_assert (startswith (request, "qMemTags:"));
2464
2465 const char *p = request + strlen ("qMemTags:");
2466
2467 /* Read address and length. */
2468 unsigned int length = 0;
2469 p = decode_m_packet_params (p, addr, &length, ':');
2470 *len = length;
2471
2472 /* Read the tag type. */
2473 ULONGEST tag_type = 0;
2474 p = unpack_varlen_hex (p, &tag_type);
2475 *type = (int) tag_type;
2476 }
2477
2478 /* Add supported btrace packets to BUF. */
2479
2480 static void
2481 supported_btrace_packets (char *buf)
2482 {
2483 strcat (buf, ";Qbtrace:bts+");
2484 strcat (buf, ";Qbtrace-conf:bts:size+");
2485 strcat (buf, ";Qbtrace:pt+");
2486 strcat (buf, ";Qbtrace-conf:pt:size+");
2487 strcat (buf, ";Qbtrace-conf:pt:ptwrite+");
2488 strcat (buf, ";Qbtrace-conf:pt:event-tracing+");
2489 strcat (buf, ";Qbtrace:off+");
2490 strcat (buf, ";qXfer:btrace:read+");
2491 strcat (buf, ";qXfer:btrace-conf:read+");
2492 }
2493
2494 /* Handle all of the extended 'q' packets. */
2495
2496 static void
2497 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
2498 {
2499 client_state &cs = get_client_state ();
2500 static owning_intrusive_list<process_info>::iterator process_iter;
2501 static owning_intrusive_list<thread_info>::iterator thread_iter;
2502
2503 auto init_thread_iter = [&] ()
2504 {
2505 process_iter = all_processes.begin ();
2506 owning_intrusive_list<thread_info> *thread_list;
2507
2508 for (; process_iter != all_processes.end (); ++process_iter)
2509 {
2510 thread_list = &process_iter->thread_list ();
2511 thread_iter = thread_list->begin ();
2512 if (thread_iter != thread_list->end ())
2513 break;
2514 }
2515 /* Make sure that there is at least one thread to iterate. */
2516 gdb_assert (process_iter != all_processes.end ());
2517 gdb_assert (thread_iter != thread_list->end ());
2518 };
2519
2520 auto advance_thread_iter = [&] ()
2521 {
2522 /* The loop below is written in the natural way as-if we'd always
2523 start at the beginning of the inferior list. This fast forwards
2524 the algorithm to the actual current position. */
2525 owning_intrusive_list<thread_info> *thread_list
2526 = &process_iter->thread_list ();
2527 goto start;
2528
2529 for (; process_iter != all_processes.end (); ++process_iter)
2530 {
2531 thread_list = &process_iter->thread_list ();
2532 thread_iter = thread_list->begin ();
2533 while (thread_iter != thread_list->end ())
2534 {
2535 return;
2536 start:
2537 ++thread_iter;
2538 }
2539 }
2540 };
2541
2542 /* Reply the current thread id. */
2543 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
2544 {
2545 ptid_t ptid;
2546 require_running_or_return (own_buf);
2547
2548 if (cs.general_thread != null_ptid && cs.general_thread != minus_one_ptid)
2549 ptid = cs.general_thread;
2550 else
2551 {
2552 init_thread_iter ();
2553 ptid = thread_iter->id;
2554 }
2555
2556 sprintf (own_buf, "QC");
2557 own_buf += 2;
2558 write_ptid (own_buf, ptid);
2559 return;
2560 }
2561
2562 if (strcmp ("qSymbol::", own_buf) == 0)
2563 {
2564 scoped_restore_current_thread restore_thread;
2565
2566 /* For qSymbol, GDB only changes the current thread if the
2567 previous current thread was of a different process. So if
2568 the previous thread is gone, we need to pick another one of
2569 the same process. This can happen e.g., if we followed an
2570 exec in a non-leader thread. */
2571 if (current_thread == NULL)
2572 {
2573 thread_info *any_thread
2574 = find_any_thread_of_pid (cs.general_thread.pid ());
2575 switch_to_thread (any_thread);
2576
2577 /* Just in case, if we didn't find a thread, then bail out
2578 instead of crashing. */
2579 if (current_thread == NULL)
2580 {
2581 write_enn (own_buf);
2582 return;
2583 }
2584 }
2585
2586 /* GDB is suggesting new symbols have been loaded. This may
2587 mean a new shared library has been detected as loaded, so
2588 take the opportunity to check if breakpoints we think are
2589 inserted, still are. Note that it isn't guaranteed that
2590 we'll see this when a shared library is loaded, and nor will
2591 we see this for unloads (although breakpoints in unloaded
2592 libraries shouldn't trigger), as GDB may not find symbols for
2593 the library at all. We also re-validate breakpoints when we
2594 see a second GDB breakpoint for the same address, and or when
2595 we access breakpoint shadows. */
2596 validate_breakpoints ();
2597
2598 if (target_supports_tracepoints ())
2599 tracepoint_look_up_symbols ();
2600
2601 if (current_thread != NULL)
2602 the_target->look_up_symbols ();
2603
2604 strcpy (own_buf, "OK");
2605 return;
2606 }
2607
2608 if (!disable_packet_qfThreadInfo)
2609 {
2610 if (strcmp ("qfThreadInfo", own_buf) == 0)
2611 {
2612 require_running_or_return (own_buf);
2613 init_thread_iter ();
2614
2615 *own_buf++ = 'm';
2616 ptid_t ptid = thread_iter->id;
2617 write_ptid (own_buf, ptid);
2618 advance_thread_iter ();
2619 return;
2620 }
2621
2622 if (strcmp ("qsThreadInfo", own_buf) == 0)
2623 {
2624 require_running_or_return (own_buf);
2625 /* We're done if the process iterator hits the end of the
2626 process list. */
2627 if (process_iter != all_processes.end ())
2628 {
2629 *own_buf++ = 'm';
2630 ptid_t ptid = thread_iter->id;
2631 write_ptid (own_buf, ptid);
2632 advance_thread_iter ();
2633 return;
2634 }
2635 else
2636 {
2637 sprintf (own_buf, "l");
2638 return;
2639 }
2640 }
2641 }
2642
2643 if (the_target->supports_read_offsets ()
2644 && strcmp ("qOffsets", own_buf) == 0)
2645 {
2646 CORE_ADDR text, data;
2647
2648 require_running_or_return (own_buf);
2649 if (the_target->read_offsets (&text, &data))
2650 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
2651 (long)text, (long)data, (long)data);
2652 else
2653 write_enn (own_buf);
2654
2655 return;
2656 }
2657
2658 /* Protocol features query. */
2659 if (startswith (own_buf, "qSupported")
2660 && (own_buf[10] == ':' || own_buf[10] == '\0'))
2661 {
2662 char *p = &own_buf[10];
2663 int gdb_supports_qRelocInsn = 0;
2664
2665 /* Process each feature being provided by GDB. The first
2666 feature will follow a ':', and latter features will follow
2667 ';'. */
2668 if (*p == ':')
2669 {
2670 std::vector<std::string> qsupported;
2671 std::vector<const char *> unknowns;
2672
2673 /* Two passes, to avoid nested strtok calls in
2674 target_process_qsupported. */
2675 char *saveptr;
2676 for (p = strtok_r (p + 1, ";", &saveptr);
2677 p != NULL;
2678 p = strtok_r (NULL, ";", &saveptr))
2679 qsupported.emplace_back (p);
2680
2681 for (const std::string &feature : qsupported)
2682 {
2683 if (feature == "multiprocess+")
2684 {
2685 /* GDB supports and wants multi-process support if
2686 possible. */
2687 if (target_supports_multi_process ())
2688 cs.multi_process = 1;
2689 }
2690 else if (feature == "qRelocInsn+")
2691 {
2692 /* GDB supports relocate instruction requests. */
2693 gdb_supports_qRelocInsn = 1;
2694 }
2695 else if (feature == "swbreak+")
2696 {
2697 /* GDB wants us to report whether a trap is caused
2698 by a software breakpoint and for us to handle PC
2699 adjustment if necessary on this target. */
2700 if (target_supports_stopped_by_sw_breakpoint ())
2701 cs.swbreak_feature = 1;
2702 }
2703 else if (feature == "hwbreak+")
2704 {
2705 /* GDB wants us to report whether a trap is caused
2706 by a hardware breakpoint. */
2707 if (target_supports_stopped_by_hw_breakpoint ())
2708 cs.hwbreak_feature = 1;
2709 }
2710 else if (feature == "fork-events+")
2711 {
2712 /* GDB supports and wants fork events if possible. */
2713 if (target_supports_fork_events ())
2714 cs.report_fork_events = 1;
2715 }
2716 else if (feature == "vfork-events+")
2717 {
2718 /* GDB supports and wants vfork events if possible. */
2719 if (target_supports_vfork_events ())
2720 cs.report_vfork_events = 1;
2721 }
2722 else if (feature == "exec-events+")
2723 {
2724 /* GDB supports and wants exec events if possible. */
2725 if (target_supports_exec_events ())
2726 cs.report_exec_events = 1;
2727 }
2728 else if (feature == "vContSupported+")
2729 cs.vCont_supported = 1;
2730 else if (feature == "QThreadEvents+")
2731 ;
2732 else if (feature == "QThreadOptions+")
2733 ;
2734 else if (feature == "no-resumed+")
2735 {
2736 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2737 events. */
2738 report_no_resumed = true;
2739 }
2740 else if (feature == "memory-tagging+")
2741 {
2742 /* GDB supports memory tagging features. */
2743 if (target_supports_memory_tagging ())
2744 cs.memory_tagging_feature = true;
2745 }
2746 else if (feature == "error-message+")
2747 cs.error_message_supported = true;
2748 else
2749 {
2750 /* Move the unknown features all together. */
2751 unknowns.push_back (feature.c_str ());
2752 }
2753 }
2754
2755 /* Give the target backend a chance to process the unknown
2756 features. */
2757 target_process_qsupported (unknowns);
2758 }
2759
2760 sprintf (own_buf,
2761 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2762 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2763 "QEnvironmentReset+;QEnvironmentUnset+;"
2764 "QSetWorkingDir+;binary-upload+",
2765 PBUFSIZ - 1);
2766
2767 if (target_supports_catch_syscall ())
2768 strcat (own_buf, ";QCatchSyscalls+");
2769
2770 if (the_target->supports_qxfer_libraries_svr4 ())
2771 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2772 ";augmented-libraries-svr4-read+");
2773 else
2774 {
2775 /* We do not have any hook to indicate whether the non-SVR4 target
2776 backend supports qXfer:libraries:read, so always report it. */
2777 strcat (own_buf, ";qXfer:libraries:read+");
2778 }
2779
2780 if (the_target->supports_read_auxv ())
2781 strcat (own_buf, ";qXfer:auxv:read+");
2782
2783 if (the_target->supports_qxfer_siginfo ())
2784 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2785
2786 if (the_target->supports_read_loadmap ())
2787 strcat (own_buf, ";qXfer:fdpic:read+");
2788
2789 /* We always report qXfer:features:read, as targets may
2790 install XML files on a subsequent call to arch_setup.
2791 If we reported to GDB on startup that we don't support
2792 qXfer:feature:read at all, we will never be re-queried. */
2793 strcat (own_buf, ";qXfer:features:read+");
2794
2795 if (cs.transport_is_reliable)
2796 strcat (own_buf, ";QStartNoAckMode+");
2797
2798 if (the_target->supports_qxfer_osdata ())
2799 strcat (own_buf, ";qXfer:osdata:read+");
2800
2801 if (target_supports_multi_process ())
2802 strcat (own_buf, ";multiprocess+");
2803
2804 if (target_supports_fork_events ())
2805 strcat (own_buf, ";fork-events+");
2806
2807 if (target_supports_vfork_events ())
2808 strcat (own_buf, ";vfork-events+");
2809
2810 if (target_supports_exec_events ())
2811 strcat (own_buf, ";exec-events+");
2812
2813 if (target_supports_non_stop ())
2814 strcat (own_buf, ";QNonStop+");
2815
2816 if (target_supports_disable_randomization ())
2817 strcat (own_buf, ";QDisableRandomization+");
2818
2819 strcat (own_buf, ";qXfer:threads:read+");
2820
2821 if (target_supports_tracepoints ())
2822 {
2823 strcat (own_buf, ";ConditionalTracepoints+");
2824 strcat (own_buf, ";TraceStateVariables+");
2825 strcat (own_buf, ";TracepointSource+");
2826 strcat (own_buf, ";DisconnectedTracing+");
2827 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2828 strcat (own_buf, ";FastTracepoints+");
2829 strcat (own_buf, ";InstallInTrace+");
2830 strcat (own_buf, ";qXfer:traceframe-info:read+");
2831 strcat (own_buf, ";EnableDisableTracepoints+");
2832 strcat (own_buf, ";QTBuffer:size+");
2833 strcat (own_buf, ";tracenz+");
2834 }
2835
2836 if (target_supports_hardware_single_step ()
2837 || target_supports_software_single_step () )
2838 {
2839 strcat (own_buf, ";ConditionalBreakpoints+");
2840 }
2841 strcat (own_buf, ";BreakpointCommands+");
2842
2843 if (target_supports_agent ())
2844 strcat (own_buf, ";QAgent+");
2845
2846 if (the_target->supports_btrace ())
2847 supported_btrace_packets (own_buf);
2848
2849 if (target_supports_stopped_by_sw_breakpoint ())
2850 strcat (own_buf, ";swbreak+");
2851
2852 if (target_supports_stopped_by_hw_breakpoint ())
2853 strcat (own_buf, ";hwbreak+");
2854
2855 if (the_target->supports_pid_to_exec_file ())
2856 strcat (own_buf, ";qXfer:exec-file:read+");
2857
2858 strcat (own_buf, ";vContSupported+");
2859
2860 gdb_thread_options supported_options = target_supported_thread_options ();
2861 if (supported_options != 0)
2862 {
2863 char *end_buf = own_buf + strlen (own_buf);
2864 sprintf (end_buf, ";QThreadOptions=%s",
2865 phex_nz (supported_options));
2866 }
2867
2868 strcat (own_buf, ";QThreadEvents+");
2869
2870 strcat (own_buf, ";no-resumed+");
2871
2872 if (target_supports_memory_tagging ())
2873 strcat (own_buf, ";memory-tagging+");
2874
2875 /* Reinitialize components as needed for the new connection. */
2876 hostio_handle_new_gdb_connection ();
2877 target_handle_new_gdb_connection ();
2878
2879 return;
2880 }
2881
2882 /* Thread-local storage support. */
2883 if (the_target->supports_get_tls_address ()
2884 && startswith (own_buf, "qGetTLSAddr:"))
2885 {
2886 char *p = own_buf + 12;
2887 CORE_ADDR parts[2], address = 0;
2888 int i, err;
2889 ptid_t ptid = null_ptid;
2890
2891 require_running_or_return (own_buf);
2892
2893 for (i = 0; i < 3; i++)
2894 {
2895 char *p2;
2896 int len;
2897
2898 if (p == NULL)
2899 break;
2900
2901 p2 = strchr (p, ',');
2902 if (p2)
2903 {
2904 len = p2 - p;
2905 p2++;
2906 }
2907 else
2908 {
2909 len = strlen (p);
2910 p2 = NULL;
2911 }
2912
2913 if (i == 0)
2914 ptid = read_ptid (p, NULL);
2915 else
2916 decode_address (&parts[i - 1], p, len);
2917 p = p2;
2918 }
2919
2920 if (p != NULL || i < 3)
2921 err = 1;
2922 else
2923 {
2924 thread_info *thread = find_thread_ptid (ptid);
2925
2926 if (thread == NULL)
2927 err = 2;
2928 else
2929 err = the_target->get_tls_address (thread, parts[0], parts[1],
2930 &address);
2931 }
2932
2933 if (err == 0)
2934 {
2935 strcpy (own_buf, paddress(address));
2936 return;
2937 }
2938 else if (err > 0)
2939 {
2940 write_enn (own_buf);
2941 return;
2942 }
2943
2944 /* Otherwise, pretend we do not understand this packet. */
2945 }
2946
2947 /* Windows OS Thread Information Block address support. */
2948 if (the_target->supports_get_tib_address ()
2949 && startswith (own_buf, "qGetTIBAddr:"))
2950 {
2951 const char *annex;
2952 int n;
2953 CORE_ADDR tlb;
2954 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2955
2956 n = the_target->get_tib_address (ptid, &tlb);
2957 if (n == 1)
2958 {
2959 strcpy (own_buf, paddress(tlb));
2960 return;
2961 }
2962 else if (n == 0)
2963 {
2964 write_enn (own_buf);
2965 return;
2966 }
2967 return;
2968 }
2969
2970 /* Handle "monitor" commands. */
2971 if (startswith (own_buf, "qRcmd,"))
2972 {
2973 char *mon = (char *) malloc (PBUFSIZ);
2974 int len = strlen (own_buf + 6);
2975
2976 if (mon == NULL)
2977 {
2978 write_enn (own_buf);
2979 return;
2980 }
2981
2982 if ((len % 2) != 0
2983 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
2984 {
2985 write_enn (own_buf);
2986 free (mon);
2987 return;
2988 }
2989 mon[len / 2] = '\0';
2990
2991 write_ok (own_buf);
2992
2993 if (the_target->handle_monitor_command (mon) == 0)
2994 /* Default processing. */
2995 handle_monitor_command (mon, own_buf);
2996
2997 free (mon);
2998 return;
2999 }
3000
3001 if (startswith (own_buf, "qSearch:memory:"))
3002 {
3003 require_running_or_return (own_buf);
3004 handle_search_memory (own_buf, packet_len);
3005 return;
3006 }
3007
3008 if (strcmp (own_buf, "qAttached") == 0
3009 || startswith (own_buf, "qAttached:"))
3010 {
3011 struct process_info *process;
3012
3013 if (own_buf[sizeof ("qAttached") - 1])
3014 {
3015 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
3016 process = find_process_pid (pid);
3017 }
3018 else
3019 {
3020 require_running_or_return (own_buf);
3021 process = current_process ();
3022 }
3023
3024 if (process == NULL)
3025 {
3026 write_enn (own_buf);
3027 return;
3028 }
3029
3030 strcpy (own_buf, process->attached ? "1" : "0");
3031 return;
3032 }
3033
3034 if (startswith (own_buf, "qCRC:"))
3035 {
3036 /* CRC check (compare-section). */
3037 const char *comma;
3038 ULONGEST base;
3039 int len;
3040 unsigned long long crc;
3041
3042 require_running_or_return (own_buf);
3043 comma = unpack_varlen_hex (own_buf + 5, &base);
3044 if (*comma++ != ',')
3045 {
3046 write_enn (own_buf);
3047 return;
3048 }
3049 len = strtoul (comma, NULL, 16);
3050 crc = crc32 (base, len, 0xffffffff);
3051 /* Check for memory failure. */
3052 if (crc == (unsigned long long) -1)
3053 {
3054 write_enn (own_buf);
3055 return;
3056 }
3057 sprintf (own_buf, "C%lx", (unsigned long) crc);
3058 return;
3059 }
3060
3061 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
3062 return;
3063
3064 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
3065 return;
3066
3067 /* Handle fetch memory tags packets. */
3068 if (startswith (own_buf, "qMemTags:")
3069 && target_supports_memory_tagging ())
3070 {
3071 gdb::byte_vector tags;
3072 CORE_ADDR addr = 0;
3073 size_t len = 0;
3074 int type = 0;
3075
3076 require_running_or_return (own_buf);
3077
3078 parse_fetch_memtags_request (own_buf, &addr, &len, &type);
3079
3080 bool ret = the_target->fetch_memtags (addr, len, tags, type);
3081
3082 if (ret)
3083 ret = create_fetch_memtags_reply (own_buf, tags);
3084
3085 if (!ret)
3086 write_enn (own_buf);
3087
3088 *new_packet_len_p = strlen (own_buf);
3089 return;
3090 }
3091
3092 /* Otherwise we didn't know what packet it was. Say we didn't
3093 understand it. */
3094 own_buf[0] = 0;
3095 }
3096
3097 static void gdb_wants_all_threads_stopped (void);
3098 static void resume (struct thread_resume *actions, size_t n);
3099
3100 /* The callback that is passed to visit_actioned_threads. */
3101 typedef int (visit_actioned_threads_callback_ftype)
3102 (const struct thread_resume *, thread_info *);
3103
3104 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
3105 true if CALLBACK returns true. Returns false if no matching thread
3106 is found or CALLBACK results false.
3107 Note: This function is itself a callback for find_thread. */
3108
3109 static bool
3110 visit_actioned_threads (thread_info *thread,
3111 const struct thread_resume *actions,
3112 size_t num_actions,
3113 visit_actioned_threads_callback_ftype *callback)
3114 {
3115 for (size_t i = 0; i < num_actions; i++)
3116 {
3117 const struct thread_resume *action = &actions[i];
3118
3119 if (action->thread == minus_one_ptid
3120 || action->thread == thread->id
3121 || ((action->thread.pid ()
3122 == thread->id.pid ())
3123 && action->thread.lwp () == -1))
3124 {
3125 if ((*callback) (action, thread))
3126 return true;
3127 }
3128 }
3129
3130 return false;
3131 }
3132
3133 /* Callback for visit_actioned_threads. If the thread has a pending
3134 status to report, report it now. */
3135
3136 static int
3137 handle_pending_status (const struct thread_resume *resumption,
3138 thread_info *thread)
3139 {
3140 client_state &cs = get_client_state ();
3141 if (thread->status_pending_p)
3142 {
3143 thread->status_pending_p = 0;
3144
3145 cs.last_status = thread->last_status;
3146 cs.last_ptid = thread->id;
3147 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
3148 return 1;
3149 }
3150 return 0;
3151 }
3152
3153 /* Parse vCont packets. */
3154 static void
3155 handle_v_cont (char *own_buf)
3156 {
3157 const char *p;
3158 int n = 0, i = 0;
3159 struct thread_resume *resume_info;
3160 struct thread_resume default_action { null_ptid };
3161
3162 /* Count the number of semicolons in the packet. There should be one
3163 for every action. */
3164 p = &own_buf[5];
3165 while (p)
3166 {
3167 n++;
3168 p++;
3169 p = strchr (p, ';');
3170 }
3171
3172 resume_info = (struct thread_resume *) malloc (n * sizeof (resume_info[0]));
3173 if (resume_info == NULL)
3174 goto err;
3175
3176 p = &own_buf[5];
3177 while (*p)
3178 {
3179 p++;
3180
3181 memset (&resume_info[i], 0, sizeof resume_info[i]);
3182
3183 if (p[0] == 's' || p[0] == 'S')
3184 resume_info[i].kind = resume_step;
3185 else if (p[0] == 'r')
3186 resume_info[i].kind = resume_step;
3187 else if (p[0] == 'c' || p[0] == 'C')
3188 resume_info[i].kind = resume_continue;
3189 else if (p[0] == 't')
3190 resume_info[i].kind = resume_stop;
3191 else
3192 goto err;
3193
3194 if (p[0] == 'S' || p[0] == 'C')
3195 {
3196 char *q;
3197 int sig = strtol (p + 1, &q, 16);
3198 if (p == q)
3199 goto err;
3200 p = q;
3201
3202 if (!gdb_signal_to_host_p ((enum gdb_signal) sig))
3203 goto err;
3204 resume_info[i].sig = gdb_signal_to_host ((enum gdb_signal) sig);
3205 }
3206 else if (p[0] == 'r')
3207 {
3208 ULONGEST addr;
3209
3210 p = unpack_varlen_hex (p + 1, &addr);
3211 resume_info[i].step_range_start = addr;
3212
3213 if (*p != ',')
3214 goto err;
3215
3216 p = unpack_varlen_hex (p + 1, &addr);
3217 resume_info[i].step_range_end = addr;
3218 }
3219 else
3220 {
3221 p = p + 1;
3222 }
3223
3224 if (p[0] == 0)
3225 {
3226 resume_info[i].thread = minus_one_ptid;
3227 default_action = resume_info[i];
3228
3229 /* Note: we don't increment i here, we'll overwrite this entry
3230 the next time through. */
3231 }
3232 else if (p[0] == ':')
3233 {
3234 const char *q;
3235 ptid_t ptid = read_ptid (p + 1, &q);
3236
3237 if (p == q)
3238 goto err;
3239 p = q;
3240 if (p[0] != ';' && p[0] != 0)
3241 goto err;
3242
3243 resume_info[i].thread = ptid;
3244
3245 i++;
3246 }
3247 }
3248
3249 if (i < n)
3250 resume_info[i] = default_action;
3251
3252 resume (resume_info, n);
3253 free (resume_info);
3254 return;
3255
3256 err:
3257 write_enn (own_buf);
3258 free (resume_info);
3259 return;
3260 }
3261
3262 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
3263
3264 static void
3265 resume (struct thread_resume *actions, size_t num_actions)
3266 {
3267 client_state &cs = get_client_state ();
3268 if (!non_stop)
3269 {
3270 /* Check if among the threads that GDB wants actioned, there's
3271 one with a pending status to report. If so, skip actually
3272 resuming/stopping and report the pending event
3273 immediately. */
3274
3275 thread_info *thread_with_status = find_thread ([&] (thread_info *thread)
3276 {
3277 return visit_actioned_threads (thread, actions, num_actions,
3278 handle_pending_status);
3279 });
3280
3281 if (thread_with_status != NULL)
3282 return;
3283
3284 enable_async_io ();
3285 }
3286
3287 the_target->resume (actions, num_actions);
3288
3289 if (non_stop)
3290 write_ok (cs.own_buf);
3291 else
3292 {
3293 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status, 0, 1);
3294
3295 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED
3296 && !report_no_resumed)
3297 {
3298 /* The client does not support this stop reply. At least
3299 return error. */
3300 sprintf (cs.own_buf, "E.No unwaited-for children left.");
3301 disable_async_io ();
3302 return;
3303 }
3304
3305 if (cs.last_status.kind () != TARGET_WAITKIND_EXITED
3306 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED
3307 && cs.last_status.kind () != TARGET_WAITKIND_THREAD_EXITED
3308 && cs.last_status.kind () != TARGET_WAITKIND_NO_RESUMED)
3309 current_thread->last_status = cs.last_status;
3310
3311 /* From the client's perspective, all-stop mode always stops all
3312 threads implicitly (and the target backend has already done
3313 so by now). Tag all threads as "want-stopped", so we don't
3314 resume them implicitly without the client telling us to. */
3315 gdb_wants_all_threads_stopped ();
3316 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
3317 disable_async_io ();
3318
3319 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
3320 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
3321 target_mourn_inferior (cs.last_ptid);
3322 }
3323 }
3324
3325 /* Attach to a new program. */
3326 static void
3327 handle_v_attach (char *own_buf)
3328 {
3329 client_state &cs = get_client_state ();
3330
3331 int pid = strtol (own_buf + 8, NULL, 16);
3332
3333 try
3334 {
3335 if (attach_inferior (pid) == 0)
3336 {
3337 /* Don't report shared library events after attaching, even if
3338 some libraries are preloaded. GDB will always poll the
3339 library list. Avoids the "stopped by shared library event"
3340 notice on the GDB side. */
3341 current_process ()->dlls_changed = false;
3342
3343 if (non_stop)
3344 {
3345 /* In non-stop, we don't send a resume reply. Stop events
3346 will follow up using the normal notification
3347 mechanism. */
3348 write_ok (own_buf);
3349 }
3350 else
3351 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3352 }
3353 else
3354 {
3355 /* Not supported. */
3356 own_buf[0] = 0;
3357 }
3358 }
3359 catch (const gdb_exception_error &exception)
3360 {
3361 sprintf (own_buf, "E.%s", exception.what ());
3362 }
3363 }
3364
3365 /* Decode an argument from the vRun packet buffer. PTR points to the
3366 first hex-encoded character in the buffer, and LEN is the number of
3367 characters to read from the packet buffer.
3368
3369 If the argument decoding is successful, return a buffer containing the
3370 decoded argument, including a null terminator at the end.
3371
3372 If the argument decoding fails for any reason, return nullptr. */
3373
3374 static gdb::unique_xmalloc_ptr<char>
3375 decode_v_run_arg (const char *ptr, size_t len)
3376 {
3377 /* Two hex characters are required for each decoded byte. */
3378 if (len % 2 != 0)
3379 return nullptr;
3380
3381 /* The length in bytes needed for the decoded argument. */
3382 len /= 2;
3383
3384 /* Buffer to decode the argument into. The '+ 1' is for the null
3385 terminator we will add. */
3386 char *arg = (char *) xmalloc (len + 1);
3387
3388 /* Decode the argument from the packet and add a null terminator. We do
3389 this within a try block as invalid characters within the PTR buffer
3390 will cause hex2bin to throw an exception. Our caller relies on us
3391 returning nullptr in order to clean up some memory allocations. */
3392 try
3393 {
3394 hex2bin (ptr, (gdb_byte *) arg, len);
3395 arg[len] = '\0';
3396 }
3397 catch (const gdb_exception_error &exception)
3398 {
3399 return nullptr;
3400 }
3401
3402 return gdb::unique_xmalloc_ptr<char> (arg);
3403 }
3404
3405 /* Run a new program. */
3406 static void
3407 handle_v_run (char *own_buf)
3408 {
3409 client_state &cs = get_client_state ();
3410 char *p, *next_p;
3411 gdb::argv_vec new_argv;
3412 gdb::unique_xmalloc_ptr<char> new_program_name;
3413 int i;
3414
3415 for (i = 0, p = own_buf + strlen ("vRun;");
3416 /* Exit condition is at the end of the loop. */;
3417 p = next_p + 1, ++i)
3418 {
3419 next_p = strchr (p, ';');
3420 if (next_p == NULL)
3421 next_p = p + strlen (p);
3422
3423 if (i == 0 && p == next_p)
3424 {
3425 /* No program specified. */
3426 gdb_assert (new_program_name == nullptr);
3427 }
3428 else if (p == next_p)
3429 {
3430 /* Empty argument. */
3431 new_argv.push_back (xstrdup (""));
3432 }
3433 else
3434 {
3435 /* The length of the argument string in the packet. */
3436 size_t len = next_p - p;
3437
3438 gdb::unique_xmalloc_ptr<char> arg = decode_v_run_arg (p, len);
3439 if (arg == nullptr)
3440 {
3441 write_enn (own_buf);
3442 return;
3443 }
3444
3445 if (i == 0)
3446 new_program_name = std::move (arg);
3447 else
3448 new_argv.push_back (arg.release ());
3449 }
3450 if (*next_p == '\0')
3451 break;
3452 }
3453
3454 if (new_program_name == nullptr)
3455 {
3456 /* GDB didn't specify a program to run. Use the program from the
3457 last run with the new argument list. */
3458 if (program_path.get () == nullptr)
3459 {
3460 write_enn (own_buf);
3461 return;
3462 }
3463 }
3464 else
3465 program_path.set (new_program_name.get ());
3466
3467 program_args = gdb::remote_args::join (new_argv.get ());
3468
3469 try
3470 {
3471 target_create_inferior (program_path.get (), program_args);
3472 }
3473 catch (const gdb_exception_error &exception)
3474 {
3475 sprintf (own_buf, "E.%s", exception.what ());
3476 return;
3477 }
3478
3479 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
3480 {
3481 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3482
3483 /* In non-stop, sending a resume reply doesn't set the general
3484 thread, but GDB assumes a vRun sets it (this is so GDB can
3485 query which is the main thread of the new inferior. */
3486 if (non_stop)
3487 cs.general_thread = cs.last_ptid;
3488 }
3489 else
3490 write_enn (own_buf);
3491 }
3492
3493 /* Kill process. */
3494 static void
3495 handle_v_kill (char *own_buf)
3496 {
3497 client_state &cs = get_client_state ();
3498 int pid;
3499 char *p = &own_buf[6];
3500 if (cs.multi_process)
3501 pid = strtol (p, NULL, 16);
3502 else
3503 pid = signal_pid;
3504
3505 process_info *proc = find_process_pid (pid);
3506
3507 if (proc != nullptr && kill_inferior (proc) == 0)
3508 {
3509 cs.last_status.set_signalled (GDB_SIGNAL_KILL);
3510 cs.last_ptid = ptid_t (pid);
3511 discard_queued_stop_replies (cs.last_ptid);
3512 write_ok (own_buf);
3513 }
3514 else
3515 write_enn (own_buf);
3516 }
3517
3518 /* Handle all of the extended 'v' packets. */
3519 void
3520 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
3521 {
3522 client_state &cs = get_client_state ();
3523 if (!disable_packet_vCont)
3524 {
3525 if (strcmp (own_buf, "vCtrlC") == 0)
3526 {
3527 the_target->request_interrupt ();
3528 write_ok (own_buf);
3529 return;
3530 }
3531
3532 if (startswith (own_buf, "vCont;"))
3533 {
3534 handle_v_cont (own_buf);
3535 return;
3536 }
3537
3538 if (startswith (own_buf, "vCont?"))
3539 {
3540 strcpy (own_buf, "vCont;c;C;t");
3541
3542 if (!disable_packet_vCont_step
3543 && (target_supports_hardware_single_step ()
3544 || target_supports_software_single_step ()
3545 || !cs.vCont_supported))
3546 {
3547 /* If target supports single step either by hardware or by
3548 software, add actions s and S to the list of supported
3549 actions. On the other hand, if GDB doesn't request the
3550 supported vCont actions in qSupported packet, add s and
3551 S to the list too. */
3552 own_buf = own_buf + strlen (own_buf);
3553 strcpy (own_buf, ";s;S");
3554 }
3555
3556 if (target_supports_range_stepping ())
3557 {
3558 own_buf = own_buf + strlen (own_buf);
3559 strcpy (own_buf, ";r");
3560 }
3561 return;
3562 }
3563 }
3564
3565 if (startswith (own_buf, "vFile:")
3566 && handle_vFile (own_buf, packet_len, new_packet_len))
3567 return;
3568
3569 if (startswith (own_buf, "vAttach;"))
3570 {
3571 if ((!extended_protocol || !cs.multi_process) && target_running ())
3572 {
3573 fprintf (stderr, "Already debugging a process\n");
3574 write_enn (own_buf);
3575 return;
3576 }
3577 handle_v_attach (own_buf);
3578 return;
3579 }
3580
3581 if (startswith (own_buf, "vRun;"))
3582 {
3583 if ((!extended_protocol || !cs.multi_process) && target_running ())
3584 {
3585 fprintf (stderr, "Already debugging a process\n");
3586 write_enn (own_buf);
3587 return;
3588 }
3589 handle_v_run (own_buf);
3590 return;
3591 }
3592
3593 if (startswith (own_buf, "vKill;"))
3594 {
3595 if (!target_running ())
3596 {
3597 fprintf (stderr, "No process to kill\n");
3598 write_enn (own_buf);
3599 return;
3600 }
3601 handle_v_kill (own_buf);
3602 return;
3603 }
3604
3605 if (handle_notif_ack (own_buf, packet_len))
3606 return;
3607
3608 /* Otherwise we didn't know what packet it was. Say we didn't
3609 understand it. */
3610 own_buf[0] = 0;
3611 return;
3612 }
3613
3614 /* Resume thread and wait for another event. In non-stop mode,
3615 don't really wait here, but return immediately to the event
3616 loop. */
3617 static void
3618 myresume (char *own_buf, int step, int sig)
3619 {
3620 client_state &cs = get_client_state ();
3621 struct thread_resume resume_info[2];
3622 int n = 0;
3623 int valid_cont_thread;
3624
3625 valid_cont_thread = (cs.cont_thread != null_ptid
3626 && cs.cont_thread != minus_one_ptid);
3627
3628 if (step || sig || valid_cont_thread)
3629 {
3630 resume_info[0].thread = current_thread->id;
3631 if (step)
3632 resume_info[0].kind = resume_step;
3633 else
3634 resume_info[0].kind = resume_continue;
3635 resume_info[0].sig = sig;
3636 n++;
3637 }
3638
3639 if (!valid_cont_thread)
3640 {
3641 resume_info[n].thread = minus_one_ptid;
3642 resume_info[n].kind = resume_continue;
3643 resume_info[n].sig = 0;
3644 n++;
3645 }
3646
3647 resume (resume_info, n);
3648 }
3649
3650 /* Callback for for_each_thread. Make a new stop reply for each
3651 stopped thread. */
3652
3653 static void
3654 queue_stop_reply_callback (thread_info *thread)
3655 {
3656 /* For now, assume targets that don't have this callback also don't
3657 manage the thread's last_status field. */
3658 if (!the_target->supports_thread_stopped ())
3659 {
3660 struct vstop_notif *new_notif = new struct vstop_notif;
3661
3662 new_notif->ptid = thread->id;
3663 new_notif->status = thread->last_status;
3664 /* Pass the last stop reply back to GDB, but don't notify
3665 yet. */
3666 notif_event_enque (&notif_stop, new_notif);
3667 }
3668 else
3669 {
3670 if (target_thread_stopped (thread))
3671 {
3672 threads_debug_printf
3673 ("Reporting thread %s as already stopped with %s",
3674 target_pid_to_str (thread->id).c_str (),
3675 thread->last_status.to_string ().c_str ());
3676
3677 gdb_assert (thread->last_status.kind () != TARGET_WAITKIND_IGNORE);
3678
3679 /* Pass the last stop reply back to GDB, but don't notify
3680 yet. */
3681 queue_stop_reply (thread->id, thread->last_status);
3682 }
3683 }
3684 }
3685
3686 /* Set this inferior threads's state as "want-stopped". We won't
3687 resume this thread until the client gives us another action for
3688 it. */
3689
3690 static void
3691 gdb_wants_thread_stopped (thread_info *thread)
3692 {
3693 thread->last_resume_kind = resume_stop;
3694
3695 if (thread->last_status.kind () == TARGET_WAITKIND_IGNORE)
3696 {
3697 /* Most threads are stopped implicitly (all-stop); tag that with
3698 signal 0. */
3699 thread->last_status.set_stopped (GDB_SIGNAL_0);
3700 }
3701 }
3702
3703 /* Set all threads' states as "want-stopped". */
3704
3705 static void
3706 gdb_wants_all_threads_stopped (void)
3707 {
3708 for_each_thread (gdb_wants_thread_stopped);
3709 }
3710
3711 /* Callback for for_each_thread. If the thread is stopped with an
3712 interesting event, mark it as having a pending event. */
3713
3714 static void
3715 set_pending_status_callback (thread_info *thread)
3716 {
3717 if (thread->last_status.kind () != TARGET_WAITKIND_STOPPED
3718 || (thread->last_status.sig () != GDB_SIGNAL_0
3719 /* A breakpoint, watchpoint or finished step from a previous
3720 GDB run isn't considered interesting for a new GDB run.
3721 If we left those pending, the new GDB could consider them
3722 random SIGTRAPs. This leaves out real async traps. We'd
3723 have to peek into the (target-specific) siginfo to
3724 distinguish those. */
3725 && thread->last_status.sig () != GDB_SIGNAL_TRAP))
3726 thread->status_pending_p = 1;
3727 }
3728
3729 /* Status handler for the '?' packet. */
3730
3731 static void
3732 handle_status (char *own_buf)
3733 {
3734 client_state &cs = get_client_state ();
3735
3736 /* GDB is connected, don't forward events to the target anymore. */
3737 for_each_process ([] (process_info *process) {
3738 process->gdb_detached = 0;
3739 });
3740
3741 /* In non-stop mode, we must send a stop reply for each stopped
3742 thread. In all-stop mode, just send one for the first stopped
3743 thread we find. */
3744
3745 if (non_stop)
3746 {
3747 for_each_thread (queue_stop_reply_callback);
3748
3749 /* The first is sent immediately. OK is sent if there is no
3750 stopped thread, which is the same handling of the vStopped
3751 packet (by design). */
3752 notif_write_event (&notif_stop, cs.own_buf);
3753 }
3754 else
3755 {
3756 thread_info *thread = NULL;
3757
3758 target_pause_all (false);
3759 target_stabilize_threads ();
3760 gdb_wants_all_threads_stopped ();
3761
3762 /* We can only report one status, but we might be coming out of
3763 non-stop -- if more than one thread is stopped with
3764 interesting events, leave events for the threads we're not
3765 reporting now pending. They'll be reported the next time the
3766 threads are resumed. Start by marking all interesting events
3767 as pending. */
3768 for_each_thread (set_pending_status_callback);
3769
3770 /* Prefer the last thread that reported an event to GDB (even if
3771 that was a GDB_SIGNAL_TRAP). */
3772 if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE
3773 && cs.last_status.kind () != TARGET_WAITKIND_EXITED
3774 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED)
3775 thread = find_thread_ptid (cs.last_ptid);
3776
3777 /* If the last event thread is not found for some reason, look
3778 for some other thread that might have an event to report. */
3779 if (thread == NULL)
3780 thread = find_thread ([] (thread_info *thr_arg)
3781 {
3782 return thr_arg->status_pending_p;
3783 });
3784
3785 /* If we're still out of luck, simply pick the first thread in
3786 the thread list. */
3787 if (thread == NULL)
3788 thread = get_first_thread ();
3789
3790 if (thread != NULL)
3791 {
3792 thread_info *tp = (thread_info *) thread;
3793
3794 /* We're reporting this event, so it's no longer
3795 pending. */
3796 tp->status_pending_p = 0;
3797
3798 /* GDB assumes the current thread is the thread we're
3799 reporting the status for. */
3800 cs.general_thread = thread->id;
3801 set_desired_thread ();
3802
3803 gdb_assert (tp->last_status.kind () != TARGET_WAITKIND_IGNORE);
3804 prepare_resume_reply (own_buf, tp->id, tp->last_status);
3805 }
3806 else
3807 strcpy (own_buf, "W00");
3808 }
3809 }
3810
3811 static void
3812 gdbserver_version (void)
3813 {
3814 printf ("GNU gdbserver %s%s\n"
3815 "Copyright (C) 2025 Free Software Foundation, Inc.\n"
3816 "gdbserver is free software, covered by the "
3817 "GNU General Public License.\n"
3818 "This gdbserver was configured as \"%s\"\n",
3819 PKGVERSION, version, host_name);
3820 }
3821
3822 static void
3823 gdbserver_usage (FILE *stream)
3824 {
3825 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3826 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3827 "\tgdbserver [OPTIONS] --multi COMM\n"
3828 "\n"
3829 "COMM may either be a tty device (for serial debugging),\n"
3830 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3831 "stdin/stdout of gdbserver.\n"
3832 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3833 "PID is the process ID to attach to, when --attach is specified.\n"
3834 "\n"
3835 "Operating modes:\n"
3836 "\n"
3837 " --attach Attach to running process PID.\n"
3838 " --multi Start server without a specific program, and\n"
3839 " only quit when explicitly commanded.\n"
3840 " --once Exit after the first connection has closed.\n"
3841 " --help Print this message and then exit.\n"
3842 " --version Display version information and exit.\n"
3843 "\n"
3844 "Other options:\n"
3845 "\n"
3846 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3847 " --disable-randomization\n"
3848 " Run PROG with address space randomization disabled.\n"
3849 " --no-disable-randomization\n"
3850 " Don't disable address space randomization when\n"
3851 " starting PROG.\n"
3852 " --startup-with-shell\n"
3853 " Start PROG using a shell. I.e., execs a shell that\n"
3854 " then execs PROG. (default)\n"
3855 " --no-startup-with-shell\n"
3856 " Exec PROG directly instead of using a shell.\n"
3857 " Disables argument globbing and variable substitution\n"
3858 " on UNIX-like systems.\n"
3859 "\n"
3860 "Debug options:\n"
3861 "\n"
3862 " --debug[=OPT1,OPT2,...]\n"
3863 " Enable debugging output.\n"
3864 " Options:\n"
3865 " all, threads, event-loop, remote\n"
3866 " With no options, 'threads' is assumed.\n"
3867 " Prefix an option with '-' to disable\n"
3868 " debugging of that component.\n"
3869 " --debug-format=OPT1[,OPT2,...]\n"
3870 " Specify extra content in debugging output.\n"
3871 " Options:\n"
3872 " all\n"
3873 " none\n"
3874 " timestamp\n"
3875 " --disable-packet=OPT1[,OPT2,...]\n"
3876 " Disable support for RSP packets or features.\n"
3877 " Options:\n"
3878 " vCont, vConts, T, Tthread, qC, qfThreadInfo and\n"
3879 " threads (disable all threading packets).\n"
3880 "\n"
3881 "For more information, consult the GDB manual (available as on-line \n"
3882 "info or a printed manual).\n");
3883 if (REPORT_BUGS_TO[0] && stream == stdout)
3884 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
3885 }
3886
3887 static void
3888 gdbserver_show_disableable (FILE *stream)
3889 {
3890 fprintf (stream, "Disableable packets:\n"
3891 " vCont \tAll vCont packets\n"
3892 " qC \tQuerying the current thread\n"
3893 " qfThreadInfo\tThread listing\n"
3894 " Tthread \tPassing the thread specifier in the "
3895 "T stop reply packet\n"
3896 " threads \tAll of the above\n"
3897 " T \tAll 'T' packets\n");
3898 }
3899
3900 /* Start up the event loop. This is the entry point to the event
3901 loop. */
3902
3903 static void
3904 start_event_loop ()
3905 {
3906 /* Loop until there is nothing to do. This is the entry point to
3907 the event loop engine. If nothing is ready at this time, wait
3908 for something to happen (via wait_for_event), then process it.
3909 Return when there are no longer event sources to wait for. */
3910
3911 keep_processing_events = true;
3912 while (keep_processing_events)
3913 {
3914 /* Any events already waiting in the queue? */
3915 int res = gdb_do_one_event ();
3916
3917 /* Was there an error? */
3918 if (res == -1)
3919 break;
3920 }
3921
3922 /* We are done with the event loop. There are no more event sources
3923 to listen to. So we exit gdbserver. */
3924 }
3925
3926 static void
3927 kill_inferior_callback (process_info *process)
3928 {
3929 kill_inferior (process);
3930 discard_queued_stop_replies (ptid_t (process->pid));
3931 }
3932
3933 /* Call this when exiting gdbserver with possible inferiors that need
3934 to be killed or detached from. */
3935
3936 static void
3937 detach_or_kill_for_exit (void)
3938 {
3939 /* First print a list of the inferiors we will be killing/detaching.
3940 This is to assist the user, for example, in case the inferior unexpectedly
3941 dies after we exit: did we screw up or did the inferior exit on its own?
3942 Having this info will save some head-scratching. */
3943
3944 if (have_started_inferiors_p ())
3945 {
3946 fprintf (stderr, "Killing process(es):");
3947
3948 for_each_process ([] (process_info *process) {
3949 if (!process->attached)
3950 fprintf (stderr, " %d", process->pid);
3951 });
3952
3953 fprintf (stderr, "\n");
3954 }
3955 if (have_attached_inferiors_p ())
3956 {
3957 fprintf (stderr, "Detaching process(es):");
3958
3959 for_each_process ([] (process_info *process) {
3960 if (process->attached)
3961 fprintf (stderr, " %d", process->pid);
3962 });
3963
3964 fprintf (stderr, "\n");
3965 }
3966
3967 /* Now we can kill or detach the inferiors. */
3968 for_each_process ([] (process_info *process) {
3969 int pid = process->pid;
3970
3971 if (process->attached)
3972 detach_inferior (process);
3973 else
3974 kill_inferior (process);
3975
3976 discard_queued_stop_replies (ptid_t (pid));
3977 });
3978 }
3979
3980 /* Value that will be passed to exit(3) when gdbserver exits. */
3981 static int exit_code;
3982
3983 /* Wrapper for detach_or_kill_for_exit that catches and prints
3984 errors. */
3985
3986 static void
3987 detach_or_kill_for_exit_cleanup ()
3988 {
3989 try
3990 {
3991 detach_or_kill_for_exit ();
3992 }
3993 catch (const gdb_exception &exception)
3994 {
3995 fflush (stdout);
3996 fprintf (stderr, "Detach or kill failed: %s\n",
3997 exception.what ());
3998 exit_code = 1;
3999 }
4000 }
4001
4002 #if GDB_SELF_TEST
4003
4004 namespace selftests {
4005
4006 static void
4007 test_memory_tagging_functions (void)
4008 {
4009 /* Setup testing. */
4010 gdb::char_vector packet;
4011 gdb::byte_vector tags, bv;
4012 std::string expected;
4013 packet.resize (32000);
4014 CORE_ADDR addr;
4015 size_t len;
4016 int type;
4017
4018 /* Test parsing a qMemTags request. */
4019
4020 /* Valid request, addr, len and type updated. */
4021 addr = 0xff;
4022 len = 255;
4023 type = 255;
4024 strcpy (packet.data (), "qMemTags:0,0:0");
4025 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
4026 SELF_CHECK (addr == 0 && len == 0 && type == 0);
4027
4028 /* Valid request, addr, len and type updated. */
4029 addr = 0;
4030 len = 0;
4031 type = 0;
4032 strcpy (packet.data (), "qMemTags:deadbeef,ff:5");
4033 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
4034 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5);
4035
4036 /* Test creating a qMemTags reply. */
4037
4038 /* Non-empty tag data. */
4039 bv.resize (0);
4040
4041 for (int i = 0; i < 5; i++)
4042 bv.push_back (i);
4043
4044 expected = "m0001020304";
4045 SELF_CHECK (create_fetch_memtags_reply (packet.data (), bv) == true);
4046 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
4047
4048 /* Test parsing a QMemTags request. */
4049
4050 /* Valid request and empty tag data: addr, len, type and tags updated. */
4051 addr = 0xff;
4052 len = 255;
4053 type = 255;
4054 tags.resize (5);
4055 strcpy (packet.data (), "QMemTags:0,0:0:");
4056 SELF_CHECK (parse_store_memtags_request (packet.data (),
4057 &addr, &len, tags, &type) == true);
4058 SELF_CHECK (addr == 0 && len == 0 && type == 0 && tags.size () == 0);
4059
4060 /* Valid request and non-empty tag data: addr, len, type
4061 and tags updated. */
4062 addr = 0;
4063 len = 0;
4064 type = 0;
4065 tags.resize (0);
4066 strcpy (packet.data (),
4067 "QMemTags:deadbeef,ff:5:0001020304");
4068 SELF_CHECK (parse_store_memtags_request (packet.data (), &addr, &len, tags,
4069 &type) == true);
4070 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5
4071 && tags.size () == 5);
4072 }
4073
4074 /* Exercise the behavior of doing a 0-length comparison for a register in a
4075 register buffer, which should return true. */
4076
4077 static void test_registers_raw_compare_zero_length ()
4078 {
4079 /* Start off with a dummy target description. */
4080 target_desc dummy_tdesc;
4081
4082 /* Make it 8 bytes long. */
4083 dummy_tdesc.registers_size = 8;
4084
4085 /* Add a couple dummy 32-bit registers. */
4086 dummy_tdesc.reg_defs.emplace_back ("r0", 0, 32);
4087 dummy_tdesc.reg_defs.emplace_back ("r1", 32, 32);
4088
4089 /* Create our dummy register cache so we can invoke the raw_compare method
4090 we want to validate. */
4091 regcache dummy_regcache (&dummy_tdesc);
4092
4093 /* Create a dummy byte buffer we can pass to the raw_compare method. */
4094 gdb_byte dummy_buffer[8];
4095
4096 /* Validate the 0-length comparison (due to the comparison offset being
4097 equal to the length of the register) returns true. */
4098 SELF_CHECK (dummy_regcache.raw_compare (0, dummy_buffer, 4));
4099 }
4100
4101 } /* namespace selftests */
4102 #endif /* GDB_SELF_TEST */
4103
4104 /* Main function. This is called by the real "main" function,
4105 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
4106
4107 [[noreturn]] static void
4108 captured_main (int argc, char *argv[])
4109 {
4110 int pid;
4111 volatile bool multi_mode = false;
4112 volatile bool attach = false;
4113 bool selftest = false;
4114 #if GDB_SELF_TEST
4115 std::vector<const char *> selftest_filters;
4116
4117 selftests::register_test ("remote_memory_tagging",
4118 selftests::test_memory_tagging_functions);
4119 selftests::register_test ("test_registers_raw_compare_zero_length",
4120 selftests::test_registers_raw_compare_zero_length);
4121 #endif
4122
4123 current_directory = getcwd (NULL, 0);
4124 client_state &cs = get_client_state ();
4125
4126 if (current_directory == NULL)
4127 {
4128 error (_("Could not find current working directory: %s"),
4129 safe_strerror (errno));
4130 }
4131
4132 enum opts { OPT_VERSION = 1, OPT_HELP, OPT_ATTACH, OPT_MULTI, OPT_WRAPPER,
4133 OPT_DEBUG, OPT_DEBUG_FILE, OPT_DEBUG_FORMAT, OPT_DISABLE_PACKET,
4134 OPT_DISABLE_RANDOMIZATION, OPT_NO_DISABLE_RANDOMIZATION,
4135 OPT_STARTUP_WITH_SHELL, OPT_NO_STARTUP_WITH_SHELL, OPT_ONCE,
4136 OPT_SELFTEST,
4137 };
4138
4139 static struct option longopts[] =
4140 {
4141 {"version", no_argument, nullptr, OPT_VERSION},
4142 {"help", no_argument, nullptr, OPT_HELP},
4143 {"attach", no_argument, nullptr, OPT_ATTACH},
4144 {"multi", no_argument, nullptr, OPT_MULTI},
4145 {"wrapper", no_argument, nullptr, OPT_WRAPPER},
4146 {"debug", optional_argument, nullptr, OPT_DEBUG},
4147 {"debug-file", required_argument, nullptr, OPT_DEBUG_FILE},
4148 {"debug-format", required_argument, nullptr, OPT_DEBUG_FORMAT},
4149 /* --disable-packet is optional_argument only so that we can print a
4150 better help list when the argument is missing. */
4151 {"disable-packet", optional_argument, nullptr, OPT_DISABLE_PACKET},
4152 {"disable-randomization", no_argument, nullptr,
4153 OPT_DISABLE_RANDOMIZATION},
4154 {"no-disable-randomization", no_argument, nullptr,
4155 OPT_NO_DISABLE_RANDOMIZATION},
4156 {"startup-with-shell", no_argument, nullptr, OPT_STARTUP_WITH_SHELL},
4157 {"no-startup-with-shell", no_argument, nullptr,
4158 OPT_NO_STARTUP_WITH_SHELL},
4159 {"once", no_argument, nullptr, OPT_ONCE},
4160 {"selftest", optional_argument, nullptr, OPT_SELFTEST},
4161 {nullptr, no_argument, nullptr, 0}
4162 };
4163
4164 /* Ask getopt_long not to print error messages, we'll do that ourselves.
4165 Look for handling of '?' from getopt_long. */
4166 opterr = 0;
4167
4168 int optc, longindex;
4169
4170 /* The '+' passed to getopt_long here stops ARGV being reordered. In a
4171 command line like: 'gdbserver PORT program --arg1 --arg2', the
4172 '--arg1' and '--arg2' are arguments to 'program', not to gdbserver.
4173 If getopt_long is free to reorder ARGV then it will try to steal those
4174 arguments for itself. */
4175 while ((longindex = -1,
4176 optc = getopt_long (argc, argv, "+", longopts, &longindex)) != -1)
4177 {
4178 /* We only support '--option=value' form, not '--option value'. To
4179 achieve this, if global OPTARG points to the start of the previous
4180 ARGV entry, then we must have used the second (unsupported) form,
4181 so set OPTARG to NULL and decrement OPTIND to make it appear that
4182 there was no value passed. If the option requires an argument,
4183 then this means we should convert OPTC to '?' to indicate an
4184 error. */
4185 if (longindex != -1
4186 && longopts[longindex].has_arg != no_argument)
4187 {
4188 if (optarg == argv[optind - 1])
4189 {
4190 optarg = nullptr;
4191 --optind;
4192 }
4193
4194 if (longopts[longindex].has_arg == required_argument
4195 && optarg == nullptr)
4196 optc = '?';
4197 }
4198
4199 switch (optc)
4200 {
4201 case OPT_VERSION:
4202 gdbserver_version ();
4203 exit (0);
4204
4205 case OPT_HELP:
4206 gdbserver_usage (stdout);
4207 exit (0);
4208
4209 case OPT_ATTACH:
4210 attach = true;
4211 break;
4212
4213 case OPT_MULTI:
4214 multi_mode = true;
4215 break;
4216
4217 case OPT_WRAPPER:
4218 {
4219 int original_optind = optind;
4220
4221 while (argv[optind] != nullptr
4222 && strcmp (argv[optind], "--") != 0)
4223 {
4224 wrapper_argv += argv[optind];
4225 wrapper_argv += ' ';
4226 ++optind;
4227 }
4228
4229 if (!wrapper_argv.empty ())
4230 {
4231 /* Erase the last whitespace. */
4232 wrapper_argv.erase (wrapper_argv.end () - 1);
4233 }
4234
4235 if (original_optind == optind || argv[optind] == nullptr)
4236 {
4237 gdbserver_usage (stderr);
4238 exit (1);
4239 }
4240
4241 /* Consume the "--". */
4242 ++optind;
4243 }
4244 break;
4245
4246 case OPT_DEBUG:
4247 {
4248 const char *debug_opt = (optarg == nullptr) ? "" : optarg;
4249 try
4250 {
4251 parse_debug_options (debug_opt);
4252 }
4253 catch (const gdb_exception_error &exception)
4254 {
4255 fflush (stdout);
4256 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4257 exit (1);
4258 }
4259 }
4260 break;
4261
4262 case OPT_DEBUG_FILE:
4263 {
4264 gdb_assert (optarg != nullptr);
4265 debug_set_output (optarg);
4266 }
4267 break;
4268
4269 case OPT_DEBUG_FORMAT:
4270 {
4271 gdb_assert (optarg != nullptr);
4272 std::string error_msg
4273 = parse_debug_format_options (optarg, 0);
4274
4275 if (!error_msg.empty ())
4276 {
4277 fprintf (stderr, "%s", error_msg.c_str ());
4278 exit (1);
4279 }
4280 }
4281 break;
4282
4283 case OPT_DISABLE_PACKET:
4284 {
4285 char *packets = optarg;
4286 if (packets == nullptr)
4287 {
4288 gdbserver_show_disableable (stdout);
4289 exit (1);
4290 }
4291 char *saveptr;
4292 for (char *tok = strtok_r (packets, ",", &saveptr);
4293 tok != nullptr;
4294 tok = strtok_r (nullptr, ",", &saveptr))
4295 {
4296 if (strcmp ("vCont", tok) == 0)
4297 disable_packet_vCont = true;
4298 else if (strcmp ("vConts", tok) == 0)
4299 disable_packet_vCont_step = true;
4300 else if (strcmp ("Tthread", tok) == 0)
4301 disable_packet_Tthread = true;
4302 else if (strcmp ("qC", tok) == 0)
4303 disable_packet_qC = true;
4304 else if (strcmp ("qfThreadInfo", tok) == 0)
4305 disable_packet_qfThreadInfo = true;
4306 else if (strcmp ("T", tok) == 0)
4307 disable_packet_T = true;
4308 else if (strcmp ("threads", tok) == 0)
4309 {
4310 disable_packet_vCont = true;
4311 disable_packet_Tthread = true;
4312 disable_packet_qC = true;
4313 disable_packet_qfThreadInfo = true;
4314 }
4315 else
4316 {
4317 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
4318 tok);
4319 gdbserver_show_disableable (stderr);
4320 exit (1);
4321 }
4322 }
4323 }
4324 break;
4325
4326 case OPT_DISABLE_RANDOMIZATION:
4327 cs.disable_randomization = 1;
4328 break;
4329
4330 case OPT_NO_DISABLE_RANDOMIZATION:
4331 cs.disable_randomization = 0;
4332 break;
4333
4334 case OPT_STARTUP_WITH_SHELL:
4335 startup_with_shell = true;
4336 break;
4337
4338 case OPT_NO_STARTUP_WITH_SHELL:
4339 startup_with_shell = false;
4340 break;
4341
4342 case OPT_ONCE:
4343 run_once = true;
4344 break;
4345
4346 case OPT_SELFTEST:
4347 {
4348 selftest = true;
4349 if (optarg != nullptr)
4350 {
4351 #if GDB_SELF_TEST
4352 if (*optarg == '\0')
4353 {
4354 fprintf (stderr, _("Error: selftest filter is empty.\n"));
4355 exit (1);
4356 }
4357
4358 selftest_filters.push_back (optarg);
4359 #endif
4360 }
4361 }
4362 break;
4363
4364 case '?':
4365 /* Figuring out which element of ARGV contained the invalid
4366 argument is not simple. There are a couple of cases we need
4367 to consider.
4368
4369 (1) Something like '-x'. gdbserver doesn't support single
4370 character options, so a '-' followed by a character is
4371 always invalid. In this case global OPTOPT will be set to
4372 'x', and global OPTIND will point to the next ARGV entry.
4373
4374 (2) Something like '-xyz'. gdbserver doesn't support single
4375 dash arguments for its command line options. The
4376 getopt_long call treats this like '-x -y -z', in which
4377 case global OPTOPT is set to 'x' and global OPTIND will
4378 point to this ARGV entry.
4379
4380 (3) Something like '--unknown'. This is just an unknown
4381 double dash argument. Global OPTOPT is set to '\0', and
4382 global OPTIND points to the next ARGV entry. */
4383 std::string bad_arg;
4384 if (optopt == '\0' || argv[optind] == nullptr
4385 || argv[optind][0] != '-' || argv[optind][1] != optopt)
4386 bad_arg = argv[optind - 1];
4387 else
4388 bad_arg = argv[optind];
4389
4390 fprintf (stderr, "Unknown argument: %s\n", bad_arg.c_str ());
4391 exit (1);
4392 }
4393 }
4394
4395 const char *port = argv[optind];
4396 ++optind;
4397 if (port != nullptr && strcmp (port, "-") == 0)
4398 {
4399 port = STDIO_CONNECTION_NAME;
4400
4401 /* Implying --once here prevents a hang after stdin has been closed. */
4402 run_once = true;
4403 }
4404
4405 char **next_arg = &argv[optind];
4406 if ((port == NULL || (!attach && !multi_mode && *next_arg == NULL))
4407 && !selftest)
4408 {
4409 gdbserver_usage (stderr);
4410 exit (1);
4411 }
4412
4413 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
4414 opened by remote_prepare. */
4415 notice_open_fds ();
4416
4417 save_original_signals_state (false);
4418
4419 /* We need to know whether the remote connection is stdio before
4420 starting the inferior. Inferiors created in this scenario have
4421 stdin,stdout redirected. So do this here before we call
4422 start_inferior. */
4423 if (port != NULL)
4424 remote_prepare (port);
4425
4426 bool bad_attach = false;
4427 pid = 0;
4428
4429 /* --attach used to come after PORT, so allow it there for
4430 compatibility. */
4431 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
4432 {
4433 attach = true;
4434 next_arg++;
4435 }
4436
4437 char *arg_end;
4438 if (attach
4439 && (*next_arg == NULL
4440 || (*next_arg)[0] == '\0'
4441 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
4442 || *arg_end != '\0'
4443 || next_arg[1] != NULL))
4444 bad_attach = true;
4445
4446 if (bad_attach)
4447 {
4448 gdbserver_usage (stderr);
4449 exit (1);
4450 }
4451
4452 /* Gather information about the environment. */
4453 our_environ = gdb_environ::from_host_environ ();
4454
4455 initialize_async_io ();
4456 initialize_low ();
4457 have_job_control ();
4458 if (target_supports_tracepoints ())
4459 initialize_tracepoint ();
4460
4461 mem_buf = (unsigned char *) xmalloc (PBUFSIZ);
4462
4463 if (selftest)
4464 {
4465 #if GDB_SELF_TEST
4466 selftests::run_tests (selftest_filters);
4467 #else
4468 printf (_("Selftests have been disabled for this build.\n"));
4469 #endif
4470 throw_quit ("Quit");
4471 }
4472
4473 if (pid == 0 && *next_arg != NULL)
4474 {
4475 program_path.set (next_arg[0]);
4476
4477 int n = argc - (next_arg - argv);
4478 program_args
4479 = construct_inferior_arguments ({&next_arg[1], &next_arg[n]}, true);
4480
4481 /* Wait till we are at first instruction in program. */
4482 target_create_inferior (program_path.get (), program_args);
4483
4484 /* We are now (hopefully) stopped at the first instruction of
4485 the target process. This assumes that the target process was
4486 successfully created. */
4487 }
4488 else if (pid != 0)
4489 {
4490 if (attach_inferior (pid) == -1)
4491 error ("Attaching not supported on this target");
4492
4493 /* Otherwise succeeded. */
4494 }
4495 else
4496 {
4497 cs.last_status.set_exited (0);
4498 cs.last_ptid = minus_one_ptid;
4499 }
4500
4501 SCOPE_EXIT { detach_or_kill_for_exit_cleanup (); };
4502
4503 /* Don't report shared library events on the initial connection,
4504 even if some libraries are preloaded. Avoids the "stopped by
4505 shared library event" notice on gdb side. */
4506 if (current_thread != nullptr)
4507 current_process ()->dlls_changed = false;
4508
4509 bool was_running;
4510 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4511 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
4512 was_running = false;
4513 else
4514 was_running = true;
4515
4516 if (!was_running && !multi_mode)
4517 error ("No program to debug");
4518
4519 while (1)
4520 {
4521 cs.noack_mode = 0;
4522 cs.multi_process = 0;
4523 cs.report_fork_events = 0;
4524 cs.report_vfork_events = 0;
4525 cs.report_exec_events = 0;
4526 /* Be sure we're out of tfind mode. */
4527 cs.current_traceframe = -1;
4528 cs.cont_thread = null_ptid;
4529 cs.swbreak_feature = 0;
4530 cs.hwbreak_feature = 0;
4531 cs.vCont_supported = 0;
4532 cs.memory_tagging_feature = false;
4533 cs.error_message_supported = false;
4534
4535 remote_open (port);
4536
4537 try
4538 {
4539 /* Wait for events. This will return when all event sources
4540 are removed from the event loop. */
4541 start_event_loop ();
4542
4543 /* If an exit was requested (using the "monitor exit"
4544 command), terminate now. */
4545 if (exit_requested)
4546 throw_quit ("Quit");
4547
4548 /* The only other way to get here is for getpkt to fail:
4549
4550 - If --once was specified, we're done.
4551
4552 - If not in extended-remote mode, and we're no longer
4553 debugging anything, simply exit: GDB has disconnected
4554 after processing the last process exit.
4555
4556 - Otherwise, close the connection and reopen it at the
4557 top of the loop. */
4558 if (run_once || (!extended_protocol && !target_running ()))
4559 throw_quit ("Quit");
4560
4561 fprintf (stderr,
4562 "Remote side has terminated connection. "
4563 "GDBserver will reopen the connection.\n");
4564
4565 /* Get rid of any pending statuses. An eventual reconnection
4566 (by the same GDB instance or another) will refresh all its
4567 state from scratch. */
4568 discard_queued_stop_replies (minus_one_ptid);
4569 for_each_thread ([] (thread_info *thread)
4570 {
4571 thread->status_pending_p = 0;
4572 });
4573
4574 if (tracing)
4575 {
4576 if (disconnected_tracing)
4577 {
4578 /* Try to enable non-stop/async mode, so we we can
4579 both wait for an async socket accept, and handle
4580 async target events simultaneously. There's also
4581 no point either in having the target always stop
4582 all threads, when we're going to pass signals
4583 down without informing GDB. */
4584 if (!non_stop)
4585 {
4586 if (the_target->start_non_stop (true))
4587 non_stop = 1;
4588
4589 /* Detaching implicitly resumes all threads;
4590 simply disconnecting does not. */
4591 }
4592 }
4593 else
4594 {
4595 fprintf (stderr,
4596 "Disconnected tracing disabled; "
4597 "stopping trace run.\n");
4598 stop_tracing ();
4599 }
4600 }
4601 }
4602 catch (const gdb_exception_error &exception)
4603 {
4604 fflush (stdout);
4605 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4606
4607 if (response_needed)
4608 {
4609 write_enn (cs.own_buf);
4610 putpkt (cs.own_buf);
4611 }
4612
4613 if (run_once)
4614 throw_quit ("Quit");
4615 }
4616 }
4617 }
4618
4619 /* Main function. */
4620
4621 int
4622 main (int argc, char *argv[])
4623 {
4624 setlocale (LC_CTYPE, "");
4625
4626 try
4627 {
4628 captured_main (argc, argv);
4629 }
4630 catch (const gdb_exception &exception)
4631 {
4632 if (exception.reason == RETURN_ERROR)
4633 {
4634 fflush (stdout);
4635 fprintf (stderr, "%s\n", exception.what ());
4636 fprintf (stderr, "Exiting\n");
4637 exit_code = 1;
4638 }
4639
4640 exit (exit_code);
4641 }
4642
4643 gdb_assert_not_reached ("captured_main should never return");
4644 }
4645
4646 /* Process options coming from Z packets for a breakpoint. PACKET is
4647 the packet buffer. *PACKET is updated to point to the first char
4648 after the last processed option. */
4649
4650 static void
4651 process_point_options (struct gdb_breakpoint *bp, const char **packet)
4652 {
4653 const char *dataptr = *packet;
4654 int persist;
4655
4656 /* Check if data has the correct format. */
4657 if (*dataptr != ';')
4658 return;
4659
4660 dataptr++;
4661
4662 while (*dataptr)
4663 {
4664 if (*dataptr == ';')
4665 ++dataptr;
4666
4667 if (*dataptr == 'X')
4668 {
4669 /* Conditional expression. */
4670 threads_debug_printf ("Found breakpoint condition.");
4671 if (!add_breakpoint_condition (bp, &dataptr))
4672 dataptr = strchrnul (dataptr, ';');
4673 }
4674 else if (startswith (dataptr, "cmds:"))
4675 {
4676 dataptr += strlen ("cmds:");
4677 threads_debug_printf ("Found breakpoint commands %s.", dataptr);
4678 persist = (*dataptr == '1');
4679 dataptr += 2;
4680 if (add_breakpoint_commands (bp, &dataptr, persist))
4681 dataptr = strchrnul (dataptr, ';');
4682 }
4683 else
4684 {
4685 fprintf (stderr, "Unknown token %c, ignoring.\n",
4686 *dataptr);
4687 /* Skip tokens until we find one that we recognize. */
4688 dataptr = strchrnul (dataptr, ';');
4689 }
4690 }
4691 *packet = dataptr;
4692 }
4693
4694 /* Event loop callback that handles a serial event. The first byte in
4695 the serial buffer gets us here. We expect characters to arrive at
4696 a brisk pace, so we read the rest of the packet with a blocking
4697 getpkt call. */
4698
4699 static int
4700 process_serial_event (void)
4701 {
4702 client_state &cs = get_client_state ();
4703 int signal;
4704 unsigned int len;
4705 CORE_ADDR mem_addr;
4706 unsigned char sig;
4707 int packet_len;
4708 int new_packet_len = -1;
4709
4710 disable_async_io ();
4711
4712 response_needed = false;
4713 packet_len = getpkt (cs.own_buf);
4714 if (packet_len <= 0)
4715 {
4716 remote_close ();
4717 /* Force an event loop break. */
4718 return -1;
4719 }
4720 response_needed = true;
4721
4722 char ch = cs.own_buf[0];
4723 switch (ch)
4724 {
4725 case 'q':
4726 handle_query (cs.own_buf, packet_len, &new_packet_len);
4727 break;
4728 case 'Q':
4729 handle_general_set (cs.own_buf);
4730 break;
4731 case 'D':
4732 handle_detach (cs.own_buf);
4733 break;
4734 case '!':
4735 extended_protocol = true;
4736 write_ok (cs.own_buf);
4737 break;
4738 case '?':
4739 handle_status (cs.own_buf);
4740 break;
4741 case 'H':
4742 if (cs.own_buf[1] == 'c' || cs.own_buf[1] == 'g' || cs.own_buf[1] == 's')
4743 {
4744 require_running_or_break (cs.own_buf);
4745
4746 ptid_t thread_id = read_ptid (&cs.own_buf[2], NULL);
4747
4748 if (thread_id == null_ptid || thread_id == minus_one_ptid)
4749 thread_id = null_ptid;
4750 else if (thread_id.is_pid ())
4751 {
4752 /* The ptid represents a pid. */
4753 thread_info *thread = find_any_thread_of_pid (thread_id.pid ());
4754
4755 if (thread == NULL)
4756 {
4757 write_enn (cs.own_buf);
4758 break;
4759 }
4760
4761 thread_id = thread->id;
4762 }
4763 else
4764 {
4765 /* The ptid represents a lwp/tid. */
4766 if (find_thread_ptid (thread_id) == NULL)
4767 {
4768 write_enn (cs.own_buf);
4769 break;
4770 }
4771 }
4772
4773 if (cs.own_buf[1] == 'g')
4774 {
4775 if (thread_id == null_ptid)
4776 {
4777 /* GDB is telling us to choose any thread. Check if
4778 the currently selected thread is still valid. If
4779 it is not, select the first available. */
4780 thread_info *thread = find_thread_ptid (cs.general_thread);
4781 if (thread == NULL)
4782 thread = get_first_thread ();
4783 thread_id = thread->id;
4784 }
4785
4786 cs.general_thread = thread_id;
4787 set_desired_thread ();
4788 gdb_assert (current_thread != NULL);
4789 }
4790 else if (cs.own_buf[1] == 'c')
4791 cs.cont_thread = thread_id;
4792
4793 write_ok (cs.own_buf);
4794 }
4795 else
4796 {
4797 /* Silently ignore it so that gdb can extend the protocol
4798 without compatibility headaches. */
4799 cs.own_buf[0] = '\0';
4800 }
4801 break;
4802 case 'g':
4803 require_running_or_break (cs.own_buf);
4804 if (cs.current_traceframe >= 0)
4805 {
4806 regcache a_regcache (current_target_desc ());
4807
4808 if (fetch_traceframe_registers (cs.current_traceframe,
4809 &a_regcache, -1) == 0)
4810 registers_to_string (&a_regcache, cs.own_buf);
4811 else
4812 write_enn (cs.own_buf);
4813 }
4814 else
4815 {
4816 struct regcache *regcache;
4817
4818 if (!set_desired_thread ())
4819 write_enn (cs.own_buf);
4820 else
4821 {
4822 regcache = get_thread_regcache (current_thread);
4823 registers_to_string (regcache, cs.own_buf);
4824 }
4825 }
4826 break;
4827 case 'G':
4828 require_running_or_break (cs.own_buf);
4829 if (cs.current_traceframe >= 0)
4830 write_enn (cs.own_buf);
4831 else
4832 {
4833 struct regcache *regcache;
4834
4835 if (!set_desired_thread ())
4836 write_enn (cs.own_buf);
4837 else
4838 {
4839 regcache = get_thread_regcache (current_thread);
4840 registers_from_string (regcache, &cs.own_buf[1]);
4841 write_ok (cs.own_buf);
4842 }
4843 }
4844 break;
4845 case 'm':
4846 {
4847 require_running_or_break (cs.own_buf);
4848 decode_m_packet (&cs.own_buf[1], &mem_addr, &len);
4849 int res = gdb_read_memory (mem_addr, mem_buf, len);
4850 if (res < 0)
4851 write_enn (cs.own_buf);
4852 else
4853 bin2hex (mem_buf, cs.own_buf, res);
4854 }
4855 break;
4856 case 'M':
4857 require_running_or_break (cs.own_buf);
4858 decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf);
4859 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
4860 write_ok (cs.own_buf);
4861 else
4862 write_enn (cs.own_buf);
4863 break;
4864 case 'x':
4865 {
4866 require_running_or_break (cs.own_buf);
4867 decode_x_packet (&cs.own_buf[1], &mem_addr, &len);
4868 int res = gdb_read_memory (mem_addr, mem_buf, len);
4869 if (res < 0)
4870 write_enn (cs.own_buf);
4871 else
4872 {
4873 gdb_byte *buffer = (gdb_byte *) cs.own_buf;
4874 *buffer++ = 'b';
4875
4876 int out_len_units;
4877 new_packet_len = remote_escape_output (mem_buf, res, 1,
4878 buffer,
4879 &out_len_units,
4880 PBUFSIZ);
4881 new_packet_len++; /* For the 'b' marker. */
4882
4883 if (out_len_units != res)
4884 {
4885 write_enn (cs.own_buf);
4886 new_packet_len = -1;
4887 }
4888 else
4889 suppress_next_putpkt_log ();
4890 }
4891 }
4892 break;
4893 case 'X':
4894 require_running_or_break (cs.own_buf);
4895 if (decode_X_packet (&cs.own_buf[1], packet_len - 1,
4896 &mem_addr, &len, &mem_buf) < 0
4897 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
4898 write_enn (cs.own_buf);
4899 else
4900 write_ok (cs.own_buf);
4901 break;
4902 case 'C':
4903 require_running_or_break (cs.own_buf);
4904 hex2bin (cs.own_buf + 1, &sig, 1);
4905 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4906 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4907 else
4908 signal = 0;
4909 myresume (cs.own_buf, 0, signal);
4910 break;
4911 case 'S':
4912 require_running_or_break (cs.own_buf);
4913 hex2bin (cs.own_buf + 1, &sig, 1);
4914 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4915 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4916 else
4917 signal = 0;
4918 myresume (cs.own_buf, 1, signal);
4919 break;
4920 case 'c':
4921 require_running_or_break (cs.own_buf);
4922 signal = 0;
4923 myresume (cs.own_buf, 0, signal);
4924 break;
4925 case 's':
4926 require_running_or_break (cs.own_buf);
4927 signal = 0;
4928 myresume (cs.own_buf, 1, signal);
4929 break;
4930 case 'Z': /* insert_ ... */
4931 /* Fallthrough. */
4932 case 'z': /* remove_ ... */
4933 {
4934 char *dataptr;
4935 ULONGEST addr;
4936 int kind;
4937 char type = cs.own_buf[1];
4938 int res;
4939 const int insert = ch == 'Z';
4940 const char *p = &cs.own_buf[3];
4941
4942 p = unpack_varlen_hex (p, &addr);
4943 kind = strtol (p + 1, &dataptr, 16);
4944
4945 if (insert)
4946 {
4947 struct gdb_breakpoint *bp;
4948
4949 bp = set_gdb_breakpoint (type, addr, kind, &res);
4950 if (bp != NULL)
4951 {
4952 res = 0;
4953
4954 /* GDB may have sent us a list of *point parameters to
4955 be evaluated on the target's side. Read such list
4956 here. If we already have a list of parameters, GDB
4957 is telling us to drop that list and use this one
4958 instead. */
4959 clear_breakpoint_conditions_and_commands (bp);
4960 const char *options = dataptr;
4961 process_point_options (bp, &options);
4962 }
4963 }
4964 else
4965 res = delete_gdb_breakpoint (type, addr, kind);
4966
4967 if (res == 0)
4968 write_ok (cs.own_buf);
4969 else if (res == 1)
4970 /* Unsupported. */
4971 cs.own_buf[0] = '\0';
4972 else
4973 write_enn (cs.own_buf);
4974 break;
4975 }
4976 case 'k':
4977 response_needed = false;
4978 if (!target_running ())
4979 /* The packet we received doesn't make sense - but we can't
4980 reply to it, either. */
4981 return 0;
4982
4983 fprintf (stderr, "Killing all inferiors\n");
4984
4985 for_each_process (kill_inferior_callback);
4986
4987 /* When using the extended protocol, we wait with no program
4988 running. The traditional protocol will exit instead. */
4989 if (extended_protocol)
4990 {
4991 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4992 return 0;
4993 }
4994 else
4995 exit (0);
4996
4997 case 'T':
4998 {
4999 require_running_or_break (cs.own_buf);
5000
5001 ptid_t thread_id = read_ptid (&cs.own_buf[1], NULL);
5002 if (find_thread_ptid (thread_id) == NULL)
5003 {
5004 write_enn (cs.own_buf);
5005 break;
5006 }
5007
5008 if (mythread_alive (thread_id))
5009 write_ok (cs.own_buf);
5010 else
5011 write_enn (cs.own_buf);
5012 }
5013 break;
5014 case 'R':
5015 response_needed = false;
5016
5017 /* Restarting the inferior is only supported in the extended
5018 protocol. */
5019 if (extended_protocol)
5020 {
5021 if (target_running ())
5022 for_each_process (kill_inferior_callback);
5023
5024 fprintf (stderr, "GDBserver restarting\n");
5025
5026 /* Wait till we are at 1st instruction in prog. */
5027 if (program_path.get () != NULL)
5028 {
5029 target_create_inferior (program_path.get (), program_args);
5030
5031 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
5032 {
5033 /* Stopped at the first instruction of the target
5034 process. */
5035 cs.general_thread = cs.last_ptid;
5036 }
5037 else
5038 {
5039 /* Something went wrong. */
5040 cs.general_thread = null_ptid;
5041 }
5042 }
5043 else
5044 {
5045 cs.last_status.set_exited (GDB_SIGNAL_KILL);
5046 }
5047 return 0;
5048 }
5049 else
5050 {
5051 /* It is a request we don't understand. Respond with an
5052 empty packet so that gdb knows that we don't support this
5053 request. */
5054 cs.own_buf[0] = '\0';
5055 break;
5056 }
5057 case 'v':
5058 /* Extended (long) request. */
5059 handle_v_requests (cs.own_buf, packet_len, &new_packet_len);
5060 break;
5061
5062 default:
5063 /* It is a request we don't understand. Respond with an empty
5064 packet so that gdb knows that we don't support this
5065 request. */
5066 cs.own_buf[0] = '\0';
5067 break;
5068 }
5069
5070 if (new_packet_len != -1)
5071 putpkt_binary (cs.own_buf, new_packet_len);
5072 else
5073 putpkt (cs.own_buf);
5074
5075 response_needed = false;
5076
5077 if (exit_requested)
5078 return -1;
5079
5080 return 0;
5081 }
5082
5083 /* Event-loop callback for serial events. */
5084
5085 void
5086 handle_serial_event (int err, gdb_client_data client_data)
5087 {
5088 threads_debug_printf ("handling possible serial event");
5089
5090 /* Really handle it. */
5091 if (process_serial_event () < 0)
5092 {
5093 keep_processing_events = false;
5094 return;
5095 }
5096
5097 /* Be sure to not change the selected thread behind GDB's back.
5098 Important in the non-stop mode asynchronous protocol. */
5099 set_desired_thread ();
5100 }
5101
5102 /* Push a stop notification on the notification queue. */
5103
5104 static void
5105 push_stop_notification (ptid_t ptid, const target_waitstatus &status)
5106 {
5107 struct vstop_notif *vstop_notif = new struct vstop_notif;
5108
5109 vstop_notif->status = status;
5110 vstop_notif->ptid = ptid;
5111 /* Push Stop notification. */
5112 notif_push (&notif_stop, vstop_notif);
5113 }
5114
5115 /* Event-loop callback for target events. */
5116
5117 void
5118 handle_target_event (int err, gdb_client_data client_data)
5119 {
5120 client_state &cs = get_client_state ();
5121 threads_debug_printf ("handling possible target event");
5122
5123 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status,
5124 TARGET_WNOHANG, 1);
5125
5126 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED)
5127 {
5128 if (gdb_connected () && report_no_resumed)
5129 push_stop_notification (null_ptid, cs.last_status);
5130 }
5131 else if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE)
5132 {
5133 int pid = cs.last_ptid.pid ();
5134 struct process_info *process = find_process_pid (pid);
5135 int forward_event = !gdb_connected () || process->gdb_detached;
5136
5137 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
5138 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
5139 {
5140 mark_breakpoints_out (process);
5141 target_mourn_inferior (cs.last_ptid);
5142 }
5143 else if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
5144 ;
5145 else
5146 {
5147 /* We're reporting this thread as stopped. Update its
5148 "want-stopped" state to what the client wants, until it
5149 gets a new resume action. */
5150 current_thread->last_resume_kind = resume_stop;
5151 current_thread->last_status = cs.last_status;
5152 }
5153
5154 if (forward_event)
5155 {
5156 if (!target_running ())
5157 {
5158 /* The last process exited. We're done. */
5159 exit (0);
5160 }
5161
5162 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
5163 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED
5164 || cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
5165 ;
5166 else
5167 {
5168 /* A thread stopped with a signal, but gdb isn't
5169 connected to handle it. Pass it down to the
5170 inferior, as if it wasn't being traced. */
5171 enum gdb_signal signal;
5172
5173 threads_debug_printf ("GDB not connected; forwarding event %d for"
5174 " [%s]",
5175 (int) cs.last_status.kind (),
5176 target_pid_to_str (cs.last_ptid).c_str ());
5177
5178 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
5179 signal = cs.last_status.sig ();
5180 else
5181 signal = GDB_SIGNAL_0;
5182 target_continue (cs.last_ptid, signal);
5183 }
5184 }
5185 else
5186 {
5187 push_stop_notification (cs.last_ptid, cs.last_status);
5188
5189 if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED
5190 && !target_any_resumed ())
5191 {
5192 target_waitstatus ws;
5193 ws.set_no_resumed ();
5194 push_stop_notification (null_ptid, ws);
5195 }
5196 }
5197 }
5198
5199 /* Be sure to not change the selected thread behind GDB's back.
5200 Important in the non-stop mode asynchronous protocol. */
5201 set_desired_thread ();
5202 }
5203
5204 /* See gdbsupport/event-loop.h. */
5205
5206 int
5207 invoke_async_signal_handlers ()
5208 {
5209 return 0;
5210 }
5211
5212 /* See gdbsupport/event-loop.h. */
5213
5214 int
5215 check_async_event_handlers ()
5216 {
5217 return 0;
5218 }
5219
5220 /* See gdbsupport/errors.h */
5221
5222 void
5223 flush_streams ()
5224 {
5225 fflush (stdout);
5226 fflush (stderr);
5227 }
5228
5229 /* See gdbsupport/gdb_select.h. */
5230
5231 int
5232 gdb_select (int n, fd_set *readfds, fd_set *writefds,
5233 fd_set *exceptfds, struct timeval *timeout)
5234 {
5235 return select (n, readfds, writefds, exceptfds, timeout);
5236 }
5237
5238 #if GDB_SELF_TEST
5239 namespace selftests
5240 {
5241
5242 void
5243 reset ()
5244 {}
5245
5246 } /* namespace selftests */
5247 #endif /* GDB_SELF_TEST */