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