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