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