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