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