GDBserver
/home/stan/gdb/src/gdb/gdbserver/server.c
Go to the documentation of this file.
00001 /* Main code for remote server for GDB.
00002    Copyright (C) 1989-2013 Free Software Foundation, Inc.
00003 
00004    This file is part of GDB.
00005 
00006    This program is free software; you can redistribute it and/or modify
00007    it under the terms of the GNU General Public License as published by
00008    the Free Software Foundation; either version 3 of the License, or
00009    (at your option) any later version.
00010 
00011    This program is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014    GNU General Public License for more details.
00015 
00016    You should have received a copy of the GNU General Public License
00017    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00018 
00019 #include "server.h"
00020 #include "gdbthread.h"
00021 #include "agent.h"
00022 #include "notif.h"
00023 #include "tdesc.h"
00024 
00025 #include <unistd.h>
00026 #if HAVE_SIGNAL_H
00027 #include <signal.h>
00028 #endif
00029 #include "gdb_wait.h"
00030 #include "btrace-common.h"
00031 #include "filestuff.h"
00032 #include "tracepoint.h"
00033 #include "dll.h"
00034 #include "hostio.h"
00035 
00036 /* The thread set with an `Hc' packet.  `Hc' is deprecated in favor of
00037    `vCont'.  Note the multi-process extensions made `vCont' a
00038    requirement, so `Hc pPID.TID' is pretty much undefined.  So
00039    CONT_THREAD can be null_ptid for no `Hc' thread, minus_one_ptid for
00040    resuming all threads of the process (again, `Hc' isn't used for
00041    multi-process), or a specific thread ptid_t.
00042 
00043    We also set this when handling a single-thread `vCont' resume, as
00044    some places in the backends check it to know when (and for which
00045    thread) single-thread scheduler-locking is in effect.  */
00046 ptid_t cont_thread;
00047 
00048 /* The thread set with an `Hg' packet.  */
00049 ptid_t general_thread;
00050 
00051 int server_waiting;
00052 
00053 static int extended_protocol;
00054 static int response_needed;
00055 static int exit_requested;
00056 
00057 /* --once: Exit after the first connection has closed.  */
00058 int run_once;
00059 
00060 int multi_process;
00061 int non_stop;
00062 
00063 /* Whether we should attempt to disable the operating system's address
00064    space randomization feature before starting an inferior.  */
00065 int disable_randomization = 1;
00066 
00067 static char **program_argv, **wrapper_argv;
00068 
00069 /* Enable miscellaneous debugging output.  The name is historical - it
00070    was originally used to debug LinuxThreads support.  */
00071 int debug_threads;
00072 
00073 /* Enable debugging of h/w breakpoint/watchpoint support.  */
00074 int debug_hw_points;
00075 
00076 int pass_signals[GDB_SIGNAL_LAST];
00077 int program_signals[GDB_SIGNAL_LAST];
00078 int program_signals_p;
00079 
00080 jmp_buf toplevel;
00081 
00082 /* The PID of the originally created or attached inferior.  Used to
00083    send signals to the process when GDB sends us an asynchronous interrupt
00084    (user hitting Control-C in the client), and to wait for the child to exit
00085    when no longer debugging it.  */
00086 
00087 unsigned long signal_pid;
00088 
00089 #ifdef SIGTTOU
00090 /* A file descriptor for the controlling terminal.  */
00091 int terminal_fd;
00092 
00093 /* TERMINAL_FD's original foreground group.  */
00094 pid_t old_foreground_pgrp;
00095 
00096 /* Hand back terminal ownership to the original foreground group.  */
00097 
00098 static void
00099 restore_old_foreground_pgrp (void)
00100 {
00101   tcsetpgrp (terminal_fd, old_foreground_pgrp);
00102 }
00103 #endif
00104 
00105 /* Set if you want to disable optional thread related packets support
00106    in gdbserver, for the sake of testing GDB against stubs that don't
00107    support them.  */
00108 int disable_packet_vCont;
00109 int disable_packet_Tthread;
00110 int disable_packet_qC;
00111 int disable_packet_qfThreadInfo;
00112 
00113 /* Last status reported to GDB.  */
00114 static struct target_waitstatus last_status;
00115 static ptid_t last_ptid;
00116 
00117 static char *own_buf;
00118 static unsigned char *mem_buf;
00119 
00120 /* A sub-class of 'struct notif_event' for stop, holding information
00121    relative to a single stop reply.  We keep a queue of these to
00122    push to GDB in non-stop mode.  */
00123 
00124 struct vstop_notif
00125 {
00126   struct notif_event base;
00127 
00128   /* Thread or process that got the event.  */
00129   ptid_t ptid;
00130 
00131   /* Event info.  */
00132   struct target_waitstatus status;
00133 };
00134 
00135 DEFINE_QUEUE_P (notif_event_p);
00136 
00137 /* Put a stop reply to the stop reply queue.  */
00138 
00139 static void
00140 queue_stop_reply (ptid_t ptid, struct target_waitstatus *status)
00141 {
00142   struct vstop_notif *new_notif = xmalloc (sizeof (*new_notif));
00143 
00144   new_notif->ptid = ptid;
00145   new_notif->status = *status;
00146 
00147   notif_event_enque (&notif_stop, (struct notif_event *) new_notif);
00148 }
00149 
00150 static int
00151 remove_all_on_match_pid (QUEUE (notif_event_p) *q,
00152                             QUEUE_ITER (notif_event_p) *iter,
00153                             struct notif_event *event,
00154                             void *data)
00155 {
00156   int *pid = data;
00157 
00158   if (*pid == -1
00159       || ptid_get_pid (((struct vstop_notif *) event)->ptid) == *pid)
00160     {
00161       if (q->free_func != NULL)
00162         q->free_func (event);
00163 
00164       QUEUE_remove_elem (notif_event_p, q, iter);
00165     }
00166 
00167   return 1;
00168 }
00169 
00170 /* Get rid of the currently pending stop replies for PID.  If PID is
00171    -1, then apply to all processes.  */
00172 
00173 static void
00174 discard_queued_stop_replies (int pid)
00175 {
00176   QUEUE_iterate (notif_event_p, notif_stop.queue,
00177                  remove_all_on_match_pid, &pid);
00178 }
00179 
00180 static void
00181 vstop_notif_reply (struct notif_event *event, char *own_buf)
00182 {
00183   struct vstop_notif *vstop = (struct vstop_notif *) event;
00184 
00185   prepare_resume_reply (own_buf, vstop->ptid, &vstop->status);
00186 }
00187 
00188 struct notif_server notif_stop =
00189 {
00190   "vStopped", "Stop", NULL, vstop_notif_reply,
00191 };
00192 
00193 static int
00194 target_running (void)
00195 {
00196   return all_threads.head != NULL;
00197 }
00198 
00199 static int
00200 start_inferior (char **argv)
00201 {
00202   char **new_argv = argv;
00203 
00204   if (wrapper_argv != NULL)
00205     {
00206       int i, count = 1;
00207 
00208       for (i = 0; wrapper_argv[i] != NULL; i++)
00209         count++;
00210       for (i = 0; argv[i] != NULL; i++)
00211         count++;
00212       new_argv = alloca (sizeof (char *) * count);
00213       count = 0;
00214       for (i = 0; wrapper_argv[i] != NULL; i++)
00215         new_argv[count++] = wrapper_argv[i];
00216       for (i = 0; argv[i] != NULL; i++)
00217         new_argv[count++] = argv[i];
00218       new_argv[count] = NULL;
00219     }
00220 
00221   if (debug_threads)
00222     {
00223       int i;
00224       for (i = 0; new_argv[i]; ++i)
00225         fprintf (stderr, "new_argv[%d] = \"%s\"\n", i, new_argv[i]);
00226       fflush (stderr);
00227     }
00228 
00229 #ifdef SIGTTOU
00230   signal (SIGTTOU, SIG_DFL);
00231   signal (SIGTTIN, SIG_DFL);
00232 #endif
00233 
00234   /* Clear this so the backend doesn't get confused, thinking
00235      CONT_THREAD died, and it needs to resume all threads.  */
00236   cont_thread = null_ptid;
00237 
00238   signal_pid = create_inferior (new_argv[0], new_argv);
00239 
00240   /* FIXME: we don't actually know at this point that the create
00241      actually succeeded.  We won't know that until we wait.  */
00242   fprintf (stderr, "Process %s created; pid = %ld\n", argv[0],
00243            signal_pid);
00244   fflush (stderr);
00245 
00246 #ifdef SIGTTOU
00247   signal (SIGTTOU, SIG_IGN);
00248   signal (SIGTTIN, SIG_IGN);
00249   terminal_fd = fileno (stderr);
00250   old_foreground_pgrp = tcgetpgrp (terminal_fd);
00251   tcsetpgrp (terminal_fd, signal_pid);
00252   atexit (restore_old_foreground_pgrp);
00253 #endif
00254 
00255   if (wrapper_argv != NULL)
00256     {
00257       struct thread_resume resume_info;
00258 
00259       memset (&resume_info, 0, sizeof (resume_info));
00260       resume_info.thread = pid_to_ptid (signal_pid);
00261       resume_info.kind = resume_continue;
00262       resume_info.sig = 0;
00263 
00264       last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
00265 
00266       if (last_status.kind != TARGET_WAITKIND_STOPPED)
00267         return signal_pid;
00268 
00269       do
00270         {
00271           (*the_target->resume) (&resume_info, 1);
00272 
00273           last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
00274           if (last_status.kind != TARGET_WAITKIND_STOPPED)
00275             return signal_pid;
00276 
00277           current_inferior->last_resume_kind = resume_stop;
00278           current_inferior->last_status = last_status;
00279         }
00280       while (last_status.value.sig != GDB_SIGNAL_TRAP);
00281 
00282       return signal_pid;
00283     }
00284 
00285   /* Wait till we are at 1st instruction in program, return new pid
00286      (assuming success).  */
00287   last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
00288 
00289   if (last_status.kind != TARGET_WAITKIND_EXITED
00290       && last_status.kind != TARGET_WAITKIND_SIGNALLED)
00291     {
00292       current_inferior->last_resume_kind = resume_stop;
00293       current_inferior->last_status = last_status;
00294     }
00295 
00296   return signal_pid;
00297 }
00298 
00299 static int
00300 attach_inferior (int pid)
00301 {
00302   /* myattach should return -1 if attaching is unsupported,
00303      0 if it succeeded, and call error() otherwise.  */
00304 
00305   if (myattach (pid) != 0)
00306     return -1;
00307 
00308   fprintf (stderr, "Attached; pid = %d\n", pid);
00309   fflush (stderr);
00310 
00311   /* FIXME - It may be that we should get the SIGNAL_PID from the
00312      attach function, so that it can be the main thread instead of
00313      whichever we were told to attach to.  */
00314   signal_pid = pid;
00315 
00316   /* Clear this so the backend doesn't get confused, thinking
00317      CONT_THREAD died, and it needs to resume all threads.  */
00318   cont_thread = null_ptid;
00319 
00320   if (!non_stop)
00321     {
00322       last_ptid = mywait (pid_to_ptid (pid), &last_status, 0, 0);
00323 
00324       /* GDB knows to ignore the first SIGSTOP after attaching to a running
00325          process using the "attach" command, but this is different; it's
00326          just using "target remote".  Pretend it's just starting up.  */
00327       if (last_status.kind == TARGET_WAITKIND_STOPPED
00328           && last_status.value.sig == GDB_SIGNAL_STOP)
00329         last_status.value.sig = GDB_SIGNAL_TRAP;
00330 
00331       current_inferior->last_resume_kind = resume_stop;
00332       current_inferior->last_status = last_status;
00333     }
00334 
00335   return 0;
00336 }
00337 
00338 extern int remote_debug;
00339 
00340 /* Decode a qXfer read request.  Return 0 if everything looks OK,
00341    or -1 otherwise.  */
00342 
00343 static int
00344 decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
00345 {
00346   /* After the read marker and annex, qXfer looks like a
00347      traditional 'm' packet.  */
00348   decode_m_packet (buf, ofs, len);
00349 
00350   return 0;
00351 }
00352 
00353 static int
00354 decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
00355 {
00356   /* Extract and NUL-terminate the object.  */
00357   *object = buf;
00358   while (*buf && *buf != ':')
00359     buf++;
00360   if (*buf == '\0')
00361     return -1;
00362   *buf++ = 0;
00363 
00364   /* Extract and NUL-terminate the read/write action.  */
00365   *rw = buf;
00366   while (*buf && *buf != ':')
00367     buf++;
00368   if (*buf == '\0')
00369     return -1;
00370   *buf++ = 0;
00371 
00372   /* Extract and NUL-terminate the annex.  */
00373   *annex = buf;
00374   while (*buf && *buf != ':')
00375     buf++;
00376   if (*buf == '\0')
00377     return -1;
00378   *buf++ = 0;
00379 
00380   *offset = buf;
00381   return 0;
00382 }
00383 
00384 /* Write the response to a successful qXfer read.  Returns the
00385    length of the (binary) data stored in BUF, corresponding
00386    to as much of DATA/LEN as we could fit.  IS_MORE controls
00387    the first character of the response.  */
00388 static int
00389 write_qxfer_response (char *buf, const void *data, int len, int is_more)
00390 {
00391   int out_len;
00392 
00393   if (is_more)
00394     buf[0] = 'm';
00395   else
00396     buf[0] = 'l';
00397 
00398   return remote_escape_output (data, len, (unsigned char *) buf + 1, &out_len,
00399                                PBUFSIZ - 2) + 1;
00400 }
00401 
00402 /* Handle btrace enabling.  */
00403 
00404 static const char *
00405 handle_btrace_enable (struct thread_info *thread)
00406 {
00407   if (thread->btrace != NULL)
00408     return "E.Btrace already enabled.";
00409 
00410   thread->btrace = target_enable_btrace (thread->entry.id);
00411   if (thread->btrace == NULL)
00412     return "E.Could not enable btrace.";
00413 
00414   return NULL;
00415 }
00416 
00417 /* Handle btrace disabling.  */
00418 
00419 static const char *
00420 handle_btrace_disable (struct thread_info *thread)
00421 {
00422 
00423   if (thread->btrace == NULL)
00424     return "E.Branch tracing not enabled.";
00425 
00426   if (target_disable_btrace (thread->btrace) != 0)
00427     return "E.Could not disable branch tracing.";
00428 
00429   thread->btrace = NULL;
00430   return NULL;
00431 }
00432 
00433 /* Handle the "Qbtrace" packet.  */
00434 
00435 static int
00436 handle_btrace_general_set (char *own_buf)
00437 {
00438   struct thread_info *thread;
00439   const char *err;
00440   char *op;
00441 
00442   if (strncmp ("Qbtrace:", own_buf, strlen ("Qbtrace:")) != 0)
00443     return 0;
00444 
00445   op = own_buf + strlen ("Qbtrace:");
00446 
00447   if (!target_supports_btrace ())
00448     {
00449       strcpy (own_buf, "E.Target does not support branch tracing.");
00450       return -1;
00451     }
00452 
00453   if (ptid_equal (general_thread, null_ptid)
00454       || ptid_equal (general_thread, minus_one_ptid))
00455     {
00456       strcpy (own_buf, "E.Must select a single thread.");
00457       return -1;
00458     }
00459 
00460   thread = find_thread_ptid (general_thread);
00461   if (thread == NULL)
00462     {
00463       strcpy (own_buf, "E.No such thread.");
00464       return -1;
00465     }
00466 
00467   err = NULL;
00468 
00469   if (strcmp (op, "bts") == 0)
00470     err = handle_btrace_enable (thread);
00471   else if (strcmp (op, "off") == 0)
00472     err = handle_btrace_disable (thread);
00473   else
00474     err = "E.Bad Qbtrace operation. Use bts or off.";
00475 
00476   if (err != 0)
00477     strcpy (own_buf, err);
00478   else
00479     write_ok (own_buf);
00480 
00481   return 1;
00482 }
00483 
00484 /* Handle all of the extended 'Q' packets.  */
00485 
00486 static void
00487 handle_general_set (char *own_buf)
00488 {
00489   if (strncmp ("QPassSignals:", own_buf, strlen ("QPassSignals:")) == 0)
00490     {
00491       int numsigs = (int) GDB_SIGNAL_LAST, i;
00492       const char *p = own_buf + strlen ("QPassSignals:");
00493       CORE_ADDR cursig;
00494 
00495       p = decode_address_to_semicolon (&cursig, p);
00496       for (i = 0; i < numsigs; i++)
00497         {
00498           if (i == cursig)
00499             {
00500               pass_signals[i] = 1;
00501               if (*p == '\0')
00502                 /* Keep looping, to clear the remaining signals.  */
00503                 cursig = -1;
00504               else
00505                 p = decode_address_to_semicolon (&cursig, p);
00506             }
00507           else
00508             pass_signals[i] = 0;
00509         }
00510       strcpy (own_buf, "OK");
00511       return;
00512     }
00513 
00514   if (strncmp ("QProgramSignals:", own_buf, strlen ("QProgramSignals:")) == 0)
00515     {
00516       int numsigs = (int) GDB_SIGNAL_LAST, i;
00517       const char *p = own_buf + strlen ("QProgramSignals:");
00518       CORE_ADDR cursig;
00519 
00520       program_signals_p = 1;
00521 
00522       p = decode_address_to_semicolon (&cursig, p);
00523       for (i = 0; i < numsigs; i++)
00524         {
00525           if (i == cursig)
00526             {
00527               program_signals[i] = 1;
00528               if (*p == '\0')
00529                 /* Keep looping, to clear the remaining signals.  */
00530                 cursig = -1;
00531               else
00532                 p = decode_address_to_semicolon (&cursig, p);
00533             }
00534           else
00535             program_signals[i] = 0;
00536         }
00537       strcpy (own_buf, "OK");
00538       return;
00539     }
00540 
00541   if (strcmp (own_buf, "QStartNoAckMode") == 0)
00542     {
00543       if (remote_debug)
00544         {
00545           fprintf (stderr, "[noack mode enabled]\n");
00546           fflush (stderr);
00547         }
00548 
00549       noack_mode = 1;
00550       write_ok (own_buf);
00551       return;
00552     }
00553 
00554   if (strncmp (own_buf, "QNonStop:", 9) == 0)
00555     {
00556       char *mode = own_buf + 9;
00557       int req = -1;
00558       char *req_str;
00559 
00560       if (strcmp (mode, "0") == 0)
00561         req = 0;
00562       else if (strcmp (mode, "1") == 0)
00563         req = 1;
00564       else
00565         {
00566           /* We don't know what this mode is, so complain to
00567              GDB.  */
00568           fprintf (stderr, "Unknown non-stop mode requested: %s\n",
00569                    own_buf);
00570           write_enn (own_buf);
00571           return;
00572         }
00573 
00574       req_str = req ? "non-stop" : "all-stop";
00575       if (start_non_stop (req) != 0)
00576         {
00577           fprintf (stderr, "Setting %s mode failed\n", req_str);
00578           write_enn (own_buf);
00579           return;
00580         }
00581 
00582       non_stop = req;
00583 
00584       if (remote_debug)
00585         fprintf (stderr, "[%s mode enabled]\n", req_str);
00586 
00587       write_ok (own_buf);
00588       return;
00589     }
00590 
00591   if (strncmp ("QDisableRandomization:", own_buf,
00592                strlen ("QDisableRandomization:")) == 0)
00593     {
00594       char *packet = own_buf + strlen ("QDisableRandomization:");
00595       ULONGEST setting;
00596 
00597       unpack_varlen_hex (packet, &setting);
00598       disable_randomization = setting;
00599 
00600       if (remote_debug)
00601         {
00602           if (disable_randomization)
00603             fprintf (stderr, "[address space randomization disabled]\n");
00604           else
00605             fprintf (stderr, "[address space randomization enabled]\n");
00606         }
00607 
00608       write_ok (own_buf);
00609       return;
00610     }
00611 
00612   if (target_supports_tracepoints ()
00613       && handle_tracepoint_general_set (own_buf))
00614     return;
00615 
00616   if (strncmp ("QAgent:", own_buf, strlen ("QAgent:")) == 0)
00617     {
00618       char *mode = own_buf + strlen ("QAgent:");
00619       int req = 0;
00620 
00621       if (strcmp (mode, "0") == 0)
00622         req = 0;
00623       else if (strcmp (mode, "1") == 0)
00624         req = 1;
00625       else
00626         {
00627           /* We don't know what this value is, so complain to GDB.  */
00628           sprintf (own_buf, "E.Unknown QAgent value");
00629           return;
00630         }
00631 
00632       /* Update the flag.  */
00633       use_agent = req;
00634       if (remote_debug)
00635         fprintf (stderr, "[%s agent]\n", req ? "Enable" : "Disable");
00636       write_ok (own_buf);
00637       return;
00638     }
00639 
00640   if (handle_btrace_general_set (own_buf))
00641     return;
00642 
00643   /* Otherwise we didn't know what packet it was.  Say we didn't
00644      understand it.  */
00645   own_buf[0] = 0;
00646 }
00647 
00648 static const char *
00649 get_features_xml (const char *annex)
00650 {
00651   const struct target_desc *desc = current_target_desc ();
00652 
00653   /* `desc->xmltarget' defines what to return when looking for the
00654      "target.xml" file.  Its contents can either be verbatim XML code
00655      (prefixed with a '@') or else the name of the actual XML file to
00656      be used in place of "target.xml".
00657 
00658      This variable is set up from the auto-generated
00659      init_registers_... routine for the current target.  */
00660 
00661   if (desc->xmltarget != NULL && strcmp (annex, "target.xml") == 0)
00662     {
00663       if (*desc->xmltarget == '@')
00664         return desc->xmltarget + 1;
00665       else
00666         annex = desc->xmltarget;
00667     }
00668 
00669 #ifdef USE_XML
00670   {
00671     extern const char *const xml_builtin[][2];
00672     int i;
00673 
00674     /* Look for the annex.  */
00675     for (i = 0; xml_builtin[i][0] != NULL; i++)
00676       if (strcmp (annex, xml_builtin[i][0]) == 0)
00677         break;
00678 
00679     if (xml_builtin[i][0] != NULL)
00680       return xml_builtin[i][1];
00681   }
00682 #endif
00683 
00684   return NULL;
00685 }
00686 
00687 void
00688 monitor_show_help (void)
00689 {
00690   monitor_output ("The following monitor commands are supported:\n");
00691   monitor_output ("  set debug <0|1>\n");
00692   monitor_output ("    Enable general debugging messages\n");
00693   monitor_output ("  set debug-hw-points <0|1>\n");
00694   monitor_output ("    Enable h/w breakpoint/watchpoint debugging messages\n");
00695   monitor_output ("  set remote-debug <0|1>\n");
00696   monitor_output ("    Enable remote protocol debugging messages\n");
00697   monitor_output ("  exit\n");
00698   monitor_output ("    Quit GDBserver\n");
00699 }
00700 
00701 /* Read trace frame or inferior memory.  Returns the number of bytes
00702    actually read, zero when no further transfer is possible, and -1 on
00703    error.  Return of a positive value smaller than LEN does not
00704    indicate there's no more to be read, only the end of the transfer.
00705    E.g., when GDB reads memory from a traceframe, a first request may
00706    be served from a memory block that does not cover the whole request
00707    length.  A following request gets the rest served from either
00708    another block (of the same traceframe) or from the read-only
00709    regions.  */
00710 
00711 static int
00712 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
00713 {
00714   int res;
00715 
00716   if (current_traceframe >= 0)
00717     {
00718       ULONGEST nbytes;
00719       ULONGEST length = len;
00720 
00721       if (traceframe_read_mem (current_traceframe,
00722                                memaddr, myaddr, len, &nbytes))
00723         return -1;
00724       /* Data read from trace buffer, we're done.  */
00725       if (nbytes > 0)
00726         return nbytes;
00727       if (!in_readonly_region (memaddr, length))
00728         return -1;
00729       /* Otherwise we have a valid readonly case, fall through.  */
00730       /* (assume no half-trace half-real blocks for now) */
00731     }
00732 
00733   res = prepare_to_access_memory ();
00734   if (res == 0)
00735     {
00736       res = read_inferior_memory (memaddr, myaddr, len);
00737       done_accessing_memory ();
00738 
00739       return res == 0 ? len : -1;
00740     }
00741   else
00742     return -1;
00743 }
00744 
00745 /* Write trace frame or inferior memory.  Actually, writing to trace
00746    frames is forbidden.  */
00747 
00748 static int
00749 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
00750 {
00751   if (current_traceframe >= 0)
00752     return EIO;
00753   else
00754     {
00755       int ret;
00756 
00757       ret = prepare_to_access_memory ();
00758       if (ret == 0)
00759         {
00760           ret = write_inferior_memory (memaddr, myaddr, len);
00761           done_accessing_memory ();
00762         }
00763       return ret;
00764     }
00765 }
00766 
00767 /* Subroutine of handle_search_memory to simplify it.  */
00768 
00769 static int
00770 handle_search_memory_1 (CORE_ADDR start_addr, CORE_ADDR search_space_len,
00771                         gdb_byte *pattern, unsigned pattern_len,
00772                         gdb_byte *search_buf,
00773                         unsigned chunk_size, unsigned search_buf_size,
00774                         CORE_ADDR *found_addrp)
00775 {
00776   /* Prime the search buffer.  */
00777 
00778   if (gdb_read_memory (start_addr, search_buf, search_buf_size)
00779       != search_buf_size)
00780     {
00781       warning ("Unable to access %ld bytes of target "
00782                "memory at 0x%lx, halting search.",
00783                (long) search_buf_size, (long) start_addr);
00784       return -1;
00785     }
00786 
00787   /* Perform the search.
00788 
00789      The loop is kept simple by allocating [N + pattern-length - 1] bytes.
00790      When we've scanned N bytes we copy the trailing bytes to the start and
00791      read in another N bytes.  */
00792 
00793   while (search_space_len >= pattern_len)
00794     {
00795       gdb_byte *found_ptr;
00796       unsigned nr_search_bytes = (search_space_len < search_buf_size
00797                                   ? search_space_len
00798                                   : search_buf_size);
00799 
00800       found_ptr = memmem (search_buf, nr_search_bytes, pattern, pattern_len);
00801 
00802       if (found_ptr != NULL)
00803         {
00804           CORE_ADDR found_addr = start_addr + (found_ptr - search_buf);
00805           *found_addrp = found_addr;
00806           return 1;
00807         }
00808 
00809       /* Not found in this chunk, skip to next chunk.  */
00810 
00811       /* Don't let search_space_len wrap here, it's unsigned.  */
00812       if (search_space_len >= chunk_size)
00813         search_space_len -= chunk_size;
00814       else
00815         search_space_len = 0;
00816 
00817       if (search_space_len >= pattern_len)
00818         {
00819           unsigned keep_len = search_buf_size - chunk_size;
00820           CORE_ADDR read_addr = start_addr + chunk_size + keep_len;
00821           int nr_to_read;
00822 
00823           /* Copy the trailing part of the previous iteration to the front
00824              of the buffer for the next iteration.  */
00825           memcpy (search_buf, search_buf + chunk_size, keep_len);
00826 
00827           nr_to_read = (search_space_len - keep_len < chunk_size
00828                         ? search_space_len - keep_len
00829                         : chunk_size);
00830 
00831           if (gdb_read_memory (read_addr, search_buf + keep_len,
00832                                nr_to_read) != search_buf_size)
00833             {
00834               warning ("Unable to access %ld bytes of target memory "
00835                        "at 0x%lx, halting search.",
00836                        (long) nr_to_read, (long) read_addr);
00837               return -1;
00838             }
00839 
00840           start_addr += chunk_size;
00841         }
00842     }
00843 
00844   /* Not found.  */
00845 
00846   return 0;
00847 }
00848 
00849 /* Handle qSearch:memory packets.  */
00850 
00851 static void
00852 handle_search_memory (char *own_buf, int packet_len)
00853 {
00854   CORE_ADDR start_addr;
00855   CORE_ADDR search_space_len;
00856   gdb_byte *pattern;
00857   unsigned int pattern_len;
00858   /* NOTE: also defined in find.c testcase.  */
00859 #define SEARCH_CHUNK_SIZE 16000
00860   const unsigned chunk_size = SEARCH_CHUNK_SIZE;
00861   /* Buffer to hold memory contents for searching.  */
00862   gdb_byte *search_buf;
00863   unsigned search_buf_size;
00864   int found;
00865   CORE_ADDR found_addr;
00866   int cmd_name_len = sizeof ("qSearch:memory:") - 1;
00867 
00868   pattern = malloc (packet_len);
00869   if (pattern == NULL)
00870     {
00871       error ("Unable to allocate memory to perform the search");
00872       strcpy (own_buf, "E00");
00873       return;
00874     }
00875   if (decode_search_memory_packet (own_buf + cmd_name_len,
00876                                    packet_len - cmd_name_len,
00877                                    &start_addr, &search_space_len,
00878                                    pattern, &pattern_len) < 0)
00879     {
00880       free (pattern);
00881       error ("Error in parsing qSearch:memory packet");
00882       strcpy (own_buf, "E00");
00883       return;
00884     }
00885 
00886   search_buf_size = chunk_size + pattern_len - 1;
00887 
00888   /* No point in trying to allocate a buffer larger than the search space.  */
00889   if (search_space_len < search_buf_size)
00890     search_buf_size = search_space_len;
00891 
00892   search_buf = malloc (search_buf_size);
00893   if (search_buf == NULL)
00894     {
00895       free (pattern);
00896       error ("Unable to allocate memory to perform the search");
00897       strcpy (own_buf, "E00");
00898       return;
00899     }
00900 
00901   found = handle_search_memory_1 (start_addr, search_space_len,
00902                                   pattern, pattern_len,
00903                                   search_buf, chunk_size, search_buf_size,
00904                                   &found_addr);
00905 
00906   if (found > 0)
00907     sprintf (own_buf, "1,%lx", (long) found_addr);
00908   else if (found == 0)
00909     strcpy (own_buf, "0");
00910   else
00911     strcpy (own_buf, "E00");
00912 
00913   free (search_buf);
00914   free (pattern);
00915 }
00916 
00917 #define require_running(BUF)                    \
00918   if (!target_running ())                       \
00919     {                                           \
00920       write_enn (BUF);                          \
00921       return;                                   \
00922     }
00923 
00924 /* Handle monitor commands not handled by target-specific handlers.  */
00925 
00926 static void
00927 handle_monitor_command (char *mon, char *own_buf)
00928 {
00929   if (strcmp (mon, "set debug 1") == 0)
00930     {
00931       debug_threads = 1;
00932       monitor_output ("Debug output enabled.\n");
00933     }
00934   else if (strcmp (mon, "set debug 0") == 0)
00935     {
00936       debug_threads = 0;
00937       monitor_output ("Debug output disabled.\n");
00938     }
00939   else if (strcmp (mon, "set debug-hw-points 1") == 0)
00940     {
00941       debug_hw_points = 1;
00942       monitor_output ("H/W point debugging output enabled.\n");
00943     }
00944   else if (strcmp (mon, "set debug-hw-points 0") == 0)
00945     {
00946       debug_hw_points = 0;
00947       monitor_output ("H/W point debugging output disabled.\n");
00948     }
00949   else if (strcmp (mon, "set remote-debug 1") == 0)
00950     {
00951       remote_debug = 1;
00952       monitor_output ("Protocol debug output enabled.\n");
00953     }
00954   else if (strcmp (mon, "set remote-debug 0") == 0)
00955     {
00956       remote_debug = 0;
00957       monitor_output ("Protocol debug output disabled.\n");
00958     }
00959   else if (strcmp (mon, "help") == 0)
00960     monitor_show_help ();
00961   else if (strcmp (mon, "exit") == 0)
00962     exit_requested = 1;
00963   else
00964     {
00965       monitor_output ("Unknown monitor command.\n\n");
00966       monitor_show_help ();
00967       write_enn (own_buf);
00968     }
00969 }
00970 
00971 /* Associates a callback with each supported qXfer'able object.  */
00972 
00973 struct qxfer
00974 {
00975   /* The object this handler handles.  */
00976   const char *object;
00977 
00978   /* Request that the target transfer up to LEN 8-bit bytes of the
00979      target's OBJECT.  The OFFSET, for a seekable object, specifies
00980      the starting point.  The ANNEX can be used to provide additional
00981      data-specific information to the target.
00982 
00983      Return the number of bytes actually transfered, zero when no
00984      further transfer is possible, -1 on error, -2 when the transfer
00985      is not supported, and -3 on a verbose error message that should
00986      be preserved.  Return of a positive value smaller than LEN does
00987      not indicate the end of the object, only the end of the transfer.
00988 
00989      One, and only one, of readbuf or writebuf must be non-NULL.  */
00990   int (*xfer) (const char *annex,
00991                gdb_byte *readbuf, const gdb_byte *writebuf,
00992                ULONGEST offset, LONGEST len);
00993 };
00994 
00995 /* Handle qXfer:auxv:read.  */
00996 
00997 static int
00998 handle_qxfer_auxv (const char *annex,
00999                    gdb_byte *readbuf, const gdb_byte *writebuf,
01000                    ULONGEST offset, LONGEST len)
01001 {
01002   if (the_target->read_auxv == NULL || writebuf != NULL)
01003     return -2;
01004 
01005   if (annex[0] != '\0' || !target_running ())
01006     return -1;
01007 
01008   return (*the_target->read_auxv) (offset, readbuf, len);
01009 }
01010 
01011 /* Handle qXfer:features:read.  */
01012 
01013 static int
01014 handle_qxfer_features (const char *annex,
01015                        gdb_byte *readbuf, const gdb_byte *writebuf,
01016                        ULONGEST offset, LONGEST len)
01017 {
01018   const char *document;
01019   size_t total_len;
01020 
01021   if (writebuf != NULL)
01022     return -2;
01023 
01024   if (!target_running ())
01025     return -1;
01026 
01027   /* Grab the correct annex.  */
01028   document = get_features_xml (annex);
01029   if (document == NULL)
01030     return -1;
01031 
01032   total_len = strlen (document);
01033 
01034   if (offset > total_len)
01035     return -1;
01036 
01037   if (offset + len > total_len)
01038     len = total_len - offset;
01039 
01040   memcpy (readbuf, document + offset, len);
01041   return len;
01042 }
01043 
01044 /* Handle qXfer:libraries:read.  */
01045 
01046 static int
01047 handle_qxfer_libraries (const char *annex,
01048                         gdb_byte *readbuf, const gdb_byte *writebuf,
01049                         ULONGEST offset, LONGEST len)
01050 {
01051   unsigned int total_len;
01052   char *document, *p;
01053   struct inferior_list_entry *dll_ptr;
01054 
01055   if (writebuf != NULL)
01056     return -2;
01057 
01058   if (annex[0] != '\0' || !target_running ())
01059     return -1;
01060 
01061   /* Over-estimate the necessary memory.  Assume that every character
01062      in the library name must be escaped.  */
01063   total_len = 64;
01064   for (dll_ptr = all_dlls.head; dll_ptr != NULL; dll_ptr = dll_ptr->next)
01065     total_len += 128 + 6 * strlen (((struct dll_info *) dll_ptr)->name);
01066 
01067   document = malloc (total_len);
01068   if (document == NULL)
01069     return -1;
01070 
01071   strcpy (document, "<library-list>\n");
01072   p = document + strlen (document);
01073 
01074   for (dll_ptr = all_dlls.head; dll_ptr != NULL; dll_ptr = dll_ptr->next)
01075     {
01076       struct dll_info *dll = (struct dll_info *) dll_ptr;
01077       char *name;
01078 
01079       strcpy (p, "  <library name=\"");
01080       p = p + strlen (p);
01081       name = xml_escape_text (dll->name);
01082       strcpy (p, name);
01083       free (name);
01084       p = p + strlen (p);
01085       strcpy (p, "\"><segment address=\"");
01086       p = p + strlen (p);
01087       sprintf (p, "0x%lx", (long) dll->base_addr);
01088       p = p + strlen (p);
01089       strcpy (p, "\"/></library>\n");
01090       p = p + strlen (p);
01091     }
01092 
01093   strcpy (p, "</library-list>\n");
01094 
01095   total_len = strlen (document);
01096 
01097   if (offset > total_len)
01098     {
01099       free (document);
01100       return -1;
01101     }
01102 
01103   if (offset + len > total_len)
01104     len = total_len - offset;
01105 
01106   memcpy (readbuf, document + offset, len);
01107   free (document);
01108   return len;
01109 }
01110 
01111 /* Handle qXfer:libraries-svr4:read.  */
01112 
01113 static int
01114 handle_qxfer_libraries_svr4 (const char *annex,
01115                              gdb_byte *readbuf, const gdb_byte *writebuf,
01116                              ULONGEST offset, LONGEST len)
01117 {
01118   if (writebuf != NULL)
01119     return -2;
01120 
01121   if (!target_running () || the_target->qxfer_libraries_svr4 == NULL)
01122     return -1;
01123 
01124   return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf, offset, len);
01125 }
01126 
01127 /* Handle qXfer:osadata:read.  */
01128 
01129 static int
01130 handle_qxfer_osdata (const char *annex,
01131                      gdb_byte *readbuf, const gdb_byte *writebuf,
01132                      ULONGEST offset, LONGEST len)
01133 {
01134   if (the_target->qxfer_osdata == NULL || writebuf != NULL)
01135     return -2;
01136 
01137   return (*the_target->qxfer_osdata) (annex, readbuf, NULL, offset, len);
01138 }
01139 
01140 /* Handle qXfer:siginfo:read and qXfer:siginfo:write.  */
01141 
01142 static int
01143 handle_qxfer_siginfo (const char *annex,
01144                       gdb_byte *readbuf, const gdb_byte *writebuf,
01145                       ULONGEST offset, LONGEST len)
01146 {
01147   if (the_target->qxfer_siginfo == NULL)
01148     return -2;
01149 
01150   if (annex[0] != '\0' || !target_running ())
01151     return -1;
01152 
01153   return (*the_target->qxfer_siginfo) (annex, readbuf, writebuf, offset, len);
01154 }
01155 
01156 /* Handle qXfer:spu:read and qXfer:spu:write.  */
01157 
01158 static int
01159 handle_qxfer_spu (const char *annex,
01160                   gdb_byte *readbuf, const gdb_byte *writebuf,
01161                   ULONGEST offset, LONGEST len)
01162 {
01163   if (the_target->qxfer_spu == NULL)
01164     return -2;
01165 
01166   if (!target_running ())
01167     return -1;
01168 
01169   return (*the_target->qxfer_spu) (annex, readbuf, writebuf, offset, len);
01170 }
01171 
01172 /* Handle qXfer:statictrace:read.  */
01173 
01174 static int
01175 handle_qxfer_statictrace (const char *annex,
01176                           gdb_byte *readbuf, const gdb_byte *writebuf,
01177                           ULONGEST offset, LONGEST len)
01178 {
01179   ULONGEST nbytes;
01180 
01181   if (writebuf != NULL)
01182     return -2;
01183 
01184   if (annex[0] != '\0' || !target_running () || current_traceframe == -1)
01185     return -1;
01186 
01187   if (traceframe_read_sdata (current_traceframe, offset,
01188                              readbuf, len, &nbytes))
01189     return -1;
01190   return nbytes;
01191 }
01192 
01193 /* Helper for handle_qxfer_threads.  */
01194 
01195 static void
01196 handle_qxfer_threads_proper (struct buffer *buffer)
01197 {
01198   struct inferior_list_entry *thread;
01199 
01200   buffer_grow_str (buffer, "<threads>\n");
01201 
01202   for (thread = all_threads.head; thread; thread = thread->next)
01203     {
01204       ptid_t ptid = thread_to_gdb_id ((struct thread_info *)thread);
01205       char ptid_s[100];
01206       int core = target_core_of_thread (ptid);
01207       char core_s[21];
01208 
01209       write_ptid (ptid_s, ptid);
01210 
01211       if (core != -1)
01212         {
01213           sprintf (core_s, "%d", core);
01214           buffer_xml_printf (buffer, "<thread id=\"%s\" core=\"%s\"/>\n",
01215                              ptid_s, core_s);
01216         }
01217       else
01218         {
01219           buffer_xml_printf (buffer, "<thread id=\"%s\"/>\n",
01220                              ptid_s);
01221         }
01222     }
01223 
01224   buffer_grow_str0 (buffer, "</threads>\n");
01225 }
01226 
01227 /* Handle qXfer:threads:read.  */
01228 
01229 static int
01230 handle_qxfer_threads (const char *annex,
01231                       gdb_byte *readbuf, const gdb_byte *writebuf,
01232                       ULONGEST offset, LONGEST len)
01233 {
01234   static char *result = 0;
01235   static unsigned int result_length = 0;
01236 
01237   if (writebuf != NULL)
01238     return -2;
01239 
01240   if (!target_running () || annex[0] != '\0')
01241     return -1;
01242 
01243   if (offset == 0)
01244     {
01245       struct buffer buffer;
01246       /* When asked for data at offset 0, generate everything and store into
01247          'result'.  Successive reads will be served off 'result'.  */
01248       if (result)
01249         free (result);
01250 
01251       buffer_init (&buffer);
01252 
01253       handle_qxfer_threads_proper (&buffer);
01254 
01255       result = buffer_finish (&buffer);
01256       result_length = strlen (result);
01257       buffer_free (&buffer);
01258     }
01259 
01260   if (offset >= result_length)
01261     {
01262       /* We're out of data.  */
01263       free (result);
01264       result = NULL;
01265       result_length = 0;
01266       return 0;
01267     }
01268 
01269   if (len > result_length - offset)
01270     len = result_length - offset;
01271 
01272   memcpy (readbuf, result + offset, len);
01273 
01274   return len;
01275 }
01276 
01277 /* Handle qXfer:traceframe-info:read.  */
01278 
01279 static int
01280 handle_qxfer_traceframe_info (const char *annex,
01281                               gdb_byte *readbuf, const gdb_byte *writebuf,
01282                               ULONGEST offset, LONGEST len)
01283 {
01284   static char *result = 0;
01285   static unsigned int result_length = 0;
01286 
01287   if (writebuf != NULL)
01288     return -2;
01289 
01290   if (!target_running () || annex[0] != '\0' || current_traceframe == -1)
01291     return -1;
01292 
01293   if (offset == 0)
01294     {
01295       struct buffer buffer;
01296 
01297       /* When asked for data at offset 0, generate everything and
01298          store into 'result'.  Successive reads will be served off
01299          'result'.  */
01300       free (result);
01301 
01302       buffer_init (&buffer);
01303 
01304       traceframe_read_info (current_traceframe, &buffer);
01305 
01306       result = buffer_finish (&buffer);
01307       result_length = strlen (result);
01308       buffer_free (&buffer);
01309     }
01310 
01311   if (offset >= result_length)
01312     {
01313       /* We're out of data.  */
01314       free (result);
01315       result = NULL;
01316       result_length = 0;
01317       return 0;
01318     }
01319 
01320   if (len > result_length - offset)
01321     len = result_length - offset;
01322 
01323   memcpy (readbuf, result + offset, len);
01324   return len;
01325 }
01326 
01327 /* Handle qXfer:fdpic:read.  */
01328 
01329 static int
01330 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
01331                     const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
01332 {
01333   if (the_target->read_loadmap == NULL)
01334     return -2;
01335 
01336   if (!target_running ())
01337     return -1;
01338 
01339   return (*the_target->read_loadmap) (annex, offset, readbuf, len);
01340 }
01341 
01342 /* Handle qXfer:btrace:read.  */
01343 
01344 static int
01345 handle_qxfer_btrace (const char *annex,
01346                      gdb_byte *readbuf, const gdb_byte *writebuf,
01347                      ULONGEST offset, LONGEST len)
01348 {
01349   static struct buffer cache;
01350   struct thread_info *thread;
01351   int type;
01352 
01353   if (the_target->read_btrace == NULL || writebuf != NULL)
01354     return -2;
01355 
01356   if (!target_running ())
01357     return -1;
01358 
01359   if (ptid_equal (general_thread, null_ptid)
01360       || ptid_equal (general_thread, minus_one_ptid))
01361     {
01362       strcpy (own_buf, "E.Must select a single thread.");
01363       return -3;
01364     }
01365 
01366   thread = find_thread_ptid (general_thread);
01367   if (thread == NULL)
01368     {
01369       strcpy (own_buf, "E.No such thread.");
01370       return -3;
01371     }
01372 
01373   if (thread->btrace == NULL)
01374     {
01375       strcpy (own_buf, "E.Btrace not enabled.");
01376       return -3;
01377     }
01378 
01379   if (strcmp (annex, "all") == 0)
01380     type = btrace_read_all;
01381   else if (strcmp (annex, "new") == 0)
01382     type = btrace_read_new;
01383   else
01384     {
01385       strcpy (own_buf, "E.Bad annex.");
01386       return -3;
01387     }
01388 
01389   if (offset == 0)
01390     {
01391       buffer_free (&cache);
01392 
01393       target_read_btrace (thread->btrace, &cache, type);
01394     }
01395   else if (offset > cache.used_size)
01396     {
01397       buffer_free (&cache);
01398       return -3;
01399     }
01400 
01401   if (len > cache.used_size - offset)
01402     len = cache.used_size - offset;
01403 
01404   memcpy (readbuf, cache.buffer + offset, len);
01405 
01406   return len;
01407 }
01408 
01409 static const struct qxfer qxfer_packets[] =
01410   {
01411     { "auxv", handle_qxfer_auxv },
01412     { "btrace", handle_qxfer_btrace },
01413     { "fdpic", handle_qxfer_fdpic},
01414     { "features", handle_qxfer_features },
01415     { "libraries", handle_qxfer_libraries },
01416     { "libraries-svr4", handle_qxfer_libraries_svr4 },
01417     { "osdata", handle_qxfer_osdata },
01418     { "siginfo", handle_qxfer_siginfo },
01419     { "spu", handle_qxfer_spu },
01420     { "statictrace", handle_qxfer_statictrace },
01421     { "threads", handle_qxfer_threads },
01422     { "traceframe-info", handle_qxfer_traceframe_info },
01423   };
01424 
01425 static int
01426 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
01427 {
01428   int i;
01429   char *object;
01430   char *rw;
01431   char *annex;
01432   char *offset;
01433 
01434   if (strncmp (own_buf, "qXfer:", 6) != 0)
01435     return 0;
01436 
01437   /* Grab the object, r/w and annex.  */
01438   if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
01439     {
01440       write_enn (own_buf);
01441       return 1;
01442     }
01443 
01444   for (i = 0;
01445        i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
01446        i++)
01447     {
01448       const struct qxfer *q = &qxfer_packets[i];
01449 
01450       if (strcmp (object, q->object) == 0)
01451         {
01452           if (strcmp (rw, "read") == 0)
01453             {
01454               unsigned char *data;
01455               int n;
01456               CORE_ADDR ofs;
01457               unsigned int len;
01458 
01459               /* Grab the offset and length.  */
01460               if (decode_xfer_read (offset, &ofs, &len) < 0)
01461                 {
01462                   write_enn (own_buf);
01463                   return 1;
01464                 }
01465 
01466               /* Read one extra byte, as an indicator of whether there is
01467                  more.  */
01468               if (len > PBUFSIZ - 2)
01469                 len = PBUFSIZ - 2;
01470               data = malloc (len + 1);
01471               if (data == NULL)
01472                 {
01473                   write_enn (own_buf);
01474                   return 1;
01475                 }
01476               n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
01477               if (n == -2)
01478                 {
01479                   free (data);
01480                   return 0;
01481                 }
01482               else if (n == -3)
01483                 {
01484                   /* Preserve error message.  */
01485                 }
01486               else if (n < 0)
01487                 write_enn (own_buf);
01488               else if (n > len)
01489                 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
01490               else
01491                 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
01492 
01493               free (data);
01494               return 1;
01495             }
01496           else if (strcmp (rw, "write") == 0)
01497             {
01498               int n;
01499               unsigned int len;
01500               CORE_ADDR ofs;
01501               unsigned char *data;
01502 
01503               strcpy (own_buf, "E00");
01504               data = malloc (packet_len - (offset - own_buf));
01505               if (data == NULL)
01506                 {
01507                   write_enn (own_buf);
01508                   return 1;
01509                 }
01510               if (decode_xfer_write (offset, packet_len - (offset - own_buf),
01511                                      &ofs, &len, data) < 0)
01512                 {
01513                   free (data);
01514                   write_enn (own_buf);
01515                   return 1;
01516                 }
01517 
01518               n = (*q->xfer) (annex, NULL, data, ofs, len);
01519               if (n == -2)
01520                 {
01521                   free (data);
01522                   return 0;
01523                 }
01524               else if (n == -3)
01525                 {
01526                   /* Preserve error message.  */
01527                 }
01528               else if (n < 0)
01529                 write_enn (own_buf);
01530               else
01531                 sprintf (own_buf, "%x", n);
01532 
01533               free (data);
01534               return 1;
01535             }
01536 
01537           return 0;
01538         }
01539     }
01540 
01541   return 0;
01542 }
01543 
01544 /* Table used by the crc32 function to calcuate the checksum.  */
01545 
01546 static unsigned int crc32_table[256] =
01547 {0, 0};
01548 
01549 /* Compute 32 bit CRC from inferior memory.
01550 
01551    On success, return 32 bit CRC.
01552    On failure, return (unsigned long long) -1.  */
01553 
01554 static unsigned long long
01555 crc32 (CORE_ADDR base, int len, unsigned int crc)
01556 {
01557   if (!crc32_table[1])
01558     {
01559       /* Initialize the CRC table and the decoding table.  */
01560       int i, j;
01561       unsigned int c;
01562 
01563       for (i = 0; i < 256; i++)
01564         {
01565           for (c = i << 24, j = 8; j > 0; --j)
01566             c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
01567           crc32_table[i] = c;
01568         }
01569     }
01570 
01571   while (len--)
01572     {
01573       unsigned char byte = 0;
01574 
01575       /* Return failure if memory read fails.  */
01576       if (read_inferior_memory (base, &byte, 1) != 0)
01577         return (unsigned long long) -1;
01578 
01579       crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ byte) & 255];
01580       base++;
01581     }
01582   return (unsigned long long) crc;
01583 }
01584 
01585 /* Handle all of the extended 'q' packets.  */
01586 
01587 void
01588 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
01589 {
01590   static struct inferior_list_entry *thread_ptr;
01591 
01592   /* Reply the current thread id.  */
01593   if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
01594     {
01595       ptid_t gdb_id;
01596       require_running (own_buf);
01597 
01598       if (!ptid_equal (general_thread, null_ptid)
01599           && !ptid_equal (general_thread, minus_one_ptid))
01600         gdb_id = general_thread;
01601       else
01602         {
01603           thread_ptr = all_threads.head;
01604           gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
01605         }
01606 
01607       sprintf (own_buf, "QC");
01608       own_buf += 2;
01609       write_ptid (own_buf, gdb_id);
01610       return;
01611     }
01612 
01613   if (strcmp ("qSymbol::", own_buf) == 0)
01614     {
01615       /* GDB is suggesting new symbols have been loaded.  This may
01616          mean a new shared library has been detected as loaded, so
01617          take the opportunity to check if breakpoints we think are
01618          inserted, still are.  Note that it isn't guaranteed that
01619          we'll see this when a shared library is loaded, and nor will
01620          we see this for unloads (although breakpoints in unloaded
01621          libraries shouldn't trigger), as GDB may not find symbols for
01622          the library at all.  We also re-validate breakpoints when we
01623          see a second GDB breakpoint for the same address, and or when
01624          we access breakpoint shadows.  */
01625       validate_breakpoints ();
01626 
01627       if (target_supports_tracepoints ())
01628         tracepoint_look_up_symbols ();
01629 
01630       if (target_running () && the_target->look_up_symbols != NULL)
01631         (*the_target->look_up_symbols) ();
01632 
01633       strcpy (own_buf, "OK");
01634       return;
01635     }
01636 
01637   if (!disable_packet_qfThreadInfo)
01638     {
01639       if (strcmp ("qfThreadInfo", own_buf) == 0)
01640         {
01641           ptid_t gdb_id;
01642 
01643           require_running (own_buf);
01644           thread_ptr = all_threads.head;
01645 
01646           *own_buf++ = 'm';
01647           gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
01648           write_ptid (own_buf, gdb_id);
01649           thread_ptr = thread_ptr->next;
01650           return;
01651         }
01652 
01653       if (strcmp ("qsThreadInfo", own_buf) == 0)
01654         {
01655           ptid_t gdb_id;
01656 
01657           require_running (own_buf);
01658           if (thread_ptr != NULL)
01659             {
01660               *own_buf++ = 'm';
01661               gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
01662               write_ptid (own_buf, gdb_id);
01663               thread_ptr = thread_ptr->next;
01664               return;
01665             }
01666           else
01667             {
01668               sprintf (own_buf, "l");
01669               return;
01670             }
01671         }
01672     }
01673 
01674   if (the_target->read_offsets != NULL
01675       && strcmp ("qOffsets", own_buf) == 0)
01676     {
01677       CORE_ADDR text, data;
01678 
01679       require_running (own_buf);
01680       if (the_target->read_offsets (&text, &data))
01681         sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
01682                  (long)text, (long)data, (long)data);
01683       else
01684         write_enn (own_buf);
01685 
01686       return;
01687     }
01688 
01689   /* Protocol features query.  */
01690   if (strncmp ("qSupported", own_buf, 10) == 0
01691       && (own_buf[10] == ':' || own_buf[10] == '\0'))
01692     {
01693       char *p = &own_buf[10];
01694       int gdb_supports_qRelocInsn = 0;
01695 
01696       /* Start processing qSupported packet.  */
01697       target_process_qsupported (NULL);
01698 
01699       /* Process each feature being provided by GDB.  The first
01700          feature will follow a ':', and latter features will follow
01701          ';'.  */
01702       if (*p == ':')
01703         {
01704           char **qsupported = NULL;
01705           int count = 0;
01706           int i;
01707 
01708           /* Two passes, to avoid nested strtok calls in
01709              target_process_qsupported.  */
01710           for (p = strtok (p + 1, ";");
01711                p != NULL;
01712                p = strtok (NULL, ";"))
01713             {
01714               count++;
01715               qsupported = xrealloc (qsupported, count * sizeof (char *));
01716               qsupported[count - 1] = xstrdup (p);
01717             }
01718 
01719           for (i = 0; i < count; i++)
01720             {
01721               p = qsupported[i];
01722               if (strcmp (p, "multiprocess+") == 0)
01723                 {
01724                   /* GDB supports and wants multi-process support if
01725                      possible.  */
01726                   if (target_supports_multi_process ())
01727                     multi_process = 1;
01728                 }
01729               else if (strcmp (p, "qRelocInsn+") == 0)
01730                 {
01731                   /* GDB supports relocate instruction requests.  */
01732                   gdb_supports_qRelocInsn = 1;
01733                 }
01734               else
01735                 target_process_qsupported (p);
01736 
01737               free (p);
01738             }
01739 
01740           free (qsupported);
01741         }
01742 
01743       sprintf (own_buf,
01744                "PacketSize=%x;QPassSignals+;QProgramSignals+",
01745                PBUFSIZ - 1);
01746 
01747       if (the_target->qxfer_libraries_svr4 != NULL)
01748         strcat (own_buf, ";qXfer:libraries-svr4:read+"
01749                 ";augmented-libraries-svr4-read+");
01750       else
01751         {
01752           /* We do not have any hook to indicate whether the non-SVR4 target
01753              backend supports qXfer:libraries:read, so always report it.  */
01754           strcat (own_buf, ";qXfer:libraries:read+");
01755         }
01756 
01757       if (the_target->read_auxv != NULL)
01758         strcat (own_buf, ";qXfer:auxv:read+");
01759 
01760       if (the_target->qxfer_spu != NULL)
01761         strcat (own_buf, ";qXfer:spu:read+;qXfer:spu:write+");
01762 
01763       if (the_target->qxfer_siginfo != NULL)
01764         strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
01765 
01766       if (the_target->read_loadmap != NULL)
01767         strcat (own_buf, ";qXfer:fdpic:read+");
01768 
01769       /* We always report qXfer:features:read, as targets may
01770          install XML files on a subsequent call to arch_setup.
01771          If we reported to GDB on startup that we don't support
01772          qXfer:feature:read at all, we will never be re-queried.  */
01773       strcat (own_buf, ";qXfer:features:read+");
01774 
01775       if (transport_is_reliable)
01776         strcat (own_buf, ";QStartNoAckMode+");
01777 
01778       if (the_target->qxfer_osdata != NULL)
01779         strcat (own_buf, ";qXfer:osdata:read+");
01780 
01781       if (target_supports_multi_process ())
01782         strcat (own_buf, ";multiprocess+");
01783 
01784       if (target_supports_non_stop ())
01785         strcat (own_buf, ";QNonStop+");
01786 
01787       if (target_supports_disable_randomization ())
01788         strcat (own_buf, ";QDisableRandomization+");
01789 
01790       strcat (own_buf, ";qXfer:threads:read+");
01791 
01792       if (target_supports_tracepoints ())
01793         {
01794           strcat (own_buf, ";ConditionalTracepoints+");
01795           strcat (own_buf, ";TraceStateVariables+");
01796           strcat (own_buf, ";TracepointSource+");
01797           strcat (own_buf, ";DisconnectedTracing+");
01798           if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
01799             strcat (own_buf, ";FastTracepoints+");
01800           strcat (own_buf, ";StaticTracepoints+");
01801           strcat (own_buf, ";InstallInTrace+");
01802           strcat (own_buf, ";qXfer:statictrace:read+");
01803           strcat (own_buf, ";qXfer:traceframe-info:read+");
01804           strcat (own_buf, ";EnableDisableTracepoints+");
01805           strcat (own_buf, ";QTBuffer:size+");
01806           strcat (own_buf, ";tracenz+");
01807         }
01808 
01809       /* Support target-side breakpoint conditions and commands.  */
01810       strcat (own_buf, ";ConditionalBreakpoints+");
01811       strcat (own_buf, ";BreakpointCommands+");
01812 
01813       if (target_supports_agent ())
01814         strcat (own_buf, ";QAgent+");
01815 
01816       if (target_supports_btrace ())
01817         {
01818           strcat (own_buf, ";Qbtrace:bts+");
01819           strcat (own_buf, ";Qbtrace:off+");
01820           strcat (own_buf, ";qXfer:btrace:read+");
01821         }
01822 
01823       return;
01824     }
01825 
01826   /* Thread-local storage support.  */
01827   if (the_target->get_tls_address != NULL
01828       && strncmp ("qGetTLSAddr:", own_buf, 12) == 0)
01829     {
01830       char *p = own_buf + 12;
01831       CORE_ADDR parts[2], address = 0;
01832       int i, err;
01833       ptid_t ptid = null_ptid;
01834 
01835       require_running (own_buf);
01836 
01837       for (i = 0; i < 3; i++)
01838         {
01839           char *p2;
01840           int len;
01841 
01842           if (p == NULL)
01843             break;
01844 
01845           p2 = strchr (p, ',');
01846           if (p2)
01847             {
01848               len = p2 - p;
01849               p2++;
01850             }
01851           else
01852             {
01853               len = strlen (p);
01854               p2 = NULL;
01855             }
01856 
01857           if (i == 0)
01858             ptid = read_ptid (p, NULL);
01859           else
01860             decode_address (&parts[i - 1], p, len);
01861           p = p2;
01862         }
01863 
01864       if (p != NULL || i < 3)
01865         err = 1;
01866       else
01867         {
01868           struct thread_info *thread = find_thread_ptid (ptid);
01869 
01870           if (thread == NULL)
01871             err = 2;
01872           else
01873             err = the_target->get_tls_address (thread, parts[0], parts[1],
01874                                                &address);
01875         }
01876 
01877       if (err == 0)
01878         {
01879           strcpy (own_buf, paddress(address));
01880           return;
01881         }
01882       else if (err > 0)
01883         {
01884           write_enn (own_buf);
01885           return;
01886         }
01887 
01888       /* Otherwise, pretend we do not understand this packet.  */
01889     }
01890 
01891   /* Windows OS Thread Information Block address support.  */
01892   if (the_target->get_tib_address != NULL
01893       && strncmp ("qGetTIBAddr:", own_buf, 12) == 0)
01894     {
01895       char *annex;
01896       int n;
01897       CORE_ADDR tlb;
01898       ptid_t ptid = read_ptid (own_buf + 12, &annex);
01899 
01900       n = (*the_target->get_tib_address) (ptid, &tlb);
01901       if (n == 1)
01902         {
01903           strcpy (own_buf, paddress(tlb));
01904           return;
01905         }
01906       else if (n == 0)
01907         {
01908           write_enn (own_buf);
01909           return;
01910         }
01911       return;
01912     }
01913 
01914   /* Handle "monitor" commands.  */
01915   if (strncmp ("qRcmd,", own_buf, 6) == 0)
01916     {
01917       char *mon = malloc (PBUFSIZ);
01918       int len = strlen (own_buf + 6);
01919 
01920       if (mon == NULL)
01921         {
01922           write_enn (own_buf);
01923           return;
01924         }
01925 
01926       if ((len % 2) != 0 || unhexify (mon, own_buf + 6, len / 2) != len / 2)
01927         {
01928           write_enn (own_buf);
01929           free (mon);
01930           return;
01931         }
01932       mon[len / 2] = '\0';
01933 
01934       write_ok (own_buf);
01935 
01936       if (the_target->handle_monitor_command == NULL
01937           || (*the_target->handle_monitor_command) (mon) == 0)
01938         /* Default processing.  */
01939         handle_monitor_command (mon, own_buf);
01940 
01941       free (mon);
01942       return;
01943     }
01944 
01945   if (strncmp ("qSearch:memory:", own_buf,
01946                sizeof ("qSearch:memory:") - 1) == 0)
01947     {
01948       require_running (own_buf);
01949       handle_search_memory (own_buf, packet_len);
01950       return;
01951     }
01952 
01953   if (strcmp (own_buf, "qAttached") == 0
01954       || strncmp (own_buf, "qAttached:", sizeof ("qAttached:") - 1) == 0)
01955     {
01956       struct process_info *process;
01957 
01958       if (own_buf[sizeof ("qAttached") - 1])
01959         {
01960           int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
01961           process = (struct process_info *)
01962             find_inferior_id (&all_processes, pid_to_ptid (pid));
01963         }
01964       else
01965         {
01966           require_running (own_buf);
01967           process = current_process ();
01968         }
01969 
01970       if (process == NULL)
01971         {
01972           write_enn (own_buf);
01973           return;
01974         }
01975 
01976       strcpy (own_buf, process->attached ? "1" : "0");
01977       return;
01978     }
01979 
01980   if (strncmp ("qCRC:", own_buf, 5) == 0)
01981     {
01982       /* CRC check (compare-section).  */
01983       char *comma;
01984       ULONGEST base;
01985       int len;
01986       unsigned long long crc;
01987 
01988       require_running (own_buf);
01989       comma = unpack_varlen_hex (own_buf + 5, &base);
01990       if (*comma++ != ',')
01991         {
01992           write_enn (own_buf);
01993           return;
01994         }
01995       len = strtoul (comma, NULL, 16);
01996       crc = crc32 (base, len, 0xffffffff);
01997       /* Check for memory failure.  */
01998       if (crc == (unsigned long long) -1)
01999         {
02000           write_enn (own_buf);
02001           return;
02002         }
02003       sprintf (own_buf, "C%lx", (unsigned long) crc);
02004       return;
02005     }
02006 
02007   if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
02008     return;
02009 
02010   if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
02011     return;
02012 
02013   /* Otherwise we didn't know what packet it was.  Say we didn't
02014      understand it.  */
02015   own_buf[0] = 0;
02016 }
02017 
02018 static void gdb_wants_all_threads_stopped (void);
02019 
02020 /* Parse vCont packets.  */
02021 void
02022 handle_v_cont (char *own_buf)
02023 {
02024   char *p, *q;
02025   int n = 0, i = 0;
02026   struct thread_resume *resume_info;
02027   struct thread_resume default_action = {{0}};
02028 
02029   /* Count the number of semicolons in the packet.  There should be one
02030      for every action.  */
02031   p = &own_buf[5];
02032   while (p)
02033     {
02034       n++;
02035       p++;
02036       p = strchr (p, ';');
02037     }
02038 
02039   resume_info = malloc (n * sizeof (resume_info[0]));
02040   if (resume_info == NULL)
02041     goto err;
02042 
02043   p = &own_buf[5];
02044   while (*p)
02045     {
02046       p++;
02047 
02048       memset (&resume_info[i], 0, sizeof resume_info[i]);
02049 
02050       if (p[0] == 's' || p[0] == 'S')
02051         resume_info[i].kind = resume_step;
02052       else if (p[0] == 'r')
02053         resume_info[i].kind = resume_step;
02054       else if (p[0] == 'c' || p[0] == 'C')
02055         resume_info[i].kind = resume_continue;
02056       else if (p[0] == 't')
02057         resume_info[i].kind = resume_stop;
02058       else
02059         goto err;
02060 
02061       if (p[0] == 'S' || p[0] == 'C')
02062         {
02063           int sig;
02064           sig = strtol (p + 1, &q, 16);
02065           if (p == q)
02066             goto err;
02067           p = q;
02068 
02069           if (!gdb_signal_to_host_p (sig))
02070             goto err;
02071           resume_info[i].sig = gdb_signal_to_host (sig);
02072         }
02073       else if (p[0] == 'r')
02074         {
02075           ULONGEST addr;
02076 
02077           p = unpack_varlen_hex (p + 1, &addr);
02078           resume_info[i].step_range_start = addr;
02079 
02080           if (*p != ',')
02081             goto err;
02082 
02083           p = unpack_varlen_hex (p + 1, &addr);
02084           resume_info[i].step_range_end = addr;
02085         }
02086       else
02087         {
02088           p = p + 1;
02089         }
02090 
02091       if (p[0] == 0)
02092         {
02093           resume_info[i].thread = minus_one_ptid;
02094           default_action = resume_info[i];
02095 
02096           /* Note: we don't increment i here, we'll overwrite this entry
02097              the next time through.  */
02098         }
02099       else if (p[0] == ':')
02100         {
02101           ptid_t ptid = read_ptid (p + 1, &q);
02102 
02103           if (p == q)
02104             goto err;
02105           p = q;
02106           if (p[0] != ';' && p[0] != 0)
02107             goto err;
02108 
02109           resume_info[i].thread = ptid;
02110 
02111           i++;
02112         }
02113     }
02114 
02115   if (i < n)
02116     resume_info[i] = default_action;
02117 
02118   /* `cont_thread' is still used in occasional places in the backend,
02119      to implement single-thread scheduler-locking.  Doesn't make sense
02120      to set it if we see a stop request, or a wildcard action (one
02121      with '-1' (all threads), or 'pPID.-1' (all threads of PID)).  */
02122   if (n == 1
02123       && !(ptid_equal (resume_info[0].thread, minus_one_ptid)
02124            || ptid_get_lwp (resume_info[0].thread) == -1)
02125       && resume_info[0].kind != resume_stop)
02126     cont_thread = resume_info[0].thread;
02127   else
02128     cont_thread = minus_one_ptid;
02129   set_desired_inferior (0);
02130 
02131   if (!non_stop)
02132     enable_async_io ();
02133 
02134   (*the_target->resume) (resume_info, n);
02135 
02136   free (resume_info);
02137 
02138   if (non_stop)
02139     write_ok (own_buf);
02140   else
02141     {
02142       last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);
02143 
02144       if (last_status.kind != TARGET_WAITKIND_EXITED
02145           && last_status.kind != TARGET_WAITKIND_SIGNALLED)
02146         current_inferior->last_status = last_status;
02147 
02148       /* From the client's perspective, all-stop mode always stops all
02149          threads implicitly (and the target backend has already done
02150          so by now).  Tag all threads as "want-stopped", so we don't
02151          resume them implicitly without the client telling us to.  */
02152       gdb_wants_all_threads_stopped ();
02153       prepare_resume_reply (own_buf, last_ptid, &last_status);
02154       disable_async_io ();
02155 
02156       if (last_status.kind == TARGET_WAITKIND_EXITED
02157           || last_status.kind == TARGET_WAITKIND_SIGNALLED)
02158         mourn_inferior (find_process_pid (ptid_get_pid (last_ptid)));
02159     }
02160   return;
02161 
02162 err:
02163   write_enn (own_buf);
02164   free (resume_info);
02165   return;
02166 }
02167 
02168 /* Attach to a new program.  Return 1 if successful, 0 if failure.  */
02169 int
02170 handle_v_attach (char *own_buf)
02171 {
02172   int pid;
02173 
02174   pid = strtol (own_buf + 8, NULL, 16);
02175   if (pid != 0 && attach_inferior (pid) == 0)
02176     {
02177       /* Don't report shared library events after attaching, even if
02178          some libraries are preloaded.  GDB will always poll the
02179          library list.  Avoids the "stopped by shared library event"
02180          notice on the GDB side.  */
02181       dlls_changed = 0;
02182 
02183       if (non_stop)
02184         {
02185           /* In non-stop, we don't send a resume reply.  Stop events
02186              will follow up using the normal notification
02187              mechanism.  */
02188           write_ok (own_buf);
02189         }
02190       else
02191         prepare_resume_reply (own_buf, last_ptid, &last_status);
02192 
02193       return 1;
02194     }
02195   else
02196     {
02197       write_enn (own_buf);
02198       return 0;
02199     }
02200 }
02201 
02202 /* Run a new program.  Return 1 if successful, 0 if failure.  */
02203 static int
02204 handle_v_run (char *own_buf)
02205 {
02206   char *p, *next_p, **new_argv;
02207   int i, new_argc;
02208 
02209   new_argc = 0;
02210   for (p = own_buf + strlen ("vRun;"); p && *p; p = strchr (p, ';'))
02211     {
02212       p++;
02213       new_argc++;
02214     }
02215 
02216   new_argv = calloc (new_argc + 2, sizeof (char *));
02217   if (new_argv == NULL)
02218     {
02219       write_enn (own_buf);
02220       return 0;
02221     }
02222 
02223   i = 0;
02224   for (p = own_buf + strlen ("vRun;"); *p; p = next_p)
02225     {
02226       next_p = strchr (p, ';');
02227       if (next_p == NULL)
02228         next_p = p + strlen (p);
02229 
02230       if (i == 0 && p == next_p)
02231         new_argv[i] = NULL;
02232       else
02233         {
02234           /* FIXME: Fail request if out of memory instead of dying.  */
02235           new_argv[i] = xmalloc (1 + (next_p - p) / 2);
02236           unhexify (new_argv[i], p, (next_p - p) / 2);
02237           new_argv[i][(next_p - p) / 2] = '\0';
02238         }
02239 
02240       if (*next_p)
02241         next_p++;
02242       i++;
02243     }
02244   new_argv[i] = NULL;
02245 
02246   if (new_argv[0] == NULL)
02247     {
02248       /* GDB didn't specify a program to run.  Use the program from the
02249          last run with the new argument list.  */
02250 
02251       if (program_argv == NULL)
02252         {
02253           write_enn (own_buf);
02254           freeargv (new_argv);
02255           return 0;
02256         }
02257 
02258       new_argv[0] = strdup (program_argv[0]);
02259       if (new_argv[0] == NULL)
02260         {
02261           write_enn (own_buf);
02262           freeargv (new_argv);
02263           return 0;
02264         }
02265     }
02266 
02267   /* Free the old argv and install the new one.  */
02268   freeargv (program_argv);
02269   program_argv = new_argv;
02270 
02271   start_inferior (program_argv);
02272   if (last_status.kind == TARGET_WAITKIND_STOPPED)
02273     {
02274       prepare_resume_reply (own_buf, last_ptid, &last_status);
02275 
02276       /* In non-stop, sending a resume reply doesn't set the general
02277          thread, but GDB assumes a vRun sets it (this is so GDB can
02278          query which is the main thread of the new inferior.  */
02279       if (non_stop)
02280         general_thread = last_ptid;
02281 
02282       return 1;
02283     }
02284   else
02285     {
02286       write_enn (own_buf);
02287       return 0;
02288     }
02289 }
02290 
02291 /* Kill process.  Return 1 if successful, 0 if failure.  */
02292 int
02293 handle_v_kill (char *own_buf)
02294 {
02295   int pid;
02296   char *p = &own_buf[6];
02297   if (multi_process)
02298     pid = strtol (p, NULL, 16);
02299   else
02300     pid = signal_pid;
02301   if (pid != 0 && kill_inferior (pid) == 0)
02302     {
02303       last_status.kind = TARGET_WAITKIND_SIGNALLED;
02304       last_status.value.sig = GDB_SIGNAL_KILL;
02305       last_ptid = pid_to_ptid (pid);
02306       discard_queued_stop_replies (pid);
02307       write_ok (own_buf);
02308       return 1;
02309     }
02310   else
02311     {
02312       write_enn (own_buf);
02313       return 0;
02314     }
02315 }
02316 
02317 /* Handle all of the extended 'v' packets.  */
02318 void
02319 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
02320 {
02321   if (!disable_packet_vCont)
02322     {
02323       if (strncmp (own_buf, "vCont;", 6) == 0)
02324         {
02325           require_running (own_buf);
02326           handle_v_cont (own_buf);
02327           return;
02328         }
02329 
02330       if (strncmp (own_buf, "vCont?", 6) == 0)
02331         {
02332           strcpy (own_buf, "vCont;c;C;s;S;t");
02333           if (target_supports_range_stepping ())
02334             {
02335               own_buf = own_buf + strlen (own_buf);
02336               strcpy (own_buf, ";r");
02337             }
02338           return;
02339         }
02340     }
02341 
02342   if (strncmp (own_buf, "vFile:", 6) == 0
02343       && handle_vFile (own_buf, packet_len, new_packet_len))
02344     return;
02345 
02346   if (strncmp (own_buf, "vAttach;", 8) == 0)
02347     {
02348       if ((!extended_protocol || !multi_process) && target_running ())
02349         {
02350           fprintf (stderr, "Already debugging a process\n");
02351           write_enn (own_buf);
02352           return;
02353         }
02354       handle_v_attach (own_buf);
02355       return;
02356     }
02357 
02358   if (strncmp (own_buf, "vRun;", 5) == 0)
02359     {
02360       if ((!extended_protocol || !multi_process) && target_running ())
02361         {
02362           fprintf (stderr, "Already debugging a process\n");
02363           write_enn (own_buf);
02364           return;
02365         }
02366       handle_v_run (own_buf);
02367       return;
02368     }
02369 
02370   if (strncmp (own_buf, "vKill;", 6) == 0)
02371     {
02372       if (!target_running ())
02373         {
02374           fprintf (stderr, "No process to kill\n");
02375           write_enn (own_buf);
02376           return;
02377         }
02378       handle_v_kill (own_buf);
02379       return;
02380     }
02381 
02382   if (handle_notif_ack (own_buf, packet_len))
02383     return;
02384 
02385   /* Otherwise we didn't know what packet it was.  Say we didn't
02386      understand it.  */
02387   own_buf[0] = 0;
02388   return;
02389 }
02390 
02391 /* Resume inferior and wait for another event.  In non-stop mode,
02392    don't really wait here, but return immediatelly to the event
02393    loop.  */
02394 static void
02395 myresume (char *own_buf, int step, int sig)
02396 {
02397   struct thread_resume resume_info[2];
02398   int n = 0;
02399   int valid_cont_thread;
02400 
02401   set_desired_inferior (0);
02402 
02403   valid_cont_thread = (!ptid_equal (cont_thread, null_ptid)
02404                          && !ptid_equal (cont_thread, minus_one_ptid));
02405 
02406   if (step || sig || valid_cont_thread)
02407     {
02408       resume_info[0].thread = current_ptid;
02409       if (step)
02410         resume_info[0].kind = resume_step;
02411       else
02412         resume_info[0].kind = resume_continue;
02413       resume_info[0].sig = sig;
02414       n++;
02415     }
02416 
02417   if (!valid_cont_thread)
02418     {
02419       resume_info[n].thread = minus_one_ptid;
02420       resume_info[n].kind = resume_continue;
02421       resume_info[n].sig = 0;
02422       n++;
02423     }
02424 
02425   if (!non_stop)
02426     enable_async_io ();
02427 
02428   (*the_target->resume) (resume_info, n);
02429 
02430   if (non_stop)
02431     write_ok (own_buf);
02432   else
02433     {
02434       last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);
02435 
02436       if (last_status.kind != TARGET_WAITKIND_EXITED
02437           && last_status.kind != TARGET_WAITKIND_SIGNALLED)
02438         {
02439           current_inferior->last_resume_kind = resume_stop;
02440           current_inferior->last_status = last_status;
02441         }
02442 
02443       prepare_resume_reply (own_buf, last_ptid, &last_status);
02444       disable_async_io ();
02445 
02446       if (last_status.kind == TARGET_WAITKIND_EXITED
02447           || last_status.kind == TARGET_WAITKIND_SIGNALLED)
02448         mourn_inferior (find_process_pid (ptid_get_pid (last_ptid)));
02449     }
02450 }
02451 
02452 /* Callback for for_each_inferior.  Make a new stop reply for each
02453    stopped thread.  */
02454 
02455 static int
02456 queue_stop_reply_callback (struct inferior_list_entry *entry, void *arg)
02457 {
02458   struct thread_info *thread = (struct thread_info *) entry;
02459 
02460   /* For now, assume targets that don't have this callback also don't
02461      manage the thread's last_status field.  */
02462   if (the_target->thread_stopped == NULL)
02463     {
02464       struct vstop_notif *new_notif = xmalloc (sizeof (*new_notif));
02465 
02466       new_notif->ptid = entry->id;
02467       new_notif->status = thread->last_status;
02468       /* Pass the last stop reply back to GDB, but don't notify
02469          yet.  */
02470       notif_event_enque (&notif_stop,
02471                          (struct notif_event *) new_notif);
02472     }
02473   else
02474     {
02475       if (thread_stopped (thread))
02476         {
02477           if (debug_threads)
02478             {
02479               char *status_string
02480                 = target_waitstatus_to_string (&thread->last_status);
02481 
02482               fprintf (stderr,
02483                        "Reporting thread %s as already stopped with %s\n",
02484                        target_pid_to_str (entry->id),
02485                        status_string);
02486 
02487               xfree (status_string);
02488             }
02489 
02490           gdb_assert (thread->last_status.kind != TARGET_WAITKIND_IGNORE);
02491 
02492           /* Pass the last stop reply back to GDB, but don't notify
02493              yet.  */
02494           queue_stop_reply (entry->id, &thread->last_status);
02495         }
02496     }
02497 
02498   return 0;
02499 }
02500 
02501 /* Set this inferior threads's state as "want-stopped".  We won't
02502    resume this thread until the client gives us another action for
02503    it.  */
02504 
02505 static void
02506 gdb_wants_thread_stopped (struct inferior_list_entry *entry)
02507 {
02508   struct thread_info *thread = (struct thread_info *) entry;
02509 
02510   thread->last_resume_kind = resume_stop;
02511 
02512   if (thread->last_status.kind == TARGET_WAITKIND_IGNORE)
02513     {
02514       /* Most threads are stopped implicitly (all-stop); tag that with
02515          signal 0.  */
02516       thread->last_status.kind = TARGET_WAITKIND_STOPPED;
02517       thread->last_status.value.sig = GDB_SIGNAL_0;
02518     }
02519 }
02520 
02521 /* Set all threads' states as "want-stopped".  */
02522 
02523 static void
02524 gdb_wants_all_threads_stopped (void)
02525 {
02526   for_each_inferior (&all_threads, gdb_wants_thread_stopped);
02527 }
02528 
02529 /* Clear the gdb_detached flag of every process.  */
02530 
02531 static void
02532 gdb_reattached_process (struct inferior_list_entry *entry)
02533 {
02534   struct process_info *process = (struct process_info *) entry;
02535 
02536   process->gdb_detached = 0;
02537 }
02538 
02539 /* Status handler for the '?' packet.  */
02540 
02541 static void
02542 handle_status (char *own_buf)
02543 {
02544   /* GDB is connected, don't forward events to the target anymore.  */
02545   for_each_inferior (&all_processes, gdb_reattached_process);
02546 
02547   /* In non-stop mode, we must send a stop reply for each stopped
02548      thread.  In all-stop mode, just send one for the first stopped
02549      thread we find.  */
02550 
02551   if (non_stop)
02552     {
02553       discard_queued_stop_replies (-1);
02554       find_inferior (&all_threads, queue_stop_reply_callback, NULL);
02555 
02556       /* The first is sent immediatly.  OK is sent if there is no
02557          stopped thread, which is the same handling of the vStopped
02558          packet (by design).  */
02559       notif_write_event (&notif_stop, own_buf);
02560     }
02561   else
02562     {
02563       pause_all (0);
02564       stabilize_threads ();
02565       gdb_wants_all_threads_stopped ();
02566 
02567       if (all_threads.head)
02568         {
02569           struct target_waitstatus status;
02570 
02571           status.kind = TARGET_WAITKIND_STOPPED;
02572           status.value.sig = GDB_SIGNAL_TRAP;
02573           prepare_resume_reply (own_buf,
02574                                 all_threads.head->id, &status);
02575         }
02576       else
02577         strcpy (own_buf, "W00");
02578     }
02579 }
02580 
02581 static void
02582 gdbserver_version (void)
02583 {
02584   printf ("GNU gdbserver %s%s\n"
02585           "Copyright (C) 2013 Free Software Foundation, Inc.\n"
02586           "gdbserver is free software, covered by the "
02587           "GNU General Public License.\n"
02588           "This gdbserver was configured as \"%s\"\n",
02589           PKGVERSION, version, host_name);
02590 }
02591 
02592 static void
02593 gdbserver_usage (FILE *stream)
02594 {
02595   fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
02596            "\tgdbserver [OPTIONS] --attach COMM PID\n"
02597            "\tgdbserver [OPTIONS] --multi COMM\n"
02598            "\n"
02599            "COMM may either be a tty device (for serial debugging), or \n"
02600            "HOST:PORT to listen for a TCP connection.\n"
02601            "\n"
02602            "Options:\n"
02603            "  --debug               Enable general debugging output.\n"
02604            "  --remote-debug        Enable remote protocol debugging output.\n"
02605            "  --version             Display version information and exit.\n"
02606            "  --wrapper WRAPPER --  Run WRAPPER to start new programs.\n"
02607            "  --once                Exit after the first connection has "
02608                                                                   "closed.\n");
02609   if (REPORT_BUGS_TO[0] && stream == stdout)
02610     fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
02611 }
02612 
02613 static void
02614 gdbserver_show_disableable (FILE *stream)
02615 {
02616   fprintf (stream, "Disableable packets:\n"
02617            "  vCont       \tAll vCont packets\n"
02618            "  qC          \tQuerying the current thread\n"
02619            "  qfThreadInfo\tThread listing\n"
02620            "  Tthread     \tPassing the thread specifier in the "
02621            "T stop reply packet\n"
02622            "  threads     \tAll of the above\n");
02623 }
02624 
02625 
02626 #undef require_running
02627 #define require_running(BUF)                    \
02628   if (!target_running ())                       \
02629     {                                           \
02630       write_enn (BUF);                          \
02631       break;                                    \
02632     }
02633 
02634 static int
02635 first_thread_of (struct inferior_list_entry *entry, void *args)
02636 {
02637   int pid = * (int *) args;
02638 
02639   if (ptid_get_pid (entry->id) == pid)
02640     return 1;
02641 
02642   return 0;
02643 }
02644 
02645 static void
02646 kill_inferior_callback (struct inferior_list_entry *entry)
02647 {
02648   struct process_info *process = (struct process_info *) entry;
02649   int pid = ptid_get_pid (process->head.id);
02650 
02651   kill_inferior (pid);
02652   discard_queued_stop_replies (pid);
02653 }
02654 
02655 /* Callback for for_each_inferior to detach or kill the inferior,
02656    depending on whether we attached to it or not.
02657    We inform the user whether we're detaching or killing the process
02658    as this is only called when gdbserver is about to exit.  */
02659 
02660 static void
02661 detach_or_kill_inferior_callback (struct inferior_list_entry *entry)
02662 {
02663   struct process_info *process = (struct process_info *) entry;
02664   int pid = ptid_get_pid (process->head.id);
02665 
02666   if (process->attached)
02667     detach_inferior (pid);
02668   else
02669     kill_inferior (pid);
02670 
02671   discard_queued_stop_replies (pid);
02672 }
02673 
02674 /* for_each_inferior callback for detach_or_kill_for_exit to print
02675    the pids of started inferiors.  */
02676 
02677 static void
02678 print_started_pid (struct inferior_list_entry *entry)
02679 {
02680   struct process_info *process = (struct process_info *) entry;
02681 
02682   if (! process->attached)
02683     {
02684       int pid = ptid_get_pid (process->head.id);
02685       fprintf (stderr, " %d", pid);
02686     }
02687 }
02688 
02689 /* for_each_inferior callback for detach_or_kill_for_exit to print
02690    the pids of attached inferiors.  */
02691 
02692 static void
02693 print_attached_pid (struct inferior_list_entry *entry)
02694 {
02695   struct process_info *process = (struct process_info *) entry;
02696 
02697   if (process->attached)
02698     {
02699       int pid = ptid_get_pid (process->head.id);
02700       fprintf (stderr, " %d", pid);
02701     }
02702 }
02703 
02704 /* Call this when exiting gdbserver with possible inferiors that need
02705    to be killed or detached from.  */
02706 
02707 static void
02708 detach_or_kill_for_exit (void)
02709 {
02710   /* First print a list of the inferiors we will be killing/detaching.
02711      This is to assist the user, for example, in case the inferior unexpectedly
02712      dies after we exit: did we screw up or did the inferior exit on its own?
02713      Having this info will save some head-scratching.  */
02714 
02715   if (have_started_inferiors_p ())
02716     {
02717       fprintf (stderr, "Killing process(es):");
02718       for_each_inferior (&all_processes, print_started_pid);
02719       fprintf (stderr, "\n");
02720     }
02721   if (have_attached_inferiors_p ())
02722     {
02723       fprintf (stderr, "Detaching process(es):");
02724       for_each_inferior (&all_processes, print_attached_pid);
02725       fprintf (stderr, "\n");
02726     }
02727 
02728   /* Now we can kill or detach the inferiors.  */
02729 
02730   for_each_inferior (&all_processes, detach_or_kill_inferior_callback);
02731 }
02732 
02733 int
02734 main (int argc, char *argv[])
02735 {
02736   int bad_attach;
02737   int pid;
02738   char *arg_end, *port;
02739   char **next_arg = &argv[1];
02740   volatile int multi_mode = 0;
02741   volatile int attach = 0;
02742   int was_running;
02743 
02744   while (*next_arg != NULL && **next_arg == '-')
02745     {
02746       if (strcmp (*next_arg, "--version") == 0)
02747         {
02748           gdbserver_version ();
02749           exit (0);
02750         }
02751       else if (strcmp (*next_arg, "--help") == 0)
02752         {
02753           gdbserver_usage (stdout);
02754           exit (0);
02755         }
02756       else if (strcmp (*next_arg, "--attach") == 0)
02757         attach = 1;
02758       else if (strcmp (*next_arg, "--multi") == 0)
02759         multi_mode = 1;
02760       else if (strcmp (*next_arg, "--wrapper") == 0)
02761         {
02762           next_arg++;
02763 
02764           wrapper_argv = next_arg;
02765           while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
02766             next_arg++;
02767 
02768           if (next_arg == wrapper_argv || *next_arg == NULL)
02769             {
02770               gdbserver_usage (stderr);
02771               exit (1);
02772             }
02773 
02774           /* Consume the "--".  */
02775           *next_arg = NULL;
02776         }
02777       else if (strcmp (*next_arg, "--debug") == 0)
02778         debug_threads = 1;
02779       else if (strcmp (*next_arg, "--remote-debug") == 0)
02780         remote_debug = 1;
02781       else if (strcmp (*next_arg, "--disable-packet") == 0)
02782         {
02783           gdbserver_show_disableable (stdout);
02784           exit (0);
02785         }
02786       else if (strncmp (*next_arg,
02787                         "--disable-packet=",
02788                         sizeof ("--disable-packet=") - 1) == 0)
02789         {
02790           char *packets, *tok;
02791 
02792           packets = *next_arg += sizeof ("--disable-packet=") - 1;
02793           for (tok = strtok (packets, ",");
02794                tok != NULL;
02795                tok = strtok (NULL, ","))
02796             {
02797               if (strcmp ("vCont", tok) == 0)
02798                 disable_packet_vCont = 1;
02799               else if (strcmp ("Tthread", tok) == 0)
02800                 disable_packet_Tthread = 1;
02801               else if (strcmp ("qC", tok) == 0)
02802                 disable_packet_qC = 1;
02803               else if (strcmp ("qfThreadInfo", tok) == 0)
02804                 disable_packet_qfThreadInfo = 1;
02805               else if (strcmp ("threads", tok) == 0)
02806                 {
02807                   disable_packet_vCont = 1;
02808                   disable_packet_Tthread = 1;
02809                   disable_packet_qC = 1;
02810                   disable_packet_qfThreadInfo = 1;
02811                 }
02812               else
02813                 {
02814                   fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
02815                            tok);
02816                   gdbserver_show_disableable (stderr);
02817                   exit (1);
02818                 }
02819             }
02820         }
02821       else if (strcmp (*next_arg, "-") == 0)
02822         {
02823           /* "-" specifies a stdio connection and is a form of port
02824              specification.  */
02825           *next_arg = STDIO_CONNECTION_NAME;
02826           break;
02827         }
02828       else if (strcmp (*next_arg, "--disable-randomization") == 0)
02829         disable_randomization = 1;
02830       else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
02831         disable_randomization = 0;
02832       else if (strcmp (*next_arg, "--once") == 0)
02833         run_once = 1;
02834       else
02835         {
02836           fprintf (stderr, "Unknown argument: %s\n", *next_arg);
02837           exit (1);
02838         }
02839 
02840       next_arg++;
02841       continue;
02842     }
02843 
02844   if (setjmp (toplevel))
02845     {
02846       fprintf (stderr, "Exiting\n");
02847       exit (1);
02848     }
02849 
02850   port = *next_arg;
02851   next_arg++;
02852   if (port == NULL || (!attach && !multi_mode && *next_arg == NULL))
02853     {
02854       gdbserver_usage (stderr);
02855       exit (1);
02856     }
02857 
02858   /* Remember stdio descriptors.  LISTEN_DESC must not be listed, it will be
02859      opened by remote_prepare.  */
02860   notice_open_fds ();
02861 
02862   /* We need to know whether the remote connection is stdio before
02863      starting the inferior.  Inferiors created in this scenario have
02864      stdin,stdout redirected.  So do this here before we call
02865      start_inferior.  */
02866   remote_prepare (port);
02867 
02868   bad_attach = 0;
02869   pid = 0;
02870 
02871   /* --attach used to come after PORT, so allow it there for
02872        compatibility.  */
02873   if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
02874     {
02875       attach = 1;
02876       next_arg++;
02877     }
02878 
02879   if (attach
02880       && (*next_arg == NULL
02881           || (*next_arg)[0] == '\0'
02882           || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
02883           || *arg_end != '\0'
02884           || next_arg[1] != NULL))
02885     bad_attach = 1;
02886 
02887   if (bad_attach)
02888     {
02889       gdbserver_usage (stderr);
02890       exit (1);
02891     }
02892 
02893   initialize_async_io ();
02894   initialize_low ();
02895   initialize_event_loop ();
02896   if (target_supports_tracepoints ())
02897     initialize_tracepoint ();
02898 
02899   own_buf = xmalloc (PBUFSIZ + 1);
02900   mem_buf = xmalloc (PBUFSIZ);
02901 
02902   if (pid == 0 && *next_arg != NULL)
02903     {
02904       int i, n;
02905 
02906       n = argc - (next_arg - argv);
02907       program_argv = xmalloc (sizeof (char *) * (n + 1));
02908       for (i = 0; i < n; i++)
02909         program_argv[i] = xstrdup (next_arg[i]);
02910       program_argv[i] = NULL;
02911 
02912       /* Wait till we are at first instruction in program.  */
02913       start_inferior (program_argv);
02914 
02915       /* We are now (hopefully) stopped at the first instruction of
02916          the target process.  This assumes that the target process was
02917          successfully created.  */
02918     }
02919   else if (pid != 0)
02920     {
02921       if (attach_inferior (pid) == -1)
02922         error ("Attaching not supported on this target");
02923 
02924       /* Otherwise succeeded.  */
02925     }
02926   else
02927     {
02928       last_status.kind = TARGET_WAITKIND_EXITED;
02929       last_status.value.integer = 0;
02930       last_ptid = minus_one_ptid;
02931     }
02932 
02933   initialize_notif ();
02934 
02935   /* Don't report shared library events on the initial connection,
02936      even if some libraries are preloaded.  Avoids the "stopped by
02937      shared library event" notice on gdb side.  */
02938   dlls_changed = 0;
02939 
02940   if (setjmp (toplevel))
02941     {
02942       /* If something fails and longjmps while detaching or killing
02943          inferiors, we'd end up here again, stuck in an infinite loop
02944          trap.  Be sure that if that happens, we exit immediately
02945          instead.  */
02946       if (setjmp (toplevel) == 0)
02947         detach_or_kill_for_exit ();
02948       else
02949         fprintf (stderr, "Detach or kill failed.  Exiting\n");
02950       exit (1);
02951     }
02952 
02953   if (last_status.kind == TARGET_WAITKIND_EXITED
02954       || last_status.kind == TARGET_WAITKIND_SIGNALLED)
02955     was_running = 0;
02956   else
02957     was_running = 1;
02958 
02959   if (!was_running && !multi_mode)
02960     {
02961       fprintf (stderr, "No program to debug.  GDBserver exiting.\n");
02962       exit (1);
02963     }
02964 
02965   while (1)
02966     {
02967       noack_mode = 0;
02968       multi_process = 0;
02969       /* Be sure we're out of tfind mode.  */
02970       current_traceframe = -1;
02971 
02972       remote_open (port);
02973 
02974       if (setjmp (toplevel) != 0)
02975         {
02976           /* An error occurred.  */
02977           if (response_needed)
02978             {
02979               write_enn (own_buf);
02980               putpkt (own_buf);
02981             }
02982         }
02983 
02984       /* Wait for events.  This will return when all event sources are
02985          removed from the event loop.  */
02986       start_event_loop ();
02987 
02988       /* If an exit was requested (using the "monitor exit" command),
02989          terminate now.  The only other way to get here is for
02990          getpkt to fail; close the connection and reopen it at the
02991          top of the loop.  */
02992 
02993       if (exit_requested || run_once)
02994         {
02995           /* If something fails and longjmps while detaching or
02996              killing inferiors, we'd end up here again, stuck in an
02997              infinite loop trap.  Be sure that if that happens, we
02998              exit immediately instead.  */
02999           if (setjmp (toplevel) == 0)
03000             {
03001               detach_or_kill_for_exit ();
03002               exit (0);
03003             }
03004           else
03005             {
03006               fprintf (stderr, "Detach or kill failed.  Exiting\n");
03007               exit (1);
03008             }
03009         }
03010 
03011       fprintf (stderr,
03012                "Remote side has terminated connection.  "
03013                "GDBserver will reopen the connection.\n");
03014 
03015       if (tracing)
03016         {
03017           if (disconnected_tracing)
03018             {
03019               /* Try to enable non-stop/async mode, so we we can both
03020                  wait for an async socket accept, and handle async
03021                  target events simultaneously.  There's also no point
03022                  either in having the target always stop all threads,
03023                  when we're going to pass signals down without
03024                  informing GDB.  */
03025               if (!non_stop)
03026                 {
03027                   if (start_non_stop (1))
03028                     non_stop = 1;
03029 
03030                   /* Detaching implicitly resumes all threads; simply
03031                      disconnecting does not.  */
03032                 }
03033             }
03034           else
03035             {
03036               fprintf (stderr,
03037                        "Disconnected tracing disabled; stopping trace run.\n");
03038               stop_tracing ();
03039             }
03040         }
03041     }
03042 }
03043 
03044 /* Process options coming from Z packets for *point at address
03045    POINT_ADDR.  PACKET is the packet buffer.  *PACKET is updated
03046    to point to the first char after the last processed option.  */
03047 
03048 static void
03049 process_point_options (CORE_ADDR point_addr, char **packet)
03050 {
03051   char *dataptr = *packet;
03052   int persist;
03053 
03054   /* Check if data has the correct format.  */
03055   if (*dataptr != ';')
03056     return;
03057 
03058   dataptr++;
03059 
03060   while (*dataptr)
03061     {
03062       if (*dataptr == ';')
03063         ++dataptr;
03064 
03065       if (*dataptr == 'X')
03066         {
03067           /* Conditional expression.  */
03068           if (debug_threads)
03069             fprintf (stderr, "Found breakpoint condition.\n");
03070           add_breakpoint_condition (point_addr, &dataptr);
03071         }
03072       else if (strncmp (dataptr, "cmds:", strlen ("cmds:")) == 0)
03073         {
03074           dataptr += strlen ("cmds:");
03075           if (debug_threads)
03076             fprintf (stderr, "Found breakpoint commands %s.\n", dataptr);
03077           persist = (*dataptr == '1');
03078           dataptr += 2;
03079           add_breakpoint_commands (point_addr, &dataptr, persist);
03080         }
03081       else
03082         {
03083           fprintf (stderr, "Unknown token %c, ignoring.\n",
03084                    *dataptr);
03085           /* Skip tokens until we find one that we recognize.  */
03086           while (*dataptr && *dataptr != ';')
03087             dataptr++;
03088         }
03089     }
03090   *packet = dataptr;
03091 }
03092 
03093 /* Event loop callback that handles a serial event.  The first byte in
03094    the serial buffer gets us here.  We expect characters to arrive at
03095    a brisk pace, so we read the rest of the packet with a blocking
03096    getpkt call.  */
03097 
03098 static int
03099 process_serial_event (void)
03100 {
03101   char ch;
03102   int i = 0;
03103   int signal;
03104   unsigned int len;
03105   int res;
03106   CORE_ADDR mem_addr;
03107   int pid;
03108   unsigned char sig;
03109   int packet_len;
03110   int new_packet_len = -1;
03111 
03112   /* Used to decide when gdbserver should exit in
03113      multi-mode/remote.  */
03114   static int have_ran = 0;
03115 
03116   if (!have_ran)
03117     have_ran = target_running ();
03118 
03119   disable_async_io ();
03120 
03121   response_needed = 0;
03122   packet_len = getpkt (own_buf);
03123   if (packet_len <= 0)
03124     {
03125       remote_close ();
03126       /* Force an event loop break.  */
03127       return -1;
03128     }
03129   response_needed = 1;
03130 
03131   i = 0;
03132   ch = own_buf[i++];
03133   switch (ch)
03134     {
03135     case 'q':
03136       handle_query (own_buf, packet_len, &new_packet_len);
03137       break;
03138     case 'Q':
03139       handle_general_set (own_buf);
03140       break;
03141     case 'D':
03142       require_running (own_buf);
03143 
03144       if (multi_process)
03145         {
03146           i++; /* skip ';' */
03147           pid = strtol (&own_buf[i], NULL, 16);
03148         }
03149       else
03150         pid = ptid_get_pid (current_ptid);
03151 
03152       if ((tracing && disconnected_tracing) || any_persistent_commands ())
03153         {
03154           struct thread_resume resume_info;
03155           struct process_info *process = find_process_pid (pid);
03156 
03157           if (process == NULL)
03158             {
03159               write_enn (own_buf);
03160               break;
03161             }
03162 
03163           if (tracing && disconnected_tracing)
03164             fprintf (stderr,
03165                      "Disconnected tracing in effect, "
03166                      "leaving gdbserver attached to the process\n");
03167 
03168           if (any_persistent_commands ())
03169             fprintf (stderr,
03170                      "Persistent commands are present, "
03171                      "leaving gdbserver attached to the process\n");
03172 
03173           /* Make sure we're in non-stop/async mode, so we we can both
03174              wait for an async socket accept, and handle async target
03175              events simultaneously.  There's also no point either in
03176              having the target stop all threads, when we're going to
03177              pass signals down without informing GDB.  */
03178           if (!non_stop)
03179             {
03180               if (debug_threads)
03181                 fprintf (stderr, "Forcing non-stop mode\n");
03182 
03183               non_stop = 1;
03184               start_non_stop (1);
03185             }
03186 
03187           process->gdb_detached = 1;
03188 
03189           /* Detaching implicitly resumes all threads.  */
03190           resume_info.thread = minus_one_ptid;
03191           resume_info.kind = resume_continue;
03192           resume_info.sig = 0;
03193           (*the_target->resume) (&resume_info, 1);
03194 
03195           write_ok (own_buf);
03196           break; /* from switch/case */
03197         }
03198 
03199       fprintf (stderr, "Detaching from process %d\n", pid);
03200       stop_tracing ();
03201       if (detach_inferior (pid) != 0)
03202         write_enn (own_buf);
03203       else
03204         {
03205           discard_queued_stop_replies (pid);
03206           write_ok (own_buf);
03207 
03208           if (extended_protocol)
03209             {
03210               /* Treat this like a normal program exit.  */
03211               last_status.kind = TARGET_WAITKIND_EXITED;
03212               last_status.value.integer = 0;
03213               last_ptid = pid_to_ptid (pid);
03214 
03215               current_inferior = NULL;
03216             }
03217           else
03218             {
03219               putpkt (own_buf);
03220               remote_close ();
03221 
03222               /* If we are attached, then we can exit.  Otherwise, we
03223                  need to hang around doing nothing, until the child is
03224                  gone.  */
03225               join_inferior (pid);
03226               exit (0);
03227             }
03228         }
03229       break;
03230     case '!':
03231       extended_protocol = 1;
03232       write_ok (own_buf);
03233       break;
03234     case '?':
03235       handle_status (own_buf);
03236       break;
03237     case 'H':
03238       if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's')
03239         {
03240           ptid_t gdb_id, thread_id;
03241           int pid;
03242 
03243           require_running (own_buf);
03244 
03245           gdb_id = read_ptid (&own_buf[2], NULL);
03246 
03247           pid = ptid_get_pid (gdb_id);
03248 
03249           if (ptid_equal (gdb_id, null_ptid)
03250               || ptid_equal (gdb_id, minus_one_ptid))
03251             thread_id = null_ptid;
03252           else if (pid != 0
03253                    && ptid_equal (pid_to_ptid (pid),
03254                                   gdb_id))
03255             {
03256               struct thread_info *thread =
03257                 (struct thread_info *) find_inferior (&all_threads,
03258                                                       first_thread_of,
03259                                                       &pid);
03260               if (!thread)
03261                 {
03262                   write_enn (own_buf);
03263                   break;
03264                 }
03265 
03266               thread_id = ((struct inferior_list_entry *)thread)->id;
03267             }
03268           else
03269             {
03270               thread_id = gdb_id_to_thread_id (gdb_id);
03271               if (ptid_equal (thread_id, null_ptid))
03272                 {
03273                   write_enn (own_buf);
03274                   break;
03275                 }
03276             }
03277 
03278           if (own_buf[1] == 'g')
03279             {
03280               if (ptid_equal (thread_id, null_ptid))
03281                 {
03282                   /* GDB is telling us to choose any thread.  Check if
03283                      the currently selected thread is still valid. If
03284                      it is not, select the first available.  */
03285                   struct thread_info *thread =
03286                     (struct thread_info *) find_inferior_id (&all_threads,
03287                                                              general_thread);
03288                   if (thread == NULL)
03289                     thread_id = all_threads.head->id;
03290                 }
03291 
03292               general_thread = thread_id;
03293               set_desired_inferior (1);
03294             }
03295           else if (own_buf[1] == 'c')
03296             cont_thread = thread_id;
03297 
03298           write_ok (own_buf);
03299         }
03300       else
03301         {
03302           /* Silently ignore it so that gdb can extend the protocol
03303              without compatibility headaches.  */
03304           own_buf[0] = '\0';
03305         }
03306       break;
03307     case 'g':
03308       require_running (own_buf);
03309       if (current_traceframe >= 0)
03310         {
03311           struct regcache *regcache
03312             = new_register_cache (current_target_desc ());
03313 
03314           if (fetch_traceframe_registers (current_traceframe,
03315                                           regcache, -1) == 0)
03316             registers_to_string (regcache, own_buf);
03317           else
03318             write_enn (own_buf);
03319           free_register_cache (regcache);
03320         }
03321       else
03322         {
03323           struct regcache *regcache;
03324 
03325           set_desired_inferior (1);
03326           regcache = get_thread_regcache (current_inferior, 1);
03327           registers_to_string (regcache, own_buf);
03328         }
03329       break;
03330     case 'G':
03331       require_running (own_buf);
03332       if (current_traceframe >= 0)
03333         write_enn (own_buf);
03334       else
03335         {
03336           struct regcache *regcache;
03337 
03338           set_desired_inferior (1);
03339           regcache = get_thread_regcache (current_inferior, 1);
03340           registers_from_string (regcache, &own_buf[1]);
03341           write_ok (own_buf);
03342         }
03343       break;
03344     case 'm':
03345       require_running (own_buf);
03346       decode_m_packet (&own_buf[1], &mem_addr, &len);
03347       res = gdb_read_memory (mem_addr, mem_buf, len);
03348       if (res < 0)
03349         write_enn (own_buf);
03350       else
03351         convert_int_to_ascii (mem_buf, own_buf, res);
03352       break;
03353     case 'M':
03354       require_running (own_buf);
03355       decode_M_packet (&own_buf[1], &mem_addr, &len, &mem_buf);
03356       if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
03357         write_ok (own_buf);
03358       else
03359         write_enn (own_buf);
03360       break;
03361     case 'X':
03362       require_running (own_buf);
03363       if (decode_X_packet (&own_buf[1], packet_len - 1,
03364                            &mem_addr, &len, &mem_buf) < 0
03365           || gdb_write_memory (mem_addr, mem_buf, len) != 0)
03366         write_enn (own_buf);
03367       else
03368         write_ok (own_buf);
03369       break;
03370     case 'C':
03371       require_running (own_buf);
03372       convert_ascii_to_int (own_buf + 1, &sig, 1);
03373       if (gdb_signal_to_host_p (sig))
03374         signal = gdb_signal_to_host (sig);
03375       else
03376         signal = 0;
03377       myresume (own_buf, 0, signal);
03378       break;
03379     case 'S':
03380       require_running (own_buf);
03381       convert_ascii_to_int (own_buf + 1, &sig, 1);
03382       if (gdb_signal_to_host_p (sig))
03383         signal = gdb_signal_to_host (sig);
03384       else
03385         signal = 0;
03386       myresume (own_buf, 1, signal);
03387       break;
03388     case 'c':
03389       require_running (own_buf);
03390       signal = 0;
03391       myresume (own_buf, 0, signal);
03392       break;
03393     case 's':
03394       require_running (own_buf);
03395       signal = 0;
03396       myresume (own_buf, 1, signal);
03397       break;
03398     case 'Z':  /* insert_ ... */
03399       /* Fallthrough.  */
03400     case 'z':  /* remove_ ... */
03401       {
03402         char *dataptr;
03403         ULONGEST addr;
03404         int len;
03405         char type = own_buf[1];
03406         int res;
03407         const int insert = ch == 'Z';
03408         char *p = &own_buf[3];
03409 
03410         p = unpack_varlen_hex (p, &addr);
03411         len = strtol (p + 1, &dataptr, 16);
03412 
03413         /* Default to unrecognized/unsupported.  */
03414         res = 1;
03415         switch (type)
03416           {
03417           case '0': /* software-breakpoint */
03418           case '1': /* hardware-breakpoint */
03419           case '2': /* write watchpoint */
03420           case '3': /* read watchpoint */
03421           case '4': /* access watchpoint */
03422             require_running (own_buf);
03423             if (insert && the_target->insert_point != NULL)
03424               {
03425                 /* Insert the breakpoint.  If it is already inserted, nothing
03426                    will take place.  */
03427                 res = (*the_target->insert_point) (type, addr, len);
03428 
03429                 /* GDB may have sent us a list of *point parameters to be
03430                    evaluated on the target's side.  Read such list here.  If we
03431                    already have a list of parameters, GDB is telling us to drop
03432                    that list and use this one instead.  */
03433                 if (!res && (type == '0' || type == '1'))
03434                   {
03435                     /* Remove previous conditions.  */
03436                     clear_gdb_breakpoint_conditions (addr);
03437                     process_point_options (addr, &dataptr);
03438                   }
03439               }
03440             else if (!insert && the_target->remove_point != NULL)
03441               res = (*the_target->remove_point) (type, addr, len);
03442             break;
03443           default:
03444             break;
03445           }
03446 
03447         if (res == 0)
03448           write_ok (own_buf);
03449         else if (res == 1)
03450           /* Unsupported.  */
03451           own_buf[0] = '\0';
03452         else
03453           write_enn (own_buf);
03454         break;
03455       }
03456     case 'k':
03457       response_needed = 0;
03458       if (!target_running ())
03459         /* The packet we received doesn't make sense - but we can't
03460            reply to it, either.  */
03461         return 0;
03462 
03463       fprintf (stderr, "Killing all inferiors\n");
03464       for_each_inferior (&all_processes, kill_inferior_callback);
03465 
03466       /* When using the extended protocol, we wait with no program
03467          running.  The traditional protocol will exit instead.  */
03468       if (extended_protocol)
03469         {
03470           last_status.kind = TARGET_WAITKIND_EXITED;
03471           last_status.value.sig = GDB_SIGNAL_KILL;
03472           return 0;
03473         }
03474       else
03475         exit (0);
03476 
03477     case 'T':
03478       {
03479         ptid_t gdb_id, thread_id;
03480 
03481         require_running (own_buf);
03482 
03483         gdb_id = read_ptid (&own_buf[1], NULL);
03484         thread_id = gdb_id_to_thread_id (gdb_id);
03485         if (ptid_equal (thread_id, null_ptid))
03486           {
03487             write_enn (own_buf);
03488             break;
03489           }
03490 
03491         if (mythread_alive (thread_id))
03492           write_ok (own_buf);
03493         else
03494           write_enn (own_buf);
03495       }
03496       break;
03497     case 'R':
03498       response_needed = 0;
03499 
03500       /* Restarting the inferior is only supported in the extended
03501          protocol.  */
03502       if (extended_protocol)
03503         {
03504           if (target_running ())
03505             for_each_inferior (&all_processes,
03506                                kill_inferior_callback);
03507           fprintf (stderr, "GDBserver restarting\n");
03508 
03509           /* Wait till we are at 1st instruction in prog.  */
03510           if (program_argv != NULL)
03511             start_inferior (program_argv);
03512           else
03513             {
03514               last_status.kind = TARGET_WAITKIND_EXITED;
03515               last_status.value.sig = GDB_SIGNAL_KILL;
03516             }
03517           return 0;
03518         }
03519       else
03520         {
03521           /* It is a request we don't understand.  Respond with an
03522              empty packet so that gdb knows that we don't support this
03523              request.  */
03524           own_buf[0] = '\0';
03525           break;
03526         }
03527     case 'v':
03528       /* Extended (long) request.  */
03529       handle_v_requests (own_buf, packet_len, &new_packet_len);
03530       break;
03531 
03532     default:
03533       /* It is a request we don't understand.  Respond with an empty
03534          packet so that gdb knows that we don't support this
03535          request.  */
03536       own_buf[0] = '\0';
03537       break;
03538     }
03539 
03540   if (new_packet_len != -1)
03541     putpkt_binary (own_buf, new_packet_len);
03542   else
03543     putpkt (own_buf);
03544 
03545   response_needed = 0;
03546 
03547   if (!extended_protocol && have_ran && !target_running ())
03548     {
03549       /* In non-stop, defer exiting until GDB had a chance to query
03550          the whole vStopped list (until it gets an OK).  */
03551       if (QUEUE_is_empty (notif_event_p, notif_stop.queue))
03552         {
03553           /* Be transparent when GDB is connected through stdio -- no
03554              need to spam GDB's console.  */
03555           if (!remote_connection_is_stdio ())
03556             fprintf (stderr, "GDBserver exiting\n");
03557           remote_close ();
03558           exit (0);
03559         }
03560     }
03561 
03562   if (exit_requested)
03563     return -1;
03564 
03565   return 0;
03566 }
03567 
03568 /* Event-loop callback for serial events.  */
03569 
03570 int
03571 handle_serial_event (int err, gdb_client_data client_data)
03572 {
03573   if (debug_threads)
03574     fprintf (stderr, "handling possible serial event\n");
03575 
03576   /* Really handle it.  */
03577   if (process_serial_event () < 0)
03578     return -1;
03579 
03580   /* Be sure to not change the selected inferior behind GDB's back.
03581      Important in the non-stop mode asynchronous protocol.  */
03582   set_desired_inferior (1);
03583 
03584   return 0;
03585 }
03586 
03587 /* Event-loop callback for target events.  */
03588 
03589 int
03590 handle_target_event (int err, gdb_client_data client_data)
03591 {
03592   if (debug_threads)
03593     fprintf (stderr, "handling possible target event\n");
03594 
03595   last_ptid = mywait (minus_one_ptid, &last_status,
03596                       TARGET_WNOHANG, 1);
03597 
03598   if (last_status.kind != TARGET_WAITKIND_IGNORE)
03599     {
03600       int pid = ptid_get_pid (last_ptid);
03601       struct process_info *process = find_process_pid (pid);
03602       int forward_event = !gdb_connected () || process->gdb_detached;
03603 
03604       if (last_status.kind == TARGET_WAITKIND_EXITED
03605           || last_status.kind == TARGET_WAITKIND_SIGNALLED)
03606         {
03607           mark_breakpoints_out (process);
03608           mourn_inferior (process);
03609         }
03610       else
03611         {
03612           /* We're reporting this thread as stopped.  Update its
03613              "want-stopped" state to what the client wants, until it
03614              gets a new resume action.  */
03615           current_inferior->last_resume_kind = resume_stop;
03616           current_inferior->last_status = last_status;
03617         }
03618 
03619       if (forward_event)
03620         {
03621           if (!target_running ())
03622             {
03623               /* The last process exited.  We're done.  */
03624               exit (0);
03625             }
03626 
03627           if (last_status.kind == TARGET_WAITKIND_STOPPED)
03628             {
03629               /* A thread stopped with a signal, but gdb isn't
03630                  connected to handle it.  Pass it down to the
03631                  inferior, as if it wasn't being traced.  */
03632               struct thread_resume resume_info;
03633 
03634               if (debug_threads)
03635                 fprintf (stderr,
03636                          "GDB not connected; forwarding event %d for [%s]\n",
03637                          (int) last_status.kind,
03638                          target_pid_to_str (last_ptid));
03639 
03640               resume_info.thread = last_ptid;
03641               resume_info.kind = resume_continue;
03642               resume_info.sig = gdb_signal_to_host (last_status.value.sig);
03643               (*the_target->resume) (&resume_info, 1);
03644             }
03645           else if (debug_threads)
03646             fprintf (stderr, "GDB not connected; ignoring event %d for [%s]\n",
03647                      (int) last_status.kind,
03648                      target_pid_to_str (last_ptid));
03649         }
03650       else
03651         {
03652           struct vstop_notif *vstop_notif
03653             = xmalloc (sizeof (struct vstop_notif));
03654 
03655           vstop_notif->status = last_status;
03656           vstop_notif->ptid = last_ptid;
03657           /* Push Stop notification.  */
03658           notif_push (&notif_stop,
03659                       (struct notif_event *) vstop_notif);
03660         }
03661     }
03662 
03663   /* Be sure to not change the selected inferior behind GDB's back.
03664      Important in the non-stop mode asynchronous protocol.  */
03665   set_desired_inferior (1);
03666 
03667   return 0;
03668 }
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Defines