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