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