Thread options & clone events (core + remote)
[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 thread_info *child = target_thread_pending_child (thread);
1353 if (child == nullptr)
1354 continue;
1355
1356 process_info *fork_child_process = get_thread_process (child);
1357 gdb_assert (fork_child_process != nullptr);
1358
1359 int fork_child_pid = fork_child_process->pid;
1360
1361 if (detach_inferior (fork_child_process) != 0)
1362 warning (_("Failed to detach fork child %s, child of %s"),
1363 target_pid_to_str (ptid_t (fork_child_pid)).c_str (),
1364 target_pid_to_str (thread->id).c_str ());
1365 }
1366
1367 if (detach_inferior (process) != 0)
1368 write_enn (own_buf);
1369 else
1370 {
1371 discard_queued_stop_replies (ptid_t (pid));
1372 write_ok (own_buf);
1373
1374 if (extended_protocol || target_running ())
1375 {
1376 /* There is still at least one inferior remaining or
1377 we are in extended mode, so don't terminate gdbserver,
1378 and instead treat this like a normal program exit. */
1379 cs.last_status.set_exited (0);
1380 cs.last_ptid = ptid_t (pid);
1381
1382 switch_to_thread (nullptr);
1383 }
1384 else
1385 {
1386 putpkt (own_buf);
1387 remote_close ();
1388
1389 /* If we are attached, then we can exit. Otherwise, we
1390 need to hang around doing nothing, until the child is
1391 gone. */
1392 join_inferior (pid);
1393 exit (0);
1394 }
1395 }
1396 }
1397
1398 /* Parse options to --debug-format= and "monitor set debug-format".
1399 ARG is the text after "--debug-format=" or "monitor set debug-format".
1400 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1401 This triggers calls to monitor_output.
1402 The result is an empty string if all options were parsed ok, otherwise an
1403 error message which the caller must free.
1404
1405 N.B. These commands affect all debug format settings, they are not
1406 cumulative. If a format is not specified, it is turned off.
1407 However, we don't go to extra trouble with things like
1408 "monitor set debug-format all,none,timestamp".
1409 Instead we just parse them one at a time, in order.
1410
1411 The syntax for "monitor set debug" we support here is not identical
1412 to gdb's "set debug foo on|off" because we also use this function to
1413 parse "--debug-format=foo,bar". */
1414
1415 static std::string
1416 parse_debug_format_options (const char *arg, int is_monitor)
1417 {
1418 /* First turn all debug format options off. */
1419 debug_timestamp = 0;
1420
1421 /* First remove leading spaces, for "monitor set debug-format". */
1422 while (isspace (*arg))
1423 ++arg;
1424
1425 std::vector<gdb::unique_xmalloc_ptr<char>> options
1426 = delim_string_to_char_ptr_vec (arg, ',');
1427
1428 for (const gdb::unique_xmalloc_ptr<char> &option : options)
1429 {
1430 if (strcmp (option.get (), "all") == 0)
1431 {
1432 debug_timestamp = 1;
1433 if (is_monitor)
1434 monitor_output ("All extra debug format options enabled.\n");
1435 }
1436 else if (strcmp (option.get (), "none") == 0)
1437 {
1438 debug_timestamp = 0;
1439 if (is_monitor)
1440 monitor_output ("All extra debug format options disabled.\n");
1441 }
1442 else if (strcmp (option.get (), "timestamp") == 0)
1443 {
1444 debug_timestamp = 1;
1445 if (is_monitor)
1446 monitor_output ("Timestamps will be added to debug output.\n");
1447 }
1448 else if (*option == '\0')
1449 {
1450 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1451 continue;
1452 }
1453 else
1454 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1455 option.get ());
1456 }
1457
1458 return std::string ();
1459 }
1460
1461 /* Handle monitor commands not handled by target-specific handlers. */
1462
1463 static void
1464 handle_monitor_command (char *mon, char *own_buf)
1465 {
1466 if (strcmp (mon, "set debug 1") == 0)
1467 {
1468 debug_threads = true;
1469 monitor_output ("Debug output enabled.\n");
1470 }
1471 else if (strcmp (mon, "set debug 0") == 0)
1472 {
1473 debug_threads = false;
1474 monitor_output ("Debug output disabled.\n");
1475 }
1476 else if (strcmp (mon, "set debug-hw-points 1") == 0)
1477 {
1478 show_debug_regs = 1;
1479 monitor_output ("H/W point debugging output enabled.\n");
1480 }
1481 else if (strcmp (mon, "set debug-hw-points 0") == 0)
1482 {
1483 show_debug_regs = 0;
1484 monitor_output ("H/W point debugging output disabled.\n");
1485 }
1486 else if (strcmp (mon, "set remote-debug 1") == 0)
1487 {
1488 remote_debug = true;
1489 monitor_output ("Protocol debug output enabled.\n");
1490 }
1491 else if (strcmp (mon, "set remote-debug 0") == 0)
1492 {
1493 remote_debug = false;
1494 monitor_output ("Protocol debug output disabled.\n");
1495 }
1496 else if (strcmp (mon, "set event-loop-debug 1") == 0)
1497 {
1498 debug_event_loop = debug_event_loop_kind::ALL;
1499 monitor_output ("Event loop debug output enabled.\n");
1500 }
1501 else if (strcmp (mon, "set event-loop-debug 0") == 0)
1502 {
1503 debug_event_loop = debug_event_loop_kind::OFF;
1504 monitor_output ("Event loop debug output disabled.\n");
1505 }
1506 else if (startswith (mon, "set debug-format "))
1507 {
1508 std::string error_msg
1509 = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
1510 1);
1511
1512 if (!error_msg.empty ())
1513 {
1514 monitor_output (error_msg.c_str ());
1515 monitor_show_help ();
1516 write_enn (own_buf);
1517 }
1518 }
1519 else if (strcmp (mon, "set debug-file") == 0)
1520 debug_set_output (nullptr);
1521 else if (startswith (mon, "set debug-file "))
1522 debug_set_output (mon + sizeof ("set debug-file ") - 1);
1523 else if (strcmp (mon, "help") == 0)
1524 monitor_show_help ();
1525 else if (strcmp (mon, "exit") == 0)
1526 exit_requested = true;
1527 else
1528 {
1529 monitor_output ("Unknown monitor command.\n\n");
1530 monitor_show_help ();
1531 write_enn (own_buf);
1532 }
1533 }
1534
1535 /* Associates a callback with each supported qXfer'able object. */
1536
1537 struct qxfer
1538 {
1539 /* The object this handler handles. */
1540 const char *object;
1541
1542 /* Request that the target transfer up to LEN 8-bit bytes of the
1543 target's OBJECT. The OFFSET, for a seekable object, specifies
1544 the starting point. The ANNEX can be used to provide additional
1545 data-specific information to the target.
1546
1547 Return the number of bytes actually transfered, zero when no
1548 further transfer is possible, -1 on error, -2 when the transfer
1549 is not supported, and -3 on a verbose error message that should
1550 be preserved. Return of a positive value smaller than LEN does
1551 not indicate the end of the object, only the end of the transfer.
1552
1553 One, and only one, of readbuf or writebuf must be non-NULL. */
1554 int (*xfer) (const char *annex,
1555 gdb_byte *readbuf, const gdb_byte *writebuf,
1556 ULONGEST offset, LONGEST len);
1557 };
1558
1559 /* Handle qXfer:auxv:read. */
1560
1561 static int
1562 handle_qxfer_auxv (const char *annex,
1563 gdb_byte *readbuf, const gdb_byte *writebuf,
1564 ULONGEST offset, LONGEST len)
1565 {
1566 if (!the_target->supports_read_auxv () || writebuf != NULL)
1567 return -2;
1568
1569 if (annex[0] != '\0' || current_thread == NULL)
1570 return -1;
1571
1572 return the_target->read_auxv (current_thread->id.pid (), offset, readbuf,
1573 len);
1574 }
1575
1576 /* Handle qXfer:exec-file:read. */
1577
1578 static int
1579 handle_qxfer_exec_file (const char *annex,
1580 gdb_byte *readbuf, const gdb_byte *writebuf,
1581 ULONGEST offset, LONGEST len)
1582 {
1583 ULONGEST pid;
1584 int total_len;
1585
1586 if (!the_target->supports_pid_to_exec_file () || writebuf != NULL)
1587 return -2;
1588
1589 if (annex[0] == '\0')
1590 {
1591 if (current_thread == NULL)
1592 return -1;
1593
1594 pid = pid_of (current_thread);
1595 }
1596 else
1597 {
1598 annex = unpack_varlen_hex (annex, &pid);
1599 if (annex[0] != '\0')
1600 return -1;
1601 }
1602
1603 if (pid <= 0)
1604 return -1;
1605
1606 const char *file = the_target->pid_to_exec_file (pid);
1607 if (file == NULL)
1608 return -1;
1609
1610 total_len = strlen (file);
1611
1612 if (offset > total_len)
1613 return -1;
1614
1615 if (offset + len > total_len)
1616 len = total_len - offset;
1617
1618 memcpy (readbuf, file + offset, len);
1619 return len;
1620 }
1621
1622 /* Handle qXfer:features:read. */
1623
1624 static int
1625 handle_qxfer_features (const char *annex,
1626 gdb_byte *readbuf, const gdb_byte *writebuf,
1627 ULONGEST offset, LONGEST len)
1628 {
1629 const char *document;
1630 size_t total_len;
1631
1632 if (writebuf != NULL)
1633 return -2;
1634
1635 if (!target_running ())
1636 return -1;
1637
1638 /* Grab the correct annex. */
1639 document = get_features_xml (annex);
1640 if (document == NULL)
1641 return -1;
1642
1643 total_len = strlen (document);
1644
1645 if (offset > total_len)
1646 return -1;
1647
1648 if (offset + len > total_len)
1649 len = total_len - offset;
1650
1651 memcpy (readbuf, document + offset, len);
1652 return len;
1653 }
1654
1655 /* Handle qXfer:libraries:read. */
1656
1657 static int
1658 handle_qxfer_libraries (const char *annex,
1659 gdb_byte *readbuf, const gdb_byte *writebuf,
1660 ULONGEST offset, LONGEST len)
1661 {
1662 if (writebuf != NULL)
1663 return -2;
1664
1665 if (annex[0] != '\0' || current_thread == NULL)
1666 return -1;
1667
1668 std::string document = "<library-list version=\"1.0\">\n";
1669
1670 process_info *proc = current_process ();
1671 for (const dll_info &dll : proc->all_dlls)
1672 document += string_printf
1673 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1674 dll.name.c_str (), paddress (dll.base_addr));
1675
1676 document += "</library-list>\n";
1677
1678 if (offset > document.length ())
1679 return -1;
1680
1681 if (offset + len > document.length ())
1682 len = document.length () - offset;
1683
1684 memcpy (readbuf, &document[offset], len);
1685
1686 return len;
1687 }
1688
1689 /* Handle qXfer:libraries-svr4:read. */
1690
1691 static int
1692 handle_qxfer_libraries_svr4 (const char *annex,
1693 gdb_byte *readbuf, const gdb_byte *writebuf,
1694 ULONGEST offset, LONGEST len)
1695 {
1696 if (writebuf != NULL)
1697 return -2;
1698
1699 if (current_thread == NULL
1700 || !the_target->supports_qxfer_libraries_svr4 ())
1701 return -1;
1702
1703 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf,
1704 offset, len);
1705 }
1706
1707 /* Handle qXfer:osadata:read. */
1708
1709 static int
1710 handle_qxfer_osdata (const char *annex,
1711 gdb_byte *readbuf, const gdb_byte *writebuf,
1712 ULONGEST offset, LONGEST len)
1713 {
1714 if (!the_target->supports_qxfer_osdata () || writebuf != NULL)
1715 return -2;
1716
1717 return the_target->qxfer_osdata (annex, readbuf, NULL, offset, len);
1718 }
1719
1720 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1721
1722 static int
1723 handle_qxfer_siginfo (const char *annex,
1724 gdb_byte *readbuf, const gdb_byte *writebuf,
1725 ULONGEST offset, LONGEST len)
1726 {
1727 if (!the_target->supports_qxfer_siginfo ())
1728 return -2;
1729
1730 if (annex[0] != '\0' || current_thread == NULL)
1731 return -1;
1732
1733 return the_target->qxfer_siginfo (annex, readbuf, writebuf, offset, len);
1734 }
1735
1736 /* Handle qXfer:statictrace:read. */
1737
1738 static int
1739 handle_qxfer_statictrace (const char *annex,
1740 gdb_byte *readbuf, const gdb_byte *writebuf,
1741 ULONGEST offset, LONGEST len)
1742 {
1743 client_state &cs = get_client_state ();
1744 ULONGEST nbytes;
1745
1746 if (writebuf != NULL)
1747 return -2;
1748
1749 if (annex[0] != '\0' || current_thread == NULL
1750 || cs.current_traceframe == -1)
1751 return -1;
1752
1753 if (traceframe_read_sdata (cs.current_traceframe, offset,
1754 readbuf, len, &nbytes))
1755 return -1;
1756 return nbytes;
1757 }
1758
1759 /* Helper for handle_qxfer_threads_proper.
1760 Emit the XML to describe the thread of INF. */
1761
1762 static void
1763 handle_qxfer_threads_worker (thread_info *thread, std::string *buffer)
1764 {
1765 ptid_t ptid = ptid_of (thread);
1766 char ptid_s[100];
1767 int core = target_core_of_thread (ptid);
1768 char core_s[21];
1769 const char *name = target_thread_name (ptid);
1770 int handle_len;
1771 gdb_byte *handle;
1772 bool handle_status = target_thread_handle (ptid, &handle, &handle_len);
1773
1774 /* If this is a fork or vfork child (has a fork parent), GDB does not yet
1775 know about this process, and must not know about it until it gets the
1776 corresponding (v)fork event. Exclude this thread from the list. */
1777 if (target_thread_pending_parent (thread) != nullptr)
1778 return;
1779
1780 write_ptid (ptid_s, ptid);
1781
1782 string_xml_appendf (*buffer, "<thread id=\"%s\"", ptid_s);
1783
1784 if (core != -1)
1785 {
1786 sprintf (core_s, "%d", core);
1787 string_xml_appendf (*buffer, " core=\"%s\"", core_s);
1788 }
1789
1790 if (name != NULL)
1791 string_xml_appendf (*buffer, " name=\"%s\"", name);
1792
1793 if (handle_status)
1794 {
1795 char *handle_s = (char *) alloca (handle_len * 2 + 1);
1796 bin2hex (handle, handle_s, handle_len);
1797 string_xml_appendf (*buffer, " handle=\"%s\"", handle_s);
1798 }
1799
1800 string_xml_appendf (*buffer, "/>\n");
1801 }
1802
1803 /* Helper for handle_qxfer_threads. Return true on success, false
1804 otherwise. */
1805
1806 static bool
1807 handle_qxfer_threads_proper (std::string *buffer)
1808 {
1809 *buffer += "<threads>\n";
1810
1811 /* The target may need to access memory and registers (e.g. via
1812 libthread_db) to fetch thread properties. Even if don't need to
1813 stop threads to access memory, we still will need to be able to
1814 access registers, and other ptrace accesses like
1815 PTRACE_GET_THREAD_AREA that require a paused thread. Pause all
1816 threads here, so that we pause each thread at most once for all
1817 accesses. */
1818 if (non_stop)
1819 target_pause_all (true);
1820
1821 for_each_thread ([&] (thread_info *thread)
1822 {
1823 handle_qxfer_threads_worker (thread, buffer);
1824 });
1825
1826 if (non_stop)
1827 target_unpause_all (true);
1828
1829 *buffer += "</threads>\n";
1830 return true;
1831 }
1832
1833 /* Handle qXfer:threads:read. */
1834
1835 static int
1836 handle_qxfer_threads (const char *annex,
1837 gdb_byte *readbuf, const gdb_byte *writebuf,
1838 ULONGEST offset, LONGEST len)
1839 {
1840 static std::string result;
1841
1842 if (writebuf != NULL)
1843 return -2;
1844
1845 if (annex[0] != '\0')
1846 return -1;
1847
1848 if (offset == 0)
1849 {
1850 /* When asked for data at offset 0, generate everything and store into
1851 'result'. Successive reads will be served off 'result'. */
1852 result.clear ();
1853
1854 bool res = handle_qxfer_threads_proper (&result);
1855
1856 if (!res)
1857 return -1;
1858 }
1859
1860 if (offset >= result.length ())
1861 {
1862 /* We're out of data. */
1863 result.clear ();
1864 return 0;
1865 }
1866
1867 if (len > result.length () - offset)
1868 len = result.length () - offset;
1869
1870 memcpy (readbuf, result.c_str () + offset, len);
1871
1872 return len;
1873 }
1874
1875 /* Handle qXfer:traceframe-info:read. */
1876
1877 static int
1878 handle_qxfer_traceframe_info (const char *annex,
1879 gdb_byte *readbuf, const gdb_byte *writebuf,
1880 ULONGEST offset, LONGEST len)
1881 {
1882 client_state &cs = get_client_state ();
1883 static std::string result;
1884
1885 if (writebuf != NULL)
1886 return -2;
1887
1888 if (!target_running () || annex[0] != '\0' || cs.current_traceframe == -1)
1889 return -1;
1890
1891 if (offset == 0)
1892 {
1893 /* When asked for data at offset 0, generate everything and
1894 store into 'result'. Successive reads will be served off
1895 'result'. */
1896 result.clear ();
1897
1898 traceframe_read_info (cs.current_traceframe, &result);
1899 }
1900
1901 if (offset >= result.length ())
1902 {
1903 /* We're out of data. */
1904 result.clear ();
1905 return 0;
1906 }
1907
1908 if (len > result.length () - offset)
1909 len = result.length () - offset;
1910
1911 memcpy (readbuf, result.c_str () + offset, len);
1912 return len;
1913 }
1914
1915 /* Handle qXfer:fdpic:read. */
1916
1917 static int
1918 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
1919 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
1920 {
1921 if (!the_target->supports_read_loadmap ())
1922 return -2;
1923
1924 if (current_thread == NULL)
1925 return -1;
1926
1927 return the_target->read_loadmap (annex, offset, readbuf, len);
1928 }
1929
1930 /* Handle qXfer:btrace:read. */
1931
1932 static int
1933 handle_qxfer_btrace (const char *annex,
1934 gdb_byte *readbuf, const gdb_byte *writebuf,
1935 ULONGEST offset, LONGEST len)
1936 {
1937 client_state &cs = get_client_state ();
1938 static std::string cache;
1939 struct thread_info *thread;
1940 enum btrace_read_type type;
1941 int result;
1942
1943 if (writebuf != NULL)
1944 return -2;
1945
1946 if (cs.general_thread == null_ptid
1947 || cs.general_thread == minus_one_ptid)
1948 {
1949 strcpy (cs.own_buf, "E.Must select a single thread.");
1950 return -3;
1951 }
1952
1953 thread = find_thread_ptid (cs.general_thread);
1954 if (thread == NULL)
1955 {
1956 strcpy (cs.own_buf, "E.No such thread.");
1957 return -3;
1958 }
1959
1960 if (thread->btrace == NULL)
1961 {
1962 strcpy (cs.own_buf, "E.Btrace not enabled.");
1963 return -3;
1964 }
1965
1966 if (strcmp (annex, "all") == 0)
1967 type = BTRACE_READ_ALL;
1968 else if (strcmp (annex, "new") == 0)
1969 type = BTRACE_READ_NEW;
1970 else if (strcmp (annex, "delta") == 0)
1971 type = BTRACE_READ_DELTA;
1972 else
1973 {
1974 strcpy (cs.own_buf, "E.Bad annex.");
1975 return -3;
1976 }
1977
1978 if (offset == 0)
1979 {
1980 cache.clear ();
1981
1982 try
1983 {
1984 result = target_read_btrace (thread->btrace, &cache, type);
1985 if (result != 0)
1986 memcpy (cs.own_buf, cache.c_str (), cache.length ());
1987 }
1988 catch (const gdb_exception_error &exception)
1989 {
1990 sprintf (cs.own_buf, "E.%s", exception.what ());
1991 result = -1;
1992 }
1993
1994 if (result != 0)
1995 return -3;
1996 }
1997 else if (offset > cache.length ())
1998 {
1999 cache.clear ();
2000 return -3;
2001 }
2002
2003 if (len > cache.length () - offset)
2004 len = cache.length () - offset;
2005
2006 memcpy (readbuf, cache.c_str () + offset, len);
2007
2008 return len;
2009 }
2010
2011 /* Handle qXfer:btrace-conf:read. */
2012
2013 static int
2014 handle_qxfer_btrace_conf (const char *annex,
2015 gdb_byte *readbuf, const gdb_byte *writebuf,
2016 ULONGEST offset, LONGEST len)
2017 {
2018 client_state &cs = get_client_state ();
2019 static std::string cache;
2020 struct thread_info *thread;
2021 int result;
2022
2023 if (writebuf != NULL)
2024 return -2;
2025
2026 if (annex[0] != '\0')
2027 return -1;
2028
2029 if (cs.general_thread == null_ptid
2030 || cs.general_thread == minus_one_ptid)
2031 {
2032 strcpy (cs.own_buf, "E.Must select a single thread.");
2033 return -3;
2034 }
2035
2036 thread = find_thread_ptid (cs.general_thread);
2037 if (thread == NULL)
2038 {
2039 strcpy (cs.own_buf, "E.No such thread.");
2040 return -3;
2041 }
2042
2043 if (thread->btrace == NULL)
2044 {
2045 strcpy (cs.own_buf, "E.Btrace not enabled.");
2046 return -3;
2047 }
2048
2049 if (offset == 0)
2050 {
2051 cache.clear ();
2052
2053 try
2054 {
2055 result = target_read_btrace_conf (thread->btrace, &cache);
2056 if (result != 0)
2057 memcpy (cs.own_buf, cache.c_str (), cache.length ());
2058 }
2059 catch (const gdb_exception_error &exception)
2060 {
2061 sprintf (cs.own_buf, "E.%s", exception.what ());
2062 result = -1;
2063 }
2064
2065 if (result != 0)
2066 return -3;
2067 }
2068 else if (offset > cache.length ())
2069 {
2070 cache.clear ();
2071 return -3;
2072 }
2073
2074 if (len > cache.length () - offset)
2075 len = cache.length () - offset;
2076
2077 memcpy (readbuf, cache.c_str () + offset, len);
2078
2079 return len;
2080 }
2081
2082 static const struct qxfer qxfer_packets[] =
2083 {
2084 { "auxv", handle_qxfer_auxv },
2085 { "btrace", handle_qxfer_btrace },
2086 { "btrace-conf", handle_qxfer_btrace_conf },
2087 { "exec-file", handle_qxfer_exec_file},
2088 { "fdpic", handle_qxfer_fdpic},
2089 { "features", handle_qxfer_features },
2090 { "libraries", handle_qxfer_libraries },
2091 { "libraries-svr4", handle_qxfer_libraries_svr4 },
2092 { "osdata", handle_qxfer_osdata },
2093 { "siginfo", handle_qxfer_siginfo },
2094 { "statictrace", handle_qxfer_statictrace },
2095 { "threads", handle_qxfer_threads },
2096 { "traceframe-info", handle_qxfer_traceframe_info },
2097 };
2098
2099 static int
2100 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
2101 {
2102 int i;
2103 char *object;
2104 char *rw;
2105 char *annex;
2106 char *offset;
2107
2108 if (!startswith (own_buf, "qXfer:"))
2109 return 0;
2110
2111 /* Grab the object, r/w and annex. */
2112 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
2113 {
2114 write_enn (own_buf);
2115 return 1;
2116 }
2117
2118 for (i = 0;
2119 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
2120 i++)
2121 {
2122 const struct qxfer *q = &qxfer_packets[i];
2123
2124 if (strcmp (object, q->object) == 0)
2125 {
2126 if (strcmp (rw, "read") == 0)
2127 {
2128 unsigned char *data;
2129 int n;
2130 CORE_ADDR ofs;
2131 unsigned int len;
2132
2133 /* Grab the offset and length. */
2134 if (decode_xfer_read (offset, &ofs, &len) < 0)
2135 {
2136 write_enn (own_buf);
2137 return 1;
2138 }
2139
2140 /* Read one extra byte, as an indicator of whether there is
2141 more. */
2142 if (len > PBUFSIZ - 2)
2143 len = PBUFSIZ - 2;
2144 data = (unsigned char *) malloc (len + 1);
2145 if (data == NULL)
2146 {
2147 write_enn (own_buf);
2148 return 1;
2149 }
2150 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
2151 if (n == -2)
2152 {
2153 free (data);
2154 return 0;
2155 }
2156 else if (n == -3)
2157 {
2158 /* Preserve error message. */
2159 }
2160 else if (n < 0)
2161 write_enn (own_buf);
2162 else if (n > len)
2163 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
2164 else
2165 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
2166
2167 free (data);
2168 return 1;
2169 }
2170 else if (strcmp (rw, "write") == 0)
2171 {
2172 int n;
2173 unsigned int len;
2174 CORE_ADDR ofs;
2175 unsigned char *data;
2176
2177 strcpy (own_buf, "E00");
2178 data = (unsigned char *) malloc (packet_len - (offset - own_buf));
2179 if (data == NULL)
2180 {
2181 write_enn (own_buf);
2182 return 1;
2183 }
2184 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
2185 &ofs, &len, data) < 0)
2186 {
2187 free (data);
2188 write_enn (own_buf);
2189 return 1;
2190 }
2191
2192 n = (*q->xfer) (annex, NULL, data, ofs, len);
2193 if (n == -2)
2194 {
2195 free (data);
2196 return 0;
2197 }
2198 else if (n == -3)
2199 {
2200 /* Preserve error message. */
2201 }
2202 else if (n < 0)
2203 write_enn (own_buf);
2204 else
2205 sprintf (own_buf, "%x", n);
2206
2207 free (data);
2208 return 1;
2209 }
2210
2211 return 0;
2212 }
2213 }
2214
2215 return 0;
2216 }
2217
2218 /* Compute 32 bit CRC from inferior memory.
2219
2220 On success, return 32 bit CRC.
2221 On failure, return (unsigned long long) -1. */
2222
2223 static unsigned long long
2224 crc32 (CORE_ADDR base, int len, unsigned int crc)
2225 {
2226 while (len--)
2227 {
2228 unsigned char byte = 0;
2229
2230 /* Return failure if memory read fails. */
2231 if (read_inferior_memory (base, &byte, 1) != 0)
2232 return (unsigned long long) -1;
2233
2234 crc = xcrc32 (&byte, 1, crc);
2235 base++;
2236 }
2237 return (unsigned long long) crc;
2238 }
2239
2240 /* Parse the qMemTags packet request into ADDR and LEN. */
2241
2242 static void
2243 parse_fetch_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
2244 int *type)
2245 {
2246 gdb_assert (startswith (request, "qMemTags:"));
2247
2248 const char *p = request + strlen ("qMemTags:");
2249
2250 /* Read address and length. */
2251 unsigned int length = 0;
2252 p = decode_m_packet_params (p, addr, &length, ':');
2253 *len = length;
2254
2255 /* Read the tag type. */
2256 ULONGEST tag_type = 0;
2257 p = unpack_varlen_hex (p, &tag_type);
2258 *type = (int) tag_type;
2259 }
2260
2261 /* Add supported btrace packets to BUF. */
2262
2263 static void
2264 supported_btrace_packets (char *buf)
2265 {
2266 strcat (buf, ";Qbtrace:bts+");
2267 strcat (buf, ";Qbtrace-conf:bts:size+");
2268 strcat (buf, ";Qbtrace:pt+");
2269 strcat (buf, ";Qbtrace-conf:pt:size+");
2270 strcat (buf, ";Qbtrace:off+");
2271 strcat (buf, ";qXfer:btrace:read+");
2272 strcat (buf, ";qXfer:btrace-conf:read+");
2273 }
2274
2275 /* Handle all of the extended 'q' packets. */
2276
2277 static void
2278 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
2279 {
2280 client_state &cs = get_client_state ();
2281 static std::list<thread_info *>::const_iterator thread_iter;
2282
2283 /* Reply the current thread id. */
2284 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
2285 {
2286 ptid_t ptid;
2287 require_running_or_return (own_buf);
2288
2289 if (cs.general_thread != null_ptid && cs.general_thread != minus_one_ptid)
2290 ptid = cs.general_thread;
2291 else
2292 {
2293 thread_iter = all_threads.begin ();
2294 ptid = (*thread_iter)->id;
2295 }
2296
2297 sprintf (own_buf, "QC");
2298 own_buf += 2;
2299 write_ptid (own_buf, ptid);
2300 return;
2301 }
2302
2303 if (strcmp ("qSymbol::", own_buf) == 0)
2304 {
2305 scoped_restore_current_thread restore_thread;
2306
2307 /* For qSymbol, GDB only changes the current thread if the
2308 previous current thread was of a different process. So if
2309 the previous thread is gone, we need to pick another one of
2310 the same process. This can happen e.g., if we followed an
2311 exec in a non-leader thread. */
2312 if (current_thread == NULL)
2313 {
2314 thread_info *any_thread
2315 = find_any_thread_of_pid (cs.general_thread.pid ());
2316 switch_to_thread (any_thread);
2317
2318 /* Just in case, if we didn't find a thread, then bail out
2319 instead of crashing. */
2320 if (current_thread == NULL)
2321 {
2322 write_enn (own_buf);
2323 return;
2324 }
2325 }
2326
2327 /* GDB is suggesting new symbols have been loaded. This may
2328 mean a new shared library has been detected as loaded, so
2329 take the opportunity to check if breakpoints we think are
2330 inserted, still are. Note that it isn't guaranteed that
2331 we'll see this when a shared library is loaded, and nor will
2332 we see this for unloads (although breakpoints in unloaded
2333 libraries shouldn't trigger), as GDB may not find symbols for
2334 the library at all. We also re-validate breakpoints when we
2335 see a second GDB breakpoint for the same address, and or when
2336 we access breakpoint shadows. */
2337 validate_breakpoints ();
2338
2339 if (target_supports_tracepoints ())
2340 tracepoint_look_up_symbols ();
2341
2342 if (current_thread != NULL)
2343 the_target->look_up_symbols ();
2344
2345 strcpy (own_buf, "OK");
2346 return;
2347 }
2348
2349 if (!disable_packet_qfThreadInfo)
2350 {
2351 if (strcmp ("qfThreadInfo", own_buf) == 0)
2352 {
2353 require_running_or_return (own_buf);
2354 thread_iter = all_threads.begin ();
2355
2356 *own_buf++ = 'm';
2357 ptid_t ptid = (*thread_iter)->id;
2358 write_ptid (own_buf, ptid);
2359 thread_iter++;
2360 return;
2361 }
2362
2363 if (strcmp ("qsThreadInfo", own_buf) == 0)
2364 {
2365 require_running_or_return (own_buf);
2366 if (thread_iter != all_threads.end ())
2367 {
2368 *own_buf++ = 'm';
2369 ptid_t ptid = (*thread_iter)->id;
2370 write_ptid (own_buf, ptid);
2371 thread_iter++;
2372 return;
2373 }
2374 else
2375 {
2376 sprintf (own_buf, "l");
2377 return;
2378 }
2379 }
2380 }
2381
2382 if (the_target->supports_read_offsets ()
2383 && strcmp ("qOffsets", own_buf) == 0)
2384 {
2385 CORE_ADDR text, data;
2386
2387 require_running_or_return (own_buf);
2388 if (the_target->read_offsets (&text, &data))
2389 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
2390 (long)text, (long)data, (long)data);
2391 else
2392 write_enn (own_buf);
2393
2394 return;
2395 }
2396
2397 /* Protocol features query. */
2398 if (startswith (own_buf, "qSupported")
2399 && (own_buf[10] == ':' || own_buf[10] == '\0'))
2400 {
2401 char *p = &own_buf[10];
2402 int gdb_supports_qRelocInsn = 0;
2403
2404 /* Process each feature being provided by GDB. The first
2405 feature will follow a ':', and latter features will follow
2406 ';'. */
2407 if (*p == ':')
2408 {
2409 std::vector<std::string> qsupported;
2410 std::vector<const char *> unknowns;
2411
2412 /* Two passes, to avoid nested strtok calls in
2413 target_process_qsupported. */
2414 char *saveptr;
2415 for (p = strtok_r (p + 1, ";", &saveptr);
2416 p != NULL;
2417 p = strtok_r (NULL, ";", &saveptr))
2418 qsupported.emplace_back (p);
2419
2420 for (const std::string &feature : qsupported)
2421 {
2422 if (feature == "multiprocess+")
2423 {
2424 /* GDB supports and wants multi-process support if
2425 possible. */
2426 if (target_supports_multi_process ())
2427 cs.multi_process = 1;
2428 }
2429 else if (feature == "qRelocInsn+")
2430 {
2431 /* GDB supports relocate instruction requests. */
2432 gdb_supports_qRelocInsn = 1;
2433 }
2434 else if (feature == "swbreak+")
2435 {
2436 /* GDB wants us to report whether a trap is caused
2437 by a software breakpoint and for us to handle PC
2438 adjustment if necessary on this target. */
2439 if (target_supports_stopped_by_sw_breakpoint ())
2440 cs.swbreak_feature = 1;
2441 }
2442 else if (feature == "hwbreak+")
2443 {
2444 /* GDB wants us to report whether a trap is caused
2445 by a hardware breakpoint. */
2446 if (target_supports_stopped_by_hw_breakpoint ())
2447 cs.hwbreak_feature = 1;
2448 }
2449 else if (feature == "fork-events+")
2450 {
2451 /* GDB supports and wants fork events if possible. */
2452 if (target_supports_fork_events ())
2453 cs.report_fork_events = 1;
2454 }
2455 else if (feature == "vfork-events+")
2456 {
2457 /* GDB supports and wants vfork events if possible. */
2458 if (target_supports_vfork_events ())
2459 cs.report_vfork_events = 1;
2460 }
2461 else if (feature == "exec-events+")
2462 {
2463 /* GDB supports and wants exec events if possible. */
2464 if (target_supports_exec_events ())
2465 cs.report_exec_events = 1;
2466 }
2467 else if (feature == "vContSupported+")
2468 cs.vCont_supported = 1;
2469 else if (feature == "QThreadEvents+")
2470 ;
2471 else if (feature == "QThreadOptions+")
2472 ;
2473 else if (feature == "no-resumed+")
2474 {
2475 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2476 events. */
2477 report_no_resumed = true;
2478 }
2479 else if (feature == "memory-tagging+")
2480 {
2481 /* GDB supports memory tagging features. */
2482 if (target_supports_memory_tagging ())
2483 cs.memory_tagging_feature = true;
2484 }
2485 else
2486 {
2487 /* Move the unknown features all together. */
2488 unknowns.push_back (feature.c_str ());
2489 }
2490 }
2491
2492 /* Give the target backend a chance to process the unknown
2493 features. */
2494 target_process_qsupported (unknowns);
2495 }
2496
2497 sprintf (own_buf,
2498 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2499 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2500 "QEnvironmentReset+;QEnvironmentUnset+;"
2501 "QSetWorkingDir+",
2502 PBUFSIZ - 1);
2503
2504 if (target_supports_catch_syscall ())
2505 strcat (own_buf, ";QCatchSyscalls+");
2506
2507 if (the_target->supports_qxfer_libraries_svr4 ())
2508 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2509 ";augmented-libraries-svr4-read+");
2510 else
2511 {
2512 /* We do not have any hook to indicate whether the non-SVR4 target
2513 backend supports qXfer:libraries:read, so always report it. */
2514 strcat (own_buf, ";qXfer:libraries:read+");
2515 }
2516
2517 if (the_target->supports_read_auxv ())
2518 strcat (own_buf, ";qXfer:auxv:read+");
2519
2520 if (the_target->supports_qxfer_siginfo ())
2521 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2522
2523 if (the_target->supports_read_loadmap ())
2524 strcat (own_buf, ";qXfer:fdpic:read+");
2525
2526 /* We always report qXfer:features:read, as targets may
2527 install XML files on a subsequent call to arch_setup.
2528 If we reported to GDB on startup that we don't support
2529 qXfer:feature:read at all, we will never be re-queried. */
2530 strcat (own_buf, ";qXfer:features:read+");
2531
2532 if (cs.transport_is_reliable)
2533 strcat (own_buf, ";QStartNoAckMode+");
2534
2535 if (the_target->supports_qxfer_osdata ())
2536 strcat (own_buf, ";qXfer:osdata:read+");
2537
2538 if (target_supports_multi_process ())
2539 strcat (own_buf, ";multiprocess+");
2540
2541 if (target_supports_fork_events ())
2542 strcat (own_buf, ";fork-events+");
2543
2544 if (target_supports_vfork_events ())
2545 strcat (own_buf, ";vfork-events+");
2546
2547 if (target_supports_exec_events ())
2548 strcat (own_buf, ";exec-events+");
2549
2550 if (target_supports_non_stop ())
2551 strcat (own_buf, ";QNonStop+");
2552
2553 if (target_supports_disable_randomization ())
2554 strcat (own_buf, ";QDisableRandomization+");
2555
2556 strcat (own_buf, ";qXfer:threads:read+");
2557
2558 if (target_supports_tracepoints ())
2559 {
2560 strcat (own_buf, ";ConditionalTracepoints+");
2561 strcat (own_buf, ";TraceStateVariables+");
2562 strcat (own_buf, ";TracepointSource+");
2563 strcat (own_buf, ";DisconnectedTracing+");
2564 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2565 strcat (own_buf, ";FastTracepoints+");
2566 strcat (own_buf, ";StaticTracepoints+");
2567 strcat (own_buf, ";InstallInTrace+");
2568 strcat (own_buf, ";qXfer:statictrace:read+");
2569 strcat (own_buf, ";qXfer:traceframe-info:read+");
2570 strcat (own_buf, ";EnableDisableTracepoints+");
2571 strcat (own_buf, ";QTBuffer:size+");
2572 strcat (own_buf, ";tracenz+");
2573 }
2574
2575 if (target_supports_hardware_single_step ()
2576 || target_supports_software_single_step () )
2577 {
2578 strcat (own_buf, ";ConditionalBreakpoints+");
2579 }
2580 strcat (own_buf, ";BreakpointCommands+");
2581
2582 if (target_supports_agent ())
2583 strcat (own_buf, ";QAgent+");
2584
2585 if (the_target->supports_btrace ())
2586 supported_btrace_packets (own_buf);
2587
2588 if (target_supports_stopped_by_sw_breakpoint ())
2589 strcat (own_buf, ";swbreak+");
2590
2591 if (target_supports_stopped_by_hw_breakpoint ())
2592 strcat (own_buf, ";hwbreak+");
2593
2594 if (the_target->supports_pid_to_exec_file ())
2595 strcat (own_buf, ";qXfer:exec-file:read+");
2596
2597 strcat (own_buf, ";vContSupported+");
2598
2599 gdb_thread_options supported_options = target_supported_thread_options ();
2600 if (supported_options != 0)
2601 {
2602 char *end_buf = own_buf + strlen (own_buf);
2603 sprintf (end_buf, ";QThreadOptions=%s",
2604 phex_nz (supported_options, sizeof (supported_options)));
2605 }
2606
2607 strcat (own_buf, ";QThreadEvents+");
2608
2609 strcat (own_buf, ";no-resumed+");
2610
2611 if (target_supports_memory_tagging ())
2612 strcat (own_buf, ";memory-tagging+");
2613
2614 /* Reinitialize components as needed for the new connection. */
2615 hostio_handle_new_gdb_connection ();
2616 target_handle_new_gdb_connection ();
2617
2618 return;
2619 }
2620
2621 /* Thread-local storage support. */
2622 if (the_target->supports_get_tls_address ()
2623 && startswith (own_buf, "qGetTLSAddr:"))
2624 {
2625 char *p = own_buf + 12;
2626 CORE_ADDR parts[2], address = 0;
2627 int i, err;
2628 ptid_t ptid = null_ptid;
2629
2630 require_running_or_return (own_buf);
2631
2632 for (i = 0; i < 3; i++)
2633 {
2634 char *p2;
2635 int len;
2636
2637 if (p == NULL)
2638 break;
2639
2640 p2 = strchr (p, ',');
2641 if (p2)
2642 {
2643 len = p2 - p;
2644 p2++;
2645 }
2646 else
2647 {
2648 len = strlen (p);
2649 p2 = NULL;
2650 }
2651
2652 if (i == 0)
2653 ptid = read_ptid (p, NULL);
2654 else
2655 decode_address (&parts[i - 1], p, len);
2656 p = p2;
2657 }
2658
2659 if (p != NULL || i < 3)
2660 err = 1;
2661 else
2662 {
2663 struct thread_info *thread = find_thread_ptid (ptid);
2664
2665 if (thread == NULL)
2666 err = 2;
2667 else
2668 err = the_target->get_tls_address (thread, parts[0], parts[1],
2669 &address);
2670 }
2671
2672 if (err == 0)
2673 {
2674 strcpy (own_buf, paddress(address));
2675 return;
2676 }
2677 else if (err > 0)
2678 {
2679 write_enn (own_buf);
2680 return;
2681 }
2682
2683 /* Otherwise, pretend we do not understand this packet. */
2684 }
2685
2686 /* Windows OS Thread Information Block address support. */
2687 if (the_target->supports_get_tib_address ()
2688 && startswith (own_buf, "qGetTIBAddr:"))
2689 {
2690 const char *annex;
2691 int n;
2692 CORE_ADDR tlb;
2693 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2694
2695 n = the_target->get_tib_address (ptid, &tlb);
2696 if (n == 1)
2697 {
2698 strcpy (own_buf, paddress(tlb));
2699 return;
2700 }
2701 else if (n == 0)
2702 {
2703 write_enn (own_buf);
2704 return;
2705 }
2706 return;
2707 }
2708
2709 /* Handle "monitor" commands. */
2710 if (startswith (own_buf, "qRcmd,"))
2711 {
2712 char *mon = (char *) malloc (PBUFSIZ);
2713 int len = strlen (own_buf + 6);
2714
2715 if (mon == NULL)
2716 {
2717 write_enn (own_buf);
2718 return;
2719 }
2720
2721 if ((len % 2) != 0
2722 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
2723 {
2724 write_enn (own_buf);
2725 free (mon);
2726 return;
2727 }
2728 mon[len / 2] = '\0';
2729
2730 write_ok (own_buf);
2731
2732 if (the_target->handle_monitor_command (mon) == 0)
2733 /* Default processing. */
2734 handle_monitor_command (mon, own_buf);
2735
2736 free (mon);
2737 return;
2738 }
2739
2740 if (startswith (own_buf, "qSearch:memory:"))
2741 {
2742 require_running_or_return (own_buf);
2743 handle_search_memory (own_buf, packet_len);
2744 return;
2745 }
2746
2747 if (strcmp (own_buf, "qAttached") == 0
2748 || startswith (own_buf, "qAttached:"))
2749 {
2750 struct process_info *process;
2751
2752 if (own_buf[sizeof ("qAttached") - 1])
2753 {
2754 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
2755 process = find_process_pid (pid);
2756 }
2757 else
2758 {
2759 require_running_or_return (own_buf);
2760 process = current_process ();
2761 }
2762
2763 if (process == NULL)
2764 {
2765 write_enn (own_buf);
2766 return;
2767 }
2768
2769 strcpy (own_buf, process->attached ? "1" : "0");
2770 return;
2771 }
2772
2773 if (startswith (own_buf, "qCRC:"))
2774 {
2775 /* CRC check (compare-section). */
2776 const char *comma;
2777 ULONGEST base;
2778 int len;
2779 unsigned long long crc;
2780
2781 require_running_or_return (own_buf);
2782 comma = unpack_varlen_hex (own_buf + 5, &base);
2783 if (*comma++ != ',')
2784 {
2785 write_enn (own_buf);
2786 return;
2787 }
2788 len = strtoul (comma, NULL, 16);
2789 crc = crc32 (base, len, 0xffffffff);
2790 /* Check for memory failure. */
2791 if (crc == (unsigned long long) -1)
2792 {
2793 write_enn (own_buf);
2794 return;
2795 }
2796 sprintf (own_buf, "C%lx", (unsigned long) crc);
2797 return;
2798 }
2799
2800 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
2801 return;
2802
2803 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
2804 return;
2805
2806 /* Handle fetch memory tags packets. */
2807 if (startswith (own_buf, "qMemTags:")
2808 && target_supports_memory_tagging ())
2809 {
2810 gdb::byte_vector tags;
2811 CORE_ADDR addr = 0;
2812 size_t len = 0;
2813 int type = 0;
2814
2815 require_running_or_return (own_buf);
2816
2817 parse_fetch_memtags_request (own_buf, &addr, &len, &type);
2818
2819 bool ret = the_target->fetch_memtags (addr, len, tags, type);
2820
2821 if (ret)
2822 ret = create_fetch_memtags_reply (own_buf, tags);
2823
2824 if (!ret)
2825 write_enn (own_buf);
2826
2827 *new_packet_len_p = strlen (own_buf);
2828 return;
2829 }
2830
2831 /* Otherwise we didn't know what packet it was. Say we didn't
2832 understand it. */
2833 own_buf[0] = 0;
2834 }
2835
2836 static void gdb_wants_all_threads_stopped (void);
2837 static void resume (struct thread_resume *actions, size_t n);
2838
2839 /* The callback that is passed to visit_actioned_threads. */
2840 typedef int (visit_actioned_threads_callback_ftype)
2841 (const struct thread_resume *, struct thread_info *);
2842
2843 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2844 true if CALLBACK returns true. Returns false if no matching thread
2845 is found or CALLBACK results false.
2846 Note: This function is itself a callback for find_thread. */
2847
2848 static bool
2849 visit_actioned_threads (thread_info *thread,
2850 const struct thread_resume *actions,
2851 size_t num_actions,
2852 visit_actioned_threads_callback_ftype *callback)
2853 {
2854 for (size_t i = 0; i < num_actions; i++)
2855 {
2856 const struct thread_resume *action = &actions[i];
2857
2858 if (action->thread == minus_one_ptid
2859 || action->thread == thread->id
2860 || ((action->thread.pid ()
2861 == thread->id.pid ())
2862 && action->thread.lwp () == -1))
2863 {
2864 if ((*callback) (action, thread))
2865 return true;
2866 }
2867 }
2868
2869 return false;
2870 }
2871
2872 /* Callback for visit_actioned_threads. If the thread has a pending
2873 status to report, report it now. */
2874
2875 static int
2876 handle_pending_status (const struct thread_resume *resumption,
2877 struct thread_info *thread)
2878 {
2879 client_state &cs = get_client_state ();
2880 if (thread->status_pending_p)
2881 {
2882 thread->status_pending_p = 0;
2883
2884 cs.last_status = thread->last_status;
2885 cs.last_ptid = thread->id;
2886 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
2887 return 1;
2888 }
2889 return 0;
2890 }
2891
2892 /* Parse vCont packets. */
2893 static void
2894 handle_v_cont (char *own_buf)
2895 {
2896 const char *p;
2897 int n = 0, i = 0;
2898 struct thread_resume *resume_info;
2899 struct thread_resume default_action { null_ptid };
2900
2901 /* Count the number of semicolons in the packet. There should be one
2902 for every action. */
2903 p = &own_buf[5];
2904 while (p)
2905 {
2906 n++;
2907 p++;
2908 p = strchr (p, ';');
2909 }
2910
2911 resume_info = (struct thread_resume *) malloc (n * sizeof (resume_info[0]));
2912 if (resume_info == NULL)
2913 goto err;
2914
2915 p = &own_buf[5];
2916 while (*p)
2917 {
2918 p++;
2919
2920 memset (&resume_info[i], 0, sizeof resume_info[i]);
2921
2922 if (p[0] == 's' || p[0] == 'S')
2923 resume_info[i].kind = resume_step;
2924 else if (p[0] == 'r')
2925 resume_info[i].kind = resume_step;
2926 else if (p[0] == 'c' || p[0] == 'C')
2927 resume_info[i].kind = resume_continue;
2928 else if (p[0] == 't')
2929 resume_info[i].kind = resume_stop;
2930 else
2931 goto err;
2932
2933 if (p[0] == 'S' || p[0] == 'C')
2934 {
2935 char *q;
2936 int sig = strtol (p + 1, &q, 16);
2937 if (p == q)
2938 goto err;
2939 p = q;
2940
2941 if (!gdb_signal_to_host_p ((enum gdb_signal) sig))
2942 goto err;
2943 resume_info[i].sig = gdb_signal_to_host ((enum gdb_signal) sig);
2944 }
2945 else if (p[0] == 'r')
2946 {
2947 ULONGEST addr;
2948
2949 p = unpack_varlen_hex (p + 1, &addr);
2950 resume_info[i].step_range_start = addr;
2951
2952 if (*p != ',')
2953 goto err;
2954
2955 p = unpack_varlen_hex (p + 1, &addr);
2956 resume_info[i].step_range_end = addr;
2957 }
2958 else
2959 {
2960 p = p + 1;
2961 }
2962
2963 if (p[0] == 0)
2964 {
2965 resume_info[i].thread = minus_one_ptid;
2966 default_action = resume_info[i];
2967
2968 /* Note: we don't increment i here, we'll overwrite this entry
2969 the next time through. */
2970 }
2971 else if (p[0] == ':')
2972 {
2973 const char *q;
2974 ptid_t ptid = read_ptid (p + 1, &q);
2975
2976 if (p == q)
2977 goto err;
2978 p = q;
2979 if (p[0] != ';' && p[0] != 0)
2980 goto err;
2981
2982 resume_info[i].thread = ptid;
2983
2984 i++;
2985 }
2986 }
2987
2988 if (i < n)
2989 resume_info[i] = default_action;
2990
2991 resume (resume_info, n);
2992 free (resume_info);
2993 return;
2994
2995 err:
2996 write_enn (own_buf);
2997 free (resume_info);
2998 return;
2999 }
3000
3001 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
3002
3003 static void
3004 resume (struct thread_resume *actions, size_t num_actions)
3005 {
3006 client_state &cs = get_client_state ();
3007 if (!non_stop)
3008 {
3009 /* Check if among the threads that GDB wants actioned, there's
3010 one with a pending status to report. If so, skip actually
3011 resuming/stopping and report the pending event
3012 immediately. */
3013
3014 thread_info *thread_with_status = find_thread ([&] (thread_info *thread)
3015 {
3016 return visit_actioned_threads (thread, actions, num_actions,
3017 handle_pending_status);
3018 });
3019
3020 if (thread_with_status != NULL)
3021 return;
3022
3023 enable_async_io ();
3024 }
3025
3026 the_target->resume (actions, num_actions);
3027
3028 if (non_stop)
3029 write_ok (cs.own_buf);
3030 else
3031 {
3032 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status, 0, 1);
3033
3034 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED
3035 && !report_no_resumed)
3036 {
3037 /* The client does not support this stop reply. At least
3038 return error. */
3039 sprintf (cs.own_buf, "E.No unwaited-for children left.");
3040 disable_async_io ();
3041 return;
3042 }
3043
3044 if (cs.last_status.kind () != TARGET_WAITKIND_EXITED
3045 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED
3046 && cs.last_status.kind () != TARGET_WAITKIND_NO_RESUMED)
3047 current_thread->last_status = cs.last_status;
3048
3049 /* From the client's perspective, all-stop mode always stops all
3050 threads implicitly (and the target backend has already done
3051 so by now). Tag all threads as "want-stopped", so we don't
3052 resume them implicitly without the client telling us to. */
3053 gdb_wants_all_threads_stopped ();
3054 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
3055 disable_async_io ();
3056
3057 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
3058 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
3059 target_mourn_inferior (cs.last_ptid);
3060 }
3061 }
3062
3063 /* Attach to a new program. */
3064 static void
3065 handle_v_attach (char *own_buf)
3066 {
3067 client_state &cs = get_client_state ();
3068 int pid;
3069
3070 pid = strtol (own_buf + 8, NULL, 16);
3071 if (pid != 0 && attach_inferior (pid) == 0)
3072 {
3073 /* Don't report shared library events after attaching, even if
3074 some libraries are preloaded. GDB will always poll the
3075 library list. Avoids the "stopped by shared library event"
3076 notice on the GDB side. */
3077 current_process ()->dlls_changed = false;
3078
3079 if (non_stop)
3080 {
3081 /* In non-stop, we don't send a resume reply. Stop events
3082 will follow up using the normal notification
3083 mechanism. */
3084 write_ok (own_buf);
3085 }
3086 else
3087 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3088 }
3089 else
3090 write_enn (own_buf);
3091 }
3092
3093 /* Decode an argument from the vRun packet buffer. PTR points to the
3094 first hex-encoded character in the buffer, and LEN is the number of
3095 characters to read from the packet buffer.
3096
3097 If the argument decoding is successful, return a buffer containing the
3098 decoded argument, including a null terminator at the end.
3099
3100 If the argument decoding fails for any reason, return nullptr. */
3101
3102 static gdb::unique_xmalloc_ptr<char>
3103 decode_v_run_arg (const char *ptr, size_t len)
3104 {
3105 /* Two hex characters are required for each decoded byte. */
3106 if (len % 2 != 0)
3107 return nullptr;
3108
3109 /* The length in bytes needed for the decoded argument. */
3110 len /= 2;
3111
3112 /* Buffer to decode the argument into. The '+ 1' is for the null
3113 terminator we will add. */
3114 char *arg = (char *) xmalloc (len + 1);
3115
3116 /* Decode the argument from the packet and add a null terminator. We do
3117 this within a try block as invalid characters within the PTR buffer
3118 will cause hex2bin to throw an exception. Our caller relies on us
3119 returning nullptr in order to clean up some memory allocations. */
3120 try
3121 {
3122 hex2bin (ptr, (gdb_byte *) arg, len);
3123 arg[len] = '\0';
3124 }
3125 catch (const gdb_exception_error &exception)
3126 {
3127 return nullptr;
3128 }
3129
3130 return gdb::unique_xmalloc_ptr<char> (arg);
3131 }
3132
3133 /* Run a new program. */
3134 static void
3135 handle_v_run (char *own_buf)
3136 {
3137 client_state &cs = get_client_state ();
3138 char *p, *next_p;
3139 std::vector<char *> new_argv;
3140 gdb::unique_xmalloc_ptr<char> new_program_name;
3141 int i;
3142
3143 for (i = 0, p = own_buf + strlen ("vRun;");
3144 /* Exit condition is at the end of the loop. */;
3145 p = next_p + 1, ++i)
3146 {
3147 next_p = strchr (p, ';');
3148 if (next_p == NULL)
3149 next_p = p + strlen (p);
3150
3151 if (i == 0 && p == next_p)
3152 {
3153 /* No program specified. */
3154 gdb_assert (new_program_name == nullptr);
3155 }
3156 else if (p == next_p)
3157 {
3158 /* Empty argument. */
3159 new_argv.push_back (xstrdup (""));
3160 }
3161 else
3162 {
3163 /* The length of the argument string in the packet. */
3164 size_t len = next_p - p;
3165
3166 gdb::unique_xmalloc_ptr<char> arg = decode_v_run_arg (p, len);
3167 if (arg == nullptr)
3168 {
3169 write_enn (own_buf);
3170 free_vector_argv (new_argv);
3171 return;
3172 }
3173
3174 if (i == 0)
3175 new_program_name = std::move (arg);
3176 else
3177 new_argv.push_back (arg.release ());
3178 }
3179 if (*next_p == '\0')
3180 break;
3181 }
3182
3183 if (new_program_name == nullptr)
3184 {
3185 /* GDB didn't specify a program to run. Use the program from the
3186 last run with the new argument list. */
3187 if (program_path.get () == nullptr)
3188 {
3189 write_enn (own_buf);
3190 free_vector_argv (new_argv);
3191 return;
3192 }
3193 }
3194 else
3195 program_path.set (new_program_name.get ());
3196
3197 /* Free the old argv and install the new one. */
3198 free_vector_argv (program_args);
3199 program_args = new_argv;
3200
3201 target_create_inferior (program_path.get (), program_args);
3202
3203 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
3204 {
3205 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3206
3207 /* In non-stop, sending a resume reply doesn't set the general
3208 thread, but GDB assumes a vRun sets it (this is so GDB can
3209 query which is the main thread of the new inferior. */
3210 if (non_stop)
3211 cs.general_thread = cs.last_ptid;
3212 }
3213 else
3214 write_enn (own_buf);
3215 }
3216
3217 /* Kill process. */
3218 static void
3219 handle_v_kill (char *own_buf)
3220 {
3221 client_state &cs = get_client_state ();
3222 int pid;
3223 char *p = &own_buf[6];
3224 if (cs.multi_process)
3225 pid = strtol (p, NULL, 16);
3226 else
3227 pid = signal_pid;
3228
3229 process_info *proc = find_process_pid (pid);
3230
3231 if (proc != nullptr && kill_inferior (proc) == 0)
3232 {
3233 cs.last_status.set_signalled (GDB_SIGNAL_KILL);
3234 cs.last_ptid = ptid_t (pid);
3235 discard_queued_stop_replies (cs.last_ptid);
3236 write_ok (own_buf);
3237 }
3238 else
3239 write_enn (own_buf);
3240 }
3241
3242 /* Handle all of the extended 'v' packets. */
3243 void
3244 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
3245 {
3246 client_state &cs = get_client_state ();
3247 if (!disable_packet_vCont)
3248 {
3249 if (strcmp (own_buf, "vCtrlC") == 0)
3250 {
3251 the_target->request_interrupt ();
3252 write_ok (own_buf);
3253 return;
3254 }
3255
3256 if (startswith (own_buf, "vCont;"))
3257 {
3258 handle_v_cont (own_buf);
3259 return;
3260 }
3261
3262 if (startswith (own_buf, "vCont?"))
3263 {
3264 strcpy (own_buf, "vCont;c;C;t");
3265
3266 if (target_supports_hardware_single_step ()
3267 || target_supports_software_single_step ()
3268 || !cs.vCont_supported)
3269 {
3270 /* If target supports single step either by hardware or by
3271 software, add actions s and S to the list of supported
3272 actions. On the other hand, if GDB doesn't request the
3273 supported vCont actions in qSupported packet, add s and
3274 S to the list too. */
3275 own_buf = own_buf + strlen (own_buf);
3276 strcpy (own_buf, ";s;S");
3277 }
3278
3279 if (target_supports_range_stepping ())
3280 {
3281 own_buf = own_buf + strlen (own_buf);
3282 strcpy (own_buf, ";r");
3283 }
3284 return;
3285 }
3286 }
3287
3288 if (startswith (own_buf, "vFile:")
3289 && handle_vFile (own_buf, packet_len, new_packet_len))
3290 return;
3291
3292 if (startswith (own_buf, "vAttach;"))
3293 {
3294 if ((!extended_protocol || !cs.multi_process) && target_running ())
3295 {
3296 fprintf (stderr, "Already debugging a process\n");
3297 write_enn (own_buf);
3298 return;
3299 }
3300 handle_v_attach (own_buf);
3301 return;
3302 }
3303
3304 if (startswith (own_buf, "vRun;"))
3305 {
3306 if ((!extended_protocol || !cs.multi_process) && target_running ())
3307 {
3308 fprintf (stderr, "Already debugging a process\n");
3309 write_enn (own_buf);
3310 return;
3311 }
3312 handle_v_run (own_buf);
3313 return;
3314 }
3315
3316 if (startswith (own_buf, "vKill;"))
3317 {
3318 if (!target_running ())
3319 {
3320 fprintf (stderr, "No process to kill\n");
3321 write_enn (own_buf);
3322 return;
3323 }
3324 handle_v_kill (own_buf);
3325 return;
3326 }
3327
3328 if (handle_notif_ack (own_buf, packet_len))
3329 return;
3330
3331 /* Otherwise we didn't know what packet it was. Say we didn't
3332 understand it. */
3333 own_buf[0] = 0;
3334 return;
3335 }
3336
3337 /* Resume thread and wait for another event. In non-stop mode,
3338 don't really wait here, but return immediately to the event
3339 loop. */
3340 static void
3341 myresume (char *own_buf, int step, int sig)
3342 {
3343 client_state &cs = get_client_state ();
3344 struct thread_resume resume_info[2];
3345 int n = 0;
3346 int valid_cont_thread;
3347
3348 valid_cont_thread = (cs.cont_thread != null_ptid
3349 && cs.cont_thread != minus_one_ptid);
3350
3351 if (step || sig || valid_cont_thread)
3352 {
3353 resume_info[0].thread = current_ptid;
3354 if (step)
3355 resume_info[0].kind = resume_step;
3356 else
3357 resume_info[0].kind = resume_continue;
3358 resume_info[0].sig = sig;
3359 n++;
3360 }
3361
3362 if (!valid_cont_thread)
3363 {
3364 resume_info[n].thread = minus_one_ptid;
3365 resume_info[n].kind = resume_continue;
3366 resume_info[n].sig = 0;
3367 n++;
3368 }
3369
3370 resume (resume_info, n);
3371 }
3372
3373 /* Callback for for_each_thread. Make a new stop reply for each
3374 stopped thread. */
3375
3376 static void
3377 queue_stop_reply_callback (thread_info *thread)
3378 {
3379 /* For now, assume targets that don't have this callback also don't
3380 manage the thread's last_status field. */
3381 if (!the_target->supports_thread_stopped ())
3382 {
3383 struct vstop_notif *new_notif = new struct vstop_notif;
3384
3385 new_notif->ptid = thread->id;
3386 new_notif->status = thread->last_status;
3387 /* Pass the last stop reply back to GDB, but don't notify
3388 yet. */
3389 notif_event_enque (&notif_stop, new_notif);
3390 }
3391 else
3392 {
3393 if (target_thread_stopped (thread))
3394 {
3395 threads_debug_printf
3396 ("Reporting thread %s as already stopped with %s",
3397 target_pid_to_str (thread->id).c_str (),
3398 thread->last_status.to_string ().c_str ());
3399
3400 gdb_assert (thread->last_status.kind () != TARGET_WAITKIND_IGNORE);
3401
3402 /* Pass the last stop reply back to GDB, but don't notify
3403 yet. */
3404 queue_stop_reply (thread->id, thread->last_status);
3405 }
3406 }
3407 }
3408
3409 /* Set this inferior threads's state as "want-stopped". We won't
3410 resume this thread until the client gives us another action for
3411 it. */
3412
3413 static void
3414 gdb_wants_thread_stopped (thread_info *thread)
3415 {
3416 thread->last_resume_kind = resume_stop;
3417
3418 if (thread->last_status.kind () == TARGET_WAITKIND_IGNORE)
3419 {
3420 /* Most threads are stopped implicitly (all-stop); tag that with
3421 signal 0. */
3422 thread->last_status.set_stopped (GDB_SIGNAL_0);
3423 }
3424 }
3425
3426 /* Set all threads' states as "want-stopped". */
3427
3428 static void
3429 gdb_wants_all_threads_stopped (void)
3430 {
3431 for_each_thread (gdb_wants_thread_stopped);
3432 }
3433
3434 /* Callback for for_each_thread. If the thread is stopped with an
3435 interesting event, mark it as having a pending event. */
3436
3437 static void
3438 set_pending_status_callback (thread_info *thread)
3439 {
3440 if (thread->last_status.kind () != TARGET_WAITKIND_STOPPED
3441 || (thread->last_status.sig () != GDB_SIGNAL_0
3442 /* A breakpoint, watchpoint or finished step from a previous
3443 GDB run isn't considered interesting for a new GDB run.
3444 If we left those pending, the new GDB could consider them
3445 random SIGTRAPs. This leaves out real async traps. We'd
3446 have to peek into the (target-specific) siginfo to
3447 distinguish those. */
3448 && thread->last_status.sig () != GDB_SIGNAL_TRAP))
3449 thread->status_pending_p = 1;
3450 }
3451
3452 /* Status handler for the '?' packet. */
3453
3454 static void
3455 handle_status (char *own_buf)
3456 {
3457 client_state &cs = get_client_state ();
3458
3459 /* GDB is connected, don't forward events to the target anymore. */
3460 for_each_process ([] (process_info *process) {
3461 process->gdb_detached = 0;
3462 });
3463
3464 /* In non-stop mode, we must send a stop reply for each stopped
3465 thread. In all-stop mode, just send one for the first stopped
3466 thread we find. */
3467
3468 if (non_stop)
3469 {
3470 for_each_thread (queue_stop_reply_callback);
3471
3472 /* The first is sent immediatly. OK is sent if there is no
3473 stopped thread, which is the same handling of the vStopped
3474 packet (by design). */
3475 notif_write_event (&notif_stop, cs.own_buf);
3476 }
3477 else
3478 {
3479 thread_info *thread = NULL;
3480
3481 target_pause_all (false);
3482 target_stabilize_threads ();
3483 gdb_wants_all_threads_stopped ();
3484
3485 /* We can only report one status, but we might be coming out of
3486 non-stop -- if more than one thread is stopped with
3487 interesting events, leave events for the threads we're not
3488 reporting now pending. They'll be reported the next time the
3489 threads are resumed. Start by marking all interesting events
3490 as pending. */
3491 for_each_thread (set_pending_status_callback);
3492
3493 /* Prefer the last thread that reported an event to GDB (even if
3494 that was a GDB_SIGNAL_TRAP). */
3495 if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE
3496 && cs.last_status.kind () != TARGET_WAITKIND_EXITED
3497 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED)
3498 thread = find_thread_ptid (cs.last_ptid);
3499
3500 /* If the last event thread is not found for some reason, look
3501 for some other thread that might have an event to report. */
3502 if (thread == NULL)
3503 thread = find_thread ([] (thread_info *thr_arg)
3504 {
3505 return thr_arg->status_pending_p;
3506 });
3507
3508 /* If we're still out of luck, simply pick the first thread in
3509 the thread list. */
3510 if (thread == NULL)
3511 thread = get_first_thread ();
3512
3513 if (thread != NULL)
3514 {
3515 struct thread_info *tp = (struct thread_info *) thread;
3516
3517 /* We're reporting this event, so it's no longer
3518 pending. */
3519 tp->status_pending_p = 0;
3520
3521 /* GDB assumes the current thread is the thread we're
3522 reporting the status for. */
3523 cs.general_thread = thread->id;
3524 set_desired_thread ();
3525
3526 gdb_assert (tp->last_status.kind () != TARGET_WAITKIND_IGNORE);
3527 prepare_resume_reply (own_buf, tp->id, tp->last_status);
3528 }
3529 else
3530 strcpy (own_buf, "W00");
3531 }
3532 }
3533
3534 static void
3535 gdbserver_version (void)
3536 {
3537 printf ("GNU gdbserver %s%s\n"
3538 "Copyright (C) 2023 Free Software Foundation, Inc.\n"
3539 "gdbserver is free software, covered by the "
3540 "GNU General Public License.\n"
3541 "This gdbserver was configured as \"%s\"\n",
3542 PKGVERSION, version, host_name);
3543 }
3544
3545 static void
3546 gdbserver_usage (FILE *stream)
3547 {
3548 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3549 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3550 "\tgdbserver [OPTIONS] --multi COMM\n"
3551 "\n"
3552 "COMM may either be a tty device (for serial debugging),\n"
3553 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3554 "stdin/stdout of gdbserver.\n"
3555 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3556 "PID is the process ID to attach to, when --attach is specified.\n"
3557 "\n"
3558 "Operating modes:\n"
3559 "\n"
3560 " --attach Attach to running process PID.\n"
3561 " --multi Start server without a specific program, and\n"
3562 " only quit when explicitly commanded.\n"
3563 " --once Exit after the first connection has closed.\n"
3564 " --help Print this message and then exit.\n"
3565 " --version Display version information and exit.\n"
3566 "\n"
3567 "Other options:\n"
3568 "\n"
3569 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3570 " --disable-randomization\n"
3571 " Run PROG with address space randomization disabled.\n"
3572 " --no-disable-randomization\n"
3573 " Don't disable address space randomization when\n"
3574 " starting PROG.\n"
3575 " --startup-with-shell\n"
3576 " Start PROG using a shell. I.e., execs a shell that\n"
3577 " then execs PROG. (default)\n"
3578 " --no-startup-with-shell\n"
3579 " Exec PROG directly instead of using a shell.\n"
3580 " Disables argument globbing and variable substitution\n"
3581 " on UNIX-like systems.\n"
3582 "\n"
3583 "Debug options:\n"
3584 "\n"
3585 " --debug Enable general debugging output.\n"
3586 " --debug-format=OPT1[,OPT2,...]\n"
3587 " Specify extra content in debugging output.\n"
3588 " Options:\n"
3589 " all\n"
3590 " none\n"
3591 " timestamp\n"
3592 " --remote-debug Enable remote protocol debugging output.\n"
3593 " --event-loop-debug Enable event loop debugging output.\n"
3594 " --disable-packet=OPT1[,OPT2,...]\n"
3595 " Disable support for RSP packets or features.\n"
3596 " Options:\n"
3597 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3598 " threads (disable all threading packets).\n"
3599 "\n"
3600 "For more information, consult the GDB manual (available as on-line \n"
3601 "info or a printed manual).\n");
3602 if (REPORT_BUGS_TO[0] && stream == stdout)
3603 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
3604 }
3605
3606 static void
3607 gdbserver_show_disableable (FILE *stream)
3608 {
3609 fprintf (stream, "Disableable packets:\n"
3610 " vCont \tAll vCont packets\n"
3611 " qC \tQuerying the current thread\n"
3612 " qfThreadInfo\tThread listing\n"
3613 " Tthread \tPassing the thread specifier in the "
3614 "T stop reply packet\n"
3615 " threads \tAll of the above\n"
3616 " T \tAll 'T' packets\n");
3617 }
3618
3619 /* Start up the event loop. This is the entry point to the event
3620 loop. */
3621
3622 static void
3623 start_event_loop ()
3624 {
3625 /* Loop until there is nothing to do. This is the entry point to
3626 the event loop engine. If nothing is ready at this time, wait
3627 for something to happen (via wait_for_event), then process it.
3628 Return when there are no longer event sources to wait for. */
3629
3630 keep_processing_events = true;
3631 while (keep_processing_events)
3632 {
3633 /* Any events already waiting in the queue? */
3634 int res = gdb_do_one_event ();
3635
3636 /* Was there an error? */
3637 if (res == -1)
3638 break;
3639 }
3640
3641 /* We are done with the event loop. There are no more event sources
3642 to listen to. So we exit gdbserver. */
3643 }
3644
3645 static void
3646 kill_inferior_callback (process_info *process)
3647 {
3648 kill_inferior (process);
3649 discard_queued_stop_replies (ptid_t (process->pid));
3650 }
3651
3652 /* Call this when exiting gdbserver with possible inferiors that need
3653 to be killed or detached from. */
3654
3655 static void
3656 detach_or_kill_for_exit (void)
3657 {
3658 /* First print a list of the inferiors we will be killing/detaching.
3659 This is to assist the user, for example, in case the inferior unexpectedly
3660 dies after we exit: did we screw up or did the inferior exit on its own?
3661 Having this info will save some head-scratching. */
3662
3663 if (have_started_inferiors_p ())
3664 {
3665 fprintf (stderr, "Killing process(es):");
3666
3667 for_each_process ([] (process_info *process) {
3668 if (!process->attached)
3669 fprintf (stderr, " %d", process->pid);
3670 });
3671
3672 fprintf (stderr, "\n");
3673 }
3674 if (have_attached_inferiors_p ())
3675 {
3676 fprintf (stderr, "Detaching process(es):");
3677
3678 for_each_process ([] (process_info *process) {
3679 if (process->attached)
3680 fprintf (stderr, " %d", process->pid);
3681 });
3682
3683 fprintf (stderr, "\n");
3684 }
3685
3686 /* Now we can kill or detach the inferiors. */
3687 for_each_process ([] (process_info *process) {
3688 int pid = process->pid;
3689
3690 if (process->attached)
3691 detach_inferior (process);
3692 else
3693 kill_inferior (process);
3694
3695 discard_queued_stop_replies (ptid_t (pid));
3696 });
3697 }
3698
3699 /* Value that will be passed to exit(3) when gdbserver exits. */
3700 static int exit_code;
3701
3702 /* Wrapper for detach_or_kill_for_exit that catches and prints
3703 errors. */
3704
3705 static void
3706 detach_or_kill_for_exit_cleanup ()
3707 {
3708 try
3709 {
3710 detach_or_kill_for_exit ();
3711 }
3712 catch (const gdb_exception &exception)
3713 {
3714 fflush (stdout);
3715 fprintf (stderr, "Detach or kill failed: %s\n",
3716 exception.what ());
3717 exit_code = 1;
3718 }
3719 }
3720
3721 #if GDB_SELF_TEST
3722
3723 namespace selftests {
3724
3725 static void
3726 test_memory_tagging_functions (void)
3727 {
3728 /* Setup testing. */
3729 gdb::char_vector packet;
3730 gdb::byte_vector tags, bv;
3731 std::string expected;
3732 packet.resize (32000);
3733 CORE_ADDR addr;
3734 size_t len;
3735 int type;
3736
3737 /* Test parsing a qMemTags request. */
3738
3739 /* Valid request, addr, len and type updated. */
3740 addr = 0xff;
3741 len = 255;
3742 type = 255;
3743 strcpy (packet.data (), "qMemTags:0,0:0");
3744 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
3745 SELF_CHECK (addr == 0 && len == 0 && type == 0);
3746
3747 /* Valid request, addr, len and type updated. */
3748 addr = 0;
3749 len = 0;
3750 type = 0;
3751 strcpy (packet.data (), "qMemTags:deadbeef,ff:5");
3752 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
3753 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5);
3754
3755 /* Test creating a qMemTags reply. */
3756
3757 /* Non-empty tag data. */
3758 bv.resize (0);
3759
3760 for (int i = 0; i < 5; i++)
3761 bv.push_back (i);
3762
3763 expected = "m0001020304";
3764 SELF_CHECK (create_fetch_memtags_reply (packet.data (), bv) == true);
3765 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
3766
3767 /* Test parsing a QMemTags request. */
3768
3769 /* Valid request and empty tag data: addr, len, type and tags updated. */
3770 addr = 0xff;
3771 len = 255;
3772 type = 255;
3773 tags.resize (5);
3774 strcpy (packet.data (), "QMemTags:0,0:0:");
3775 SELF_CHECK (parse_store_memtags_request (packet.data (),
3776 &addr, &len, tags, &type) == true);
3777 SELF_CHECK (addr == 0 && len == 0 && type == 0 && tags.size () == 0);
3778
3779 /* Valid request and non-empty tag data: addr, len, type
3780 and tags updated. */
3781 addr = 0;
3782 len = 0;
3783 type = 0;
3784 tags.resize (0);
3785 strcpy (packet.data (),
3786 "QMemTags:deadbeef,ff:5:0001020304");
3787 SELF_CHECK (parse_store_memtags_request (packet.data (), &addr, &len, tags,
3788 &type) == true);
3789 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5
3790 && tags.size () == 5);
3791 }
3792
3793 } // namespace selftests
3794 #endif /* GDB_SELF_TEST */
3795
3796 /* Main function. This is called by the real "main" function,
3797 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3798
3799 static void ATTRIBUTE_NORETURN
3800 captured_main (int argc, char *argv[])
3801 {
3802 int bad_attach;
3803 int pid;
3804 char *arg_end;
3805 const char *port = NULL;
3806 char **next_arg = &argv[1];
3807 volatile int multi_mode = 0;
3808 volatile int attach = 0;
3809 int was_running;
3810 bool selftest = false;
3811 #if GDB_SELF_TEST
3812 std::vector<const char *> selftest_filters;
3813
3814 selftests::register_test ("remote_memory_tagging",
3815 selftests::test_memory_tagging_functions);
3816 #endif
3817
3818 current_directory = getcwd (NULL, 0);
3819 client_state &cs = get_client_state ();
3820
3821 if (current_directory == NULL)
3822 {
3823 error (_("Could not find current working directory: %s"),
3824 safe_strerror (errno));
3825 }
3826
3827 while (*next_arg != NULL && **next_arg == '-')
3828 {
3829 if (strcmp (*next_arg, "--version") == 0)
3830 {
3831 gdbserver_version ();
3832 exit (0);
3833 }
3834 else if (strcmp (*next_arg, "--help") == 0)
3835 {
3836 gdbserver_usage (stdout);
3837 exit (0);
3838 }
3839 else if (strcmp (*next_arg, "--attach") == 0)
3840 attach = 1;
3841 else if (strcmp (*next_arg, "--multi") == 0)
3842 multi_mode = 1;
3843 else if (strcmp (*next_arg, "--wrapper") == 0)
3844 {
3845 char **tmp;
3846
3847 next_arg++;
3848
3849 tmp = next_arg;
3850 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
3851 {
3852 wrapper_argv += *next_arg;
3853 wrapper_argv += ' ';
3854 next_arg++;
3855 }
3856
3857 if (!wrapper_argv.empty ())
3858 {
3859 /* Erase the last whitespace. */
3860 wrapper_argv.erase (wrapper_argv.end () - 1);
3861 }
3862
3863 if (next_arg == tmp || *next_arg == NULL)
3864 {
3865 gdbserver_usage (stderr);
3866 exit (1);
3867 }
3868
3869 /* Consume the "--". */
3870 *next_arg = NULL;
3871 }
3872 else if (strcmp (*next_arg, "--debug") == 0)
3873 debug_threads = true;
3874 else if (startswith (*next_arg, "--debug-format="))
3875 {
3876 std::string error_msg
3877 = parse_debug_format_options ((*next_arg)
3878 + sizeof ("--debug-format=") - 1, 0);
3879
3880 if (!error_msg.empty ())
3881 {
3882 fprintf (stderr, "%s", error_msg.c_str ());
3883 exit (1);
3884 }
3885 }
3886 else if (strcmp (*next_arg, "--remote-debug") == 0)
3887 remote_debug = true;
3888 else if (strcmp (*next_arg, "--event-loop-debug") == 0)
3889 debug_event_loop = debug_event_loop_kind::ALL;
3890 else if (startswith (*next_arg, "--debug-file="))
3891 debug_set_output ((*next_arg) + sizeof ("--debug-file=") -1);
3892 else if (strcmp (*next_arg, "--disable-packet") == 0)
3893 {
3894 gdbserver_show_disableable (stdout);
3895 exit (0);
3896 }
3897 else if (startswith (*next_arg, "--disable-packet="))
3898 {
3899 char *packets = *next_arg += sizeof ("--disable-packet=") - 1;
3900 char *saveptr;
3901 for (char *tok = strtok_r (packets, ",", &saveptr);
3902 tok != NULL;
3903 tok = strtok_r (NULL, ",", &saveptr))
3904 {
3905 if (strcmp ("vCont", tok) == 0)
3906 disable_packet_vCont = true;
3907 else if (strcmp ("Tthread", tok) == 0)
3908 disable_packet_Tthread = true;
3909 else if (strcmp ("qC", tok) == 0)
3910 disable_packet_qC = true;
3911 else if (strcmp ("qfThreadInfo", tok) == 0)
3912 disable_packet_qfThreadInfo = true;
3913 else if (strcmp ("T", tok) == 0)
3914 disable_packet_T = true;
3915 else if (strcmp ("threads", tok) == 0)
3916 {
3917 disable_packet_vCont = true;
3918 disable_packet_Tthread = true;
3919 disable_packet_qC = true;
3920 disable_packet_qfThreadInfo = true;
3921 }
3922 else
3923 {
3924 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
3925 tok);
3926 gdbserver_show_disableable (stderr);
3927 exit (1);
3928 }
3929 }
3930 }
3931 else if (strcmp (*next_arg, "-") == 0)
3932 {
3933 /* "-" specifies a stdio connection and is a form of port
3934 specification. */
3935 port = STDIO_CONNECTION_NAME;
3936 next_arg++;
3937 break;
3938 }
3939 else if (strcmp (*next_arg, "--disable-randomization") == 0)
3940 cs.disable_randomization = 1;
3941 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
3942 cs.disable_randomization = 0;
3943 else if (strcmp (*next_arg, "--startup-with-shell") == 0)
3944 startup_with_shell = true;
3945 else if (strcmp (*next_arg, "--no-startup-with-shell") == 0)
3946 startup_with_shell = false;
3947 else if (strcmp (*next_arg, "--once") == 0)
3948 run_once = true;
3949 else if (strcmp (*next_arg, "--selftest") == 0)
3950 selftest = true;
3951 else if (startswith (*next_arg, "--selftest="))
3952 {
3953 selftest = true;
3954
3955 #if GDB_SELF_TEST
3956 const char *filter = *next_arg + strlen ("--selftest=");
3957 if (*filter == '\0')
3958 {
3959 fprintf (stderr, _("Error: selftest filter is empty.\n"));
3960 exit (1);
3961 }
3962
3963 selftest_filters.push_back (filter);
3964 #endif
3965 }
3966 else
3967 {
3968 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
3969 exit (1);
3970 }
3971
3972 next_arg++;
3973 continue;
3974 }
3975
3976 if (port == NULL)
3977 {
3978 port = *next_arg;
3979 next_arg++;
3980 }
3981 if ((port == NULL || (!attach && !multi_mode && *next_arg == NULL))
3982 && !selftest)
3983 {
3984 gdbserver_usage (stderr);
3985 exit (1);
3986 }
3987
3988 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3989 opened by remote_prepare. */
3990 notice_open_fds ();
3991
3992 save_original_signals_state (false);
3993
3994 /* We need to know whether the remote connection is stdio before
3995 starting the inferior. Inferiors created in this scenario have
3996 stdin,stdout redirected. So do this here before we call
3997 start_inferior. */
3998 if (port != NULL)
3999 remote_prepare (port);
4000
4001 bad_attach = 0;
4002 pid = 0;
4003
4004 /* --attach used to come after PORT, so allow it there for
4005 compatibility. */
4006 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
4007 {
4008 attach = 1;
4009 next_arg++;
4010 }
4011
4012 if (attach
4013 && (*next_arg == NULL
4014 || (*next_arg)[0] == '\0'
4015 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
4016 || *arg_end != '\0'
4017 || next_arg[1] != NULL))
4018 bad_attach = 1;
4019
4020 if (bad_attach)
4021 {
4022 gdbserver_usage (stderr);
4023 exit (1);
4024 }
4025
4026 /* Gather information about the environment. */
4027 our_environ = gdb_environ::from_host_environ ();
4028
4029 initialize_async_io ();
4030 initialize_low ();
4031 have_job_control ();
4032 if (target_supports_tracepoints ())
4033 initialize_tracepoint ();
4034
4035 mem_buf = (unsigned char *) xmalloc (PBUFSIZ);
4036
4037 if (selftest)
4038 {
4039 #if GDB_SELF_TEST
4040 selftests::run_tests (selftest_filters);
4041 #else
4042 printf (_("Selftests have been disabled for this build.\n"));
4043 #endif
4044 throw_quit ("Quit");
4045 }
4046
4047 if (pid == 0 && *next_arg != NULL)
4048 {
4049 int i, n;
4050
4051 n = argc - (next_arg - argv);
4052 program_path.set (next_arg[0]);
4053 for (i = 1; i < n; i++)
4054 program_args.push_back (xstrdup (next_arg[i]));
4055
4056 /* Wait till we are at first instruction in program. */
4057 target_create_inferior (program_path.get (), program_args);
4058
4059 /* We are now (hopefully) stopped at the first instruction of
4060 the target process. This assumes that the target process was
4061 successfully created. */
4062 }
4063 else if (pid != 0)
4064 {
4065 if (attach_inferior (pid) == -1)
4066 error ("Attaching not supported on this target");
4067
4068 /* Otherwise succeeded. */
4069 }
4070 else
4071 {
4072 cs.last_status.set_exited (0);
4073 cs.last_ptid = minus_one_ptid;
4074 }
4075
4076 SCOPE_EXIT { detach_or_kill_for_exit_cleanup (); };
4077
4078 /* Don't report shared library events on the initial connection,
4079 even if some libraries are preloaded. Avoids the "stopped by
4080 shared library event" notice on gdb side. */
4081 if (current_thread != nullptr)
4082 current_process ()->dlls_changed = false;
4083
4084 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4085 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
4086 was_running = 0;
4087 else
4088 was_running = 1;
4089
4090 if (!was_running && !multi_mode)
4091 error ("No program to debug");
4092
4093 while (1)
4094 {
4095 cs.noack_mode = 0;
4096 cs.multi_process = 0;
4097 cs.report_fork_events = 0;
4098 cs.report_vfork_events = 0;
4099 cs.report_exec_events = 0;
4100 /* Be sure we're out of tfind mode. */
4101 cs.current_traceframe = -1;
4102 cs.cont_thread = null_ptid;
4103 cs.swbreak_feature = 0;
4104 cs.hwbreak_feature = 0;
4105 cs.vCont_supported = 0;
4106 cs.memory_tagging_feature = false;
4107
4108 remote_open (port);
4109
4110 try
4111 {
4112 /* Wait for events. This will return when all event sources
4113 are removed from the event loop. */
4114 start_event_loop ();
4115
4116 /* If an exit was requested (using the "monitor exit"
4117 command), terminate now. */
4118 if (exit_requested)
4119 throw_quit ("Quit");
4120
4121 /* The only other way to get here is for getpkt to fail:
4122
4123 - If --once was specified, we're done.
4124
4125 - If not in extended-remote mode, and we're no longer
4126 debugging anything, simply exit: GDB has disconnected
4127 after processing the last process exit.
4128
4129 - Otherwise, close the connection and reopen it at the
4130 top of the loop. */
4131 if (run_once || (!extended_protocol && !target_running ()))
4132 throw_quit ("Quit");
4133
4134 fprintf (stderr,
4135 "Remote side has terminated connection. "
4136 "GDBserver will reopen the connection.\n");
4137
4138 /* Get rid of any pending statuses. An eventual reconnection
4139 (by the same GDB instance or another) will refresh all its
4140 state from scratch. */
4141 discard_queued_stop_replies (minus_one_ptid);
4142 for_each_thread ([] (thread_info *thread)
4143 {
4144 thread->status_pending_p = 0;
4145 });
4146
4147 if (tracing)
4148 {
4149 if (disconnected_tracing)
4150 {
4151 /* Try to enable non-stop/async mode, so we we can
4152 both wait for an async socket accept, and handle
4153 async target events simultaneously. There's also
4154 no point either in having the target always stop
4155 all threads, when we're going to pass signals
4156 down without informing GDB. */
4157 if (!non_stop)
4158 {
4159 if (the_target->start_non_stop (true))
4160 non_stop = 1;
4161
4162 /* Detaching implicitly resumes all threads;
4163 simply disconnecting does not. */
4164 }
4165 }
4166 else
4167 {
4168 fprintf (stderr,
4169 "Disconnected tracing disabled; "
4170 "stopping trace run.\n");
4171 stop_tracing ();
4172 }
4173 }
4174 }
4175 catch (const gdb_exception_error &exception)
4176 {
4177 fflush (stdout);
4178 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4179
4180 if (response_needed)
4181 {
4182 write_enn (cs.own_buf);
4183 putpkt (cs.own_buf);
4184 }
4185
4186 if (run_once)
4187 throw_quit ("Quit");
4188 }
4189 }
4190 }
4191
4192 /* Main function. */
4193
4194 int
4195 main (int argc, char *argv[])
4196 {
4197
4198 try
4199 {
4200 captured_main (argc, argv);
4201 }
4202 catch (const gdb_exception &exception)
4203 {
4204 if (exception.reason == RETURN_ERROR)
4205 {
4206 fflush (stdout);
4207 fprintf (stderr, "%s\n", exception.what ());
4208 fprintf (stderr, "Exiting\n");
4209 exit_code = 1;
4210 }
4211
4212 exit (exit_code);
4213 }
4214
4215 gdb_assert_not_reached ("captured_main should never return");
4216 }
4217
4218 /* Process options coming from Z packets for a breakpoint. PACKET is
4219 the packet buffer. *PACKET is updated to point to the first char
4220 after the last processed option. */
4221
4222 static void
4223 process_point_options (struct gdb_breakpoint *bp, const char **packet)
4224 {
4225 const char *dataptr = *packet;
4226 int persist;
4227
4228 /* Check if data has the correct format. */
4229 if (*dataptr != ';')
4230 return;
4231
4232 dataptr++;
4233
4234 while (*dataptr)
4235 {
4236 if (*dataptr == ';')
4237 ++dataptr;
4238
4239 if (*dataptr == 'X')
4240 {
4241 /* Conditional expression. */
4242 threads_debug_printf ("Found breakpoint condition.");
4243 if (!add_breakpoint_condition (bp, &dataptr))
4244 dataptr = strchrnul (dataptr, ';');
4245 }
4246 else if (startswith (dataptr, "cmds:"))
4247 {
4248 dataptr += strlen ("cmds:");
4249 threads_debug_printf ("Found breakpoint commands %s.", dataptr);
4250 persist = (*dataptr == '1');
4251 dataptr += 2;
4252 if (add_breakpoint_commands (bp, &dataptr, persist))
4253 dataptr = strchrnul (dataptr, ';');
4254 }
4255 else
4256 {
4257 fprintf (stderr, "Unknown token %c, ignoring.\n",
4258 *dataptr);
4259 /* Skip tokens until we find one that we recognize. */
4260 dataptr = strchrnul (dataptr, ';');
4261 }
4262 }
4263 *packet = dataptr;
4264 }
4265
4266 /* Event loop callback that handles a serial event. The first byte in
4267 the serial buffer gets us here. We expect characters to arrive at
4268 a brisk pace, so we read the rest of the packet with a blocking
4269 getpkt call. */
4270
4271 static int
4272 process_serial_event (void)
4273 {
4274 client_state &cs = get_client_state ();
4275 int signal;
4276 unsigned int len;
4277 CORE_ADDR mem_addr;
4278 unsigned char sig;
4279 int packet_len;
4280 int new_packet_len = -1;
4281
4282 disable_async_io ();
4283
4284 response_needed = false;
4285 packet_len = getpkt (cs.own_buf);
4286 if (packet_len <= 0)
4287 {
4288 remote_close ();
4289 /* Force an event loop break. */
4290 return -1;
4291 }
4292 response_needed = true;
4293
4294 char ch = cs.own_buf[0];
4295 switch (ch)
4296 {
4297 case 'q':
4298 handle_query (cs.own_buf, packet_len, &new_packet_len);
4299 break;
4300 case 'Q':
4301 handle_general_set (cs.own_buf);
4302 break;
4303 case 'D':
4304 handle_detach (cs.own_buf);
4305 break;
4306 case '!':
4307 extended_protocol = true;
4308 write_ok (cs.own_buf);
4309 break;
4310 case '?':
4311 handle_status (cs.own_buf);
4312 break;
4313 case 'H':
4314 if (cs.own_buf[1] == 'c' || cs.own_buf[1] == 'g' || cs.own_buf[1] == 's')
4315 {
4316 require_running_or_break (cs.own_buf);
4317
4318 ptid_t thread_id = read_ptid (&cs.own_buf[2], NULL);
4319
4320 if (thread_id == null_ptid || thread_id == minus_one_ptid)
4321 thread_id = null_ptid;
4322 else if (thread_id.is_pid ())
4323 {
4324 /* The ptid represents a pid. */
4325 thread_info *thread = find_any_thread_of_pid (thread_id.pid ());
4326
4327 if (thread == NULL)
4328 {
4329 write_enn (cs.own_buf);
4330 break;
4331 }
4332
4333 thread_id = thread->id;
4334 }
4335 else
4336 {
4337 /* The ptid represents a lwp/tid. */
4338 if (find_thread_ptid (thread_id) == NULL)
4339 {
4340 write_enn (cs.own_buf);
4341 break;
4342 }
4343 }
4344
4345 if (cs.own_buf[1] == 'g')
4346 {
4347 if (thread_id == null_ptid)
4348 {
4349 /* GDB is telling us to choose any thread. Check if
4350 the currently selected thread is still valid. If
4351 it is not, select the first available. */
4352 thread_info *thread = find_thread_ptid (cs.general_thread);
4353 if (thread == NULL)
4354 thread = get_first_thread ();
4355 thread_id = thread->id;
4356 }
4357
4358 cs.general_thread = thread_id;
4359 set_desired_thread ();
4360 gdb_assert (current_thread != NULL);
4361 }
4362 else if (cs.own_buf[1] == 'c')
4363 cs.cont_thread = thread_id;
4364
4365 write_ok (cs.own_buf);
4366 }
4367 else
4368 {
4369 /* Silently ignore it so that gdb can extend the protocol
4370 without compatibility headaches. */
4371 cs.own_buf[0] = '\0';
4372 }
4373 break;
4374 case 'g':
4375 require_running_or_break (cs.own_buf);
4376 if (cs.current_traceframe >= 0)
4377 {
4378 struct regcache *regcache
4379 = new_register_cache (current_target_desc ());
4380
4381 if (fetch_traceframe_registers (cs.current_traceframe,
4382 regcache, -1) == 0)
4383 registers_to_string (regcache, cs.own_buf);
4384 else
4385 write_enn (cs.own_buf);
4386 free_register_cache (regcache);
4387 }
4388 else
4389 {
4390 struct regcache *regcache;
4391
4392 if (!set_desired_thread ())
4393 write_enn (cs.own_buf);
4394 else
4395 {
4396 regcache = get_thread_regcache (current_thread, 1);
4397 registers_to_string (regcache, cs.own_buf);
4398 }
4399 }
4400 break;
4401 case 'G':
4402 require_running_or_break (cs.own_buf);
4403 if (cs.current_traceframe >= 0)
4404 write_enn (cs.own_buf);
4405 else
4406 {
4407 struct regcache *regcache;
4408
4409 if (!set_desired_thread ())
4410 write_enn (cs.own_buf);
4411 else
4412 {
4413 regcache = get_thread_regcache (current_thread, 1);
4414 registers_from_string (regcache, &cs.own_buf[1]);
4415 write_ok (cs.own_buf);
4416 }
4417 }
4418 break;
4419 case 'm':
4420 {
4421 require_running_or_break (cs.own_buf);
4422 decode_m_packet (&cs.own_buf[1], &mem_addr, &len);
4423 int res = gdb_read_memory (mem_addr, mem_buf, len);
4424 if (res < 0)
4425 write_enn (cs.own_buf);
4426 else
4427 bin2hex (mem_buf, cs.own_buf, res);
4428 }
4429 break;
4430 case 'M':
4431 require_running_or_break (cs.own_buf);
4432 decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf);
4433 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
4434 write_ok (cs.own_buf);
4435 else
4436 write_enn (cs.own_buf);
4437 break;
4438 case 'X':
4439 require_running_or_break (cs.own_buf);
4440 if (decode_X_packet (&cs.own_buf[1], packet_len - 1,
4441 &mem_addr, &len, &mem_buf) < 0
4442 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
4443 write_enn (cs.own_buf);
4444 else
4445 write_ok (cs.own_buf);
4446 break;
4447 case 'C':
4448 require_running_or_break (cs.own_buf);
4449 hex2bin (cs.own_buf + 1, &sig, 1);
4450 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4451 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4452 else
4453 signal = 0;
4454 myresume (cs.own_buf, 0, signal);
4455 break;
4456 case 'S':
4457 require_running_or_break (cs.own_buf);
4458 hex2bin (cs.own_buf + 1, &sig, 1);
4459 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4460 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4461 else
4462 signal = 0;
4463 myresume (cs.own_buf, 1, signal);
4464 break;
4465 case 'c':
4466 require_running_or_break (cs.own_buf);
4467 signal = 0;
4468 myresume (cs.own_buf, 0, signal);
4469 break;
4470 case 's':
4471 require_running_or_break (cs.own_buf);
4472 signal = 0;
4473 myresume (cs.own_buf, 1, signal);
4474 break;
4475 case 'Z': /* insert_ ... */
4476 /* Fallthrough. */
4477 case 'z': /* remove_ ... */
4478 {
4479 char *dataptr;
4480 ULONGEST addr;
4481 int kind;
4482 char type = cs.own_buf[1];
4483 int res;
4484 const int insert = ch == 'Z';
4485 const char *p = &cs.own_buf[3];
4486
4487 p = unpack_varlen_hex (p, &addr);
4488 kind = strtol (p + 1, &dataptr, 16);
4489
4490 if (insert)
4491 {
4492 struct gdb_breakpoint *bp;
4493
4494 bp = set_gdb_breakpoint (type, addr, kind, &res);
4495 if (bp != NULL)
4496 {
4497 res = 0;
4498
4499 /* GDB may have sent us a list of *point parameters to
4500 be evaluated on the target's side. Read such list
4501 here. If we already have a list of parameters, GDB
4502 is telling us to drop that list and use this one
4503 instead. */
4504 clear_breakpoint_conditions_and_commands (bp);
4505 const char *options = dataptr;
4506 process_point_options (bp, &options);
4507 }
4508 }
4509 else
4510 res = delete_gdb_breakpoint (type, addr, kind);
4511
4512 if (res == 0)
4513 write_ok (cs.own_buf);
4514 else if (res == 1)
4515 /* Unsupported. */
4516 cs.own_buf[0] = '\0';
4517 else
4518 write_enn (cs.own_buf);
4519 break;
4520 }
4521 case 'k':
4522 response_needed = false;
4523 if (!target_running ())
4524 /* The packet we received doesn't make sense - but we can't
4525 reply to it, either. */
4526 return 0;
4527
4528 fprintf (stderr, "Killing all inferiors\n");
4529
4530 for_each_process (kill_inferior_callback);
4531
4532 /* When using the extended protocol, we wait with no program
4533 running. The traditional protocol will exit instead. */
4534 if (extended_protocol)
4535 {
4536 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4537 return 0;
4538 }
4539 else
4540 exit (0);
4541
4542 case 'T':
4543 {
4544 require_running_or_break (cs.own_buf);
4545
4546 ptid_t thread_id = read_ptid (&cs.own_buf[1], NULL);
4547 if (find_thread_ptid (thread_id) == NULL)
4548 {
4549 write_enn (cs.own_buf);
4550 break;
4551 }
4552
4553 if (mythread_alive (thread_id))
4554 write_ok (cs.own_buf);
4555 else
4556 write_enn (cs.own_buf);
4557 }
4558 break;
4559 case 'R':
4560 response_needed = false;
4561
4562 /* Restarting the inferior is only supported in the extended
4563 protocol. */
4564 if (extended_protocol)
4565 {
4566 if (target_running ())
4567 for_each_process (kill_inferior_callback);
4568
4569 fprintf (stderr, "GDBserver restarting\n");
4570
4571 /* Wait till we are at 1st instruction in prog. */
4572 if (program_path.get () != NULL)
4573 {
4574 target_create_inferior (program_path.get (), program_args);
4575
4576 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
4577 {
4578 /* Stopped at the first instruction of the target
4579 process. */
4580 cs.general_thread = cs.last_ptid;
4581 }
4582 else
4583 {
4584 /* Something went wrong. */
4585 cs.general_thread = null_ptid;
4586 }
4587 }
4588 else
4589 {
4590 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4591 }
4592 return 0;
4593 }
4594 else
4595 {
4596 /* It is a request we don't understand. Respond with an
4597 empty packet so that gdb knows that we don't support this
4598 request. */
4599 cs.own_buf[0] = '\0';
4600 break;
4601 }
4602 case 'v':
4603 /* Extended (long) request. */
4604 handle_v_requests (cs.own_buf, packet_len, &new_packet_len);
4605 break;
4606
4607 default:
4608 /* It is a request we don't understand. Respond with an empty
4609 packet so that gdb knows that we don't support this
4610 request. */
4611 cs.own_buf[0] = '\0';
4612 break;
4613 }
4614
4615 if (new_packet_len != -1)
4616 putpkt_binary (cs.own_buf, new_packet_len);
4617 else
4618 putpkt (cs.own_buf);
4619
4620 response_needed = false;
4621
4622 if (exit_requested)
4623 return -1;
4624
4625 return 0;
4626 }
4627
4628 /* Event-loop callback for serial events. */
4629
4630 void
4631 handle_serial_event (int err, gdb_client_data client_data)
4632 {
4633 threads_debug_printf ("handling possible serial event");
4634
4635 /* Really handle it. */
4636 if (process_serial_event () < 0)
4637 {
4638 keep_processing_events = false;
4639 return;
4640 }
4641
4642 /* Be sure to not change the selected thread behind GDB's back.
4643 Important in the non-stop mode asynchronous protocol. */
4644 set_desired_thread ();
4645 }
4646
4647 /* Push a stop notification on the notification queue. */
4648
4649 static void
4650 push_stop_notification (ptid_t ptid, const target_waitstatus &status)
4651 {
4652 struct vstop_notif *vstop_notif = new struct vstop_notif;
4653
4654 vstop_notif->status = status;
4655 vstop_notif->ptid = ptid;
4656 /* Push Stop notification. */
4657 notif_push (&notif_stop, vstop_notif);
4658 }
4659
4660 /* Event-loop callback for target events. */
4661
4662 void
4663 handle_target_event (int err, gdb_client_data client_data)
4664 {
4665 client_state &cs = get_client_state ();
4666 threads_debug_printf ("handling possible target event");
4667
4668 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status,
4669 TARGET_WNOHANG, 1);
4670
4671 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED)
4672 {
4673 if (gdb_connected () && report_no_resumed)
4674 push_stop_notification (null_ptid, cs.last_status);
4675 }
4676 else if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE)
4677 {
4678 int pid = cs.last_ptid.pid ();
4679 struct process_info *process = find_process_pid (pid);
4680 int forward_event = !gdb_connected () || process->gdb_detached;
4681
4682 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4683 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
4684 {
4685 mark_breakpoints_out (process);
4686 target_mourn_inferior (cs.last_ptid);
4687 }
4688 else if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
4689 ;
4690 else
4691 {
4692 /* We're reporting this thread as stopped. Update its
4693 "want-stopped" state to what the client wants, until it
4694 gets a new resume action. */
4695 current_thread->last_resume_kind = resume_stop;
4696 current_thread->last_status = cs.last_status;
4697 }
4698
4699 if (forward_event)
4700 {
4701 if (!target_running ())
4702 {
4703 /* The last process exited. We're done. */
4704 exit (0);
4705 }
4706
4707 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4708 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED
4709 || cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
4710 ;
4711 else
4712 {
4713 /* A thread stopped with a signal, but gdb isn't
4714 connected to handle it. Pass it down to the
4715 inferior, as if it wasn't being traced. */
4716 enum gdb_signal signal;
4717
4718 threads_debug_printf ("GDB not connected; forwarding event %d for"
4719 " [%s]",
4720 (int) cs.last_status.kind (),
4721 target_pid_to_str (cs.last_ptid).c_str ());
4722
4723 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
4724 signal = cs.last_status.sig ();
4725 else
4726 signal = GDB_SIGNAL_0;
4727 target_continue (cs.last_ptid, signal);
4728 }
4729 }
4730 else
4731 push_stop_notification (cs.last_ptid, cs.last_status);
4732 }
4733
4734 /* Be sure to not change the selected thread behind GDB's back.
4735 Important in the non-stop mode asynchronous protocol. */
4736 set_desired_thread ();
4737 }
4738
4739 /* See gdbsupport/event-loop.h. */
4740
4741 int
4742 invoke_async_signal_handlers ()
4743 {
4744 return 0;
4745 }
4746
4747 /* See gdbsupport/event-loop.h. */
4748
4749 int
4750 check_async_event_handlers ()
4751 {
4752 return 0;
4753 }
4754
4755 /* See gdbsupport/errors.h */
4756
4757 void
4758 flush_streams ()
4759 {
4760 fflush (stdout);
4761 fflush (stderr);
4762 }
4763
4764 /* See gdbsupport/gdb_select.h. */
4765
4766 int
4767 gdb_select (int n, fd_set *readfds, fd_set *writefds,
4768 fd_set *exceptfds, struct timeval *timeout)
4769 {
4770 return select (n, readfds, writefds, exceptfds, timeout);
4771 }
4772
4773 #if GDB_SELF_TEST
4774 namespace selftests
4775 {
4776
4777 void
4778 reset ()
4779 {}
4780
4781 } // namespace selftests
4782 #endif /* GDB_SELF_TEST */