OSDN Git Service

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