gdb/gdbserver/server.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Main code for remote server for GDB.
  2.    Copyright (C) 1989-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "server.h"
  15. #include "gdbthread.h"
  16. #include "agent.h"
  17. #include "notif.h"
  18. #include "tdesc.h"
  19. #include "rsp-low.h"

  20. #include <ctype.h>
  21. #include <unistd.h>
  22. #if HAVE_SIGNAL_H
  23. #include <signal.h>
  24. #endif
  25. #include "gdb_vecs.h"
  26. #include "gdb_wait.h"
  27. #include "btrace-common.h"
  28. #include "filestuff.h"
  29. #include "tracepoint.h"
  30. #include "dll.h"
  31. #include "hostio.h"

  32. /* The thread set with an `Hc' packet.  `Hc' is deprecated in favor of
  33.    `vCont'.  Note the multi-process extensions made `vCont' a
  34.    requirement, so `Hc pPID.TID' is pretty much undefined.  So
  35.    CONT_THREAD can be null_ptid for no `Hc' thread, minus_one_ptid for
  36.    resuming all threads of the process (again, `Hc' isn't used for
  37.    multi-process), or a specific thread ptid_t.  */
  38. ptid_t cont_thread;

  39. /* The thread set with an `Hg' packet.  */
  40. ptid_t general_thread;

  41. int server_waiting;

  42. static int extended_protocol;
  43. static int response_needed;
  44. static int exit_requested;

  45. /* --once: Exit after the first connection has closed.  */
  46. int run_once;

  47. int multi_process;
  48. int non_stop;

  49. /* Whether we should attempt to disable the operating system's address
  50.    space randomization feature before starting an inferior.  */
  51. int disable_randomization = 1;

  52. static char **program_argv, **wrapper_argv;

  53. int pass_signals[GDB_SIGNAL_LAST];
  54. int program_signals[GDB_SIGNAL_LAST];
  55. int program_signals_p;

  56. /* The PID of the originally created or attached inferior.  Used to
  57.    send signals to the process when GDB sends us an asynchronous interrupt
  58.    (user hitting Control-C in the client), and to wait for the child to exit
  59.    when no longer debugging it.  */

  60. unsigned long signal_pid;

  61. #ifdef SIGTTOU
  62. /* A file descriptor for the controlling terminal.  */
  63. int terminal_fd;

  64. /* TERMINAL_FD's original foreground group.  */
  65. pid_t old_foreground_pgrp;

  66. /* Hand back terminal ownership to the original foreground group.  */

  67. static void
  68. restore_old_foreground_pgrp (void)
  69. {
  70.   tcsetpgrp (terminal_fd, old_foreground_pgrp);
  71. }
  72. #endif

  73. /* Set if you want to disable optional thread related packets support
  74.    in gdbserver, for the sake of testing GDB against stubs that don't
  75.    support them.  */
  76. int disable_packet_vCont;
  77. int disable_packet_Tthread;
  78. int disable_packet_qC;
  79. int disable_packet_qfThreadInfo;

  80. /* Last status reported to GDB.  */
  81. static struct target_waitstatus last_status;
  82. static ptid_t last_ptid;

  83. static char *own_buf;
  84. static unsigned char *mem_buf;

  85. /* A sub-class of 'struct notif_event' for stop, holding information
  86.    relative to a single stop reply.  We keep a queue of these to
  87.    push to GDB in non-stop mode.  */

  88. struct vstop_notif
  89. {
  90.   struct notif_event base;

  91.   /* Thread or process that got the event.  */
  92.   ptid_t ptid;

  93.   /* Event info.  */
  94.   struct target_waitstatus status;
  95. };

  96. DEFINE_QUEUE_P (notif_event_p);

  97. /* Put a stop reply to the stop reply queue.  */

  98. static void
  99. queue_stop_reply (ptid_t ptid, struct target_waitstatus *status)
  100. {
  101.   struct vstop_notif *new_notif = xmalloc (sizeof (*new_notif));

  102.   new_notif->ptid = ptid;
  103.   new_notif->status = *status;

  104.   notif_event_enque (&notif_stop, (struct notif_event *) new_notif);
  105. }

  106. static int
  107. remove_all_on_match_pid (QUEUE (notif_event_p) *q,
  108.                             QUEUE_ITER (notif_event_p) *iter,
  109.                             struct notif_event *event,
  110.                             void *data)
  111. {
  112.   int *pid = data;

  113.   if (*pid == -1
  114.       || ptid_get_pid (((struct vstop_notif *) event)->ptid) == *pid)
  115.     {
  116.       if (q->free_func != NULL)
  117.         q->free_func (event);

  118.       QUEUE_remove_elem (notif_event_p, q, iter);
  119.     }

  120.   return 1;
  121. }

  122. /* Get rid of the currently pending stop replies for PID.  If PID is
  123.    -1, then apply to all processes.  */

  124. static void
  125. discard_queued_stop_replies (int pid)
  126. {
  127.   QUEUE_iterate (notif_event_p, notif_stop.queue,
  128.                  remove_all_on_match_pid, &pid);
  129. }

  130. static void
  131. vstop_notif_reply (struct notif_event *event, char *own_buf)
  132. {
  133.   struct vstop_notif *vstop = (struct vstop_notif *) event;

  134.   prepare_resume_reply (own_buf, vstop->ptid, &vstop->status);
  135. }

  136. struct notif_server notif_stop =
  137. {
  138.   "vStopped", "Stop", NULL, vstop_notif_reply,
  139. };

  140. static int
  141. target_running (void)
  142. {
  143.   return get_first_thread () != NULL;
  144. }

  145. static int
  146. start_inferior (char **argv)
  147. {
  148.   char **new_argv = argv;

  149.   if (wrapper_argv != NULL)
  150.     {
  151.       int i, count = 1;

  152.       for (i = 0; wrapper_argv[i] != NULL; i++)
  153.         count++;
  154.       for (i = 0; argv[i] != NULL; i++)
  155.         count++;
  156.       new_argv = alloca (sizeof (char *) * count);
  157.       count = 0;
  158.       for (i = 0; wrapper_argv[i] != NULL; i++)
  159.         new_argv[count++] = wrapper_argv[i];
  160.       for (i = 0; argv[i] != NULL; i++)
  161.         new_argv[count++] = argv[i];
  162.       new_argv[count] = NULL;
  163.     }

  164.   if (debug_threads)
  165.     {
  166.       int i;
  167.       for (i = 0; new_argv[i]; ++i)
  168.         debug_printf ("new_argv[%d] = \"%s\"\n", i, new_argv[i]);
  169.       debug_flush ();
  170.     }

  171. #ifdef SIGTTOU
  172.   signal (SIGTTOU, SIG_DFL);
  173.   signal (SIGTTIN, SIG_DFL);
  174. #endif

  175.   signal_pid = create_inferior (new_argv[0], new_argv);

  176.   /* FIXME: we don't actually know at this point that the create
  177.      actually succeeded.  We won't know that until we wait.  */
  178.   fprintf (stderr, "Process %s created; pid = %ld\n", argv[0],
  179.            signal_pid);
  180.   fflush (stderr);

  181. #ifdef SIGTTOU
  182.   signal (SIGTTOU, SIG_IGN);
  183.   signal (SIGTTIN, SIG_IGN);
  184.   terminal_fd = fileno (stderr);
  185.   old_foreground_pgrp = tcgetpgrp (terminal_fd);
  186.   tcsetpgrp (terminal_fd, signal_pid);
  187.   atexit (restore_old_foreground_pgrp);
  188. #endif

  189.   if (wrapper_argv != NULL)
  190.     {
  191.       struct thread_resume resume_info;

  192.       memset (&resume_info, 0, sizeof (resume_info));
  193.       resume_info.thread = pid_to_ptid (signal_pid);
  194.       resume_info.kind = resume_continue;
  195.       resume_info.sig = 0;

  196.       last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);

  197.       if (last_status.kind != TARGET_WAITKIND_STOPPED)
  198.         return signal_pid;

  199.       do
  200.         {
  201.           (*the_target->resume) (&resume_info, 1);

  202.            last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
  203.           if (last_status.kind != TARGET_WAITKIND_STOPPED)
  204.             return signal_pid;

  205.           current_thread->last_resume_kind = resume_stop;
  206.           current_thread->last_status = last_status;
  207.         }
  208.       while (last_status.value.sig != GDB_SIGNAL_TRAP);

  209.       return signal_pid;
  210.     }

  211.   /* Wait till we are at 1st instruction in program, return new pid
  212.      (assuming success).  */
  213.   last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);

  214.   if (last_status.kind != TARGET_WAITKIND_EXITED
  215.       && last_status.kind != TARGET_WAITKIND_SIGNALLED)
  216.     {
  217.       current_thread->last_resume_kind = resume_stop;
  218.       current_thread->last_status = last_status;
  219.     }

  220.   return signal_pid;
  221. }

  222. static int
  223. attach_inferior (int pid)
  224. {
  225.   /* myattach should return -1 if attaching is unsupported,
  226.      0 if it succeeded, and call error() otherwise.  */

  227.   if (myattach (pid) != 0)
  228.     return -1;

  229.   fprintf (stderr, "Attached; pid = %d\n", pid);
  230.   fflush (stderr);

  231.   /* FIXME - It may be that we should get the SIGNAL_PID from the
  232.      attach function, so that it can be the main thread instead of
  233.      whichever we were told to attach to.  */
  234.   signal_pid = pid;

  235.   if (!non_stop)
  236.     {
  237.       last_ptid = mywait (pid_to_ptid (pid), &last_status, 0, 0);

  238.       /* GDB knows to ignore the first SIGSTOP after attaching to a running
  239.          process using the "attach" command, but this is different; it's
  240.          just using "target remote".  Pretend it's just starting up.  */
  241.       if (last_status.kind == TARGET_WAITKIND_STOPPED
  242.           && last_status.value.sig == GDB_SIGNAL_STOP)
  243.         last_status.value.sig = GDB_SIGNAL_TRAP;

  244.       current_thread->last_resume_kind = resume_stop;
  245.       current_thread->last_status = last_status;
  246.     }

  247.   return 0;
  248. }

  249. extern int remote_debug;

  250. /* Decode a qXfer read request.  Return 0 if everything looks OK,
  251.    or -1 otherwise.  */

  252. static int
  253. decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
  254. {
  255.   /* After the read marker and annex, qXfer looks like a
  256.      traditional 'm' packet.  */
  257.   decode_m_packet (buf, ofs, len);

  258.   return 0;
  259. }

  260. static int
  261. decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
  262. {
  263.   /* Extract and NUL-terminate the object.  */
  264.   *object = buf;
  265.   while (*buf && *buf != ':')
  266.     buf++;
  267.   if (*buf == '\0')
  268.     return -1;
  269.   *buf++ = 0;

  270.   /* Extract and NUL-terminate the read/write action.  */
  271.   *rw = buf;
  272.   while (*buf && *buf != ':')
  273.     buf++;
  274.   if (*buf == '\0')
  275.     return -1;
  276.   *buf++ = 0;

  277.   /* Extract and NUL-terminate the annex.  */
  278.   *annex = buf;
  279.   while (*buf && *buf != ':')
  280.     buf++;
  281.   if (*buf == '\0')
  282.     return -1;
  283.   *buf++ = 0;

  284.   *offset = buf;
  285.   return 0;
  286. }

  287. /* Write the response to a successful qXfer read.  Returns the
  288.    length of the (binary) data stored in BUF, corresponding
  289.    to as much of DATA/LEN as we could fit.  IS_MORE controls
  290.    the first character of the response.  */
  291. static int
  292. write_qxfer_response (char *buf, const void *data, int len, int is_more)
  293. {
  294.   int out_len;

  295.   if (is_more)
  296.     buf[0] = 'm';
  297.   else
  298.     buf[0] = 'l';

  299.   return remote_escape_output (data, len, (unsigned char *) buf + 1, &out_len,
  300.                                PBUFSIZ - 2) + 1;
  301. }

  302. /* Handle btrace enabling.  */

  303. static const char *
  304. handle_btrace_enable (struct thread_info *thread)
  305. {
  306.   if (thread->btrace != NULL)
  307.     return "E.Btrace already enabled.";

  308.   thread->btrace = target_enable_btrace (thread->entry.id);
  309.   if (thread->btrace == NULL)
  310.     return "E.Could not enable btrace.";

  311.   return NULL;
  312. }

  313. /* Handle btrace disabling.  */

  314. static const char *
  315. handle_btrace_disable (struct thread_info *thread)
  316. {

  317.   if (thread->btrace == NULL)
  318.     return "E.Branch tracing not enabled.";

  319.   if (target_disable_btrace (thread->btrace) != 0)
  320.     return "E.Could not disable branch tracing.";

  321.   thread->btrace = NULL;
  322.   return NULL;
  323. }

  324. /* Handle the "Qbtrace" packet.  */

  325. static int
  326. handle_btrace_general_set (char *own_buf)
  327. {
  328.   struct thread_info *thread;
  329.   const char *err;
  330.   char *op;

  331.   if (strncmp ("Qbtrace:", own_buf, strlen ("Qbtrace:")) != 0)
  332.     return 0;

  333.   op = own_buf + strlen ("Qbtrace:");

  334.   if (!target_supports_btrace ())
  335.     {
  336.       strcpy (own_buf, "E.Target does not support branch tracing.");
  337.       return -1;
  338.     }

  339.   if (ptid_equal (general_thread, null_ptid)
  340.       || ptid_equal (general_thread, minus_one_ptid))
  341.     {
  342.       strcpy (own_buf, "E.Must select a single thread.");
  343.       return -1;
  344.     }

  345.   thread = find_thread_ptid (general_thread);
  346.   if (thread == NULL)
  347.     {
  348.       strcpy (own_buf, "E.No such thread.");
  349.       return -1;
  350.     }

  351.   err = NULL;

  352.   if (strcmp (op, "bts") == 0)
  353.     err = handle_btrace_enable (thread);
  354.   else if (strcmp (op, "off") == 0)
  355.     err = handle_btrace_disable (thread);
  356.   else
  357.     err = "E.Bad Qbtrace operation. Use bts or off.";

  358.   if (err != 0)
  359.     strcpy (own_buf, err);
  360.   else
  361.     write_ok (own_buf);

  362.   return 1;
  363. }

  364. /* Handle all of the extended 'Q' packets.  */

  365. static void
  366. handle_general_set (char *own_buf)
  367. {
  368.   if (strncmp ("QPassSignals:", own_buf, strlen ("QPassSignals:")) == 0)
  369.     {
  370.       int numsigs = (int) GDB_SIGNAL_LAST, i;
  371.       const char *p = own_buf + strlen ("QPassSignals:");
  372.       CORE_ADDR cursig;

  373.       p = decode_address_to_semicolon (&cursig, p);
  374.       for (i = 0; i < numsigs; i++)
  375.         {
  376.           if (i == cursig)
  377.             {
  378.               pass_signals[i] = 1;
  379.               if (*p == '\0')
  380.                 /* Keep looping, to clear the remaining signals.  */
  381.                 cursig = -1;
  382.               else
  383.                 p = decode_address_to_semicolon (&cursig, p);
  384.             }
  385.           else
  386.             pass_signals[i] = 0;
  387.         }
  388.       strcpy (own_buf, "OK");
  389.       return;
  390.     }

  391.   if (strncmp ("QProgramSignals:", own_buf, strlen ("QProgramSignals:")) == 0)
  392.     {
  393.       int numsigs = (int) GDB_SIGNAL_LAST, i;
  394.       const char *p = own_buf + strlen ("QProgramSignals:");
  395.       CORE_ADDR cursig;

  396.       program_signals_p = 1;

  397.       p = decode_address_to_semicolon (&cursig, p);
  398.       for (i = 0; i < numsigs; i++)
  399.         {
  400.           if (i == cursig)
  401.             {
  402.               program_signals[i] = 1;
  403.               if (*p == '\0')
  404.                 /* Keep looping, to clear the remaining signals.  */
  405.                 cursig = -1;
  406.               else
  407.                 p = decode_address_to_semicolon (&cursig, p);
  408.             }
  409.           else
  410.             program_signals[i] = 0;
  411.         }
  412.       strcpy (own_buf, "OK");
  413.       return;
  414.     }

  415.   if (strcmp (own_buf, "QStartNoAckMode") == 0)
  416.     {
  417.       if (remote_debug)
  418.         {
  419.           fprintf (stderr, "[noack mode enabled]\n");
  420.           fflush (stderr);
  421.         }

  422.       noack_mode = 1;
  423.       write_ok (own_buf);
  424.       return;
  425.     }

  426.   if (strncmp (own_buf, "QNonStop:", 9) == 0)
  427.     {
  428.       char *mode = own_buf + 9;
  429.       int req = -1;
  430.       char *req_str;

  431.       if (strcmp (mode, "0") == 0)
  432.         req = 0;
  433.       else if (strcmp (mode, "1") == 0)
  434.         req = 1;
  435.       else
  436.         {
  437.           /* We don't know what this mode is, so complain to
  438.              GDB.  */
  439.           fprintf (stderr, "Unknown non-stop mode requested: %s\n",
  440.                    own_buf);
  441.           write_enn (own_buf);
  442.           return;
  443.         }

  444.       req_str = req ? "non-stop" : "all-stop";
  445.       if (start_non_stop (req) != 0)
  446.         {
  447.           fprintf (stderr, "Setting %s mode failed\n", req_str);
  448.           write_enn (own_buf);
  449.           return;
  450.         }

  451.       non_stop = req;

  452.       if (remote_debug)
  453.         fprintf (stderr, "[%s mode enabled]\n", req_str);

  454.       write_ok (own_buf);
  455.       return;
  456.     }

  457.   if (strncmp ("QDisableRandomization:", own_buf,
  458.                strlen ("QDisableRandomization:")) == 0)
  459.     {
  460.       char *packet = own_buf + strlen ("QDisableRandomization:");
  461.       ULONGEST setting;

  462.       unpack_varlen_hex (packet, &setting);
  463.       disable_randomization = setting;

  464.       if (remote_debug)
  465.         {
  466.           if (disable_randomization)
  467.             fprintf (stderr, "[address space randomization disabled]\n");
  468.           else
  469.             fprintf (stderr, "[address space randomization enabled]\n");
  470.         }

  471.       write_ok (own_buf);
  472.       return;
  473.     }

  474.   if (target_supports_tracepoints ()
  475.       && handle_tracepoint_general_set (own_buf))
  476.     return;

  477.   if (strncmp ("QAgent:", own_buf, strlen ("QAgent:")) == 0)
  478.     {
  479.       char *mode = own_buf + strlen ("QAgent:");
  480.       int req = 0;

  481.       if (strcmp (mode, "0") == 0)
  482.         req = 0;
  483.       else if (strcmp (mode, "1") == 0)
  484.         req = 1;
  485.       else
  486.         {
  487.           /* We don't know what this value is, so complain to GDB.  */
  488.           sprintf (own_buf, "E.Unknown QAgent value");
  489.           return;
  490.         }

  491.       /* Update the flag.  */
  492.       use_agent = req;
  493.       if (remote_debug)
  494.         fprintf (stderr, "[%s agent]\n", req ? "Enable" : "Disable");
  495.       write_ok (own_buf);
  496.       return;
  497.     }

  498.   if (handle_btrace_general_set (own_buf))
  499.     return;

  500.   /* Otherwise we didn't know what packet it was.  Say we didn't
  501.      understand it.  */
  502.   own_buf[0] = 0;
  503. }

  504. static const char *
  505. get_features_xml (const char *annex)
  506. {
  507.   const struct target_desc *desc = current_target_desc ();

  508.   /* `desc->xmltarget' defines what to return when looking for the
  509.      "target.xml" file.  Its contents can either be verbatim XML code
  510.      (prefixed with a '@') or else the name of the actual XML file to
  511.      be used in place of "target.xml".

  512.      This variable is set up from the auto-generated
  513.      init_registers_... routine for the current target.  */

  514.   if (desc->xmltarget != NULL && strcmp (annex, "target.xml") == 0)
  515.     {
  516.       if (*desc->xmltarget == '@')
  517.         return desc->xmltarget + 1;
  518.       else
  519.         annex = desc->xmltarget;
  520.     }

  521. #ifdef USE_XML
  522.   {
  523.     extern const char *const xml_builtin[][2];
  524.     int i;

  525.     /* Look for the annex.  */
  526.     for (i = 0; xml_builtin[i][0] != NULL; i++)
  527.       if (strcmp (annex, xml_builtin[i][0]) == 0)
  528.         break;

  529.     if (xml_builtin[i][0] != NULL)
  530.       return xml_builtin[i][1];
  531.   }
  532. #endif

  533.   return NULL;
  534. }

  535. void
  536. monitor_show_help (void)
  537. {
  538.   monitor_output ("The following monitor commands are supported:\n");
  539.   monitor_output (set debug <0|1>\n");
  540.   monitor_output ("    Enable general debugging messages\n");
  541.   monitor_output (set debug-hw-points <0|1>\n");
  542.   monitor_output ("    Enable h/w breakpoint/watchpoint debugging messages\n");
  543.   monitor_output (set remote-debug <0|1>\n");
  544.   monitor_output ("    Enable remote protocol debugging messages\n");
  545.   monitor_output (set debug-format option1[,option2,...]\n");
  546.   monitor_output ("    Add additional information to debugging messages\n");
  547.   monitor_output ("    Options: all, none");
  548.   monitor_output (", timestamp");
  549.   monitor_output ("\n");
  550.   monitor_output ("  exit\n");
  551.   monitor_output ("    Quit GDBserver\n");
  552. }

  553. /* Read trace frame or inferior memory.  Returns the number of bytes
  554.    actually read, zero when no further transfer is possible, and -1 on
  555.    error.  Return of a positive value smaller than LEN does not
  556.    indicate there's no more to be read, only the end of the transfer.
  557.    E.g., when GDB reads memory from a traceframe, a first request may
  558.    be served from a memory block that does not cover the whole request
  559.    length.  A following request gets the rest served from either
  560.    another block (of the same traceframe) or from the read-only
  561.    regions.  */

  562. static int
  563. gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
  564. {
  565.   int res;

  566.   if (current_traceframe >= 0)
  567.     {
  568.       ULONGEST nbytes;
  569.       ULONGEST length = len;

  570.       if (traceframe_read_mem (current_traceframe,
  571.                                memaddr, myaddr, len, &nbytes))
  572.         return -1;
  573.       /* Data read from trace buffer, we're done.  */
  574.       if (nbytes > 0)
  575.         return nbytes;
  576.       if (!in_readonly_region (memaddr, length))
  577.         return -1;
  578.       /* Otherwise we have a valid readonly case, fall through.  */
  579.       /* (assume no half-trace half-real blocks for now) */
  580.     }

  581.   res = prepare_to_access_memory ();
  582.   if (res == 0)
  583.     {
  584.       res = read_inferior_memory (memaddr, myaddr, len);
  585.       done_accessing_memory ();

  586.       return res == 0 ? len : -1;
  587.     }
  588.   else
  589.     return -1;
  590. }

  591. /* Write trace frame or inferior memory.  Actually, writing to trace
  592.    frames is forbidden.  */

  593. static int
  594. gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
  595. {
  596.   if (current_traceframe >= 0)
  597.     return EIO;
  598.   else
  599.     {
  600.       int ret;

  601.       ret = prepare_to_access_memory ();
  602.       if (ret == 0)
  603.         {
  604.           ret = write_inferior_memory (memaddr, myaddr, len);
  605.           done_accessing_memory ();
  606.         }
  607.       return ret;
  608.     }
  609. }

  610. /* Subroutine of handle_search_memory to simplify it.  */

  611. static int
  612. handle_search_memory_1 (CORE_ADDR start_addr, CORE_ADDR search_space_len,
  613.                         gdb_byte *pattern, unsigned pattern_len,
  614.                         gdb_byte *search_buf,
  615.                         unsigned chunk_size, unsigned search_buf_size,
  616.                         CORE_ADDR *found_addrp)
  617. {
  618.   /* Prime the search buffer.  */

  619.   if (gdb_read_memory (start_addr, search_buf, search_buf_size)
  620.       != search_buf_size)
  621.     {
  622.       warning ("Unable to access %ld bytes of target "
  623.                "memory at 0x%lx, halting search.",
  624.                (long) search_buf_size, (long) start_addr);
  625.       return -1;
  626.     }

  627.   /* Perform the search.

  628.      The loop is kept simple by allocating [N + pattern-length - 1] bytes.
  629.      When we've scanned N bytes we copy the trailing bytes to the start and
  630.      read in another N bytes.  */

  631.   while (search_space_len >= pattern_len)
  632.     {
  633.       gdb_byte *found_ptr;
  634.       unsigned nr_search_bytes = (search_space_len < search_buf_size
  635.                                   ? search_space_len
  636.                                   : search_buf_size);

  637.       found_ptr = memmem (search_buf, nr_search_bytes, pattern, pattern_len);

  638.       if (found_ptr != NULL)
  639.         {
  640.           CORE_ADDR found_addr = start_addr + (found_ptr - search_buf);
  641.           *found_addrp = found_addr;
  642.           return 1;
  643.         }

  644.       /* Not found in this chunk, skip to next chunk.  */

  645.       /* Don't let search_space_len wrap here, it's unsigned.  */
  646.       if (search_space_len >= chunk_size)
  647.         search_space_len -= chunk_size;
  648.       else
  649.         search_space_len = 0;

  650.       if (search_space_len >= pattern_len)
  651.         {
  652.           unsigned keep_len = search_buf_size - chunk_size;
  653.           CORE_ADDR read_addr = start_addr + chunk_size + keep_len;
  654.           int nr_to_read;

  655.           /* Copy the trailing part of the previous iteration to the front
  656.              of the buffer for the next iteration.  */
  657.           memcpy (search_buf, search_buf + chunk_size, keep_len);

  658.           nr_to_read = (search_space_len - keep_len < chunk_size
  659.                         ? search_space_len - keep_len
  660.                         : chunk_size);

  661.           if (gdb_read_memory (read_addr, search_buf + keep_len,
  662.                                nr_to_read) != search_buf_size)
  663.             {
  664.               warning ("Unable to access %ld bytes of target memory "
  665.                        "at 0x%lx, halting search.",
  666.                        (long) nr_to_read, (long) read_addr);
  667.               return -1;
  668.             }

  669.           start_addr += chunk_size;
  670.         }
  671.     }

  672.   /* Not found.  */

  673.   return 0;
  674. }

  675. /* Handle qSearch:memory packets.  */

  676. static void
  677. handle_search_memory (char *own_buf, int packet_len)
  678. {
  679.   CORE_ADDR start_addr;
  680.   CORE_ADDR search_space_len;
  681.   gdb_byte *pattern;
  682.   unsigned int pattern_len;
  683.   /* NOTE: also defined in find.c testcase.  */
  684. #define SEARCH_CHUNK_SIZE 16000
  685.   const unsigned chunk_size = SEARCH_CHUNK_SIZE;
  686.   /* Buffer to hold memory contents for searching.  */
  687.   gdb_byte *search_buf;
  688.   unsigned search_buf_size;
  689.   int found;
  690.   CORE_ADDR found_addr;
  691.   int cmd_name_len = sizeof ("qSearch:memory:") - 1;

  692.   pattern = malloc (packet_len);
  693.   if (pattern == NULL)
  694.     {
  695.       error ("Unable to allocate memory to perform the search");
  696.       strcpy (own_buf, "E00");
  697.       return;
  698.     }
  699.   if (decode_search_memory_packet (own_buf + cmd_name_len,
  700.                                    packet_len - cmd_name_len,
  701.                                    &start_addr, &search_space_len,
  702.                                    pattern, &pattern_len) < 0)
  703.     {
  704.       free (pattern);
  705.       error ("Error in parsing qSearch:memory packet");
  706.       strcpy (own_buf, "E00");
  707.       return;
  708.     }

  709.   search_buf_size = chunk_size + pattern_len - 1;

  710.   /* No point in trying to allocate a buffer larger than the search space.  */
  711.   if (search_space_len < search_buf_size)
  712.     search_buf_size = search_space_len;

  713.   search_buf = malloc (search_buf_size);
  714.   if (search_buf == NULL)
  715.     {
  716.       free (pattern);
  717.       error ("Unable to allocate memory to perform the search");
  718.       strcpy (own_buf, "E00");
  719.       return;
  720.     }

  721.   found = handle_search_memory_1 (start_addr, search_space_len,
  722.                                   pattern, pattern_len,
  723.                                   search_buf, chunk_size, search_buf_size,
  724.                                   &found_addr);

  725.   if (found > 0)
  726.     sprintf (own_buf, "1,%lx", (long) found_addr);
  727.   else if (found == 0)
  728.     strcpy (own_buf, "0");
  729.   else
  730.     strcpy (own_buf, "E00");

  731.   free (search_buf);
  732.   free (pattern);
  733. }

  734. #define require_running(BUF)                        \
  735.   if (!target_running ())                        \
  736.     {                                                \
  737.       write_enn (BUF);                                \
  738.       return;                                        \
  739.     }

  740. /* Parse options to --debug-format= and "monitor set debug-format".
  741.    ARG is the text after "--debug-format=" or "monitor set debug-format".
  742.    IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
  743.    This triggers calls to monitor_output.
  744.    The result is NULL if all options were parsed ok, otherwise an error
  745.    message which the caller must free.

  746.    N.B. These commands affect all debug format settings, they are not
  747.    cumulative.  If a format is not specified, it is turned off.
  748.    However, we don't go to extra trouble with things like
  749.    "monitor set debug-format all,none,timestamp".
  750.    Instead we just parse them one at a time, in order.

  751.    The syntax for "monitor set debug" we support here is not identical
  752.    to gdb's "set debug foo on|off" because we also use this function to
  753.    parse "--debug-format=foo,bar".  */

  754. static char *
  755. parse_debug_format_options (const char *arg, int is_monitor)
  756. {
  757.   VEC (char_ptr) *options;
  758.   int ix;
  759.   char *option;

  760.   /* First turn all debug format options off.  */
  761.   debug_timestamp = 0;

  762.   /* First remove leading spaces, for "monitor set debug-format".  */
  763.   while (isspace (*arg))
  764.     ++arg;

  765.   options = delim_string_to_char_ptr_vec (arg, ',');

  766.   for (ix = 0; VEC_iterate (char_ptr, options, ix, option); ++ix)
  767.     {
  768.       if (strcmp (option, "all") == 0)
  769.         {
  770.           debug_timestamp = 1;
  771.           if (is_monitor)
  772.             monitor_output ("All extra debug format options enabled.\n");
  773.         }
  774.       else if (strcmp (option, "none") == 0)
  775.         {
  776.           debug_timestamp = 0;
  777.           if (is_monitor)
  778.             monitor_output ("All extra debug format options disabled.\n");
  779.         }
  780.       else if (strcmp (option, "timestamp") == 0)
  781.         {
  782.           debug_timestamp = 1;
  783.           if (is_monitor)
  784.             monitor_output ("Timestamps will be added to debug output.\n");
  785.         }
  786.       else if (*option == '\0')
  787.         {
  788.           /* An empty option, e.g., "--debug-format=foo,,bar", is ignored.  */
  789.           continue;
  790.         }
  791.       else
  792.         {
  793.           char *msg = xstrprintf ("Unknown debug-format argument: \"%s\"\n",
  794.                                   option);

  795.           free_char_ptr_vec (options);
  796.           return msg;
  797.         }
  798.     }

  799.   free_char_ptr_vec (options);
  800.   return NULL;
  801. }

  802. /* Handle monitor commands not handled by target-specific handlers.  */

  803. static void
  804. handle_monitor_command (char *mon, char *own_buf)
  805. {
  806.   if (strcmp (mon, "set debug 1") == 0)
  807.     {
  808.       debug_threads = 1;
  809.       monitor_output ("Debug output enabled.\n");
  810.     }
  811.   else if (strcmp (mon, "set debug 0") == 0)
  812.     {
  813.       debug_threads = 0;
  814.       monitor_output ("Debug output disabled.\n");
  815.     }
  816.   else if (strcmp (mon, "set debug-hw-points 1") == 0)
  817.     {
  818.       show_debug_regs = 1;
  819.       monitor_output ("H/W point debugging output enabled.\n");
  820.     }
  821.   else if (strcmp (mon, "set debug-hw-points 0") == 0)
  822.     {
  823.       show_debug_regs = 0;
  824.       monitor_output ("H/W point debugging output disabled.\n");
  825.     }
  826.   else if (strcmp (mon, "set remote-debug 1") == 0)
  827.     {
  828.       remote_debug = 1;
  829.       monitor_output ("Protocol debug output enabled.\n");
  830.     }
  831.   else if (strcmp (mon, "set remote-debug 0") == 0)
  832.     {
  833.       remote_debug = 0;
  834.       monitor_output ("Protocol debug output disabled.\n");
  835.     }
  836.   else if (strncmp (mon, "set debug-format ",
  837.                     sizeof ("set debug-format ") - 1) == 0)
  838.     {
  839.       char *error_msg
  840.         = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
  841.                                       1);

  842.       if (error_msg != NULL)
  843.         {
  844.           monitor_output (error_msg);
  845.           monitor_show_help ();
  846.           write_enn (own_buf);
  847.           xfree (error_msg);
  848.         }
  849.     }
  850.   else if (strcmp (mon, "help") == 0)
  851.     monitor_show_help ();
  852.   else if (strcmp (mon, "exit") == 0)
  853.     exit_requested = 1;
  854.   else
  855.     {
  856.       monitor_output ("Unknown monitor command.\n\n");
  857.       monitor_show_help ();
  858.       write_enn (own_buf);
  859.     }
  860. }

  861. /* Associates a callback with each supported qXfer'able object.  */

  862. struct qxfer
  863. {
  864.   /* The object this handler handles.  */
  865.   const char *object;

  866.   /* Request that the target transfer up to LEN 8-bit bytes of the
  867.      target's OBJECT.  The OFFSET, for a seekable object, specifies
  868.      the starting point.  The ANNEX can be used to provide additional
  869.      data-specific information to the target.

  870.      Return the number of bytes actually transfered, zero when no
  871.      further transfer is possible, -1 on error, -2 when the transfer
  872.      is not supported, and -3 on a verbose error message that should
  873.      be preserved.  Return of a positive value smaller than LEN does
  874.      not indicate the end of the object, only the end of the transfer.

  875.      One, and only one, of readbuf or writebuf must be non-NULL.  */
  876.   int (*xfer) (const char *annex,
  877.                gdb_byte *readbuf, const gdb_byte *writebuf,
  878.                ULONGEST offset, LONGEST len);
  879. };

  880. /* Handle qXfer:auxv:read.  */

  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.   if (annex[0] != '\0' || !target_running ())
  889.     return -1;

  890.   return (*the_target->read_auxv) (offset, readbuf, len);
  891. }

  892. /* Handle qXfer:features:read.  */

  893. static int
  894. handle_qxfer_features (const char *annex,
  895.                        gdb_byte *readbuf, const gdb_byte *writebuf,
  896.                        ULONGEST offset, LONGEST len)
  897. {
  898.   const char *document;
  899.   size_t total_len;

  900.   if (writebuf != NULL)
  901.     return -2;

  902.   if (!target_running ())
  903.     return -1;

  904.   /* Grab the correct annex.  */
  905.   document = get_features_xml (annex);
  906.   if (document == NULL)
  907.     return -1;

  908.   total_len = strlen (document);

  909.   if (offset > total_len)
  910.     return -1;

  911.   if (offset + len > total_len)
  912.     len = total_len - offset;

  913.   memcpy (readbuf, document + offset, len);
  914.   return len;
  915. }

  916. /* Worker routine for handle_qxfer_libraries.
  917.    Add to the length pointed to by ARG a conservative estimate of the
  918.    length needed to transmit the file name of INF.  */

  919. static void
  920. accumulate_file_name_length (struct inferior_list_entry *inf, void *arg)
  921. {
  922.   struct dll_info *dll = (struct dll_info *) inf;
  923.   unsigned int *total_len = arg;

  924.   /* Over-estimate the necessary memory.  Assume that every character
  925.      in the library name must be escaped.  */
  926.   *total_len += 128 + 6 * strlen (dll->name);
  927. }

  928. /* Worker routine for handle_qxfer_libraries.
  929.    Emit the XML to describe the library in INF.  */

  930. static void
  931. emit_dll_description (struct inferior_list_entry *inf, void *arg)
  932. {
  933.   struct dll_info *dll = (struct dll_info *) inf;
  934.   char **p_ptr = arg;
  935.   char *p = *p_ptr;
  936.   char *name;

  937.   strcpy (p, "  <library name=\"");
  938.   p = p + strlen (p);
  939.   name = xml_escape_text (dll->name);
  940.   strcpy (p, name);
  941.   free (name);
  942.   p = p + strlen (p);
  943.   strcpy (p, "\"><segment address=\"");
  944.   p = p + strlen (p);
  945.   sprintf (p, "0x%lx", (long) dll->base_addr);
  946.   p = p + strlen (p);
  947.   strcpy (p, "\"/></library>\n");
  948.   p = p + strlen (p);

  949.   *p_ptr = p;
  950. }

  951. /* Handle qXfer:libraries:read.  */

  952. static int
  953. handle_qxfer_libraries (const char *annex,
  954.                         gdb_byte *readbuf, const gdb_byte *writebuf,
  955.                         ULONGEST offset, LONGEST len)
  956. {
  957.   unsigned int total_len;
  958.   char *document, *p;

  959.   if (writebuf != NULL)
  960.     return -2;

  961.   if (annex[0] != '\0' || !target_running ())
  962.     return -1;

  963.   total_len = 64;
  964.   for_each_inferior_with_data (&all_dlls, accumulate_file_name_length,
  965.                                &total_len);

  966.   document = malloc (total_len);
  967.   if (document == NULL)
  968.     return -1;

  969.   strcpy (document, "<library-list>\n");
  970.   p = document + strlen (document);

  971.   for_each_inferior_with_data (&all_dlls, emit_dll_description, &p);

  972.   strcpy (p, "</library-list>\n");

  973.   total_len = strlen (document);

  974.   if (offset > total_len)
  975.     {
  976.       free (document);
  977.       return -1;
  978.     }

  979.   if (offset + len > total_len)
  980.     len = total_len - offset;

  981.   memcpy (readbuf, document + offset, len);
  982.   free (document);
  983.   return len;
  984. }

  985. /* Handle qXfer:libraries-svr4:read.  */

  986. static int
  987. handle_qxfer_libraries_svr4 (const char *annex,
  988.                              gdb_byte *readbuf, const gdb_byte *writebuf,
  989.                              ULONGEST offset, LONGEST len)
  990. {
  991.   if (writebuf != NULL)
  992.     return -2;

  993.   if (!target_running () || the_target->qxfer_libraries_svr4 == NULL)
  994.     return -1;

  995.   return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf, offset, len);
  996. }

  997. /* Handle qXfer:osadata:read.  */

  998. static int
  999. handle_qxfer_osdata (const char *annex,
  1000.                      gdb_byte *readbuf, const gdb_byte *writebuf,
  1001.                      ULONGEST offset, LONGEST len)
  1002. {
  1003.   if (the_target->qxfer_osdata == NULL || writebuf != NULL)
  1004.     return -2;

  1005.   return (*the_target->qxfer_osdata) (annex, readbuf, NULL, offset, len);
  1006. }

  1007. /* Handle qXfer:siginfo:read and qXfer:siginfo:write.  */

  1008. static int
  1009. handle_qxfer_siginfo (const char *annex,
  1010.                       gdb_byte *readbuf, const gdb_byte *writebuf,
  1011.                       ULONGEST offset, LONGEST len)
  1012. {
  1013.   if (the_target->qxfer_siginfo == NULL)
  1014.     return -2;

  1015.   if (annex[0] != '\0' || !target_running ())
  1016.     return -1;

  1017.   return (*the_target->qxfer_siginfo) (annex, readbuf, writebuf, offset, len);
  1018. }

  1019. /* Handle qXfer:spu:read and qXfer:spu:write.  */

  1020. static int
  1021. handle_qxfer_spu (const char *annex,
  1022.                   gdb_byte *readbuf, const gdb_byte *writebuf,
  1023.                   ULONGEST offset, LONGEST len)
  1024. {
  1025.   if (the_target->qxfer_spu == NULL)
  1026.     return -2;

  1027.   if (!target_running ())
  1028.     return -1;

  1029.   return (*the_target->qxfer_spu) (annex, readbuf, writebuf, offset, len);
  1030. }

  1031. /* Handle qXfer:statictrace:read.  */

  1032. static int
  1033. handle_qxfer_statictrace (const char *annex,
  1034.                           gdb_byte *readbuf, const gdb_byte *writebuf,
  1035.                           ULONGEST offset, LONGEST len)
  1036. {
  1037.   ULONGEST nbytes;

  1038.   if (writebuf != NULL)
  1039.     return -2;

  1040.   if (annex[0] != '\0' || !target_running () || current_traceframe == -1)
  1041.     return -1;

  1042.   if (traceframe_read_sdata (current_traceframe, offset,
  1043.                              readbuf, len, &nbytes))
  1044.     return -1;
  1045.   return nbytes;
  1046. }

  1047. /* Helper for handle_qxfer_threads_proper.
  1048.    Emit the XML to describe the thread of INF.  */

  1049. static void
  1050. handle_qxfer_threads_worker (struct inferior_list_entry *inf, void *arg)
  1051. {
  1052.   struct thread_info *thread = (struct thread_info *) inf;
  1053.   struct buffer *buffer = arg;
  1054.   ptid_t ptid = thread_to_gdb_id (thread);
  1055.   char ptid_s[100];
  1056.   int core = target_core_of_thread (ptid);
  1057.   char core_s[21];

  1058.   write_ptid (ptid_s, ptid);

  1059.   if (core != -1)
  1060.     {
  1061.       sprintf (core_s, "%d", core);
  1062.       buffer_xml_printf (buffer, "<thread id=\"%s\" core=\"%s\"/>\n",
  1063.                          ptid_s, core_s);
  1064.     }
  1065.   else
  1066.     {
  1067.       buffer_xml_printf (buffer, "<thread id=\"%s\"/>\n",
  1068.                          ptid_s);
  1069.     }
  1070. }

  1071. /* Helper for handle_qxfer_threads.  */

  1072. static void
  1073. handle_qxfer_threads_proper (struct buffer *buffer)
  1074. {
  1075.   buffer_grow_str (buffer, "<threads>\n");

  1076.   for_each_inferior_with_data (&all_threads, handle_qxfer_threads_worker,
  1077.                                buffer);

  1078.   buffer_grow_str0 (buffer, "</threads>\n");
  1079. }

  1080. /* Handle qXfer:threads:read.  */

  1081. static int
  1082. handle_qxfer_threads (const char *annex,
  1083.                       gdb_byte *readbuf, const gdb_byte *writebuf,
  1084.                       ULONGEST offset, LONGEST len)
  1085. {
  1086.   static char *result = 0;
  1087.   static unsigned int result_length = 0;

  1088.   if (writebuf != NULL)
  1089.     return -2;

  1090.   if (!target_running () || annex[0] != '\0')
  1091.     return -1;

  1092.   if (offset == 0)
  1093.     {
  1094.       struct buffer buffer;
  1095.       /* When asked for data at offset 0, generate everything and store into
  1096.          'result'.  Successive reads will be served off 'result'.  */
  1097.       if (result)
  1098.         free (result);

  1099.       buffer_init (&buffer);

  1100.       handle_qxfer_threads_proper (&buffer);

  1101.       result = buffer_finish (&buffer);
  1102.       result_length = strlen (result);
  1103.       buffer_free (&buffer);
  1104.     }

  1105.   if (offset >= result_length)
  1106.     {
  1107.       /* We're out of data.  */
  1108.       free (result);
  1109.       result = NULL;
  1110.       result_length = 0;
  1111.       return 0;
  1112.     }

  1113.   if (len > result_length - offset)
  1114.     len = result_length - offset;

  1115.   memcpy (readbuf, result + offset, len);

  1116.   return len;
  1117. }

  1118. /* Handle qXfer:traceframe-info:read.  */

  1119. static int
  1120. handle_qxfer_traceframe_info (const char *annex,
  1121.                               gdb_byte *readbuf, const gdb_byte *writebuf,
  1122.                               ULONGEST offset, LONGEST len)
  1123. {
  1124.   static char *result = 0;
  1125.   static unsigned int result_length = 0;

  1126.   if (writebuf != NULL)
  1127.     return -2;

  1128.   if (!target_running () || annex[0] != '\0' || current_traceframe == -1)
  1129.     return -1;

  1130.   if (offset == 0)
  1131.     {
  1132.       struct buffer buffer;

  1133.       /* When asked for data at offset 0, generate everything and
  1134.          store into 'result'.  Successive reads will be served off
  1135.          'result'.  */
  1136.       free (result);

  1137.       buffer_init (&buffer);

  1138.       traceframe_read_info (current_traceframe, &buffer);

  1139.       result = buffer_finish (&buffer);
  1140.       result_length = strlen (result);
  1141.       buffer_free (&buffer);
  1142.     }

  1143.   if (offset >= result_length)
  1144.     {
  1145.       /* We're out of data.  */
  1146.       free (result);
  1147.       result = NULL;
  1148.       result_length = 0;
  1149.       return 0;
  1150.     }

  1151.   if (len > result_length - offset)
  1152.     len = result_length - offset;

  1153.   memcpy (readbuf, result + offset, len);
  1154.   return len;
  1155. }

  1156. /* Handle qXfer:fdpic:read.  */

  1157. static int
  1158. handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
  1159.                     const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
  1160. {
  1161.   if (the_target->read_loadmap == NULL)
  1162.     return -2;

  1163.   if (!target_running ())
  1164.     return -1;

  1165.   return (*the_target->read_loadmap) (annex, offset, readbuf, len);
  1166. }

  1167. /* Handle qXfer:btrace:read.  */

  1168. static int
  1169. handle_qxfer_btrace (const char *annex,
  1170.                      gdb_byte *readbuf, const gdb_byte *writebuf,
  1171.                      ULONGEST offset, LONGEST len)
  1172. {
  1173.   static struct buffer cache;
  1174.   struct thread_info *thread;
  1175.   int type, result;

  1176.   if (the_target->read_btrace == NULL || writebuf != NULL)
  1177.     return -2;

  1178.   if (!target_running ())
  1179.     return -1;

  1180.   if (ptid_equal (general_thread, null_ptid)
  1181.       || ptid_equal (general_thread, minus_one_ptid))
  1182.     {
  1183.       strcpy (own_buf, "E.Must select a single thread.");
  1184.       return -3;
  1185.     }

  1186.   thread = find_thread_ptid (general_thread);
  1187.   if (thread == NULL)
  1188.     {
  1189.       strcpy (own_buf, "E.No such thread.");
  1190.       return -3;
  1191.     }

  1192.   if (thread->btrace == NULL)
  1193.     {
  1194.       strcpy (own_buf, "E.Btrace not enabled.");
  1195.       return -3;
  1196.     }

  1197.   if (strcmp (annex, "all") == 0)
  1198.     type = BTRACE_READ_ALL;
  1199.   else if (strcmp (annex, "new") == 0)
  1200.     type = BTRACE_READ_NEW;
  1201.   else if (strcmp (annex, "delta") == 0)
  1202.     type = BTRACE_READ_DELTA;
  1203.   else
  1204.     {
  1205.       strcpy (own_buf, "E.Bad annex.");
  1206.       return -3;
  1207.     }

  1208.   if (offset == 0)
  1209.     {
  1210.       buffer_free (&cache);

  1211.       result = target_read_btrace (thread->btrace, &cache, type);
  1212.       if (result != 0)
  1213.         {
  1214.           memcpy (own_buf, cache.buffer, cache.used_size);
  1215.           return -3;
  1216.         }
  1217.     }
  1218.   else if (offset > cache.used_size)
  1219.     {
  1220.       buffer_free (&cache);
  1221.       return -3;
  1222.     }

  1223.   if (len > cache.used_size - offset)
  1224.     len = cache.used_size - offset;

  1225.   memcpy (readbuf, cache.buffer + offset, len);

  1226.   return len;
  1227. }

  1228. static const struct qxfer qxfer_packets[] =
  1229.   {
  1230.     { "auxv", handle_qxfer_auxv },
  1231.     { "btrace", handle_qxfer_btrace },
  1232.     { "fdpic", handle_qxfer_fdpic},
  1233.     { "features", handle_qxfer_features },
  1234.     { "libraries", handle_qxfer_libraries },
  1235.     { "libraries-svr4", handle_qxfer_libraries_svr4 },
  1236.     { "osdata", handle_qxfer_osdata },
  1237.     { "siginfo", handle_qxfer_siginfo },
  1238.     { "spu", handle_qxfer_spu },
  1239.     { "statictrace", handle_qxfer_statictrace },
  1240.     { "threads", handle_qxfer_threads },
  1241.     { "traceframe-info", handle_qxfer_traceframe_info },
  1242.   };

  1243. static int
  1244. handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
  1245. {
  1246.   int i;
  1247.   char *object;
  1248.   char *rw;
  1249.   char *annex;
  1250.   char *offset;

  1251.   if (strncmp (own_buf, "qXfer:", 6) != 0)
  1252.     return 0;

  1253.   /* Grab the object, r/w and annex.  */
  1254.   if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
  1255.     {
  1256.       write_enn (own_buf);
  1257.       return 1;
  1258.     }

  1259.   for (i = 0;
  1260.        i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
  1261.        i++)
  1262.     {
  1263.       const struct qxfer *q = &qxfer_packets[i];

  1264.       if (strcmp (object, q->object) == 0)
  1265.         {
  1266.           if (strcmp (rw, "read") == 0)
  1267.             {
  1268.               unsigned char *data;
  1269.               int n;
  1270.               CORE_ADDR ofs;
  1271.               unsigned int len;

  1272.               /* Grab the offset and length.  */
  1273.               if (decode_xfer_read (offset, &ofs, &len) < 0)
  1274.                 {
  1275.                   write_enn (own_buf);
  1276.                   return 1;
  1277.                 }

  1278.               /* Read one extra byte, as an indicator of whether there is
  1279.                  more.  */
  1280.               if (len > PBUFSIZ - 2)
  1281.                 len = PBUFSIZ - 2;
  1282.               data = malloc (len + 1);
  1283.               if (data == NULL)
  1284.                 {
  1285.                   write_enn (own_buf);
  1286.                   return 1;
  1287.                 }
  1288.               n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
  1289.               if (n == -2)
  1290.                 {
  1291.                   free (data);
  1292.                   return 0;
  1293.                 }
  1294.               else if (n == -3)
  1295.                 {
  1296.                   /* Preserve error message.  */
  1297.                 }
  1298.               else if (n < 0)
  1299.                 write_enn (own_buf);
  1300.               else if (n > len)
  1301.                 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
  1302.               else
  1303.                 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);

  1304.               free (data);
  1305.               return 1;
  1306.             }
  1307.           else if (strcmp (rw, "write") == 0)
  1308.             {
  1309.               int n;
  1310.               unsigned int len;
  1311.               CORE_ADDR ofs;
  1312.               unsigned char *data;

  1313.               strcpy (own_buf, "E00");
  1314.               data = malloc (packet_len - (offset - own_buf));
  1315.               if (data == NULL)
  1316.                 {
  1317.                   write_enn (own_buf);
  1318.                   return 1;
  1319.                 }
  1320.               if (decode_xfer_write (offset, packet_len - (offset - own_buf),
  1321.                                      &ofs, &len, data) < 0)
  1322.                 {
  1323.                   free (data);
  1324.                   write_enn (own_buf);
  1325.                   return 1;
  1326.                 }

  1327.               n = (*q->xfer) (annex, NULL, data, ofs, len);
  1328.               if (n == -2)
  1329.                 {
  1330.                   free (data);
  1331.                   return 0;
  1332.                 }
  1333.               else if (n == -3)
  1334.                 {
  1335.                   /* Preserve error message.  */
  1336.                 }
  1337.               else if (n < 0)
  1338.                 write_enn (own_buf);
  1339.               else
  1340.                 sprintf (own_buf, "%x", n);

  1341.               free (data);
  1342.               return 1;
  1343.             }

  1344.           return 0;
  1345.         }
  1346.     }

  1347.   return 0;
  1348. }

  1349. /* Table used by the crc32 function to calcuate the checksum.  */

  1350. static unsigned int crc32_table[256] =
  1351. {0, 0};

  1352. /* Compute 32 bit CRC from inferior memory.

  1353.    On success, return 32 bit CRC.
  1354.    On failure, return (unsigned long long) -1.  */

  1355. static unsigned long long
  1356. crc32 (CORE_ADDR base, int len, unsigned int crc)
  1357. {
  1358.   if (!crc32_table[1])
  1359.     {
  1360.       /* Initialize the CRC table and the decoding table.  */
  1361.       int i, j;
  1362.       unsigned int c;

  1363.       for (i = 0; i < 256; i++)
  1364.         {
  1365.           for (c = i << 24, j = 8; j > 0; --j)
  1366.             c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
  1367.           crc32_table[i] = c;
  1368.         }
  1369.     }

  1370.   while (len--)
  1371.     {
  1372.       unsigned char byte = 0;

  1373.       /* Return failure if memory read fails.  */
  1374.       if (read_inferior_memory (base, &byte, 1) != 0)
  1375.         return (unsigned long long) -1;

  1376.       crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ byte) & 255];
  1377.       base++;
  1378.     }
  1379.   return (unsigned long long) crc;
  1380. }

  1381. /* Handle all of the extended 'q' packets.  */

  1382. void
  1383. handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
  1384. {
  1385.   static struct inferior_list_entry *thread_ptr;

  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.       if (!ptid_equal (general_thread, null_ptid)
  1392.           && !ptid_equal (general_thread, minus_one_ptid))
  1393.         gdb_id = general_thread;
  1394.       else
  1395.         {
  1396.           thread_ptr = get_first_inferior (&all_threads);
  1397.           gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
  1398.         }

  1399.       sprintf (own_buf, "QC");
  1400.       own_buf += 2;
  1401.       write_ptid (own_buf, gdb_id);
  1402.       return;
  1403.     }

  1404.   if (strcmp ("qSymbol::", own_buf) == 0)
  1405.     {
  1406.       /* GDB is suggesting new symbols have been loaded.  This may
  1407.          mean a new shared library has been detected as loaded, so
  1408.          take the opportunity to check if breakpoints we think are
  1409.          inserted, still are.  Note that it isn't guaranteed that
  1410.          we'll see this when a shared library is loaded, and nor will
  1411.          we see this for unloads (although breakpoints in unloaded
  1412.          libraries shouldn't trigger), as GDB may not find symbols for
  1413.          the library at all.  We also re-validate breakpoints when we
  1414.          see a second GDB breakpoint for the same address, and or when
  1415.          we access breakpoint shadows.  */
  1416.       validate_breakpoints ();

  1417.       if (target_supports_tracepoints ())
  1418.         tracepoint_look_up_symbols ();

  1419.       if (target_running () && the_target->look_up_symbols != NULL)
  1420.         (*the_target->look_up_symbols) ();

  1421.       strcpy (own_buf, "OK");
  1422.       return;
  1423.     }

  1424.   if (!disable_packet_qfThreadInfo)
  1425.     {
  1426.       if (strcmp ("qfThreadInfo", own_buf) == 0)
  1427.         {
  1428.           ptid_t gdb_id;

  1429.           require_running (own_buf);
  1430.           thread_ptr = get_first_inferior (&all_threads);

  1431.           *own_buf++ = 'm';
  1432.           gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
  1433.           write_ptid (own_buf, gdb_id);
  1434.           thread_ptr = thread_ptr->next;
  1435.           return;
  1436.         }

  1437.       if (strcmp ("qsThreadInfo", own_buf) == 0)
  1438.         {
  1439.           ptid_t gdb_id;

  1440.           require_running (own_buf);
  1441.           if (thread_ptr != NULL)
  1442.             {
  1443.               *own_buf++ = 'm';
  1444.               gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
  1445.               write_ptid (own_buf, gdb_id);
  1446.               thread_ptr = thread_ptr->next;
  1447.               return;
  1448.             }
  1449.           else
  1450.             {
  1451.               sprintf (own_buf, "l");
  1452.               return;
  1453.             }
  1454.         }
  1455.     }

  1456.   if (the_target->read_offsets != NULL
  1457.       && strcmp ("qOffsets", own_buf) == 0)
  1458.     {
  1459.       CORE_ADDR text, data;

  1460.       require_running (own_buf);
  1461.       if (the_target->read_offsets (&text, &data))
  1462.         sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
  1463.                  (long)text, (long)data, (long)data);
  1464.       else
  1465.         write_enn (own_buf);

  1466.       return;
  1467.     }

  1468.   /* Protocol features query.  */
  1469.   if (strncmp ("qSupported", own_buf, 10) == 0
  1470.       && (own_buf[10] == ':' || own_buf[10] == '\0'))
  1471.     {
  1472.       char *p = &own_buf[10];
  1473.       int gdb_supports_qRelocInsn = 0;

  1474.       /* Start processing qSupported packet.  */
  1475.       target_process_qsupported (NULL);

  1476.       /* Process each feature being provided by GDB.  The first
  1477.          feature will follow a ':', and latter features will follow
  1478.          ';'.  */
  1479.       if (*p == ':')
  1480.         {
  1481.           char **qsupported = NULL;
  1482.           int count = 0;
  1483.           int i;

  1484.           /* Two passes, to avoid nested strtok calls in
  1485.              target_process_qsupported.  */
  1486.           for (p = strtok (p + 1, ";");
  1487.                p != NULL;
  1488.                p = strtok (NULL, ";"))
  1489.             {
  1490.               count++;
  1491.               qsupported = xrealloc (qsupported, count * sizeof (char *));
  1492.               qsupported[count - 1] = xstrdup (p);
  1493.             }

  1494.           for (i = 0; i < count; i++)
  1495.             {
  1496.               p = qsupported[i];
  1497.               if (strcmp (p, "multiprocess+") == 0)
  1498.                 {
  1499.                   /* GDB supports and wants multi-process support if
  1500.                      possible.  */
  1501.                   if (target_supports_multi_process ())
  1502.                     multi_process = 1;
  1503.                 }
  1504.               else if (strcmp (p, "qRelocInsn+") == 0)
  1505.                 {
  1506.                   /* GDB supports relocate instruction requests.  */
  1507.                   gdb_supports_qRelocInsn = 1;
  1508.                 }
  1509.               else
  1510.                 target_process_qsupported (p);

  1511.               free (p);
  1512.             }

  1513.           free (qsupported);
  1514.         }

  1515.       sprintf (own_buf,
  1516.                "PacketSize=%x;QPassSignals+;QProgramSignals+",
  1517.                PBUFSIZ - 1);

  1518.       if (the_target->qxfer_libraries_svr4 != NULL)
  1519.         strcat (own_buf, ";qXfer:libraries-svr4:read+"
  1520.                 ";augmented-libraries-svr4-read+");
  1521.       else
  1522.         {
  1523.           /* We do not have any hook to indicate whether the non-SVR4 target
  1524.              backend supports qXfer:libraries:read, so always report it.  */
  1525.           strcat (own_buf, ";qXfer:libraries:read+");
  1526.         }

  1527.       if (the_target->read_auxv != NULL)
  1528.         strcat (own_buf, ";qXfer:auxv:read+");

  1529.       if (the_target->qxfer_spu != NULL)
  1530.         strcat (own_buf, ";qXfer:spu:read+;qXfer:spu:write+");

  1531.       if (the_target->qxfer_siginfo != NULL)
  1532.         strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");

  1533.       if (the_target->read_loadmap != NULL)
  1534.         strcat (own_buf, ";qXfer:fdpic:read+");

  1535.       /* We always report qXfer:features:read, as targets may
  1536.          install XML files on a subsequent call to arch_setup.
  1537.          If we reported to GDB on startup that we don't support
  1538.          qXfer:feature:read at all, we will never be re-queried.  */
  1539.       strcat (own_buf, ";qXfer:features:read+");

  1540.       if (transport_is_reliable)
  1541.         strcat (own_buf, ";QStartNoAckMode+");

  1542.       if (the_target->qxfer_osdata != NULL)
  1543.         strcat (own_buf, ";qXfer:osdata:read+");

  1544.       if (target_supports_multi_process ())
  1545.         strcat (own_buf, ";multiprocess+");

  1546.       if (target_supports_non_stop ())
  1547.         strcat (own_buf, ";QNonStop+");

  1548.       if (target_supports_disable_randomization ())
  1549.         strcat (own_buf, ";QDisableRandomization+");

  1550.       strcat (own_buf, ";qXfer:threads:read+");

  1551.       if (target_supports_tracepoints ())
  1552.         {
  1553.           strcat (own_buf, ";ConditionalTracepoints+");
  1554.           strcat (own_buf, ";TraceStateVariables+");
  1555.           strcat (own_buf, ";TracepointSource+");
  1556.           strcat (own_buf, ";DisconnectedTracing+");
  1557.           if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
  1558.             strcat (own_buf, ";FastTracepoints+");
  1559.           strcat (own_buf, ";StaticTracepoints+");
  1560.           strcat (own_buf, ";InstallInTrace+");
  1561.           strcat (own_buf, ";qXfer:statictrace:read+");
  1562.           strcat (own_buf, ";qXfer:traceframe-info:read+");
  1563.           strcat (own_buf, ";EnableDisableTracepoints+");
  1564.           strcat (own_buf, ";QTBuffer:size+");
  1565.           strcat (own_buf, ";tracenz+");
  1566.         }

  1567.       /* Support target-side breakpoint conditions and commands.  */
  1568.       strcat (own_buf, ";ConditionalBreakpoints+");
  1569.       strcat (own_buf, ";BreakpointCommands+");

  1570.       if (target_supports_agent ())
  1571.         strcat (own_buf, ";QAgent+");

  1572.       if (target_supports_btrace ())
  1573.         {
  1574.           strcat (own_buf, ";Qbtrace:bts+");
  1575.           strcat (own_buf, ";Qbtrace:off+");
  1576.           strcat (own_buf, ";qXfer:btrace:read+");
  1577.         }

  1578.       return;
  1579.     }

  1580.   /* Thread-local storage support.  */
  1581.   if (the_target->get_tls_address != NULL
  1582.       && strncmp ("qGetTLSAddr:", own_buf, 12) == 0)
  1583.     {
  1584.       char *p = own_buf + 12;
  1585.       CORE_ADDR parts[2], address = 0;
  1586.       int i, err;
  1587.       ptid_t ptid = null_ptid;

  1588.       require_running (own_buf);

  1589.       for (i = 0; i < 3; i++)
  1590.         {
  1591.           char *p2;
  1592.           int len;

  1593.           if (p == NULL)
  1594.             break;

  1595.           p2 = strchr (p, ',');
  1596.           if (p2)
  1597.             {
  1598.               len = p2 - p;
  1599.               p2++;
  1600.             }
  1601.           else
  1602.             {
  1603.               len = strlen (p);
  1604.               p2 = NULL;
  1605.             }

  1606.           if (i == 0)
  1607.             ptid = read_ptid (p, NULL);
  1608.           else
  1609.             decode_address (&parts[i - 1], p, len);
  1610.           p = p2;
  1611.         }

  1612.       if (p != NULL || i < 3)
  1613.         err = 1;
  1614.       else
  1615.         {
  1616.           struct thread_info *thread = find_thread_ptid (ptid);

  1617.           if (thread == NULL)
  1618.             err = 2;
  1619.           else
  1620.             err = the_target->get_tls_address (thread, parts[0], parts[1],
  1621.                                                &address);
  1622.         }

  1623.       if (err == 0)
  1624.         {
  1625.           strcpy (own_buf, paddress(address));
  1626.           return;
  1627.         }
  1628.       else if (err > 0)
  1629.         {
  1630.           write_enn (own_buf);
  1631.           return;
  1632.         }

  1633.       /* Otherwise, pretend we do not understand this packet.  */
  1634.     }

  1635.   /* Windows OS Thread Information Block address support.  */
  1636.   if (the_target->get_tib_address != NULL
  1637.       && strncmp ("qGetTIBAddr:", own_buf, 12) == 0)
  1638.     {
  1639.       char *annex;
  1640.       int n;
  1641.       CORE_ADDR tlb;
  1642.       ptid_t ptid = read_ptid (own_buf + 12, &annex);

  1643.       n = (*the_target->get_tib_address) (ptid, &tlb);
  1644.       if (n == 1)
  1645.         {
  1646.           strcpy (own_buf, paddress(tlb));
  1647.           return;
  1648.         }
  1649.       else if (n == 0)
  1650.         {
  1651.           write_enn (own_buf);
  1652.           return;
  1653.         }
  1654.       return;
  1655.     }

  1656.   /* Handle "monitor" commands.  */
  1657.   if (strncmp ("qRcmd,", own_buf, 6) == 0)
  1658.     {
  1659.       char *mon = malloc (PBUFSIZ);
  1660.       int len = strlen (own_buf + 6);

  1661.       if (mon == NULL)
  1662.         {
  1663.           write_enn (own_buf);
  1664.           return;
  1665.         }

  1666.       if ((len % 2) != 0
  1667.           || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
  1668.         {
  1669.           write_enn (own_buf);
  1670.           free (mon);
  1671.           return;
  1672.         }
  1673.       mon[len / 2] = '\0';

  1674.       write_ok (own_buf);

  1675.       if (the_target->handle_monitor_command == NULL
  1676.           || (*the_target->handle_monitor_command) (mon) == 0)
  1677.         /* Default processing.  */
  1678.         handle_monitor_command (mon, own_buf);

  1679.       free (mon);
  1680.       return;
  1681.     }

  1682.   if (strncmp ("qSearch:memory:", own_buf,
  1683.                sizeof ("qSearch:memory:") - 1) == 0)
  1684.     {
  1685.       require_running (own_buf);
  1686.       handle_search_memory (own_buf, packet_len);
  1687.       return;
  1688.     }

  1689.   if (strcmp (own_buf, "qAttached") == 0
  1690.       || strncmp (own_buf, "qAttached:", sizeof ("qAttached:") - 1) == 0)
  1691.     {
  1692.       struct process_info *process;

  1693.       if (own_buf[sizeof ("qAttached") - 1])
  1694.         {
  1695.           int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
  1696.           process = (struct process_info *)
  1697.             find_inferior_id (&all_processes, pid_to_ptid (pid));
  1698.         }
  1699.       else
  1700.         {
  1701.           require_running (own_buf);
  1702.           process = current_process ();
  1703.         }

  1704.       if (process == NULL)
  1705.         {
  1706.           write_enn (own_buf);
  1707.           return;
  1708.         }

  1709.       strcpy (own_buf, process->attached ? "1" : "0");
  1710.       return;
  1711.     }

  1712.   if (strncmp ("qCRC:", own_buf, 5) == 0)
  1713.     {
  1714.       /* CRC check (compare-section).  */
  1715.       char *comma;
  1716.       ULONGEST base;
  1717.       int len;
  1718.       unsigned long long crc;

  1719.       require_running (own_buf);
  1720.       comma = unpack_varlen_hex (own_buf + 5, &base);
  1721.       if (*comma++ != ',')
  1722.         {
  1723.           write_enn (own_buf);
  1724.           return;
  1725.         }
  1726.       len = strtoul (comma, NULL, 16);
  1727.       crc = crc32 (base, len, 0xffffffff);
  1728.       /* Check for memory failure.  */
  1729.       if (crc == (unsigned long long) -1)
  1730.         {
  1731.           write_enn (own_buf);
  1732.           return;
  1733.         }
  1734.       sprintf (own_buf, "C%lx", (unsigned long) crc);
  1735.       return;
  1736.     }

  1737.   if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
  1738.     return;

  1739.   if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
  1740.     return;

  1741.   /* Otherwise we didn't know what packet it was.  Say we didn't
  1742.      understand it.  */
  1743.   own_buf[0] = 0;
  1744. }

  1745. static void gdb_wants_all_threads_stopped (void);
  1746. static void resume (struct thread_resume *actions, size_t n);

  1747. /* The callback that is passed to visit_actioned_threads.  */
  1748. typedef int (visit_actioned_threads_callback_ftype)
  1749.   (const struct thread_resume *, struct thread_info *);

  1750. /* Struct to pass data to visit_actioned_threads.  */

  1751. struct visit_actioned_threads_data
  1752. {
  1753.   const struct thread_resume *actions;
  1754.   size_t num_actions;
  1755.   visit_actioned_threads_callback_ftype *callback;
  1756. };

  1757. /* Call CALLBACK for any thread to which ACTIONS applies to.  Returns
  1758.    true if CALLBACK returns true.  Returns false if no matching thread
  1759.    is found or CALLBACK results false.
  1760.    Note: This function is itself a callback for find_inferior.  */

  1761. static int
  1762. visit_actioned_threads (struct inferior_list_entry *entry, void *datap)
  1763. {
  1764.   struct visit_actioned_threads_data *data = datap;
  1765.   const struct thread_resume *actions = data->actions;
  1766.   size_t num_actions = data->num_actions;
  1767.   visit_actioned_threads_callback_ftype *callback = data->callback;
  1768.   size_t i;

  1769.   for (i = 0; i < num_actions; i++)
  1770.     {
  1771.       const struct thread_resume *action = &actions[i];

  1772.       if (ptid_equal (action->thread, minus_one_ptid)
  1773.           || ptid_equal (action->thread, entry->id)
  1774.           || ((ptid_get_pid (action->thread)
  1775.                == ptid_get_pid (entry->id))
  1776.               && ptid_get_lwp (action->thread) == -1))
  1777.         {
  1778.           struct thread_info *thread = (struct thread_info *) entry;

  1779.           if ((*callback) (action, thread))
  1780.             return 1;
  1781.         }
  1782.     }

  1783.   return 0;
  1784. }

  1785. /* Callback for visit_actioned_threads.  If the thread has a pending
  1786.    status to report, report it now.  */

  1787. static int
  1788. handle_pending_status (const struct thread_resume *resumption,
  1789.                        struct thread_info *thread)
  1790. {
  1791.   if (thread->status_pending_p)
  1792.     {
  1793.       thread->status_pending_p = 0;

  1794.       last_status = thread->last_status;
  1795.       last_ptid = thread->entry.id;
  1796.       prepare_resume_reply (own_buf, last_ptid, &last_status);
  1797.       return 1;
  1798.     }
  1799.   return 0;
  1800. }

  1801. /* Parse vCont packets.  */
  1802. void
  1803. handle_v_cont (char *own_buf)
  1804. {
  1805.   char *p, *q;
  1806.   int n = 0, i = 0;
  1807.   struct thread_resume *resume_info;
  1808.   struct thread_resume default_action = {{0}};

  1809.   /* Count the number of semicolons in the packet.  There should be one
  1810.      for every action.  */
  1811.   p = &own_buf[5];
  1812.   while (p)
  1813.     {
  1814.       n++;
  1815.       p++;
  1816.       p = strchr (p, ';');
  1817.     }

  1818.   resume_info = malloc (n * sizeof (resume_info[0]));
  1819.   if (resume_info == NULL)
  1820.     goto err;

  1821.   p = &own_buf[5];
  1822.   while (*p)
  1823.     {
  1824.       p++;

  1825.       memset (&resume_info[i], 0, sizeof resume_info[i]);

  1826.       if (p[0] == 's' || p[0] == 'S')
  1827.         resume_info[i].kind = resume_step;
  1828.       else if (p[0] == 'r')
  1829.         resume_info[i].kind = resume_step;
  1830.       else if (p[0] == 'c' || p[0] == 'C')
  1831.         resume_info[i].kind = resume_continue;
  1832.       else if (p[0] == 't')
  1833.         resume_info[i].kind = resume_stop;
  1834.       else
  1835.         goto err;

  1836.       if (p[0] == 'S' || p[0] == 'C')
  1837.         {
  1838.           int sig;
  1839.           sig = strtol (p + 1, &q, 16);
  1840.           if (p == q)
  1841.             goto err;
  1842.           p = q;

  1843.           if (!gdb_signal_to_host_p (sig))
  1844.             goto err;
  1845.           resume_info[i].sig = gdb_signal_to_host (sig);
  1846.         }
  1847.       else if (p[0] == 'r')
  1848.         {
  1849.           ULONGEST addr;

  1850.           p = unpack_varlen_hex (p + 1, &addr);
  1851.           resume_info[i].step_range_start = addr;

  1852.           if (*p != ',')
  1853.             goto err;

  1854.           p = unpack_varlen_hex (p + 1, &addr);
  1855.           resume_info[i].step_range_end = addr;
  1856.         }
  1857.       else
  1858.         {
  1859.           p = p + 1;
  1860.         }

  1861.       if (p[0] == 0)
  1862.         {
  1863.           resume_info[i].thread = minus_one_ptid;
  1864.           default_action = resume_info[i];

  1865.           /* Note: we don't increment i here, we'll overwrite this entry
  1866.              the next time through.  */
  1867.         }
  1868.       else if (p[0] == ':')
  1869.         {
  1870.           ptid_t ptid = read_ptid (p + 1, &q);

  1871.           if (p == q)
  1872.             goto err;
  1873.           p = q;
  1874.           if (p[0] != ';' && p[0] != 0)
  1875.             goto err;

  1876.           resume_info[i].thread = ptid;

  1877.           i++;
  1878.         }
  1879.     }

  1880.   if (i < n)
  1881.     resume_info[i] = default_action;

  1882.   set_desired_thread (0);

  1883.   resume (resume_info, n);
  1884.   free (resume_info);
  1885.   return;

  1886. err:
  1887.   write_enn (own_buf);
  1888.   free (resume_info);
  1889.   return;
  1890. }

  1891. /* Resume target with ACTIONS, an array of NUM_ACTIONS elements.  */

  1892. static void
  1893. resume (struct thread_resume *actions, size_t num_actions)
  1894. {
  1895.   if (!non_stop)
  1896.     {
  1897.       /* Check if among the threads that GDB wants actioned, there's
  1898.          one with a pending status to report.  If so, skip actually
  1899.          resuming/stopping and report the pending event
  1900.          immediately.  */
  1901.       struct visit_actioned_threads_data data;

  1902.       data.actions = actions;
  1903.       data.num_actions = num_actions;
  1904.       data.callback = handle_pending_status;
  1905.       if (find_inferior (&all_threads, visit_actioned_threads, &data) != NULL)
  1906.         return;

  1907.       enable_async_io ();
  1908.     }

  1909.   (*the_target->resume) (actions, num_actions);

  1910.   if (non_stop)
  1911.     write_ok (own_buf);
  1912.   else
  1913.     {
  1914.       last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);

  1915.       if (last_status.kind == TARGET_WAITKIND_NO_RESUMED)
  1916.         {
  1917.           /* No proper RSP support for this yet.  At least return
  1918.              error.  */
  1919.           sprintf (own_buf, "E.No unwaited-for children left.");
  1920.           disable_async_io ();
  1921.           return;
  1922.         }

  1923.       if (last_status.kind != TARGET_WAITKIND_EXITED
  1924.           && last_status.kind != TARGET_WAITKIND_SIGNALLED
  1925.           && last_status.kind != TARGET_WAITKIND_NO_RESUMED)
  1926.         current_thread->last_status = last_status;

  1927.       /* From the client's perspective, all-stop mode always stops all
  1928.          threads implicitly (and the target backend has already done
  1929.          so by now).  Tag all threads as "want-stopped", so we don't
  1930.          resume them implicitly without the client telling us to.  */
  1931.       gdb_wants_all_threads_stopped ();
  1932.       prepare_resume_reply (own_buf, last_ptid, &last_status);
  1933.       disable_async_io ();

  1934.       if (last_status.kind == TARGET_WAITKIND_EXITED
  1935.           || last_status.kind == TARGET_WAITKIND_SIGNALLED)
  1936.         mourn_inferior (find_process_pid (ptid_get_pid (last_ptid)));
  1937.     }
  1938. }

  1939. /* Attach to a new program.  Return 1 if successful, 0 if failure.  */
  1940. int
  1941. handle_v_attach (char *own_buf)
  1942. {
  1943.   int pid;

  1944.   pid = strtol (own_buf + 8, NULL, 16);
  1945.   if (pid != 0 && attach_inferior (pid) == 0)
  1946.     {
  1947.       /* Don't report shared library events after attaching, even if
  1948.          some libraries are preloaded.  GDB will always poll the
  1949.          library list.  Avoids the "stopped by shared library event"
  1950.          notice on the GDB side.  */
  1951.       dlls_changed = 0;

  1952.       if (non_stop)
  1953.         {
  1954.           /* In non-stop, we don't send a resume reply.  Stop events
  1955.              will follow up using the normal notification
  1956.              mechanism.  */
  1957.           write_ok (own_buf);
  1958.         }
  1959.       else
  1960.         prepare_resume_reply (own_buf, last_ptid, &last_status);

  1961.       return 1;
  1962.     }
  1963.   else
  1964.     {
  1965.       write_enn (own_buf);
  1966.       return 0;
  1967.     }
  1968. }

  1969. /* Run a new program.  Return 1 if successful, 0 if failure.  */
  1970. static int
  1971. handle_v_run (char *own_buf)
  1972. {
  1973.   char *p, *next_p, **new_argv;
  1974.   int i, new_argc;

  1975.   new_argc = 0;
  1976.   for (p = own_buf + strlen ("vRun;"); p && *p; p = strchr (p, ';'))
  1977.     {
  1978.       p++;
  1979.       new_argc++;
  1980.     }

  1981.   new_argv = calloc (new_argc + 2, sizeof (char *));
  1982.   if (new_argv == NULL)
  1983.     {
  1984.       write_enn (own_buf);
  1985.       return 0;
  1986.     }

  1987.   i = 0;
  1988.   for (p = own_buf + strlen ("vRun;"); *p; p = next_p)
  1989.     {
  1990.       next_p = strchr (p, ';');
  1991.       if (next_p == NULL)
  1992.         next_p = p + strlen (p);

  1993.       if (i == 0 && p == next_p)
  1994.         new_argv[i] = NULL;
  1995.       else
  1996.         {
  1997.           /* FIXME: Fail request if out of memory instead of dying.  */
  1998.           new_argv[i] = xmalloc (1 + (next_p - p) / 2);
  1999.           hex2bin (p, (gdb_byte *) new_argv[i], (next_p - p) / 2);
  2000.           new_argv[i][(next_p - p) / 2] = '\0';
  2001.         }

  2002.       if (*next_p)
  2003.         next_p++;
  2004.       i++;
  2005.     }
  2006.   new_argv[i] = NULL;

  2007.   if (new_argv[0] == NULL)
  2008.     {
  2009.       /* GDB didn't specify a program to run.  Use the program from the
  2010.          last run with the new argument list.  */

  2011.       if (program_argv == NULL)
  2012.         {
  2013.           write_enn (own_buf);
  2014.           freeargv (new_argv);
  2015.           return 0;
  2016.         }

  2017.       new_argv[0] = strdup (program_argv[0]);
  2018.       if (new_argv[0] == NULL)
  2019.         {
  2020.           write_enn (own_buf);
  2021.           freeargv (new_argv);
  2022.           return 0;
  2023.         }
  2024.     }

  2025.   /* Free the old argv and install the new one.  */
  2026.   freeargv (program_argv);
  2027.   program_argv = new_argv;

  2028.   start_inferior (program_argv);
  2029.   if (last_status.kind == TARGET_WAITKIND_STOPPED)
  2030.     {
  2031.       prepare_resume_reply (own_buf, last_ptid, &last_status);

  2032.       /* In non-stop, sending a resume reply doesn't set the general
  2033.          thread, but GDB assumes a vRun sets it (this is so GDB can
  2034.          query which is the main thread of the new inferior.  */
  2035.       if (non_stop)
  2036.         general_thread = last_ptid;

  2037.       return 1;
  2038.     }
  2039.   else
  2040.     {
  2041.       write_enn (own_buf);
  2042.       return 0;
  2043.     }
  2044. }

  2045. /* Kill process.  Return 1 if successful, 0 if failure.  */
  2046. int
  2047. handle_v_kill (char *own_buf)
  2048. {
  2049.   int pid;
  2050.   char *p = &own_buf[6];
  2051.   if (multi_process)
  2052.     pid = strtol (p, NULL, 16);
  2053.   else
  2054.     pid = signal_pid;
  2055.   if (pid != 0 && kill_inferior (pid) == 0)
  2056.     {
  2057.       last_status.kind = TARGET_WAITKIND_SIGNALLED;
  2058.       last_status.value.sig = GDB_SIGNAL_KILL;
  2059.       last_ptid = pid_to_ptid (pid);
  2060.       discard_queued_stop_replies (pid);
  2061.       write_ok (own_buf);
  2062.       return 1;
  2063.     }
  2064.   else
  2065.     {
  2066.       write_enn (own_buf);
  2067.       return 0;
  2068.     }
  2069. }

  2070. /* Handle all of the extended 'v' packets.  */
  2071. void
  2072. handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
  2073. {
  2074.   if (!disable_packet_vCont)
  2075.     {
  2076.       if (strncmp (own_buf, "vCont;", 6) == 0)
  2077.         {
  2078.           require_running (own_buf);
  2079.           handle_v_cont (own_buf);
  2080.           return;
  2081.         }

  2082.       if (strncmp (own_buf, "vCont?", 6) == 0)
  2083.         {
  2084.           strcpy (own_buf, "vCont;c;C;s;S;t");
  2085.           if (target_supports_range_stepping ())
  2086.             {
  2087.               own_buf = own_buf + strlen (own_buf);
  2088.               strcpy (own_buf, ";r");
  2089.             }
  2090.           return;
  2091.         }
  2092.     }

  2093.   if (strncmp (own_buf, "vFile:", 6) == 0
  2094.       && handle_vFile (own_buf, packet_len, new_packet_len))
  2095.     return;

  2096.   if (strncmp (own_buf, "vAttach;", 8) == 0)
  2097.     {
  2098.       if ((!extended_protocol || !multi_process) && target_running ())
  2099.         {
  2100.           fprintf (stderr, "Already debugging a process\n");
  2101.           write_enn (own_buf);
  2102.           return;
  2103.         }
  2104.       handle_v_attach (own_buf);
  2105.       return;
  2106.     }

  2107.   if (strncmp (own_buf, "vRun;", 5) == 0)
  2108.     {
  2109.       if ((!extended_protocol || !multi_process) && target_running ())
  2110.         {
  2111.           fprintf (stderr, "Already debugging a process\n");
  2112.           write_enn (own_buf);
  2113.           return;
  2114.         }
  2115.       handle_v_run (own_buf);
  2116.       return;
  2117.     }

  2118.   if (strncmp (own_buf, "vKill;", 6) == 0)
  2119.     {
  2120.       if (!target_running ())
  2121.         {
  2122.           fprintf (stderr, "No process to kill\n");
  2123.           write_enn (own_buf);
  2124.           return;
  2125.         }
  2126.       handle_v_kill (own_buf);
  2127.       return;
  2128.     }

  2129.   if (handle_notif_ack (own_buf, packet_len))
  2130.     return;

  2131.   /* Otherwise we didn't know what packet it was.  Say we didn't
  2132.      understand it.  */
  2133.   own_buf[0] = 0;
  2134.   return;
  2135. }

  2136. /* Resume thread and wait for another event.  In non-stop mode,
  2137.    don't really wait here, but return immediatelly to the event
  2138.    loop.  */
  2139. static void
  2140. myresume (char *own_buf, int step, int sig)
  2141. {
  2142.   struct thread_resume resume_info[2];
  2143.   int n = 0;
  2144.   int valid_cont_thread;

  2145.   set_desired_thread (0);

  2146.   valid_cont_thread = (!ptid_equal (cont_thread, null_ptid)
  2147.                          && !ptid_equal (cont_thread, minus_one_ptid));

  2148.   if (step || sig || valid_cont_thread)
  2149.     {
  2150.       resume_info[0].thread = current_ptid;
  2151.       if (step)
  2152.         resume_info[0].kind = resume_step;
  2153.       else
  2154.         resume_info[0].kind = resume_continue;
  2155.       resume_info[0].sig = sig;
  2156.       n++;
  2157.     }

  2158.   if (!valid_cont_thread)
  2159.     {
  2160.       resume_info[n].thread = minus_one_ptid;
  2161.       resume_info[n].kind = resume_continue;
  2162.       resume_info[n].sig = 0;
  2163.       n++;
  2164.     }

  2165.   resume (resume_info, n);
  2166. }

  2167. /* Callback for for_each_inferior.  Make a new stop reply for each
  2168.    stopped thread.  */

  2169. static int
  2170. queue_stop_reply_callback (struct inferior_list_entry *entry, void *arg)
  2171. {
  2172.   struct thread_info *thread = (struct thread_info *) entry;

  2173.   /* For now, assume targets that don't have this callback also don't
  2174.      manage the thread's last_status field.  */
  2175.   if (the_target->thread_stopped == NULL)
  2176.     {
  2177.       struct vstop_notif *new_notif = xmalloc (sizeof (*new_notif));

  2178.       new_notif->ptid = entry->id;
  2179.       new_notif->status = thread->last_status;
  2180.       /* Pass the last stop reply back to GDB, but don't notify
  2181.          yet.  */
  2182.       notif_event_enque (&notif_stop,
  2183.                          (struct notif_event *) new_notif);
  2184.     }
  2185.   else
  2186.     {
  2187.       if (thread_stopped (thread))
  2188.         {
  2189.           if (debug_threads)
  2190.             {
  2191.               char *status_string
  2192.                 = target_waitstatus_to_string (&thread->last_status);

  2193.               debug_printf ("Reporting thread %s as already stopped with %s\n",
  2194.                             target_pid_to_str (entry->id),
  2195.                             status_string);

  2196.               xfree (status_string);
  2197.             }

  2198.           gdb_assert (thread->last_status.kind != TARGET_WAITKIND_IGNORE);

  2199.           /* Pass the last stop reply back to GDB, but don't notify
  2200.              yet.  */
  2201.           queue_stop_reply (entry->id, &thread->last_status);
  2202.         }
  2203.     }

  2204.   return 0;
  2205. }

  2206. /* Set this inferior threads's state as "want-stopped".  We won't
  2207.    resume this thread until the client gives us another action for
  2208.    it.  */

  2209. static void
  2210. gdb_wants_thread_stopped (struct inferior_list_entry *entry)
  2211. {
  2212.   struct thread_info *thread = (struct thread_info *) entry;

  2213.   thread->last_resume_kind = resume_stop;

  2214.   if (thread->last_status.kind == TARGET_WAITKIND_IGNORE)
  2215.     {
  2216.       /* Most threads are stopped implicitly (all-stop); tag that with
  2217.          signal 0.  */
  2218.       thread->last_status.kind = TARGET_WAITKIND_STOPPED;
  2219.       thread->last_status.value.sig = GDB_SIGNAL_0;
  2220.     }
  2221. }

  2222. /* Set all threads' states as "want-stopped".  */

  2223. static void
  2224. gdb_wants_all_threads_stopped (void)
  2225. {
  2226.   for_each_inferior (&all_threads, gdb_wants_thread_stopped);
  2227. }

  2228. /* Clear the gdb_detached flag of every process.  */

  2229. static void
  2230. gdb_reattached_process (struct inferior_list_entry *entry)
  2231. {
  2232.   struct process_info *process = (struct process_info *) entry;

  2233.   process->gdb_detached = 0;
  2234. }

  2235. /* Callback for for_each_inferior.  Clear the thread's pending status
  2236.    flag.  */

  2237. static void
  2238. clear_pending_status_callback (struct inferior_list_entry *entry)
  2239. {
  2240.   struct thread_info *thread = (struct thread_info *) entry;

  2241.   thread->status_pending_p = 0;
  2242. }

  2243. /* Callback for for_each_inferior.  If the thread is stopped with an
  2244.    interesting event, mark it as having a pending event.  */

  2245. static void
  2246. set_pending_status_callback (struct inferior_list_entry *entry)
  2247. {
  2248.   struct thread_info *thread = (struct thread_info *) entry;

  2249.   if (thread->last_status.kind != TARGET_WAITKIND_STOPPED
  2250.       || (thread->last_status.value.sig != GDB_SIGNAL_0
  2251.           /* A breakpoint, watchpoint or finished step from a previous
  2252.              GDB run isn't considered interesting for a new GDB run.
  2253.              If we left those pending, the new GDB could consider them
  2254.              random SIGTRAPs.  This leaves out real async traps.  We'd
  2255.              have to peek into the (target-specific) siginfo to
  2256.              distinguish those.  */
  2257.           && thread->last_status.value.sig != GDB_SIGNAL_TRAP))
  2258.     thread->status_pending_p = 1;
  2259. }

  2260. /* Callback for find_inferior.  Return true if ENTRY (a thread) has a
  2261.    pending status to report to GDB.  */

  2262. static int
  2263. find_status_pending_thread_callback (struct inferior_list_entry *entry, void *data)
  2264. {
  2265.   struct thread_info *thread = (struct thread_info *) entry;

  2266.   return thread->status_pending_p;
  2267. }

  2268. /* Status handler for the '?' packet.  */

  2269. static void
  2270. handle_status (char *own_buf)
  2271. {
  2272.   /* GDB is connected, don't forward events to the target anymore.  */
  2273.   for_each_inferior (&all_processes, gdb_reattached_process);

  2274.   /* In non-stop mode, we must send a stop reply for each stopped
  2275.      thread.  In all-stop mode, just send one for the first stopped
  2276.      thread we find.  */

  2277.   if (non_stop)
  2278.     {
  2279.       find_inferior (&all_threads, queue_stop_reply_callback, NULL);

  2280.       /* The first is sent immediatly.  OK is sent if there is no
  2281.          stopped thread, which is the same handling of the vStopped
  2282.          packet (by design).  */
  2283.       notif_write_event (&notif_stop, own_buf);
  2284.     }
  2285.   else
  2286.     {
  2287.       struct inferior_list_entry *thread = NULL;

  2288.       pause_all (0);
  2289.       stabilize_threads ();
  2290.       gdb_wants_all_threads_stopped ();

  2291.       /* We can only report one status, but we might be coming out of
  2292.          non-stop -- if more than one thread is stopped with
  2293.          interesting events, leave events for the threads we're not
  2294.          reporting now pending.  They'll be reported the next time the
  2295.          threads are resumed.  Start by marking all interesting events
  2296.          as pending.  */
  2297.       for_each_inferior (&all_threads, set_pending_status_callback);

  2298.       /* Prefer the last thread that reported an event to GDB (even if
  2299.          that was a GDB_SIGNAL_TRAP).  */
  2300.       if (last_status.kind != TARGET_WAITKIND_IGNORE
  2301.           && last_status.kind != TARGET_WAITKIND_EXITED
  2302.           && last_status.kind != TARGET_WAITKIND_SIGNALLED)
  2303.         thread = find_inferior_id (&all_threads, last_ptid);

  2304.       /* If the last event thread is not found for some reason, look
  2305.          for some other thread that might have an event to report.  */
  2306.       if (thread == NULL)
  2307.         thread = find_inferior (&all_threads,
  2308.                                 find_status_pending_thread_callback, NULL);

  2309.       /* If we're still out of luck, simply pick the first thread in
  2310.          the thread list.  */
  2311.       if (thread == NULL)
  2312.         thread = get_first_inferior (&all_threads);

  2313.       if (thread != NULL)
  2314.         {
  2315.           struct thread_info *tp = (struct thread_info *) thread;

  2316.           /* We're reporting this event, so it's no longer
  2317.              pending.  */
  2318.           tp->status_pending_p = 0;

  2319.           /* GDB assumes the current thread is the thread we're
  2320.              reporting the status for.  */
  2321.           general_thread = thread->id;
  2322.           set_desired_thread (1);

  2323.           gdb_assert (tp->last_status.kind != TARGET_WAITKIND_IGNORE);
  2324.           prepare_resume_reply (own_buf, tp->entry.id, &tp->last_status);
  2325.         }
  2326.       else
  2327.         strcpy (own_buf, "W00");
  2328.     }
  2329. }

  2330. static void
  2331. gdbserver_version (void)
  2332. {
  2333.   printf ("GNU gdbserver %s%s\n"
  2334.           "Copyright (C) 2015 Free Software Foundation, Inc.\n"
  2335.           "gdbserver is free software, covered by the "
  2336.           "GNU General Public License.\n"
  2337.           "This gdbserver was configured as \"%s\"\n",
  2338.           PKGVERSION, version, host_name);
  2339. }

  2340. static void
  2341. gdbserver_usage (FILE *stream)
  2342. {
  2343.   fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
  2344.            "\tgdbserver [OPTIONS] --attach COMM PID\n"
  2345.            "\tgdbserver [OPTIONS] --multi COMM\n"
  2346.            "\n"
  2347.            "COMM may either be a tty device (for serial debugging), or \n"
  2348.            "HOST:PORT to listen for a TCP connection.\n"
  2349.            "\n"
  2350.            "Options:\n"
  2351.            "  --debug               Enable general debugging output.\n"
  2352.            "  --debug-format=opt1[,opt2,...]\n"
  2353.            "                        Specify extra content in debugging output.\n"
  2354.            "                          Options:\n"
  2355.            "                            all\n"
  2356.            "                            none\n"
  2357.            "                            timestamp\n"
  2358.            "  --remote-debug        Enable remote protocol debugging output.\n"
  2359.            "  --version             Display version information and exit.\n"
  2360.            "  --wrapper WRAPPER --  Run WRAPPER to start new programs.\n"
  2361.            "  --once                Exit after the first connection has "
  2362.                                                                   "closed.\n");
  2363.   if (REPORT_BUGS_TO[0] && stream == stdout)
  2364.     fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
  2365. }

  2366. static void
  2367. gdbserver_show_disableable (FILE *stream)
  2368. {
  2369.   fprintf (stream, "Disableable packets:\n"
  2370.            "  vCont       \tAll vCont packets\n"
  2371.            "  qC          \tQuerying the current thread\n"
  2372.            "  qfThreadInfo\tThread listing\n"
  2373.            "  Tthread     \tPassing the thread specifier in the "
  2374.            "T stop reply packet\n"
  2375.            threads     \tAll of the above\n");
  2376. }


  2377. #undef require_running
  2378. #define require_running(BUF)                        \
  2379.   if (!target_running ())                        \
  2380.     {                                                \
  2381.       write_enn (BUF);                                \
  2382.       break;                                        \
  2383.     }

  2384. static int
  2385. first_thread_of (struct inferior_list_entry *entry, void *args)
  2386. {
  2387.   int pid = * (int *) args;

  2388.   if (ptid_get_pid (entry->id) == pid)
  2389.     return 1;

  2390.   return 0;
  2391. }

  2392. static void
  2393. kill_inferior_callback (struct inferior_list_entry *entry)
  2394. {
  2395.   struct process_info *process = (struct process_info *) entry;
  2396.   int pid = ptid_get_pid (process->entry.id);

  2397.   kill_inferior (pid);
  2398.   discard_queued_stop_replies (pid);
  2399. }

  2400. /* Callback for for_each_inferior to detach or kill the inferior,
  2401.    depending on whether we attached to it or not.
  2402.    We inform the user whether we're detaching or killing the process
  2403.    as this is only called when gdbserver is about to exit.  */

  2404. static void
  2405. detach_or_kill_inferior_callback (struct inferior_list_entry *entry)
  2406. {
  2407.   struct process_info *process = (struct process_info *) entry;
  2408.   int pid = ptid_get_pid (process->entry.id);

  2409.   if (process->attached)
  2410.     detach_inferior (pid);
  2411.   else
  2412.     kill_inferior (pid);

  2413.   discard_queued_stop_replies (pid);
  2414. }

  2415. /* for_each_inferior callback for detach_or_kill_for_exit to print
  2416.    the pids of started inferiors.  */

  2417. static void
  2418. print_started_pid (struct inferior_list_entry *entry)
  2419. {
  2420.   struct process_info *process = (struct process_info *) entry;

  2421.   if (! process->attached)
  2422.     {
  2423.       int pid = ptid_get_pid (process->entry.id);
  2424.       fprintf (stderr, " %d", pid);
  2425.     }
  2426. }

  2427. /* for_each_inferior callback for detach_or_kill_for_exit to print
  2428.    the pids of attached inferiors.  */

  2429. static void
  2430. print_attached_pid (struct inferior_list_entry *entry)
  2431. {
  2432.   struct process_info *process = (struct process_info *) entry;

  2433.   if (process->attached)
  2434.     {
  2435.       int pid = ptid_get_pid (process->entry.id);
  2436.       fprintf (stderr, " %d", pid);
  2437.     }
  2438. }

  2439. /* Call this when exiting gdbserver with possible inferiors that need
  2440.    to be killed or detached from.  */

  2441. static void
  2442. detach_or_kill_for_exit (void)
  2443. {
  2444.   /* First print a list of the inferiors we will be killing/detaching.
  2445.      This is to assist the user, for example, in case the inferior unexpectedly
  2446.      dies after we exit: did we screw up or did the inferior exit on its own?
  2447.      Having this info will save some head-scratching.  */

  2448.   if (have_started_inferiors_p ())
  2449.     {
  2450.       fprintf (stderr, "Killing process(es):");
  2451.       for_each_inferior (&all_processes, print_started_pid);
  2452.       fprintf (stderr, "\n");
  2453.     }
  2454.   if (have_attached_inferiors_p ())
  2455.     {
  2456.       fprintf (stderr, "Detaching process(es):");
  2457.       for_each_inferior (&all_processes, print_attached_pid);
  2458.       fprintf (stderr, "\n");
  2459.     }

  2460.   /* Now we can kill or detach the inferiors.  */

  2461.   for_each_inferior (&all_processes, detach_or_kill_inferior_callback);
  2462. }

  2463. /* Value that will be passed to exit(3) when gdbserver exits.  */
  2464. static int exit_code;

  2465. /* Cleanup version of detach_or_kill_for_exit.  */

  2466. static void
  2467. detach_or_kill_for_exit_cleanup (void *ignore)
  2468. {
  2469.   volatile struct gdb_exception exception;

  2470.   TRY_CATCH (exception, RETURN_MASK_ALL)
  2471.     {
  2472.       detach_or_kill_for_exit ();
  2473.     }

  2474.   if (exception.reason < 0)
  2475.     {
  2476.       fflush (stdout);
  2477.       fprintf (stderr, "Detach or kill failed: %s\n", exception.message);
  2478.       exit_code = 1;
  2479.     }
  2480. }

  2481. /* Main function.  This is called by the real "main" function,
  2482.    wrapped in a TRY_CATCH that handles any uncaught exceptions.  */

  2483. static void ATTRIBUTE_NORETURN
  2484. captured_main (int argc, char *argv[])
  2485. {
  2486.   int bad_attach;
  2487.   int pid;
  2488.   char *arg_end, *port;
  2489.   char **next_arg = &argv[1];
  2490.   volatile int multi_mode = 0;
  2491.   volatile int attach = 0;
  2492.   int was_running;

  2493.   while (*next_arg != NULL && **next_arg == '-')
  2494.     {
  2495.       if (strcmp (*next_arg, "--version") == 0)
  2496.         {
  2497.           gdbserver_version ();
  2498.           exit (0);
  2499.         }
  2500.       else if (strcmp (*next_arg, "--help") == 0)
  2501.         {
  2502.           gdbserver_usage (stdout);
  2503.           exit (0);
  2504.         }
  2505.       else if (strcmp (*next_arg, "--attach") == 0)
  2506.         attach = 1;
  2507.       else if (strcmp (*next_arg, "--multi") == 0)
  2508.         multi_mode = 1;
  2509.       else if (strcmp (*next_arg, "--wrapper") == 0)
  2510.         {
  2511.           next_arg++;

  2512.           wrapper_argv = next_arg;
  2513.           while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
  2514.             next_arg++;

  2515.           if (next_arg == wrapper_argv || *next_arg == NULL)
  2516.             {
  2517.               gdbserver_usage (stderr);
  2518.               exit (1);
  2519.             }

  2520.           /* Consume the "--".  */
  2521.           *next_arg = NULL;
  2522.         }
  2523.       else if (strcmp (*next_arg, "--debug") == 0)
  2524.         debug_threads = 1;
  2525.       else if (strncmp (*next_arg,
  2526.                         "--debug-format=",
  2527.                         sizeof ("--debug-format=") - 1) == 0)
  2528.         {
  2529.           char *error_msg
  2530.             = parse_debug_format_options ((*next_arg)
  2531.                                           + sizeof ("--debug-format=") - 1, 0);

  2532.           if (error_msg != NULL)
  2533.             {
  2534.               fprintf (stderr, "%s", error_msg);
  2535.               exit (1);
  2536.             }
  2537.         }
  2538.       else if (strcmp (*next_arg, "--remote-debug") == 0)
  2539.         remote_debug = 1;
  2540.       else if (strcmp (*next_arg, "--disable-packet") == 0)
  2541.         {
  2542.           gdbserver_show_disableable (stdout);
  2543.           exit (0);
  2544.         }
  2545.       else if (strncmp (*next_arg,
  2546.                         "--disable-packet=",
  2547.                         sizeof ("--disable-packet=") - 1) == 0)
  2548.         {
  2549.           char *packets, *tok;

  2550.           packets = *next_arg += sizeof ("--disable-packet=") - 1;
  2551.           for (tok = strtok (packets, ",");
  2552.                tok != NULL;
  2553.                tok = strtok (NULL, ","))
  2554.             {
  2555.               if (strcmp ("vCont", tok) == 0)
  2556.                 disable_packet_vCont = 1;
  2557.               else if (strcmp ("Tthread", tok) == 0)
  2558.                 disable_packet_Tthread = 1;
  2559.               else if (strcmp ("qC", tok) == 0)
  2560.                 disable_packet_qC = 1;
  2561.               else if (strcmp ("qfThreadInfo", tok) == 0)
  2562.                 disable_packet_qfThreadInfo = 1;
  2563.               else if (strcmp ("threads", tok) == 0)
  2564.                 {
  2565.                   disable_packet_vCont = 1;
  2566.                   disable_packet_Tthread = 1;
  2567.                   disable_packet_qC = 1;
  2568.                   disable_packet_qfThreadInfo = 1;
  2569.                 }
  2570.               else
  2571.                 {
  2572.                   fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
  2573.                            tok);
  2574.                   gdbserver_show_disableable (stderr);
  2575.                   exit (1);
  2576.                 }
  2577.             }
  2578.         }
  2579.       else if (strcmp (*next_arg, "-") == 0)
  2580.         {
  2581.           /* "-" specifies a stdio connection and is a form of port
  2582.              specification.  */
  2583.           *next_arg = STDIO_CONNECTION_NAME;
  2584.           break;
  2585.         }
  2586.       else if (strcmp (*next_arg, "--disable-randomization") == 0)
  2587.         disable_randomization = 1;
  2588.       else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
  2589.         disable_randomization = 0;
  2590.       else if (strcmp (*next_arg, "--once") == 0)
  2591.         run_once = 1;
  2592.       else
  2593.         {
  2594.           fprintf (stderr, "Unknown argument: %s\n", *next_arg);
  2595.           exit (1);
  2596.         }

  2597.       next_arg++;
  2598.       continue;
  2599.     }

  2600.   port = *next_arg;
  2601.   next_arg++;
  2602.   if (port == NULL || (!attach && !multi_mode && *next_arg == NULL))
  2603.     {
  2604.       gdbserver_usage (stderr);
  2605.       exit (1);
  2606.     }

  2607.   /* Remember stdio descriptors.  LISTEN_DESC must not be listed, it will be
  2608.      opened by remote_prepare.  */
  2609.   notice_open_fds ();

  2610.   /* We need to know whether the remote connection is stdio before
  2611.      starting the inferior.  Inferiors created in this scenario have
  2612.      stdin,stdout redirected.  So do this here before we call
  2613.      start_inferior.  */
  2614.   remote_prepare (port);

  2615.   bad_attach = 0;
  2616.   pid = 0;

  2617.   /* --attach used to come after PORT, so allow it there for
  2618.        compatibility.  */
  2619.   if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
  2620.     {
  2621.       attach = 1;
  2622.       next_arg++;
  2623.     }

  2624.   if (attach
  2625.       && (*next_arg == NULL
  2626.           || (*next_arg)[0] == '\0'
  2627.           || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
  2628.           || *arg_end != '\0'
  2629.           || next_arg[1] != NULL))
  2630.     bad_attach = 1;

  2631.   if (bad_attach)
  2632.     {
  2633.       gdbserver_usage (stderr);
  2634.       exit (1);
  2635.     }

  2636.   initialize_async_io ();
  2637.   initialize_low ();
  2638.   initialize_event_loop ();
  2639.   if (target_supports_tracepoints ())
  2640.     initialize_tracepoint ();

  2641.   own_buf = xmalloc (PBUFSIZ + 1);
  2642.   mem_buf = xmalloc (PBUFSIZ);

  2643.   if (pid == 0 && *next_arg != NULL)
  2644.     {
  2645.       int i, n;

  2646.       n = argc - (next_arg - argv);
  2647.       program_argv = xmalloc (sizeof (char *) * (n + 1));
  2648.       for (i = 0; i < n; i++)
  2649.         program_argv[i] = xstrdup (next_arg[i]);
  2650.       program_argv[i] = NULL;

  2651.       /* Wait till we are at first instruction in program.  */
  2652.       start_inferior (program_argv);

  2653.       /* We are now (hopefully) stopped at the first instruction of
  2654.          the target process.  This assumes that the target process was
  2655.          successfully created.  */
  2656.     }
  2657.   else if (pid != 0)
  2658.     {
  2659.       if (attach_inferior (pid) == -1)
  2660.         error ("Attaching not supported on this target");

  2661.       /* Otherwise succeeded.  */
  2662.     }
  2663.   else
  2664.     {
  2665.       last_status.kind = TARGET_WAITKIND_EXITED;
  2666.       last_status.value.integer = 0;
  2667.       last_ptid = minus_one_ptid;
  2668.     }
  2669.   make_cleanup (detach_or_kill_for_exit_cleanup, NULL);

  2670.   initialize_notif ();

  2671.   /* Don't report shared library events on the initial connection,
  2672.      even if some libraries are preloaded.  Avoids the "stopped by
  2673.      shared library event" notice on gdb side.  */
  2674.   dlls_changed = 0;

  2675.   if (last_status.kind == TARGET_WAITKIND_EXITED
  2676.       || last_status.kind == TARGET_WAITKIND_SIGNALLED)
  2677.     was_running = 0;
  2678.   else
  2679.     was_running = 1;

  2680.   if (!was_running && !multi_mode)
  2681.     error ("No program to debug");

  2682.   while (1)
  2683.     {
  2684.       volatile struct gdb_exception exception;

  2685.       noack_mode = 0;
  2686.       multi_process = 0;
  2687.       /* Be sure we're out of tfind mode.  */
  2688.       current_traceframe = -1;
  2689.       cont_thread = null_ptid;

  2690.       remote_open (port);

  2691.       TRY_CATCH (exception, RETURN_MASK_ERROR)
  2692.         {
  2693.           /* Wait for events.  This will return when all event sources
  2694.              are removed from the event loop.  */
  2695.           start_event_loop ();

  2696.           /* If an exit was requested (using the "monitor exit"
  2697.              command), terminate now.  The only other way to get
  2698.              here is for getpkt to fail; close the connection
  2699.              and reopen it at the top of the loop.  */

  2700.           if (exit_requested || run_once)
  2701.             throw_quit ("Quit");

  2702.           fprintf (stderr,
  2703.                    "Remote side has terminated connection.  "
  2704.                    "GDBserver will reopen the connection.\n");

  2705.           /* Get rid of any pending statuses.  An eventual reconnection
  2706.              (by the same GDB instance or another) will refresh all its
  2707.              state from scratch.  */
  2708.           discard_queued_stop_replies (-1);
  2709.           for_each_inferior (&all_threads,
  2710.                              clear_pending_status_callback);

  2711.           if (tracing)
  2712.             {
  2713.               if (disconnected_tracing)
  2714.                 {
  2715.                   /* Try to enable non-stop/async mode, so we we can
  2716.                      both wait for an async socket accept, and handle
  2717.                      async target events simultaneously.  There's also
  2718.                      no point either in having the target always stop
  2719.                      all threads, when we're going to pass signals
  2720.                      down without informing GDB.  */
  2721.                   if (!non_stop)
  2722.                     {
  2723.                       if (start_non_stop (1))
  2724.                         non_stop = 1;

  2725.                       /* Detaching implicitly resumes all threads;
  2726.                          simply disconnecting does not.  */
  2727.                     }
  2728.                 }
  2729.               else
  2730.                 {
  2731.                   fprintf (stderr,
  2732.                            "Disconnected tracing disabled; "
  2733.                            "stopping trace run.\n");
  2734.                   stop_tracing ();
  2735.                 }
  2736.             }
  2737.         }

  2738.       if (exception.reason == RETURN_ERROR)
  2739.         {
  2740.           if (response_needed)
  2741.             {
  2742.               write_enn (own_buf);
  2743.               putpkt (own_buf);
  2744.             }
  2745.         }
  2746.     }
  2747. }

  2748. /* Main function.  */

  2749. int
  2750. main (int argc, char *argv[])
  2751. {
  2752.   volatile struct gdb_exception exception;

  2753.   TRY_CATCH (exception, RETURN_MASK_ALL)
  2754.     {
  2755.       captured_main (argc, argv);
  2756.     }

  2757.   /* captured_main should never return.  */
  2758.   gdb_assert (exception.reason < 0);

  2759.   if (exception.reason == RETURN_ERROR)
  2760.     {
  2761.       fflush (stdout);
  2762.       fprintf (stderr, "%s\n", exception.message);
  2763.       fprintf (stderr, "Exiting\n");
  2764.       exit_code = 1;
  2765.     }

  2766.   exit (exit_code);
  2767. }

  2768. /* Skip PACKET until the next semi-colon (or end of string).  */

  2769. static void
  2770. skip_to_semicolon (char **packet)
  2771. {
  2772.   while (**packet != '\0' && **packet != ';')
  2773.     (*packet)++;
  2774. }

  2775. /* Process options coming from Z packets for a breakpoint.  PACKET is
  2776.    the packet buffer.  *PACKET is updated to point to the first char
  2777.    after the last processed option.  */

  2778. static void
  2779. process_point_options (struct breakpoint *bp, char **packet)
  2780. {
  2781.   char *dataptr = *packet;
  2782.   int persist;

  2783.   /* Check if data has the correct format.  */
  2784.   if (*dataptr != ';')
  2785.     return;

  2786.   dataptr++;

  2787.   while (*dataptr)
  2788.     {
  2789.       if (*dataptr == ';')
  2790.         ++dataptr;

  2791.       if (*dataptr == 'X')
  2792.         {
  2793.           /* Conditional expression.  */
  2794.           if (debug_threads)
  2795.             debug_printf ("Found breakpoint condition.\n");
  2796.           if (!add_breakpoint_condition (bp, &dataptr))
  2797.             skip_to_semicolon (&dataptr);
  2798.         }
  2799.       else if (strncmp (dataptr, "cmds:", strlen ("cmds:")) == 0)
  2800.         {
  2801.           dataptr += strlen ("cmds:");
  2802.           if (debug_threads)
  2803.             debug_printf ("Found breakpoint commands %s.\n", dataptr);
  2804.           persist = (*dataptr == '1');
  2805.           dataptr += 2;
  2806.           if (add_breakpoint_commands (bp, &dataptr, persist))
  2807.             skip_to_semicolon (&dataptr);
  2808.         }
  2809.       else
  2810.         {
  2811.           fprintf (stderr, "Unknown token %c, ignoring.\n",
  2812.                    *dataptr);
  2813.           /* Skip tokens until we find one that we recognize.  */
  2814.           skip_to_semicolon (&dataptr);
  2815.         }
  2816.     }
  2817.   *packet = dataptr;
  2818. }

  2819. /* Event loop callback that handles a serial event.  The first byte in
  2820.    the serial buffer gets us here.  We expect characters to arrive at
  2821.    a brisk pace, so we read the rest of the packet with a blocking
  2822.    getpkt call.  */

  2823. static int
  2824. process_serial_event (void)
  2825. {
  2826.   char ch;
  2827.   int i = 0;
  2828.   int signal;
  2829.   unsigned int len;
  2830.   int res;
  2831.   CORE_ADDR mem_addr;
  2832.   int pid;
  2833.   unsigned char sig;
  2834.   int packet_len;
  2835.   int new_packet_len = -1;

  2836.   /* Used to decide when gdbserver should exit in
  2837.      multi-mode/remote.  */
  2838.   static int have_ran = 0;

  2839.   if (!have_ran)
  2840.     have_ran = target_running ();

  2841.   disable_async_io ();

  2842.   response_needed = 0;
  2843.   packet_len = getpkt (own_buf);
  2844.   if (packet_len <= 0)
  2845.     {
  2846.       remote_close ();
  2847.       /* Force an event loop break.  */
  2848.       return -1;
  2849.     }
  2850.   response_needed = 1;

  2851.   i = 0;
  2852.   ch = own_buf[i++];
  2853.   switch (ch)
  2854.     {
  2855.     case 'q':
  2856.       handle_query (own_buf, packet_len, &new_packet_len);
  2857.       break;
  2858.     case 'Q':
  2859.       handle_general_set (own_buf);
  2860.       break;
  2861.     case 'D':
  2862.       require_running (own_buf);

  2863.       if (multi_process)
  2864.         {
  2865.           i++; /* skip ';' */
  2866.           pid = strtol (&own_buf[i], NULL, 16);
  2867.         }
  2868.       else
  2869.         pid = ptid_get_pid (current_ptid);

  2870.       if ((tracing && disconnected_tracing) || any_persistent_commands ())
  2871.         {
  2872.           struct thread_resume resume_info;
  2873.           struct process_info *process = find_process_pid (pid);

  2874.           if (process == NULL)
  2875.             {
  2876.               write_enn (own_buf);
  2877.               break;
  2878.             }

  2879.           if (tracing && disconnected_tracing)
  2880.             fprintf (stderr,
  2881.                      "Disconnected tracing in effect, "
  2882.                      "leaving gdbserver attached to the process\n");

  2883.           if (any_persistent_commands ())
  2884.             fprintf (stderr,
  2885.                      "Persistent commands are present, "
  2886.                      "leaving gdbserver attached to the process\n");

  2887.           /* Make sure we're in non-stop/async mode, so we we can both
  2888.              wait for an async socket accept, and handle async target
  2889.              events simultaneously.  There's also no point either in
  2890.              having the target stop all threads, when we're going to
  2891.              pass signals down without informing GDB.  */
  2892.           if (!non_stop)
  2893.             {
  2894.               if (debug_threads)
  2895.                 debug_printf ("Forcing non-stop mode\n");

  2896.               non_stop = 1;
  2897.               start_non_stop (1);
  2898.             }

  2899.           process->gdb_detached = 1;

  2900.           /* Detaching implicitly resumes all threads.  */
  2901.           resume_info.thread = minus_one_ptid;
  2902.           resume_info.kind = resume_continue;
  2903.           resume_info.sig = 0;
  2904.           (*the_target->resume) (&resume_info, 1);

  2905.           write_ok (own_buf);
  2906.           break; /* from switch/case */
  2907.         }

  2908.       fprintf (stderr, "Detaching from process %d\n", pid);
  2909.       stop_tracing ();
  2910.       if (detach_inferior (pid) != 0)
  2911.         write_enn (own_buf);
  2912.       else
  2913.         {
  2914.           discard_queued_stop_replies (pid);
  2915.           write_ok (own_buf);

  2916.           if (extended_protocol)
  2917.             {
  2918.               /* Treat this like a normal program exit.  */
  2919.               last_status.kind = TARGET_WAITKIND_EXITED;
  2920.               last_status.value.integer = 0;
  2921.               last_ptid = pid_to_ptid (pid);

  2922.               current_thread = NULL;
  2923.             }
  2924.           else
  2925.             {
  2926.               putpkt (own_buf);
  2927.               remote_close ();

  2928.               /* If we are attached, then we can exit.  Otherwise, we
  2929.                  need to hang around doing nothing, until the child is
  2930.                  gone.  */
  2931.               join_inferior (pid);
  2932.               exit (0);
  2933.             }
  2934.         }
  2935.       break;
  2936.     case '!':
  2937.       extended_protocol = 1;
  2938.       write_ok (own_buf);
  2939.       break;
  2940.     case '?':
  2941.       handle_status (own_buf);
  2942.       break;
  2943.     case 'H':
  2944.       if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's')
  2945.         {
  2946.           ptid_t gdb_id, thread_id;
  2947.           int pid;

  2948.           require_running (own_buf);

  2949.           gdb_id = read_ptid (&own_buf[2], NULL);

  2950.           pid = ptid_get_pid (gdb_id);

  2951.           if (ptid_equal (gdb_id, null_ptid)
  2952.               || ptid_equal (gdb_id, minus_one_ptid))
  2953.             thread_id = null_ptid;
  2954.           else if (pid != 0
  2955.                    && ptid_equal (pid_to_ptid (pid),
  2956.                                   gdb_id))
  2957.             {
  2958.               struct thread_info *thread =
  2959.                 (struct thread_info *) find_inferior (&all_threads,
  2960.                                                       first_thread_of,
  2961.                                                       &pid);
  2962.               if (!thread)
  2963.                 {
  2964.                   write_enn (own_buf);
  2965.                   break;
  2966.                 }

  2967.               thread_id = thread->entry.id;
  2968.             }
  2969.           else
  2970.             {
  2971.               thread_id = gdb_id_to_thread_id (gdb_id);
  2972.               if (ptid_equal (thread_id, null_ptid))
  2973.                 {
  2974.                   write_enn (own_buf);
  2975.                   break;
  2976.                 }
  2977.             }

  2978.           if (own_buf[1] == 'g')
  2979.             {
  2980.               if (ptid_equal (thread_id, null_ptid))
  2981.                 {
  2982.                   /* GDB is telling us to choose any thread.  Check if
  2983.                      the currently selected thread is still valid. If
  2984.                      it is not, select the first available.  */
  2985.                   struct thread_info *thread =
  2986.                     (struct thread_info *) find_inferior_id (&all_threads,
  2987.                                                              general_thread);
  2988.                   if (thread == NULL)
  2989.                     {
  2990.                       thread = get_first_thread ();
  2991.                       thread_id = thread->entry.id;
  2992.                     }
  2993.                 }

  2994.               general_thread = thread_id;
  2995.               set_desired_thread (1);
  2996.             }
  2997.           else if (own_buf[1] == 'c')
  2998.             cont_thread = thread_id;

  2999.           write_ok (own_buf);
  3000.         }
  3001.       else
  3002.         {
  3003.           /* Silently ignore it so that gdb can extend the protocol
  3004.              without compatibility headaches.  */
  3005.           own_buf[0] = '\0';
  3006.         }
  3007.       break;
  3008.     case 'g':
  3009.       require_running (own_buf);
  3010.       if (current_traceframe >= 0)
  3011.         {
  3012.           struct regcache *regcache
  3013.             = new_register_cache (current_target_desc ());

  3014.           if (fetch_traceframe_registers (current_traceframe,
  3015.                                           regcache, -1) == 0)
  3016.             registers_to_string (regcache, own_buf);
  3017.           else
  3018.             write_enn (own_buf);
  3019.           free_register_cache (regcache);
  3020.         }
  3021.       else
  3022.         {
  3023.           struct regcache *regcache;

  3024.           set_desired_thread (1);
  3025.           regcache = get_thread_regcache (current_thread, 1);
  3026.           registers_to_string (regcache, own_buf);
  3027.         }
  3028.       break;
  3029.     case 'G':
  3030.       require_running (own_buf);
  3031.       if (current_traceframe >= 0)
  3032.         write_enn (own_buf);
  3033.       else
  3034.         {
  3035.           struct regcache *regcache;

  3036.           set_desired_thread (1);
  3037.           regcache = get_thread_regcache (current_thread, 1);
  3038.           registers_from_string (regcache, &own_buf[1]);
  3039.           write_ok (own_buf);
  3040.         }
  3041.       break;
  3042.     case 'm':
  3043.       require_running (own_buf);
  3044.       decode_m_packet (&own_buf[1], &mem_addr, &len);
  3045.       res = gdb_read_memory (mem_addr, mem_buf, len);
  3046.       if (res < 0)
  3047.         write_enn (own_buf);
  3048.       else
  3049.         bin2hex (mem_buf, own_buf, res);
  3050.       break;
  3051.     case 'M':
  3052.       require_running (own_buf);
  3053.       decode_M_packet (&own_buf[1], &mem_addr, &len, &mem_buf);
  3054.       if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
  3055.         write_ok (own_buf);
  3056.       else
  3057.         write_enn (own_buf);
  3058.       break;
  3059.     case 'X':
  3060.       require_running (own_buf);
  3061.       if (decode_X_packet (&own_buf[1], packet_len - 1,
  3062.                            &mem_addr, &len, &mem_buf) < 0
  3063.           || gdb_write_memory (mem_addr, mem_buf, len) != 0)
  3064.         write_enn (own_buf);
  3065.       else
  3066.         write_ok (own_buf);
  3067.       break;
  3068.     case 'C':
  3069.       require_running (own_buf);
  3070.       hex2bin (own_buf + 1, &sig, 1);
  3071.       if (gdb_signal_to_host_p (sig))
  3072.         signal = gdb_signal_to_host (sig);
  3073.       else
  3074.         signal = 0;
  3075.       myresume (own_buf, 0, signal);
  3076.       break;
  3077.     case 'S':
  3078.       require_running (own_buf);
  3079.       hex2bin (own_buf + 1, &sig, 1);
  3080.       if (gdb_signal_to_host_p (sig))
  3081.         signal = gdb_signal_to_host (sig);
  3082.       else
  3083.         signal = 0;
  3084.       myresume (own_buf, 1, signal);
  3085.       break;
  3086.     case 'c':
  3087.       require_running (own_buf);
  3088.       signal = 0;
  3089.       myresume (own_buf, 0, signal);
  3090.       break;
  3091.     case 's':
  3092.       require_running (own_buf);
  3093.       signal = 0;
  3094.       myresume (own_buf, 1, signal);
  3095.       break;
  3096.     case 'Z'/* insert_ ... */
  3097.       /* Fallthrough.  */
  3098.     case 'z'/* remove_ ... */
  3099.       {
  3100.         char *dataptr;
  3101.         ULONGEST addr;
  3102.         int len;
  3103.         char type = own_buf[1];
  3104.         int res;
  3105.         const int insert = ch == 'Z';
  3106.         char *p = &own_buf[3];

  3107.         p = unpack_varlen_hex (p, &addr);
  3108.         len = strtol (p + 1, &dataptr, 16);

  3109.         if (insert)
  3110.           {
  3111.             struct breakpoint *bp;

  3112.             bp = set_gdb_breakpoint (type, addr, len, &res);
  3113.             if (bp != NULL)
  3114.               {
  3115.                 res = 0;

  3116.                 /* GDB may have sent us a list of *point parameters to
  3117.                    be evaluated on the target's side.  Read such list
  3118.                    here.  If we already have a list of parameters, GDB
  3119.                    is telling us to drop that list and use this one
  3120.                    instead.  */
  3121.                 clear_breakpoint_conditions_and_commands (bp);
  3122.                 process_point_options (bp, &dataptr);
  3123.               }
  3124.           }
  3125.         else
  3126.           res = delete_gdb_breakpoint (type, addr, len);

  3127.         if (res == 0)
  3128.           write_ok (own_buf);
  3129.         else if (res == 1)
  3130.           /* Unsupported.  */
  3131.           own_buf[0] = '\0';
  3132.         else
  3133.           write_enn (own_buf);
  3134.         break;
  3135.       }
  3136.     case 'k':
  3137.       response_needed = 0;
  3138.       if (!target_running ())
  3139.         /* The packet we received doesn't make sense - but we can't
  3140.            reply to it, either.  */
  3141.         return 0;

  3142.       fprintf (stderr, "Killing all inferiors\n");
  3143.       for_each_inferior (&all_processes, kill_inferior_callback);

  3144.       /* When using the extended protocol, we wait with no program
  3145.          running.  The traditional protocol will exit instead.  */
  3146.       if (extended_protocol)
  3147.         {
  3148.           last_status.kind = TARGET_WAITKIND_EXITED;
  3149.           last_status.value.sig = GDB_SIGNAL_KILL;
  3150.           return 0;
  3151.         }
  3152.       else
  3153.         exit (0);

  3154.     case 'T':
  3155.       {
  3156.         ptid_t gdb_id, thread_id;

  3157.         require_running (own_buf);

  3158.         gdb_id = read_ptid (&own_buf[1], NULL);
  3159.         thread_id = gdb_id_to_thread_id (gdb_id);
  3160.         if (ptid_equal (thread_id, null_ptid))
  3161.           {
  3162.             write_enn (own_buf);
  3163.             break;
  3164.           }

  3165.         if (mythread_alive (thread_id))
  3166.           write_ok (own_buf);
  3167.         else
  3168.           write_enn (own_buf);
  3169.       }
  3170.       break;
  3171.     case 'R':
  3172.       response_needed = 0;

  3173.       /* Restarting the inferior is only supported in the extended
  3174.          protocol.  */
  3175.       if (extended_protocol)
  3176.         {
  3177.           if (target_running ())
  3178.             for_each_inferior (&all_processes,
  3179.                                kill_inferior_callback);
  3180.           fprintf (stderr, "GDBserver restarting\n");

  3181.           /* Wait till we are at 1st instruction in prog.  */
  3182.           if (program_argv != NULL)
  3183.             start_inferior (program_argv);
  3184.           else
  3185.             {
  3186.               last_status.kind = TARGET_WAITKIND_EXITED;
  3187.               last_status.value.sig = GDB_SIGNAL_KILL;
  3188.             }
  3189.           return 0;
  3190.         }
  3191.       else
  3192.         {
  3193.           /* It is a request we don't understand.  Respond with an
  3194.              empty packet so that gdb knows that we don't support this
  3195.              request.  */
  3196.           own_buf[0] = '\0';
  3197.           break;
  3198.         }
  3199.     case 'v':
  3200.       /* Extended (long) request.  */
  3201.       handle_v_requests (own_buf, packet_len, &new_packet_len);
  3202.       break;

  3203.     default:
  3204.       /* It is a request we don't understand.  Respond with an empty
  3205.          packet so that gdb knows that we don't support this
  3206.          request.  */
  3207.       own_buf[0] = '\0';
  3208.       break;
  3209.     }

  3210.   if (new_packet_len != -1)
  3211.     putpkt_binary (own_buf, new_packet_len);
  3212.   else
  3213.     putpkt (own_buf);

  3214.   response_needed = 0;

  3215.   if (!extended_protocol && have_ran && !target_running ())
  3216.     {
  3217.       /* In non-stop, defer exiting until GDB had a chance to query
  3218.          the whole vStopped list (until it gets an OK).  */
  3219.       if (QUEUE_is_empty (notif_event_p, notif_stop.queue))
  3220.         {
  3221.           /* Be transparent when GDB is connected through stdio -- no
  3222.              need to spam GDB's console.  */
  3223.           if (!remote_connection_is_stdio ())
  3224.             fprintf (stderr, "GDBserver exiting\n");
  3225.           remote_close ();
  3226.           exit (0);
  3227.         }
  3228.     }

  3229.   if (exit_requested)
  3230.     return -1;

  3231.   return 0;
  3232. }

  3233. /* Event-loop callback for serial events.  */

  3234. int
  3235. handle_serial_event (int err, gdb_client_data client_data)
  3236. {
  3237.   if (debug_threads)
  3238.     debug_printf ("handling possible serial event\n");

  3239.   /* Really handle it.  */
  3240.   if (process_serial_event () < 0)
  3241.     return -1;

  3242.   /* Be sure to not change the selected thread behind GDB's back.
  3243.      Important in the non-stop mode asynchronous protocol.  */
  3244.   set_desired_thread (1);

  3245.   return 0;
  3246. }

  3247. /* Event-loop callback for target events.  */

  3248. int
  3249. handle_target_event (int err, gdb_client_data client_data)
  3250. {
  3251.   if (debug_threads)
  3252.     debug_printf ("handling possible target event\n");

  3253.   last_ptid = mywait (minus_one_ptid, &last_status,
  3254.                       TARGET_WNOHANG, 1);

  3255.   if (last_status.kind == TARGET_WAITKIND_NO_RESUMED)
  3256.     {
  3257.       /* No RSP support for this yet.  */
  3258.     }
  3259.   else if (last_status.kind != TARGET_WAITKIND_IGNORE)
  3260.     {
  3261.       int pid = ptid_get_pid (last_ptid);
  3262.       struct process_info *process = find_process_pid (pid);
  3263.       int forward_event = !gdb_connected () || process->gdb_detached;

  3264.       if (last_status.kind == TARGET_WAITKIND_EXITED
  3265.           || last_status.kind == TARGET_WAITKIND_SIGNALLED)
  3266.         {
  3267.           mark_breakpoints_out (process);
  3268.           mourn_inferior (process);
  3269.         }
  3270.       else
  3271.         {
  3272.           /* We're reporting this thread as stopped.  Update its
  3273.              "want-stopped" state to what the client wants, until it
  3274.              gets a new resume action.  */
  3275.           current_thread->last_resume_kind = resume_stop;
  3276.           current_thread->last_status = last_status;
  3277.         }

  3278.       if (forward_event)
  3279.         {
  3280.           if (!target_running ())
  3281.             {
  3282.               /* The last process exited.  We're done.  */
  3283.               exit (0);
  3284.             }

  3285.           if (last_status.kind == TARGET_WAITKIND_STOPPED)
  3286.             {
  3287.               /* A thread stopped with a signal, but gdb isn't
  3288.                  connected to handle it.  Pass it down to the
  3289.                  inferior, as if it wasn't being traced.  */
  3290.               struct thread_resume resume_info;

  3291.               if (debug_threads)
  3292.                 debug_printf ("GDB not connected; forwarding event %d for"
  3293.                               " [%s]\n",
  3294.                               (int) last_status.kind,
  3295.                               target_pid_to_str (last_ptid));

  3296.               resume_info.thread = last_ptid;
  3297.               resume_info.kind = resume_continue;
  3298.               resume_info.sig = gdb_signal_to_host (last_status.value.sig);
  3299.               (*the_target->resume) (&resume_info, 1);
  3300.             }
  3301.           else if (debug_threads)
  3302.             debug_printf ("GDB not connected; ignoring event %d for [%s]\n",
  3303.                           (int) last_status.kind,
  3304.                           target_pid_to_str (last_ptid));
  3305.         }
  3306.       else
  3307.         {
  3308.           struct vstop_notif *vstop_notif
  3309.             = xmalloc (sizeof (struct vstop_notif));

  3310.           vstop_notif->status = last_status;
  3311.           vstop_notif->ptid = last_ptid;
  3312.           /* Push Stop notification.  */
  3313.           notif_push (&notif_stop,
  3314.                       (struct notif_event *) vstop_notif);
  3315.         }
  3316.     }

  3317.   /* Be sure to not change the selected thread behind GDB's back.
  3318.      Important in the non-stop mode asynchronous protocol.  */
  3319.   set_desired_thread (1);

  3320.   return 0;
  3321. }