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