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