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