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