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