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