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