* linux-low.c (linux_kill_one_lwp): Assume the lwp is stopped.
[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_running () && the_target->look_up_symbols != NULL)
924         (*the_target->look_up_symbols) ();
925
926       strcpy (own_buf, "OK");
927       return;
928     }
929
930   if (!disable_packet_qfThreadInfo)
931     {
932       if (strcmp ("qfThreadInfo", own_buf) == 0)
933         {
934           ptid_t gdb_id;
935
936           require_running (own_buf);
937           thread_ptr = all_threads.head;
938
939           *own_buf++ = 'm';
940           gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
941           write_ptid (own_buf, gdb_id);
942           thread_ptr = thread_ptr->next;
943           return;
944         }
945
946       if (strcmp ("qsThreadInfo", own_buf) == 0)
947         {
948           ptid_t gdb_id;
949
950           require_running (own_buf);
951           if (thread_ptr != NULL)
952             {
953               *own_buf++ = 'm';
954               gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
955               write_ptid (own_buf, gdb_id);
956               thread_ptr = thread_ptr->next;
957               return;
958             }
959           else
960             {
961               sprintf (own_buf, "l");
962               return;
963             }
964         }
965     }
966
967   if (the_target->read_offsets != NULL
968       && strcmp ("qOffsets", own_buf) == 0)
969     {
970       CORE_ADDR text, data;
971
972       require_running (own_buf);
973       if (the_target->read_offsets (&text, &data))
974         sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
975                  (long)text, (long)data, (long)data);
976       else
977         write_enn (own_buf);
978
979       return;
980     }
981
982   if (the_target->qxfer_spu != NULL
983       && strncmp ("qXfer:spu:read:", own_buf, 15) == 0)
984     {
985       char *annex;
986       int n;
987       unsigned int len;
988       CORE_ADDR ofs;
989       unsigned char *spu_buf;
990
991       require_running (own_buf);
992       strcpy (own_buf, "E00");
993       if (decode_xfer_read (own_buf + 15, &annex, &ofs, &len) < 0)
994         return;
995       if (len > PBUFSIZ - 2)
996         len = PBUFSIZ - 2;
997       spu_buf = malloc (len + 1);
998       if (!spu_buf)
999         return;
1000
1001       n = (*the_target->qxfer_spu) (annex, spu_buf, NULL, ofs, len + 1);
1002       if (n < 0)
1003         write_enn (own_buf);
1004       else if (n > len)
1005         *new_packet_len_p = write_qxfer_response (own_buf, spu_buf, len, 1);
1006       else
1007         *new_packet_len_p = write_qxfer_response (own_buf, spu_buf, n, 0);
1008
1009       free (spu_buf);
1010       return;
1011     }
1012
1013   if (the_target->qxfer_spu != NULL
1014       && strncmp ("qXfer:spu:write:", own_buf, 16) == 0)
1015     {
1016       char *annex;
1017       int n;
1018       unsigned int len;
1019       CORE_ADDR ofs;
1020       unsigned char *spu_buf;
1021
1022       require_running (own_buf);
1023       strcpy (own_buf, "E00");
1024       spu_buf = malloc (packet_len - 15);
1025       if (!spu_buf)
1026         return;
1027       if (decode_xfer_write (own_buf + 16, packet_len - 16, &annex,
1028                              &ofs, &len, spu_buf) < 0)
1029         {
1030           free (spu_buf);
1031           return;
1032         }
1033
1034       n = (*the_target->qxfer_spu)
1035         (annex, NULL, (unsigned const char *)spu_buf, ofs, len);
1036       if (n < 0)
1037         write_enn (own_buf);
1038       else
1039         sprintf (own_buf, "%x", n);
1040
1041       free (spu_buf);
1042       return;
1043     }
1044
1045   if (the_target->read_auxv != NULL
1046       && strncmp ("qXfer:auxv:read:", own_buf, 16) == 0)
1047     {
1048       unsigned char *data;
1049       int n;
1050       CORE_ADDR ofs;
1051       unsigned int len;
1052       char *annex;
1053
1054       require_running (own_buf);
1055
1056       /* Reject any annex; grab the offset and length.  */
1057       if (decode_xfer_read (own_buf + 16, &annex, &ofs, &len) < 0
1058           || annex[0] != '\0')
1059         {
1060           strcpy (own_buf, "E00");
1061           return;
1062         }
1063
1064       /* Read one extra byte, as an indicator of whether there is
1065          more.  */
1066       if (len > PBUFSIZ - 2)
1067         len = PBUFSIZ - 2;
1068       data = malloc (len + 1);
1069       if (data == NULL)
1070         {
1071           write_enn (own_buf);
1072           return;
1073         }
1074       n = (*the_target->read_auxv) (ofs, data, len + 1);
1075       if (n < 0)
1076         write_enn (own_buf);
1077       else if (n > len)
1078         *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
1079       else
1080         *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
1081
1082       free (data);
1083
1084       return;
1085     }
1086
1087   if (strncmp ("qXfer:features:read:", own_buf, 20) == 0)
1088     {
1089       CORE_ADDR ofs;
1090       unsigned int len, total_len;
1091       const char *document;
1092       char *annex;
1093
1094       require_running (own_buf);
1095
1096       /* Grab the annex, offset, and length.  */
1097       if (decode_xfer_read (own_buf + 20, &annex, &ofs, &len) < 0)
1098         {
1099           strcpy (own_buf, "E00");
1100           return;
1101         }
1102
1103       /* Now grab the correct annex.  */
1104       document = get_features_xml (annex);
1105       if (document == NULL)
1106         {
1107           strcpy (own_buf, "E00");
1108           return;
1109         }
1110
1111       total_len = strlen (document);
1112       if (len > PBUFSIZ - 2)
1113         len = PBUFSIZ - 2;
1114
1115       if (ofs > total_len)
1116         write_enn (own_buf);
1117       else if (len < total_len - ofs)
1118         *new_packet_len_p = write_qxfer_response (own_buf, document + ofs,
1119                                                   len, 1);
1120       else
1121         *new_packet_len_p = write_qxfer_response (own_buf, document + ofs,
1122                                                   total_len - ofs, 0);
1123
1124       return;
1125     }
1126
1127   if (strncmp ("qXfer:libraries:read:", own_buf, 21) == 0)
1128     {
1129       CORE_ADDR ofs;
1130       unsigned int len, total_len;
1131       char *document, *p;
1132       struct inferior_list_entry *dll_ptr;
1133       char *annex;
1134
1135       require_running (own_buf);
1136
1137       /* Reject any annex; grab the offset and length.  */
1138       if (decode_xfer_read (own_buf + 21, &annex, &ofs, &len) < 0
1139           || annex[0] != '\0')
1140         {
1141           strcpy (own_buf, "E00");
1142           return;
1143         }
1144
1145       /* Over-estimate the necessary memory.  Assume that every character
1146          in the library name must be escaped.  */
1147       total_len = 64;
1148       for (dll_ptr = all_dlls.head; dll_ptr != NULL; dll_ptr = dll_ptr->next)
1149         total_len += 128 + 6 * strlen (((struct dll_info *) dll_ptr)->name);
1150
1151       document = malloc (total_len);
1152       if (document == NULL)
1153         {
1154           write_enn (own_buf);
1155           return;
1156         }
1157       strcpy (document, "<library-list>\n");
1158       p = document + strlen (document);
1159
1160       for (dll_ptr = all_dlls.head; dll_ptr != NULL; dll_ptr = dll_ptr->next)
1161         {
1162           struct dll_info *dll = (struct dll_info *) dll_ptr;
1163           char *name;
1164
1165           strcpy (p, "  <library name=\"");
1166           p = p + strlen (p);
1167           name = xml_escape_text (dll->name);
1168           strcpy (p, name);
1169           free (name);
1170           p = p + strlen (p);
1171           strcpy (p, "\"><segment address=\"");
1172           p = p + strlen (p);
1173           sprintf (p, "0x%lx", (long) dll->base_addr);
1174           p = p + strlen (p);
1175           strcpy (p, "\"/></library>\n");
1176           p = p + strlen (p);
1177         }
1178
1179       strcpy (p, "</library-list>\n");
1180
1181       total_len = strlen (document);
1182       if (len > PBUFSIZ - 2)
1183         len = PBUFSIZ - 2;
1184
1185       if (ofs > total_len)
1186         write_enn (own_buf);
1187       else if (len < total_len - ofs)
1188         *new_packet_len_p = write_qxfer_response (own_buf, document + ofs,
1189                                                   len, 1);
1190       else
1191         *new_packet_len_p = write_qxfer_response (own_buf, document + ofs,
1192                                                   total_len - ofs, 0);
1193
1194       free (document);
1195       return;
1196     }
1197
1198   if (the_target->qxfer_osdata != NULL
1199       && strncmp ("qXfer:osdata:read:", own_buf, 18) == 0)
1200     {
1201       char *annex;
1202       int n;
1203       unsigned int len;
1204       CORE_ADDR ofs;
1205       unsigned char *workbuf;
1206
1207       strcpy (own_buf, "E00");
1208       if (decode_xfer_read (own_buf + 18, &annex, &ofs, &len) < 0)
1209         return;
1210       if (len > PBUFSIZ - 2)
1211         len = PBUFSIZ - 2;
1212       workbuf = malloc (len + 1);
1213       if (!workbuf)
1214         return;
1215
1216       n = (*the_target->qxfer_osdata) (annex, workbuf, NULL, ofs, len + 1);
1217       if (n < 0)
1218         write_enn (own_buf);
1219       else if (n > len)
1220         *new_packet_len_p = write_qxfer_response (own_buf, workbuf, len, 1);
1221       else
1222         *new_packet_len_p = write_qxfer_response (own_buf, workbuf, n, 0);
1223
1224       free (workbuf);
1225       return;
1226     }
1227
1228   if (the_target->qxfer_siginfo != NULL
1229       && strncmp ("qXfer:siginfo:read:", own_buf, 19) == 0)
1230     {
1231       unsigned char *data;
1232       int n;
1233       CORE_ADDR ofs;
1234       unsigned int len;
1235       char *annex;
1236
1237       require_running (own_buf);
1238
1239       /* Reject any annex; grab the offset and length.  */
1240       if (decode_xfer_read (own_buf + 19, &annex, &ofs, &len) < 0
1241           || annex[0] != '\0')
1242         {
1243           strcpy (own_buf, "E00");
1244           return;
1245         }
1246
1247       /* Read one extra byte, as an indicator of whether there is
1248          more.  */
1249       if (len > PBUFSIZ - 2)
1250         len = PBUFSIZ - 2;
1251       data = malloc (len + 1);
1252       if (!data)
1253         return;
1254       n = (*the_target->qxfer_siginfo) (annex, data, NULL, ofs, len + 1);
1255       if (n < 0)
1256         write_enn (own_buf);
1257       else if (n > len)
1258         *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
1259       else
1260         *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
1261
1262       free (data);
1263       return;
1264     }
1265
1266   if (the_target->qxfer_siginfo != NULL
1267       && strncmp ("qXfer:siginfo:write:", own_buf, 20) == 0)
1268     {
1269       char *annex;
1270       int n;
1271       unsigned int len;
1272       CORE_ADDR ofs;
1273       unsigned char *data;
1274
1275       require_running (own_buf);
1276
1277       strcpy (own_buf, "E00");
1278       data = malloc (packet_len - 19);
1279       if (!data)
1280         return;
1281       if (decode_xfer_write (own_buf + 20, packet_len - 20, &annex,
1282                              &ofs, &len, data) < 0)
1283         {
1284           free (data);
1285           return;
1286         }
1287
1288       n = (*the_target->qxfer_siginfo)
1289         (annex, NULL, (unsigned const char *)data, ofs, len);
1290       if (n < 0)
1291         write_enn (own_buf);
1292       else
1293         sprintf (own_buf, "%x", n);
1294
1295       free (data);
1296       return;
1297     }
1298
1299   if (strncmp ("qXfer:threads:read:", own_buf, 19) == 0)
1300     {
1301       unsigned char *data;
1302       int n;
1303       CORE_ADDR ofs;
1304       unsigned int len;
1305       char *annex;
1306
1307       require_running (own_buf);
1308
1309       /* Reject any annex; grab the offset and length.  */
1310       if (decode_xfer_read (own_buf + 19, &annex, &ofs, &len) < 0
1311           || annex[0] != '\0')
1312         {
1313           strcpy (own_buf, "E00");
1314           return;
1315         }
1316
1317       /* Read one extra byte, as an indicator of whether there is
1318          more.  */
1319       if (len > PBUFSIZ - 2)
1320         len = PBUFSIZ - 2;
1321       data = malloc (len + 1);
1322       if (!data)
1323         return;
1324       n = handle_threads_qxfer (annex, data, ofs, len + 1);
1325       if (n < 0)
1326         write_enn (own_buf);
1327       else if (n > len)
1328         *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
1329       else
1330         *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
1331
1332       free (data);
1333       return;
1334     }
1335
1336   /* Protocol features query.  */
1337   if (strncmp ("qSupported", own_buf, 10) == 0
1338       && (own_buf[10] == ':' || own_buf[10] == '\0'))
1339     {
1340       char *p = &own_buf[10];
1341
1342       /* Start processing qSupported packet.  */
1343       target_process_qsupported (NULL);
1344
1345       /* Process each feature being provided by GDB.  The first
1346          feature will follow a ':', and latter features will follow
1347          ';'.  */
1348       if (*p == ':')
1349         for (p = strtok (p + 1, ";");
1350              p != NULL;
1351              p = strtok (NULL, ";"))
1352           {
1353             if (strcmp (p, "multiprocess+") == 0)
1354               {
1355                 /* GDB supports and wants multi-process support if
1356                    possible.  */
1357                 if (target_supports_multi_process ())
1358                   multi_process = 1;
1359               }
1360             else
1361               target_process_qsupported (p);
1362           }
1363
1364       sprintf (own_buf, "PacketSize=%x;QPassSignals+", PBUFSIZ - 1);
1365
1366       /* We do not have any hook to indicate whether the target backend
1367          supports qXfer:libraries:read, so always report it.  */
1368       strcat (own_buf, ";qXfer:libraries:read+");
1369
1370       if (the_target->read_auxv != NULL)
1371         strcat (own_buf, ";qXfer:auxv:read+");
1372
1373       if (the_target->qxfer_spu != NULL)
1374         strcat (own_buf, ";qXfer:spu:read+;qXfer:spu:write+");
1375
1376       if (the_target->qxfer_siginfo != NULL)
1377         strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
1378
1379       /* We always report qXfer:features:read, as targets may
1380          install XML files on a subsequent call to arch_setup.
1381          If we reported to GDB on startup that we don't support
1382          qXfer:feature:read at all, we will never be re-queried.  */
1383       strcat (own_buf, ";qXfer:features:read+");
1384
1385       if (transport_is_reliable)
1386         strcat (own_buf, ";QStartNoAckMode+");
1387
1388       if (the_target->qxfer_osdata != NULL)
1389         strcat (own_buf, ";qXfer:osdata:read+");
1390
1391       if (target_supports_multi_process ())
1392         strcat (own_buf, ";multiprocess+");
1393
1394       if (target_supports_non_stop ())
1395         strcat (own_buf, ";QNonStop+");
1396
1397       strcat (own_buf, ";qXfer:threads:read+");
1398
1399       if (target_supports_tracepoints ())
1400         {
1401           strcat (own_buf, ";ConditionalTracepoints+");
1402           strcat (own_buf, ";TraceStateVariables+");
1403           strcat (own_buf, ";TracepointSource+");
1404           strcat (own_buf, ";DisconnectedTracing+");
1405         }
1406
1407       return;
1408     }
1409
1410   /* Thread-local storage support.  */
1411   if (the_target->get_tls_address != NULL
1412       && strncmp ("qGetTLSAddr:", own_buf, 12) == 0)
1413     {
1414       char *p = own_buf + 12;
1415       CORE_ADDR parts[2], address = 0;
1416       int i, err;
1417       ptid_t ptid = null_ptid;
1418
1419       require_running (own_buf);
1420
1421       for (i = 0; i < 3; i++)
1422         {
1423           char *p2;
1424           int len;
1425
1426           if (p == NULL)
1427             break;
1428
1429           p2 = strchr (p, ',');
1430           if (p2)
1431             {
1432               len = p2 - p;
1433               p2++;
1434             }
1435           else
1436             {
1437               len = strlen (p);
1438               p2 = NULL;
1439             }
1440
1441           if (i == 0)
1442             ptid = read_ptid (p, NULL);
1443           else
1444             decode_address (&parts[i - 1], p, len);
1445           p = p2;
1446         }
1447
1448       if (p != NULL || i < 3)
1449         err = 1;
1450       else
1451         {
1452           struct thread_info *thread = find_thread_ptid (ptid);
1453
1454           if (thread == NULL)
1455             err = 2;
1456           else
1457             err = the_target->get_tls_address (thread, parts[0], parts[1],
1458                                                &address);
1459         }
1460
1461       if (err == 0)
1462         {
1463           sprintf (own_buf, "%llx", address);
1464           return;
1465         }
1466       else if (err > 0)
1467         {
1468           write_enn (own_buf);
1469           return;
1470         }
1471
1472       /* Otherwise, pretend we do not understand this packet.  */
1473     }
1474
1475   /* Windows OS Thread Information Block address support.  */
1476   if (the_target->get_tib_address != NULL
1477       && strncmp ("qGetTIBAddr:", own_buf, 12) == 0)
1478     {
1479       char *annex;
1480       int n;
1481       CORE_ADDR tlb;
1482       ptid_t ptid = read_ptid (own_buf + 12, &annex);
1483
1484       n = (*the_target->get_tib_address) (ptid, &tlb);
1485       if (n == 1)
1486         {
1487           sprintf (own_buf, "%llx", tlb);
1488           return;
1489         }
1490       else if (n == 0)
1491         {
1492           write_enn (own_buf);
1493           return;
1494         }
1495       return;
1496     }
1497
1498   /* Handle "monitor" commands.  */
1499   if (strncmp ("qRcmd,", own_buf, 6) == 0)
1500     {
1501       char *mon = malloc (PBUFSIZ);
1502       int len = strlen (own_buf + 6);
1503
1504       if (mon == NULL)
1505         {
1506           write_enn (own_buf);
1507           return;
1508         }
1509
1510       if ((len % 2) != 0 || unhexify (mon, own_buf + 6, len / 2) != len / 2)
1511         {
1512           write_enn (own_buf);
1513           free (mon);
1514           return;
1515         }
1516       mon[len / 2] = '\0';
1517
1518       write_ok (own_buf);
1519
1520       if (the_target->handle_monitor_command == NULL
1521           || (*the_target->handle_monitor_command) (mon) == 0)
1522         /* Default processing.  */
1523         handle_monitor_command (mon);
1524
1525       free (mon);
1526       return;
1527     }
1528
1529   if (strncmp ("qSearch:memory:", own_buf, sizeof ("qSearch:memory:") - 1) == 0)
1530     {
1531       require_running (own_buf);
1532       handle_search_memory (own_buf, packet_len);
1533       return;
1534     }
1535
1536   if (strcmp (own_buf, "qAttached") == 0
1537       || strncmp (own_buf, "qAttached:", sizeof ("qAttached:") - 1) == 0)
1538     {
1539       struct process_info *process;
1540
1541       if (own_buf[sizeof ("qAttached") - 1])
1542         {
1543           int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
1544           process = (struct process_info *)
1545             find_inferior_id (&all_processes, pid_to_ptid (pid));
1546         }
1547       else
1548         {
1549           require_running (own_buf);
1550           process = current_process ();
1551         }
1552
1553       if (process == NULL)
1554         {
1555           write_enn (own_buf);
1556           return;
1557         }
1558
1559       strcpy (own_buf, process->attached ? "1" : "0");
1560       return;
1561     }
1562
1563   if (strncmp ("qCRC:", own_buf, 5) == 0)
1564     {
1565       /* CRC check (compare-section).  */
1566       char *comma;
1567       CORE_ADDR base;
1568       int len;
1569       unsigned long long crc;
1570
1571       require_running (own_buf);
1572       base = strtoul (own_buf + 5, &comma, 16);
1573       if (*comma++ != ',')
1574         {
1575           write_enn (own_buf);
1576           return;
1577         }
1578       len = strtoul (comma, NULL, 16);
1579       crc = crc32 (base, len, 0xffffffff);
1580       /* Check for memory failure.  */
1581       if (crc == (unsigned long long) -1)
1582         {
1583           write_enn (own_buf);
1584           return;
1585         }
1586       sprintf (own_buf, "C%lx", (unsigned long) crc);
1587       return;
1588     }
1589
1590   if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
1591     return;
1592
1593   /* Otherwise we didn't know what packet it was.  Say we didn't
1594      understand it.  */
1595   own_buf[0] = 0;
1596 }
1597
1598 /* Parse vCont packets.  */
1599 void
1600 handle_v_cont (char *own_buf)
1601 {
1602   char *p, *q;
1603   int n = 0, i = 0;
1604   struct thread_resume *resume_info;
1605   struct thread_resume default_action = {{0}};
1606
1607   /* Count the number of semicolons in the packet.  There should be one
1608      for every action.  */
1609   p = &own_buf[5];
1610   while (p)
1611     {
1612       n++;
1613       p++;
1614       p = strchr (p, ';');
1615     }
1616
1617   resume_info = malloc (n * sizeof (resume_info[0]));
1618   if (resume_info == NULL)
1619     goto err;
1620
1621   p = &own_buf[5];
1622   while (*p)
1623     {
1624       p++;
1625
1626       if (p[0] == 's' || p[0] == 'S')
1627         resume_info[i].kind = resume_step;
1628       else if (p[0] == 'c' || p[0] == 'C')
1629         resume_info[i].kind = resume_continue;
1630       else if (p[0] == 't')
1631         resume_info[i].kind = resume_stop;
1632       else
1633         goto err;
1634
1635       if (p[0] == 'S' || p[0] == 'C')
1636         {
1637           int sig;
1638           sig = strtol (p + 1, &q, 16);
1639           if (p == q)
1640             goto err;
1641           p = q;
1642
1643           if (!target_signal_to_host_p (sig))
1644             goto err;
1645           resume_info[i].sig = target_signal_to_host (sig);
1646         }
1647       else
1648         {
1649           resume_info[i].sig = 0;
1650           p = p + 1;
1651         }
1652
1653       if (p[0] == 0)
1654         {
1655           resume_info[i].thread = minus_one_ptid;
1656           default_action = resume_info[i];
1657
1658           /* Note: we don't increment i here, we'll overwrite this entry
1659              the next time through.  */
1660         }
1661       else if (p[0] == ':')
1662         {
1663           ptid_t ptid = read_ptid (p + 1, &q);
1664
1665           if (p == q)
1666             goto err;
1667           p = q;
1668           if (p[0] != ';' && p[0] != 0)
1669             goto err;
1670
1671           resume_info[i].thread = ptid;
1672
1673           i++;
1674         }
1675     }
1676
1677   if (i < n)
1678     resume_info[i] = default_action;
1679
1680   /* Still used in occasional places in the backend.  */
1681   if (n == 1
1682       && !ptid_equal (resume_info[0].thread, minus_one_ptid)
1683       && resume_info[0].kind != resume_stop)
1684     cont_thread = resume_info[0].thread;
1685   else
1686     cont_thread = minus_one_ptid;
1687   set_desired_inferior (0);
1688
1689   if (!non_stop)
1690     enable_async_io ();
1691
1692   (*the_target->resume) (resume_info, n);
1693
1694   free (resume_info);
1695
1696   if (non_stop)
1697     write_ok (own_buf);
1698   else
1699     {
1700       last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);
1701       prepare_resume_reply (own_buf, last_ptid, &last_status);
1702       disable_async_io ();
1703     }
1704   return;
1705
1706 err:
1707   write_enn (own_buf);
1708   free (resume_info);
1709   return;
1710 }
1711
1712 /* Attach to a new program.  Return 1 if successful, 0 if failure.  */
1713 int
1714 handle_v_attach (char *own_buf)
1715 {
1716   int pid;
1717
1718   pid = strtol (own_buf + 8, NULL, 16);
1719   if (pid != 0 && attach_inferior (pid) == 0)
1720     {
1721       /* Don't report shared library events after attaching, even if
1722          some libraries are preloaded.  GDB will always poll the
1723          library list.  Avoids the "stopped by shared library event"
1724          notice on the GDB side.  */
1725       dlls_changed = 0;
1726
1727       if (non_stop)
1728         {
1729           /* In non-stop, we don't send a resume reply.  Stop events
1730              will follow up using the normal notification
1731              mechanism.  */
1732           write_ok (own_buf);
1733         }
1734       else
1735         prepare_resume_reply (own_buf, last_ptid, &last_status);
1736
1737       return 1;
1738     }
1739   else
1740     {
1741       write_enn (own_buf);
1742       return 0;
1743     }
1744 }
1745
1746 /* Run a new program.  Return 1 if successful, 0 if failure.  */
1747 static int
1748 handle_v_run (char *own_buf)
1749 {
1750   char *p, *next_p, **new_argv;
1751   int i, new_argc;
1752
1753   new_argc = 0;
1754   for (p = own_buf + strlen ("vRun;"); p && *p; p = strchr (p, ';'))
1755     {
1756       p++;
1757       new_argc++;
1758     }
1759
1760   new_argv = calloc (new_argc + 2, sizeof (char *));
1761   if (new_argv == NULL)
1762     {
1763       write_enn (own_buf);
1764       return 0;
1765     }
1766
1767   i = 0;
1768   for (p = own_buf + strlen ("vRun;"); *p; p = next_p)
1769     {
1770       next_p = strchr (p, ';');
1771       if (next_p == NULL)
1772         next_p = p + strlen (p);
1773
1774       if (i == 0 && p == next_p)
1775         new_argv[i] = NULL;
1776       else
1777         {
1778           /* FIXME: Fail request if out of memory instead of dying.  */
1779           new_argv[i] = xmalloc (1 + (next_p - p) / 2);
1780           unhexify (new_argv[i], p, (next_p - p) / 2);
1781           new_argv[i][(next_p - p) / 2] = '\0';
1782         }
1783
1784       if (*next_p)
1785         next_p++;
1786       i++;
1787     }
1788   new_argv[i] = NULL;
1789
1790   if (new_argv[0] == NULL)
1791     {
1792       /* GDB didn't specify a program to run.  Use the program from the
1793          last run with the new argument list.  */
1794
1795       if (program_argv == NULL)
1796         {
1797           /* FIXME: new_argv memory leak */
1798           write_enn (own_buf);
1799           return 0;
1800         }
1801
1802       new_argv[0] = strdup (program_argv[0]);
1803       if (new_argv[0] == NULL)
1804         {
1805           /* FIXME: new_argv memory leak */
1806           write_enn (own_buf);
1807           return 0;
1808         }
1809     }
1810
1811   /* Free the old argv and install the new one.  */
1812   freeargv (program_argv);
1813   program_argv = new_argv;
1814
1815   start_inferior (program_argv);
1816   if (last_status.kind == TARGET_WAITKIND_STOPPED)
1817     {
1818       prepare_resume_reply (own_buf, last_ptid, &last_status);
1819
1820       /* In non-stop, sending a resume reply doesn't set the general
1821          thread, but GDB assumes a vRun sets it (this is so GDB can
1822          query which is the main thread of the new inferior.  */
1823       if (non_stop)
1824         general_thread = last_ptid;
1825
1826       return 1;
1827     }
1828   else
1829     {
1830       write_enn (own_buf);
1831       return 0;
1832     }
1833 }
1834
1835 /* Kill process.  Return 1 if successful, 0 if failure.  */
1836 int
1837 handle_v_kill (char *own_buf)
1838 {
1839   int pid;
1840   char *p = &own_buf[6];
1841   if (multi_process)
1842     pid = strtol (p, NULL, 16);
1843   else
1844     pid = signal_pid;
1845   if (pid != 0 && kill_inferior (pid) == 0)
1846     {
1847       last_status.kind = TARGET_WAITKIND_SIGNALLED;
1848       last_status.value.sig = TARGET_SIGNAL_KILL;
1849       last_ptid = pid_to_ptid (pid);
1850       discard_queued_stop_replies (pid);
1851       write_ok (own_buf);
1852       return 1;
1853     }
1854   else
1855     {
1856       write_enn (own_buf);
1857       return 0;
1858     }
1859 }
1860
1861 /* Handle a 'vStopped' packet.  */
1862 static void
1863 handle_v_stopped (char *own_buf)
1864 {
1865   /* If we're waiting for GDB to acknowledge a pending stop reply,
1866      consider that done.  */
1867   if (notif_queue)
1868     {
1869       struct vstop_notif *head;
1870
1871       if (remote_debug)
1872         fprintf (stderr, "vStopped: acking %s\n",
1873                  target_pid_to_str (notif_queue->ptid));
1874
1875       head = notif_queue;
1876       notif_queue = notif_queue->next;
1877       free (head);
1878     }
1879
1880   /* Push another stop reply, or if there are no more left, an OK.  */
1881   send_next_stop_reply (own_buf);
1882 }
1883
1884 /* Handle all of the extended 'v' packets.  */
1885 void
1886 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
1887 {
1888   if (!disable_packet_vCont)
1889     {
1890       if (strncmp (own_buf, "vCont;", 6) == 0)
1891         {
1892           require_running (own_buf);
1893           handle_v_cont (own_buf);
1894           return;
1895         }
1896
1897       if (strncmp (own_buf, "vCont?", 6) == 0)
1898         {
1899           strcpy (own_buf, "vCont;c;C;s;S;t");
1900           return;
1901         }
1902     }
1903
1904   if (strncmp (own_buf, "vFile:", 6) == 0
1905       && handle_vFile (own_buf, packet_len, new_packet_len))
1906     return;
1907
1908   if (strncmp (own_buf, "vAttach;", 8) == 0)
1909     {
1910       if (!multi_process && target_running ())
1911         {
1912           fprintf (stderr, "Already debugging a process\n");
1913           write_enn (own_buf);
1914           return;
1915         }
1916       handle_v_attach (own_buf);
1917       return;
1918     }
1919
1920   if (strncmp (own_buf, "vRun;", 5) == 0)
1921     {
1922       if (!multi_process && target_running ())
1923         {
1924           fprintf (stderr, "Already debugging a process\n");
1925           write_enn (own_buf);
1926           return;
1927         }
1928       handle_v_run (own_buf);
1929       return;
1930     }
1931
1932   if (strncmp (own_buf, "vKill;", 6) == 0)
1933     {
1934       if (!target_running ())
1935         {
1936           fprintf (stderr, "No process to kill\n");
1937           write_enn (own_buf);
1938           return;
1939         }
1940       handle_v_kill (own_buf);
1941       return;
1942     }
1943
1944   if (strncmp (own_buf, "vStopped", 8) == 0)
1945     {
1946       handle_v_stopped (own_buf);
1947       return;
1948     }
1949
1950   /* Otherwise we didn't know what packet it was.  Say we didn't
1951      understand it.  */
1952   own_buf[0] = 0;
1953   return;
1954 }
1955
1956 /* Resume inferior and wait for another event.  In non-stop mode,
1957    don't really wait here, but return immediatelly to the event
1958    loop.  */
1959 void
1960 myresume (char *own_buf, int step, int sig)
1961 {
1962   struct thread_resume resume_info[2];
1963   int n = 0;
1964   int valid_cont_thread;
1965
1966   set_desired_inferior (0);
1967
1968   valid_cont_thread = (!ptid_equal (cont_thread, null_ptid)
1969                          && !ptid_equal (cont_thread, minus_one_ptid));
1970
1971   if (step || sig || valid_cont_thread)
1972     {
1973       resume_info[0].thread
1974         = ((struct inferior_list_entry *) current_inferior)->id;
1975       if (step)
1976         resume_info[0].kind = resume_step;
1977       else
1978         resume_info[0].kind = resume_continue;
1979       resume_info[0].sig = sig;
1980       n++;
1981     }
1982
1983   if (!valid_cont_thread)
1984     {
1985       resume_info[n].thread = minus_one_ptid;
1986       resume_info[n].kind = resume_continue;
1987       resume_info[n].sig = 0;
1988       n++;
1989     }
1990
1991   if (!non_stop)
1992     enable_async_io ();
1993
1994   (*the_target->resume) (resume_info, n);
1995
1996   if (non_stop)
1997     write_ok (own_buf);
1998   else
1999     {
2000       last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);
2001       prepare_resume_reply (own_buf, last_ptid, &last_status);
2002       disable_async_io ();
2003     }
2004 }
2005
2006 /* Callback for for_each_inferior.  Make a new stop reply for each
2007    stopped thread.  */
2008
2009 static int
2010 queue_stop_reply_callback (struct inferior_list_entry *entry, void *arg)
2011 {
2012   struct thread_info *thread = (struct thread_info *) entry;
2013
2014   /* For now, assume targets that don't have this callback also don't
2015      manage the thread's last_status field.  */
2016   if (the_target->thread_stopped == NULL)
2017     {
2018       struct target_waitstatus status;
2019
2020       status.kind = TARGET_WAITKIND_STOPPED;
2021       status.value.sig = TARGET_SIGNAL_TRAP;
2022
2023       /* Pass the last stop reply back to GDB, but don't notify
2024          yet.  */
2025       queue_stop_reply (entry->id, &thread->last_status);
2026     }
2027   else
2028     {
2029       if (thread_stopped (thread))
2030         {
2031           if (debug_threads)
2032             fprintf (stderr, "Reporting thread %s as already stopped with %s\n",
2033                      target_pid_to_str (entry->id),
2034                      target_waitstatus_to_string (&thread->last_status));
2035
2036           /* Pass the last stop reply back to GDB, but don't notify
2037              yet.  */
2038           queue_stop_reply (entry->id, &thread->last_status);
2039         }
2040     }
2041
2042   return 0;
2043 }
2044
2045 /* Set this inferior LWP's state as "want-stopped".  We won't resume
2046    this LWP until the client gives us another action for it.  */
2047
2048 static void
2049 gdb_wants_thread_stopped (struct inferior_list_entry *entry)
2050 {
2051   struct thread_info *thread = (struct thread_info *) entry;
2052
2053   thread->last_resume_kind = resume_stop;
2054
2055   if (thread->last_status.kind == TARGET_WAITKIND_IGNORE)
2056     {
2057       thread->last_status.kind = TARGET_WAITKIND_STOPPED;
2058       thread->last_status.value.sig = TARGET_SIGNAL_0;
2059     }
2060 }
2061
2062 /* Set all threads' states as "want-stopped".  */
2063
2064 static void
2065 gdb_wants_all_threads_stopped (void)
2066 {
2067   for_each_inferior (&all_threads, gdb_wants_thread_stopped);
2068 }
2069
2070 /* Clear the gdb_detached flag of every process.  */
2071
2072 static void
2073 gdb_reattached_process (struct inferior_list_entry *entry)
2074 {
2075   struct process_info *process = (struct process_info *) entry;
2076
2077   process->gdb_detached = 0;
2078 }
2079
2080 /* Status handler for the '?' packet.  */
2081
2082 static void
2083 handle_status (char *own_buf)
2084 {
2085   /* GDB is connected, don't forward events to the target anymore.  */
2086   for_each_inferior (&all_processes, gdb_reattached_process);
2087
2088   /* In non-stop mode, we must send a stop reply for each stopped
2089      thread.  In all-stop mode, just send one for the first stopped
2090      thread we find.  */
2091
2092   if (non_stop)
2093     {
2094       discard_queued_stop_replies (-1);
2095       find_inferior (&all_threads, queue_stop_reply_callback, NULL);
2096
2097       /* The first is sent immediatly.  OK is sent if there is no
2098          stopped thread, which is the same handling of the vStopped
2099          packet (by design).  */
2100       send_next_stop_reply (own_buf);
2101     }
2102   else
2103     {
2104       pause_all ();
2105       gdb_wants_all_threads_stopped ();
2106
2107       if (all_threads.head)
2108         {
2109           struct target_waitstatus status;
2110
2111           status.kind = TARGET_WAITKIND_STOPPED;
2112           status.value.sig = TARGET_SIGNAL_TRAP;
2113           prepare_resume_reply (own_buf,
2114                                 all_threads.head->id, &status);
2115         }
2116       else
2117         strcpy (own_buf, "W00");
2118     }
2119 }
2120
2121 static void
2122 gdbserver_version (void)
2123 {
2124   printf ("GNU gdbserver %s%s\n"
2125           "Copyright (C) 2010 Free Software Foundation, Inc.\n"
2126           "gdbserver is free software, covered by the GNU General Public License.\n"
2127           "This gdbserver was configured as \"%s\"\n",
2128           PKGVERSION, version, host_name);
2129 }
2130
2131 static void
2132 gdbserver_usage (FILE *stream)
2133 {
2134   fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
2135            "\tgdbserver [OPTIONS] --attach COMM PID\n"
2136            "\tgdbserver [OPTIONS] --multi COMM\n"
2137            "\n"
2138            "COMM may either be a tty device (for serial debugging), or \n"
2139            "HOST:PORT to listen for a TCP connection.\n"
2140            "\n"
2141            "Options:\n"
2142            "  --debug               Enable general debugging output.\n"
2143            "  --remote-debug        Enable remote protocol debugging output.\n"
2144            "  --version             Display version information and exit.\n"
2145            "  --wrapper WRAPPER --  Run WRAPPER to start new programs.\n");
2146   if (REPORT_BUGS_TO[0] && stream == stdout)
2147     fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
2148 }
2149
2150 static void
2151 gdbserver_show_disableable (FILE *stream)
2152 {
2153   fprintf (stream, "Disableable packets:\n"
2154            "  vCont       \tAll vCont packets\n"
2155            "  qC          \tQuerying the current thread\n"
2156            "  qfThreadInfo\tThread listing\n"
2157            "  Tthread     \tPassing the thread specifier in the T stop reply packet\n"
2158            "  threads     \tAll of the above\n");
2159 }
2160
2161
2162 #undef require_running
2163 #define require_running(BUF)                    \
2164   if (!target_running ())                       \
2165     {                                           \
2166       write_enn (BUF);                          \
2167       break;                                    \
2168     }
2169
2170 static int
2171 first_thread_of (struct inferior_list_entry *entry, void *args)
2172 {
2173   int pid = * (int *) args;
2174
2175   if (ptid_get_pid (entry->id) == pid)
2176     return 1;
2177
2178   return 0;
2179 }
2180
2181 static void
2182 kill_inferior_callback (struct inferior_list_entry *entry)
2183 {
2184   struct process_info *process = (struct process_info *) entry;
2185   int pid = ptid_get_pid (process->head.id);
2186
2187   kill_inferior (pid);
2188   discard_queued_stop_replies (pid);
2189 }
2190
2191 /* Callback for for_each_inferior to detach or kill the inferior,
2192    depending on whether we attached to it or not.
2193    We inform the user whether we're detaching or killing the process
2194    as this is only called when gdbserver is about to exit.  */
2195
2196 static void
2197 detach_or_kill_inferior_callback (struct inferior_list_entry *entry)
2198 {
2199   struct process_info *process = (struct process_info *) entry;
2200   int pid = ptid_get_pid (process->head.id);
2201
2202   if (process->attached)
2203     detach_inferior (pid);
2204   else
2205     kill_inferior (pid);
2206
2207   discard_queued_stop_replies (pid);
2208 }
2209
2210 /* for_each_inferior callback for detach_or_kill_for_exit to print
2211    the pids of started inferiors.  */
2212
2213 static void
2214 print_started_pid (struct inferior_list_entry *entry)
2215 {
2216   struct process_info *process = (struct process_info *) entry;
2217
2218   if (! process->attached)
2219     {
2220       int pid = ptid_get_pid (process->head.id);
2221       fprintf (stderr, " %d", pid);
2222     }
2223 }
2224
2225 /* for_each_inferior callback for detach_or_kill_for_exit to print
2226    the pids of attached inferiors.  */
2227
2228 static void
2229 print_attached_pid (struct inferior_list_entry *entry)
2230 {
2231   struct process_info *process = (struct process_info *) entry;
2232
2233   if (process->attached)
2234     {
2235       int pid = ptid_get_pid (process->head.id);
2236       fprintf (stderr, " %d", pid);
2237     }
2238 }
2239
2240 /* Call this when exiting gdbserver with possible inferiors that need
2241    to be killed or detached from.  */
2242
2243 static void
2244 detach_or_kill_for_exit (void)
2245 {
2246   /* First print a list of the inferiors we will be killing/detaching.
2247      This is to assist the user, for example, in case the inferior unexpectedly
2248      dies after we exit: did we screw up or did the inferior exit on its own?
2249      Having this info will save some head-scratching.  */
2250
2251   if (have_started_inferiors_p ())
2252     {
2253       fprintf (stderr, "Killing process(es):");
2254       for_each_inferior (&all_processes, print_started_pid);
2255       fprintf (stderr, "\n");
2256     }
2257   if (have_attached_inferiors_p ())
2258     {
2259       fprintf (stderr, "Detaching process(es):");
2260       for_each_inferior (&all_processes, print_attached_pid);
2261       fprintf (stderr, "\n");
2262     }
2263
2264   /* Now we can kill or detach the inferiors.  */
2265
2266   for_each_inferior (&all_processes, detach_or_kill_inferior_callback);
2267 }
2268
2269 static void
2270 join_inferiors_callback (struct inferior_list_entry *entry)
2271 {
2272   struct process_info *process = (struct process_info *) entry;
2273
2274   /* If we are attached, then we can exit.  Otherwise, we need to hang
2275      around doing nothing, until the child is gone.  */
2276   if (!process->attached)
2277     join_inferior (ptid_get_pid (process->head.id));
2278 }
2279
2280 int
2281 main (int argc, char *argv[])
2282 {
2283   int bad_attach;
2284   int pid;
2285   char *arg_end, *port;
2286   char **next_arg = &argv[1];
2287   int multi_mode = 0;
2288   int attach = 0;
2289   int was_running;
2290
2291   while (*next_arg != NULL && **next_arg == '-')
2292     {
2293       if (strcmp (*next_arg, "--version") == 0)
2294         {
2295           gdbserver_version ();
2296           exit (0);
2297         }
2298       else if (strcmp (*next_arg, "--help") == 0)
2299         {
2300           gdbserver_usage (stdout);
2301           exit (0);
2302         }
2303       else if (strcmp (*next_arg, "--attach") == 0)
2304         attach = 1;
2305       else if (strcmp (*next_arg, "--multi") == 0)
2306         multi_mode = 1;
2307       else if (strcmp (*next_arg, "--wrapper") == 0)
2308         {
2309           next_arg++;
2310
2311           wrapper_argv = next_arg;
2312           while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
2313             next_arg++;
2314
2315           if (next_arg == wrapper_argv || *next_arg == NULL)
2316             {
2317               gdbserver_usage (stderr);
2318               exit (1);
2319             }
2320
2321           /* Consume the "--".  */
2322           *next_arg = NULL;
2323         }
2324       else if (strcmp (*next_arg, "--debug") == 0)
2325         debug_threads = 1;
2326       else if (strcmp (*next_arg, "--remote-debug") == 0)
2327         remote_debug = 1;
2328       else if (strcmp (*next_arg, "--disable-packet") == 0)
2329         {
2330           gdbserver_show_disableable (stdout);
2331           exit (0);
2332         }
2333       else if (strncmp (*next_arg,
2334                         "--disable-packet=",
2335                         sizeof ("--disable-packet=") - 1) == 0)
2336         {
2337           char *packets, *tok;
2338
2339           packets = *next_arg += sizeof ("--disable-packet=") - 1;
2340           for (tok = strtok (packets, ",");
2341                tok != NULL;
2342                tok = strtok (NULL, ","))
2343             {
2344               if (strcmp ("vCont", tok) == 0)
2345                 disable_packet_vCont = 1;
2346               else if (strcmp ("Tthread", tok) == 0)
2347                 disable_packet_Tthread = 1;
2348               else if (strcmp ("qC", tok) == 0)
2349                 disable_packet_qC = 1;
2350               else if (strcmp ("qfThreadInfo", tok) == 0)
2351                 disable_packet_qfThreadInfo = 1;
2352               else if (strcmp ("threads", tok) == 0)
2353                 {
2354                   disable_packet_vCont = 1;
2355                   disable_packet_Tthread = 1;
2356                   disable_packet_qC = 1;
2357                   disable_packet_qfThreadInfo = 1;
2358                 }
2359               else
2360                 {
2361                   fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
2362                            tok);
2363                   gdbserver_show_disableable (stderr);
2364                   exit (1);
2365                 }
2366             }
2367         }
2368       else
2369         {
2370           fprintf (stderr, "Unknown argument: %s\n", *next_arg);
2371           exit (1);
2372         }
2373
2374       next_arg++;
2375       continue;
2376     }
2377
2378   if (setjmp (toplevel))
2379     {
2380       fprintf (stderr, "Exiting\n");
2381       exit (1);
2382     }
2383
2384   port = *next_arg;
2385   next_arg++;
2386   if (port == NULL || (!attach && !multi_mode && *next_arg == NULL))
2387     {
2388       gdbserver_usage (stderr);
2389       exit (1);
2390     }
2391
2392   bad_attach = 0;
2393   pid = 0;
2394
2395   /* --attach used to come after PORT, so allow it there for
2396        compatibility.  */
2397   if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
2398     {
2399       attach = 1;
2400       next_arg++;
2401     }
2402
2403   if (attach
2404       && (*next_arg == NULL
2405           || (*next_arg)[0] == '\0'
2406           || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
2407           || *arg_end != '\0'
2408           || next_arg[1] != NULL))
2409     bad_attach = 1;
2410
2411   if (bad_attach)
2412     {
2413       gdbserver_usage (stderr);
2414       exit (1);
2415     }
2416
2417   initialize_inferiors ();
2418   initialize_async_io ();
2419   initialize_low ();
2420   if (target_supports_tracepoints ())
2421     initialize_tracepoint ();
2422
2423   own_buf = xmalloc (PBUFSIZ + 1);
2424   mem_buf = xmalloc (PBUFSIZ);
2425
2426   if (pid == 0 && *next_arg != NULL)
2427     {
2428       int i, n;
2429
2430       n = argc - (next_arg - argv);
2431       program_argv = xmalloc (sizeof (char *) * (n + 1));
2432       for (i = 0; i < n; i++)
2433         program_argv[i] = xstrdup (next_arg[i]);
2434       program_argv[i] = NULL;
2435
2436       /* Wait till we are at first instruction in program.  */
2437       start_inferior (program_argv);
2438
2439       /* We are now (hopefully) stopped at the first instruction of
2440          the target process.  This assumes that the target process was
2441          successfully created.  */
2442     }
2443   else if (pid != 0)
2444     {
2445       if (attach_inferior (pid) == -1)
2446         error ("Attaching not supported on this target");
2447
2448       /* Otherwise succeeded.  */
2449     }
2450   else
2451     {
2452       last_status.kind = TARGET_WAITKIND_EXITED;
2453       last_status.value.integer = 0;
2454       last_ptid = minus_one_ptid;
2455     }
2456
2457   /* Don't report shared library events on the initial connection,
2458      even if some libraries are preloaded.  Avoids the "stopped by
2459      shared library event" notice on gdb side.  */
2460   dlls_changed = 0;
2461
2462   if (setjmp (toplevel))
2463     {
2464       detach_or_kill_for_exit ();
2465       exit (1);
2466     }
2467
2468   if (last_status.kind == TARGET_WAITKIND_EXITED
2469       || last_status.kind == TARGET_WAITKIND_SIGNALLED)
2470     was_running = 0;
2471   else
2472     was_running = 1;
2473
2474   if (!was_running && !multi_mode)
2475     {
2476       fprintf (stderr, "No program to debug.  GDBserver exiting.\n");
2477       exit (1);
2478     }
2479
2480   while (1)
2481     {
2482       noack_mode = 0;
2483       multi_process = 0;
2484       /* Be sure we're out of tfind mode.  */
2485       current_traceframe = -1;
2486
2487       remote_open (port);
2488
2489       if (setjmp (toplevel) != 0)
2490         {
2491           /* An error occurred.  */
2492           if (response_needed)
2493             {
2494               write_enn (own_buf);
2495               putpkt (own_buf);
2496             }
2497         }
2498
2499       /* Wait for events.  This will return when all event sources are
2500          removed from the event loop.  */
2501       start_event_loop ();
2502
2503       /* If an exit was requested (using the "monitor exit" command),
2504          terminate now.  The only other way to get here is for
2505          getpkt to fail; close the connection and reopen it at the
2506          top of the loop.  */
2507
2508       if (exit_requested)
2509         {
2510           detach_or_kill_for_exit ();
2511           exit (0);
2512         }
2513
2514       fprintf (stderr,
2515                "Remote side has terminated connection.  "
2516                "GDBserver will reopen the connection.\n");
2517
2518       if (tracing)
2519         {
2520           if (disconnected_tracing)
2521             {
2522               /* Try to enable non-stop/async mode, so we we can both
2523                  wait for an async socket accept, and handle async
2524                  target events simultaneously.  There's also no point
2525                  either in having the target always stop all threads,
2526                  when we're going to pass signals down without
2527                  informing GDB.  */
2528               if (!non_stop)
2529                 {
2530                   if (start_non_stop (1))
2531                     non_stop = 1;
2532
2533                   /* Detaching implicitly resumes all threads; simply
2534                      disconnecting does not.  */
2535                 }
2536             }
2537           else
2538             {
2539               fprintf (stderr,
2540                        "Disconnected tracing disabled; stopping trace run.\n");
2541               stop_tracing ();
2542             }
2543         }
2544     }
2545 }
2546
2547 /* Event loop callback that handles a serial event.  The first byte in
2548    the serial buffer gets us here.  We expect characters to arrive at
2549    a brisk pace, so we read the rest of the packet with a blocking
2550    getpkt call.  */
2551
2552 static int
2553 process_serial_event (void)
2554 {
2555   char ch;
2556   int i = 0;
2557   int signal;
2558   unsigned int len;
2559   CORE_ADDR mem_addr;
2560   int pid;
2561   unsigned char sig;
2562   int packet_len;
2563   int new_packet_len = -1;
2564
2565   /* Used to decide when gdbserver should exit in
2566      multi-mode/remote.  */
2567   static int have_ran = 0;
2568
2569   if (!have_ran)
2570     have_ran = target_running ();
2571
2572   disable_async_io ();
2573
2574   response_needed = 0;
2575   packet_len = getpkt (own_buf);
2576   if (packet_len <= 0)
2577     {
2578       remote_close ();
2579       /* Force an event loop break.  */
2580       return -1;
2581     }
2582   response_needed = 1;
2583
2584   i = 0;
2585   ch = own_buf[i++];
2586   switch (ch)
2587     {
2588     case 'q':
2589       handle_query (own_buf, packet_len, &new_packet_len);
2590       break;
2591     case 'Q':
2592       handle_general_set (own_buf);
2593       break;
2594     case 'D':
2595       require_running (own_buf);
2596
2597       if (multi_process)
2598         {
2599           i++; /* skip ';' */
2600           pid = strtol (&own_buf[i], NULL, 16);
2601         }
2602       else
2603         pid =
2604           ptid_get_pid (((struct inferior_list_entry *) current_inferior)->id);
2605
2606       if (tracing && disconnected_tracing)
2607         {
2608           struct thread_resume resume_info;
2609           struct process_info *process = find_process_pid (pid);
2610
2611           if (process == NULL)
2612             {
2613               write_enn (own_buf);
2614               break;
2615             }
2616
2617           fprintf (stderr,
2618                    "Disconnected tracing in effect, "
2619                    "leaving gdbserver attached to the process\n");
2620
2621           /* Make sure we're in non-stop/async mode, so we we can both
2622              wait for an async socket accept, and handle async target
2623              events simultaneously.  There's also no point either in
2624              having the target stop all threads, when we're going to
2625              pass signals down without informing GDB.  */
2626           if (!non_stop)
2627             {
2628               if (debug_threads)
2629                 fprintf (stderr, "Forcing non-stop mode\n");
2630
2631               non_stop = 1;
2632               start_non_stop (1);
2633             }
2634
2635           process->gdb_detached = 1;
2636
2637           /* Detaching implicitly resumes all threads.  */
2638           resume_info.thread = minus_one_ptid;
2639           resume_info.kind = resume_continue;
2640           resume_info.sig = 0;
2641           (*the_target->resume) (&resume_info, 1);
2642
2643           write_ok (own_buf);
2644           break; /* from switch/case */
2645         }
2646
2647       fprintf (stderr, "Detaching from process %d\n", pid);
2648       stop_tracing ();
2649       if (detach_inferior (pid) != 0)
2650         write_enn (own_buf);
2651       else
2652         {
2653           discard_queued_stop_replies (pid);
2654           write_ok (own_buf);
2655
2656           if (extended_protocol)
2657             {
2658               /* Treat this like a normal program exit.  */
2659               last_status.kind = TARGET_WAITKIND_EXITED;
2660               last_status.value.integer = 0;
2661               last_ptid = pid_to_ptid (pid);
2662
2663               current_inferior = NULL;
2664             }
2665           else
2666             {
2667               putpkt (own_buf);
2668               remote_close ();
2669
2670               /* If we are attached, then we can exit.  Otherwise, we
2671                  need to hang around doing nothing, until the child is
2672                  gone.  */
2673               for_each_inferior (&all_processes,
2674                                  join_inferiors_callback);
2675               exit (0);
2676             }
2677         }
2678       break;
2679     case '!':
2680       extended_protocol = 1;
2681       write_ok (own_buf);
2682       break;
2683     case '?':
2684       handle_status (own_buf);
2685       break;
2686     case 'H':
2687       if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's')
2688         {
2689           ptid_t gdb_id, thread_id;
2690           int pid;
2691
2692           require_running (own_buf);
2693
2694           gdb_id = read_ptid (&own_buf[2], NULL);
2695
2696           pid = ptid_get_pid (gdb_id);
2697
2698           if (ptid_equal (gdb_id, null_ptid)
2699               || ptid_equal (gdb_id, minus_one_ptid))
2700             thread_id = null_ptid;
2701           else if (pid != 0
2702                    && ptid_equal (pid_to_ptid (pid),
2703                                   gdb_id))
2704             {
2705               struct thread_info *thread =
2706                 (struct thread_info *) find_inferior (&all_threads,
2707                                                       first_thread_of,
2708                                                       &pid);
2709               if (!thread)
2710                 {
2711                   write_enn (own_buf);
2712                   break;
2713                 }
2714
2715               thread_id = ((struct inferior_list_entry *)thread)->id;
2716             }
2717           else
2718             {
2719               thread_id = gdb_id_to_thread_id (gdb_id);
2720               if (ptid_equal (thread_id, null_ptid))
2721                 {
2722                   write_enn (own_buf);
2723                   break;
2724                 }
2725             }
2726
2727           if (own_buf[1] == 'g')
2728             {
2729               if (ptid_equal (thread_id, null_ptid))
2730                 {
2731                   /* GDB is telling us to choose any thread.  Check if
2732                      the currently selected thread is still valid. If
2733                      it is not, select the first available.  */
2734                   struct thread_info *thread =
2735                     (struct thread_info *) find_inferior_id (&all_threads,
2736                                                              general_thread);
2737                   if (thread == NULL)
2738                     thread_id = all_threads.head->id;
2739                 }
2740
2741               general_thread = thread_id;
2742               set_desired_inferior (1);
2743             }
2744           else if (own_buf[1] == 'c')
2745             cont_thread = thread_id;
2746           else if (own_buf[1] == 's')
2747             step_thread = thread_id;
2748
2749           write_ok (own_buf);
2750         }
2751       else
2752         {
2753           /* Silently ignore it so that gdb can extend the protocol
2754              without compatibility headaches.  */
2755           own_buf[0] = '\0';
2756         }
2757       break;
2758     case 'g':
2759       require_running (own_buf);
2760       if (current_traceframe >= 0)
2761         {
2762           struct regcache *regcache = new_register_cache ();
2763
2764           if (fetch_traceframe_registers (current_traceframe,
2765                                           regcache, -1) == 0)
2766             registers_to_string (regcache, own_buf);
2767           else
2768             write_enn (own_buf);
2769           free_register_cache (regcache);
2770         }
2771       else
2772         {
2773           struct regcache *regcache;
2774
2775           set_desired_inferior (1);
2776           regcache = get_thread_regcache (current_inferior, 1);
2777           registers_to_string (regcache, own_buf);
2778         }
2779       break;
2780     case 'G':
2781       require_running (own_buf);
2782       if (current_traceframe >= 0)
2783         write_enn (own_buf);
2784       else
2785         {
2786           struct regcache *regcache;
2787
2788           set_desired_inferior (1);
2789           regcache = get_thread_regcache (current_inferior, 1);
2790           registers_from_string (regcache, &own_buf[1]);
2791           write_ok (own_buf);
2792         }
2793       break;
2794     case 'm':
2795       require_running (own_buf);
2796       decode_m_packet (&own_buf[1], &mem_addr, &len);
2797       if (read_memory (mem_addr, mem_buf, len) == 0)
2798         convert_int_to_ascii (mem_buf, own_buf, len);
2799       else
2800         write_enn (own_buf);
2801       break;
2802     case 'M':
2803       require_running (own_buf);
2804       decode_M_packet (&own_buf[1], &mem_addr, &len, mem_buf);
2805       if (write_memory (mem_addr, mem_buf, len) == 0)
2806         write_ok (own_buf);
2807       else
2808         write_enn (own_buf);
2809       break;
2810     case 'X':
2811       require_running (own_buf);
2812       if (decode_X_packet (&own_buf[1], packet_len - 1,
2813                            &mem_addr, &len, mem_buf) < 0
2814           || write_memory (mem_addr, mem_buf, len) != 0)
2815         write_enn (own_buf);
2816       else
2817         write_ok (own_buf);
2818       break;
2819     case 'C':
2820       require_running (own_buf);
2821       convert_ascii_to_int (own_buf + 1, &sig, 1);
2822       if (target_signal_to_host_p (sig))
2823         signal = target_signal_to_host (sig);
2824       else
2825         signal = 0;
2826       myresume (own_buf, 0, signal);
2827       break;
2828     case 'S':
2829       require_running (own_buf);
2830       convert_ascii_to_int (own_buf + 1, &sig, 1);
2831       if (target_signal_to_host_p (sig))
2832         signal = target_signal_to_host (sig);
2833       else
2834         signal = 0;
2835       myresume (own_buf, 1, signal);
2836       break;
2837     case 'c':
2838       require_running (own_buf);
2839       signal = 0;
2840       myresume (own_buf, 0, signal);
2841       break;
2842     case 's':
2843       require_running (own_buf);
2844       signal = 0;
2845       myresume (own_buf, 1, signal);
2846       break;
2847     case 'Z':  /* insert_ ... */
2848       /* Fallthrough.  */
2849     case 'z':  /* remove_ ... */
2850       {
2851         char *lenptr;
2852         char *dataptr;
2853         CORE_ADDR addr = strtoul (&own_buf[3], &lenptr, 16);
2854         int len = strtol (lenptr + 1, &dataptr, 16);
2855         char type = own_buf[1];
2856         int res;
2857         const int insert = ch == 'Z';
2858
2859         /* Default to unrecognized/unsupported.  */
2860         res = 1;
2861         switch (type)
2862           {
2863           case '0': /* software-breakpoint */
2864           case '1': /* hardware-breakpoint */
2865           case '2': /* write watchpoint */
2866           case '3': /* read watchpoint */
2867           case '4': /* access watchpoint */
2868             require_running (own_buf);
2869             if (insert && the_target->insert_point != NULL)
2870               res = (*the_target->insert_point) (type, addr, len);
2871             else if (!insert && the_target->remove_point != NULL)
2872               res = (*the_target->remove_point) (type, addr, len);
2873             break;
2874           default:
2875             break;
2876           }
2877
2878         if (res == 0)
2879           write_ok (own_buf);
2880         else if (res == 1)
2881           /* Unsupported.  */
2882           own_buf[0] = '\0';
2883         else
2884           write_enn (own_buf);
2885         break;
2886       }
2887     case 'k':
2888       response_needed = 0;
2889       if (!target_running ())
2890         /* The packet we received doesn't make sense - but we can't
2891            reply to it, either.  */
2892         return 0;
2893
2894       fprintf (stderr, "Killing all inferiors\n");
2895       for_each_inferior (&all_processes, kill_inferior_callback);
2896
2897       /* When using the extended protocol, we wait with no program
2898          running.  The traditional protocol will exit instead.  */
2899       if (extended_protocol)
2900         {
2901           last_status.kind = TARGET_WAITKIND_EXITED;
2902           last_status.value.sig = TARGET_SIGNAL_KILL;
2903           return 0;
2904         }
2905       else
2906         exit (0);
2907
2908     case 'T':
2909       {
2910         ptid_t gdb_id, thread_id;
2911
2912         require_running (own_buf);
2913
2914         gdb_id = read_ptid (&own_buf[1], NULL);
2915         thread_id = gdb_id_to_thread_id (gdb_id);
2916         if (ptid_equal (thread_id, null_ptid))
2917           {
2918             write_enn (own_buf);
2919             break;
2920           }
2921
2922         if (mythread_alive (thread_id))
2923           write_ok (own_buf);
2924         else
2925           write_enn (own_buf);
2926       }
2927       break;
2928     case 'R':
2929       response_needed = 0;
2930
2931       /* Restarting the inferior is only supported in the extended
2932          protocol.  */
2933       if (extended_protocol)
2934         {
2935           if (target_running ())
2936             for_each_inferior (&all_processes,
2937                                kill_inferior_callback);
2938           fprintf (stderr, "GDBserver restarting\n");
2939
2940           /* Wait till we are at 1st instruction in prog.  */
2941           if (program_argv != NULL)
2942             start_inferior (program_argv);
2943           else
2944             {
2945               last_status.kind = TARGET_WAITKIND_EXITED;
2946               last_status.value.sig = TARGET_SIGNAL_KILL;
2947             }
2948           return 0;
2949         }
2950       else
2951         {
2952           /* It is a request we don't understand.  Respond with an
2953              empty packet so that gdb knows that we don't support this
2954              request.  */
2955           own_buf[0] = '\0';
2956           break;
2957         }
2958     case 'v':
2959       /* Extended (long) request.  */
2960       handle_v_requests (own_buf, packet_len, &new_packet_len);
2961       break;
2962
2963     default:
2964       /* It is a request we don't understand.  Respond with an empty
2965          packet so that gdb knows that we don't support this
2966          request.  */
2967       own_buf[0] = '\0';
2968       break;
2969     }
2970
2971   if (new_packet_len != -1)
2972     putpkt_binary (own_buf, new_packet_len);
2973   else
2974     putpkt (own_buf);
2975
2976   response_needed = 0;
2977
2978   if (!extended_protocol && have_ran && !target_running ())
2979     {
2980       /* In non-stop, defer exiting until GDB had a chance to query
2981          the whole vStopped list (until it gets an OK).  */
2982       if (!notif_queue)
2983         {
2984           fprintf (stderr, "GDBserver exiting\n");
2985           remote_close ();
2986           exit (0);
2987         }
2988     }
2989
2990   if (exit_requested)
2991     return -1;
2992
2993   return 0;
2994 }
2995
2996 /* Event-loop callback for serial events.  */
2997
2998 int
2999 handle_serial_event (int err, gdb_client_data client_data)
3000 {
3001   if (debug_threads)
3002     fprintf (stderr, "handling possible serial event\n");
3003
3004   /* Really handle it.  */
3005   if (process_serial_event () < 0)
3006     return -1;
3007
3008   /* Be sure to not change the selected inferior behind GDB's back.
3009      Important in the non-stop mode asynchronous protocol.  */
3010   set_desired_inferior (1);
3011
3012   return 0;
3013 }
3014
3015 /* Event-loop callback for target events.  */
3016
3017 int
3018 handle_target_event (int err, gdb_client_data client_data)
3019 {
3020   if (debug_threads)
3021     fprintf (stderr, "handling possible target event\n");
3022
3023   last_ptid = mywait (minus_one_ptid, &last_status,
3024                       TARGET_WNOHANG, 1);
3025
3026   if (last_status.kind != TARGET_WAITKIND_IGNORE)
3027     {
3028       int pid = ptid_get_pid (last_ptid);
3029       struct process_info *process = find_process_pid (pid);
3030       int forward_event = !gdb_connected () || process->gdb_detached;
3031
3032       if (last_status.kind == TARGET_WAITKIND_EXITED
3033           || last_status.kind == TARGET_WAITKIND_SIGNALLED)
3034         {
3035           mark_breakpoints_out (process);
3036           mourn_inferior (process);
3037         }
3038
3039       if (forward_event)
3040         {
3041           if (!target_running ())
3042             {
3043               /* The last process exited.  We're done.  */
3044               exit (0);
3045             }
3046
3047           if (last_status.kind == TARGET_WAITKIND_STOPPED)
3048             {
3049               /* A thread stopped with a signal, but gdb isn't
3050                  connected to handle it.  Pass it down to the
3051                  inferior, as if it wasn't being traced.  */
3052               struct thread_resume resume_info;
3053
3054               if (debug_threads)
3055                 fprintf (stderr,
3056                          "GDB not connected; forwarding event %d for [%s]\n",
3057                          (int) last_status.kind,
3058                          target_pid_to_str (last_ptid));
3059
3060               resume_info.thread = last_ptid;
3061               resume_info.kind = resume_continue;
3062               resume_info.sig = last_status.value.sig;
3063               (*the_target->resume) (&resume_info, 1);
3064             }
3065           else if (debug_threads)
3066             fprintf (stderr, "GDB not connected; ignoring event %d for [%s]\n",
3067                      (int) last_status.kind,
3068                      target_pid_to_str (last_ptid));
3069         }
3070       else
3071         {
3072           /* Something interesting.  Tell GDB about it.  */
3073           push_event (last_ptid, &last_status);
3074         }
3075     }
3076
3077   /* Be sure to not change the selected inferior behind GDB's back.
3078      Important in the non-stop mode asynchronous protocol.  */
3079   set_desired_inferior (1);
3080
3081   return 0;
3082 }