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