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