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