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