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