Home | History | Annotate | Download | only in m_gdbserver
      1 /* Main code for remote server for GDB.
      2    Copyright (C) 1989, 1993, 1994, 1995, 1997, 1998, 1999, 2000, 2002, 2003,
      3    2004, 2005, 2006, 2011
      4    Free Software Foundation, Inc.
      5 
      6    This file is part of GDB.
      7    It has been modified to integrate it in valgrind
      8 
      9    This program is free software; you can redistribute it and/or modify
     10    it under the terms of the GNU General Public License as published by
     11    the Free Software Foundation; either version 2 of the License, or
     12    (at your option) any later version.
     13 
     14    This program is distributed in the hope that it will be useful,
     15    but WITHOUT ANY WARRANTY; without even the implied warranty of
     16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     17    GNU General Public License for more details.
     18 
     19    You should have received a copy of the GNU General Public License
     20    along with this program; if not, write to the Free Software
     21    Foundation, Inc., 51 Franklin Street, Fifth Floor,
     22    Boston, MA 02110-1301, USA.  */
     23 
     24 #include "server.h"
     25 #include "regdef.h"
     26 #include "pub_core_options.h"
     27 #include "pub_core_translate.h"
     28 #include "pub_core_mallocfree.h"
     29 #include "pub_core_initimg.h"
     30 #include "pub_core_execontext.h"
     31 #include "pub_core_syswrap.h"      // VG_(show_open_fds)
     32 #include "pub_core_scheduler.h"
     33 #include "pub_core_transtab.h"
     34 #include "pub_core_debuginfo.h"
     35 #include "pub_core_addrinfo.h"
     36 
     37 unsigned long cont_thread;
     38 unsigned long general_thread;
     39 unsigned long step_thread;
     40 unsigned long thread_from_wait;
     41 unsigned long old_thread_from_wait;
     42 
     43 int pass_signals[TARGET_SIGNAL_LAST]; /* indexed by gdb signal nr */
     44 
     45 /* for a gdbserver integrated in valgrind, resuming the process consists
     46    in returning the control to valgrind.
     47    The guess process resumes its execution.
     48    Then at the next error or break or ..., valgrind calls gdbserver again.
     49    A resume reply packet must then be built to inform GDB that the
     50    resume request is finished.
     51    resume_reply_packet_needed records the fact that the next call to gdbserver
     52    must send a resume packet to gdb. */
     53 static Bool resume_reply_packet_needed = False;
     54 
     55 VG_MINIMAL_JMP_BUF(toplevel);
     56 
     57 /* Decode a qXfer read request.  Return 0 if everything looks OK,
     58    or -1 otherwise.  */
     59 
     60 static
     61 int decode_xfer_read (char *buf, const char **annex, CORE_ADDR *ofs, unsigned int *len)
     62 {
     63    /* Extract and NUL-terminate the annex.  */
     64    *annex = buf;
     65    while (*buf && *buf != ':')
     66       buf++;
     67    if (*buf == '\0')
     68       return -1;
     69    *buf++ = 0;
     70 
     71    /* After the read/write marker and annex, qXfer looks like a
     72       traditional 'm' packet.  */
     73    decode_m_packet (buf, ofs, len);
     74 
     75    return 0;
     76 }
     77 
     78 /* Write the response to a successful qXfer read.  Returns the
     79    length of the (binary) data stored in BUF, corresponding
     80    to as much of DATA/LEN as we could fit.  IS_MORE controls
     81    the first character of the response.  */
     82 static
     83 int write_qxfer_response (char *buf, unsigned char *data, int len, int is_more)
     84 {
     85    int out_len;
     86 
     87    if (is_more)
     88       buf[0] = 'm';
     89    else
     90       buf[0] = 'l';
     91 
     92    return remote_escape_output (data, len, (unsigned char *) buf + 1, &out_len,
     93                                 PBUFSIZ - POVERHSIZ - 1) + 1;
     94 }
     95 
     96 static Bool initial_valgrind_sink_saved = False;
     97 /* True <=> valgrind log sink saved in initial_valgrind_sink */
     98 static OutputSink initial_valgrind_sink;
     99 
    100 static Bool command_output_to_log = False;
    101 /* True <=> command output goes to log instead of gdb */
    102 
    103 void reset_valgrind_sink(const char *info)
    104 {
    105    if (VG_(log_output_sink).fd != initial_valgrind_sink.fd
    106        && initial_valgrind_sink_saved) {
    107       VG_(log_output_sink).fd = initial_valgrind_sink.fd;
    108       VG_(umsg) ("Reset valgrind output to log (%s)\n",
    109                  (info = NULL ? "" : info));
    110    }
    111 }
    112 
    113 void print_to_initial_valgrind_sink (const char *msg)
    114 {
    115    vg_assert (initial_valgrind_sink_saved);
    116    VG_(write) (initial_valgrind_sink.fd, msg, strlen(msg));
    117 }
    118 
    119 
    120 static
    121 void kill_request (const char *msg)
    122 {
    123    VG_(umsg) ("%s", msg);
    124    VG_(exit) (0);
    125 }
    126 
    127 // s is a NULL terminated string made of O or more words (separated by spaces).
    128 // Returns a pointer to the Nth word in s.
    129 // If Nth word does not exist, return a pointer to the last (0) byte of s.
    130 static
    131 const char *wordn (const char *s, int n)
    132 {
    133    int word_seen = 0;
    134    Bool searching_word = True;
    135 
    136    while (*s) {
    137       if (*s == ' ')
    138          searching_word = True;
    139       else {
    140          if (searching_word) {
    141             searching_word = False;
    142             word_seen++;
    143             if (word_seen == n)
    144                return s;
    145          }
    146       }
    147       s++;
    148    }
    149    return s;
    150 }
    151 
    152 void VG_(print_all_stats) (Bool memory_stats, Bool tool_stats)
    153 {
    154    if (memory_stats) {
    155       VG_(message)(Vg_DebugMsg, "\n");
    156       VG_(message)(Vg_DebugMsg,
    157          "------ Valgrind's internal memory use stats follow ------\n" );
    158       VG_(sanity_check_malloc_all)();
    159       VG_(message)(Vg_DebugMsg, "------\n" );
    160       VG_(print_all_arena_stats)();
    161       if (VG_(clo_profile_heap))
    162          VG_(print_arena_cc_analysis) ();
    163       VG_(message)(Vg_DebugMsg, "\n");
    164    }
    165 
    166    VG_(print_translation_stats)();
    167    VG_(print_tt_tc_stats)();
    168    VG_(print_scheduler_stats)();
    169    VG_(print_ExeContext_stats)( False /* with_stacktraces */ );
    170    VG_(print_errormgr_stats)();
    171    if (tool_stats && VG_(needs).print_stats) {
    172       VG_TDICT_CALL(tool_print_stats);
    173    }
    174 }
    175 
    176 /* handle_gdb_valgrind_command handles the provided mon string command.
    177    If command is recognised, return 1 else return 0.
    178    Note that in case of ambiguous command, 1 is returned.
    179 
    180    *sink_wanted_at_return is modified if one of the commands
    181    'v.set *_output' is handled.
    182 */
    183 static
    184 int handle_gdb_valgrind_command (char *mon, OutputSink *sink_wanted_at_return)
    185 {
    186    UWord ret = 0;
    187    char s[strlen(mon)+1]; /* copy for strtok_r */
    188    char *wcmd;
    189    HChar *ssaveptr;
    190    const char *endptr;
    191    int   kwdid;
    192    int int_value;
    193 
    194    vg_assert (initial_valgrind_sink_saved);
    195 
    196    strcpy (s, mon);
    197    wcmd = strtok_r (s, " ", &ssaveptr);
    198    /* NB: if possible, avoid introducing a new command below which
    199       starts with the same 3 first letters as an already existing
    200       command. This ensures a shorter abbreviation for the user. */
    201    switch (VG_(keyword_id) ("help v.set v.info v.wait v.kill v.translate"
    202                             " v.do",
    203                             wcmd, kwd_report_duplicated_matches)) {
    204    case -2:
    205       ret = 1;
    206       break;
    207    case -1:
    208       break;
    209    case  0: /* help */
    210       ret = 1;
    211       wcmd = strtok_r (NULL, " ", &ssaveptr);
    212       if (wcmd == NULL) {
    213          int_value = 0;
    214       } else {
    215          switch (VG_(keyword_id) ("debug", wcmd, kwd_report_all)) {
    216          case -2: int_value = 0; break;
    217          case -1: int_value = 0; break;
    218          case  0: int_value = 1; break;
    219          default: tl_assert (0);
    220          }
    221       }
    222 
    223       VG_(gdb_printf) (
    224 "general valgrind monitor commands:\n"
    225 "  help [debug]            : monitor command help. With debug: + debugging commands\n"
    226 "  v.wait [<ms>]           : sleep <ms> (default 0) then continue\n"
    227 "  v.info all_errors       : show all errors found so far\n"
    228 "  v.info last_error       : show last error found\n"
    229 "  v.info location <addr>  : show information about location <addr>\n"
    230 "  v.info n_errs_found [msg] : show the nr of errors found so far and the given msg\n"
    231 "  v.info open_fds         : show open file descriptors (only if --track-fds=yes)\n"
    232 "  v.kill                  : kill the Valgrind process\n"
    233 "  v.set gdb_output        : set valgrind output to gdb\n"
    234 "  v.set log_output        : set valgrind output to log\n"
    235 "  v.set mixed_output      : set valgrind output to log, interactive output to gdb\n"
    236 "  v.set merge-recursive-frames <num> : merge recursive calls in max <num> frames\n"
    237 "  v.set vgdb-error <errornr> : debug me at error >= <errornr> \n");
    238       if (int_value) { VG_(gdb_printf) (
    239 "debugging valgrind internals monitor commands:\n"
    240 "  v.do   expensive_sanity_check_general : do an expensive sanity check now\n"
    241 "  v.info gdbserver_status : show gdbserver status\n"
    242 "  v.info memory [aspacemgr] : show valgrind heap memory stats\n"
    243 "     (with aspacemgr arg, also shows valgrind segments on log ouput)\n"
    244 "  v.info exectxt          : show stacktraces and stats of all execontexts\n"
    245 "  v.info scheduler        : show valgrind thread state and stacktrace\n"
    246 "  v.info stats            : show various valgrind and tool stats\n"
    247 "  v.set debuglog <level>  : set valgrind debug log level to <level>\n"
    248 "  v.set hostvisibility [yes*|no] : (en/dis)ables access by gdb/gdbserver to\n"
    249 "    Valgrind internal host status/memory\n"
    250 "  v.translate <addr> [<traceflags>]  : debug translation of <addr> with <traceflags>\n"
    251 "    (default traceflags 0b00100000 : show after instrumentation)\n"
    252 "   An additional flag  0b100000000 allows to show gdbserver instrumentation\n");
    253       }
    254       break;
    255    case  1: /* v.set */
    256       ret = 1;
    257       wcmd = strtok_r (NULL, " ", &ssaveptr);
    258       switch (kwdid = VG_(keyword_id)
    259               ("vgdb-error debuglog merge-recursive-frames"
    260                " gdb_output log_output mixed_output hostvisibility ",
    261                wcmd, kwd_report_all)) {
    262       case -2:
    263       case -1:
    264          break;
    265       case 0: /* vgdb-error */
    266       case 1: /* debuglog */
    267       case 2: /* merge-recursive-frames */
    268          wcmd = strtok_r (NULL, " ", &ssaveptr);
    269          if (wcmd == NULL) {
    270             int_value = 0;
    271             endptr = "empty"; /* to report an error below */
    272          } else {
    273             HChar *the_end;
    274             int_value = strtol (wcmd, &the_end, 10);
    275             endptr = the_end;
    276          }
    277          if (*endptr != '\0') {
    278             VG_(gdb_printf) ("missing or malformed integer value\n");
    279          } else if (kwdid == 0) {
    280             VG_(printf) ("vgdb-error value changed from %d to %d\n",
    281                              VG_(dyn_vgdb_error), int_value);
    282             VG_(dyn_vgdb_error) = int_value;
    283          } else if (kwdid == 1) {
    284             VG_(printf) ("debuglog value changed from %d to %d\n",
    285                              VG_(debugLog_getLevel)(), int_value);
    286             VG_(debugLog_startup) (int_value, "gdbsrv");
    287          } else if (kwdid == 2) {
    288             VG_(printf)
    289                ("merge-recursive-frames value changed from %d to %d\n",
    290                 VG_(clo_merge_recursive_frames), int_value);
    291             VG_(clo_merge_recursive_frames) = int_value;
    292          } else {
    293             vg_assert (0);
    294          }
    295          break;
    296       case 3: /* gdb_output */
    297          (*sink_wanted_at_return).fd = -2;
    298          command_output_to_log = False;
    299          VG_(gdb_printf) ("valgrind output will go to gdb\n");
    300          break;
    301       case 4: /* log_output */
    302          (*sink_wanted_at_return).fd = initial_valgrind_sink.fd;
    303          command_output_to_log = True;
    304          VG_(gdb_printf) ("valgrind output will go to log\n");
    305          break;
    306       case 5: /* mixed output */
    307          (*sink_wanted_at_return).fd = initial_valgrind_sink.fd;
    308          command_output_to_log = False;
    309          VG_(gdb_printf)
    310             ("valgrind output will go to log, interactive output will go to gdb\n");
    311          break;
    312       case 6: /* hostvisibility */
    313          wcmd = strtok_r (NULL, " ", &ssaveptr);
    314          if (wcmd != NULL) {
    315             switch (VG_(keyword_id) ("yes no", wcmd, kwd_report_all)) {
    316             case -2:
    317             case -1: break;
    318             case  0:
    319                hostvisibility = True;
    320                break;
    321             case 1:
    322                hostvisibility = False;
    323                break;
    324             default: tl_assert (0);
    325             }
    326          } else {
    327             hostvisibility = True;
    328          }
    329          if (hostvisibility)
    330             VG_(gdb_printf)
    331                ("Enabled access to Valgrind memory/status by GDB\n"
    332                 "If not yet done, tell GDB which valgrind file(s) to use:\n"
    333                 "add-symbol-file <tool or preloaded file> <loadaddr>\n");
    334          else
    335             VG_(gdb_printf)
    336                ("Disabled access to Valgrind memory/status by GDB\n");
    337          break;
    338       default:
    339          vg_assert (0);
    340       }
    341       break;
    342    case  2: /* v.info */ {
    343       ret = 1;
    344       wcmd = strtok_r (NULL, " ", &ssaveptr);
    345       switch (kwdid = VG_(keyword_id)
    346               ("all_errors n_errs_found last_error gdbserver_status memory"
    347                " scheduler stats open_fds exectxt location",
    348                wcmd, kwd_report_all)) {
    349       case -2:
    350       case -1:
    351          break;
    352       case 0: // all_errors
    353          // A verbosity of minimum 2 is needed to show the errors.
    354          VG_(show_all_errors)(/* verbosity */ 2, /* xml */ False);
    355          break;
    356       case  1: // n_errs_found
    357          VG_(printf) ("n_errs_found %d n_errs_shown %d (vgdb-error %d) %s\n",
    358                       VG_(get_n_errs_found) (),
    359                       VG_(get_n_errs_shown) (),
    360                       VG_(dyn_vgdb_error),
    361                       wordn (mon, 3));
    362          break;
    363       case 2: // last_error
    364          VG_(show_last_error)();
    365          break;
    366       case  3: // gdbserver_status
    367          VG_(gdbserver_status_output)();
    368          break;
    369       case  4: /* memory */
    370          VG_(printf) ("%llu bytes have already been allocated.\n",
    371                       VG_(am_get_anonsize_total)());
    372          VG_(print_all_arena_stats) ();
    373          if (VG_(clo_profile_heap))
    374             VG_(print_arena_cc_analysis) ();
    375          wcmd = strtok_r (NULL, " ", &ssaveptr);
    376          if (wcmd != NULL) {
    377             switch (VG_(keyword_id) ("aspacemgr", wcmd, kwd_report_all)) {
    378             case -2:
    379             case -1: break;
    380             case  0:
    381                VG_(am_show_nsegments) (0, "gdbserver v.info memory aspacemgr");
    382                break;
    383             default: tl_assert (0);
    384             }
    385          }
    386 
    387          ret = 1;
    388          break;
    389       case  5: /* scheduler */
    390          VG_(show_sched_status) (True,  // host_stacktrace
    391                                  True,  // valgrind_stack_usage
    392                                  True); // exited_threads
    393          ret = 1;
    394          break;
    395       case  6: /* stats */
    396          VG_(print_all_stats)(False, /* Memory stats */
    397                               True   /* Tool stats */);
    398          ret = 1;
    399          break;
    400       case  7: /* open_fds */
    401          if (VG_(clo_track_fds))
    402             VG_(show_open_fds) ("");
    403          else
    404             VG_(gdb_printf)
    405                ("Valgrind must be started with --track-fds=yes"
    406                 " to show open fds\n");
    407          ret = 1;
    408          break;
    409       case  8: /* exectxt */
    410          VG_(print_ExeContext_stats) (True /* with_stacktraces */);
    411          ret = 1;
    412          break;
    413       case  9: { /* location */
    414          /* Note: we prefer 'v.info location' and not 'v.info address' as
    415             v.info address is inconsistent with the GDB (native)
    416             command 'info address' which gives the address for a symbol.
    417             GDB equivalent command of 'v.info location' is 'info symbol'. */
    418          Addr address;
    419          SizeT dummy_sz = 0x1234;
    420          if (VG_(strtok_get_address_and_size) (&address, &dummy_sz, &ssaveptr)) {
    421             // If tool provides location information, use that.
    422             if (VG_(needs).info_location) {
    423                VG_TDICT_CALL(tool_info_location, address);
    424             }
    425             // If tool does not provide location information, use the common one.
    426             // Also use the common to compare with tool when debug log is set.
    427             if (!VG_(needs).info_location || VG_(debugLog_getLevel)() > 0 ) {
    428                AddrInfo ai;
    429                ai.tag = Addr_Undescribed;
    430                VG_(describe_addr) (address, &ai);
    431                VG_(pp_addrinfo) (address, &ai);
    432                VG_(clear_addrinfo) (&ai);
    433             }
    434          }
    435          ret = 1;
    436          break;
    437       }
    438       default:
    439          vg_assert(0);
    440       }
    441       break;
    442    }
    443    case  3: /* v.wait */
    444       wcmd = strtok_r (NULL, " ", &ssaveptr);
    445       if (wcmd != NULL) {
    446          int_value = strtol (wcmd, NULL, 10);
    447          VG_(printf) ("gdbserver: continuing in %d ms ...\n", int_value);
    448          VG_(poll)(NULL, 0, int_value);
    449       }
    450       VG_(printf) ("gdbserver: continuing after wait ...\n");
    451       ret = 1;
    452       break;
    453    case  4: /* v.kill */
    454       kill_request ("monitor command request to kill this process\n");
    455       break;
    456    case  5: { /* v.translate */
    457       Addr address;
    458       SizeT verbosity = 0x20;
    459 
    460       ret = 1;
    461 
    462       if (VG_(strtok_get_address_and_size) (&address, &verbosity, &ssaveptr)) {
    463          /* we need to force the output to log for the translation trace,
    464             as low level VEX tracing cannot be redirected to gdb. */
    465          int saved_command_output_to_log = command_output_to_log;
    466          int saved_fd = VG_(log_output_sink).fd;
    467          Bool single_stepping_on_entry = valgrind_single_stepping();
    468          int vex_verbosity = verbosity & 0xff;
    469          VG_(log_output_sink).fd = initial_valgrind_sink.fd;
    470          if ((verbosity & 0x100) && !single_stepping_on_entry) {
    471             valgrind_set_single_stepping(True);
    472             // to force gdbserver instrumentation.
    473          }
    474 #        if defined(VGA_arm)
    475          // on arm, we need to (potentially) convert this address
    476          // to the thumb form.
    477          address = thumb_pc (address);
    478 #        endif
    479 
    480          VG_(translate) ( 0 /* dummy ThreadId; irrelevant due to debugging*/,
    481                           address,
    482                           /*debugging*/True,
    483                           (Int) vex_verbosity,
    484                           /*bbs_done*/0,
    485                           /*allow redir?*/True);
    486          if ((verbosity & 0x100) && !single_stepping_on_entry) {
    487             valgrind_set_single_stepping(False);
    488             // reset single stepping.
    489          }
    490          command_output_to_log = saved_command_output_to_log;
    491          VG_(log_output_sink).fd = saved_fd;
    492       }
    493       break;
    494    }
    495 
    496    case  6: /* v.do */
    497       ret = 1;
    498       wcmd = strtok_r (NULL, " ", &ssaveptr);
    499       switch (VG_(keyword_id) ("expensive_sanity_check_general",
    500                                wcmd, kwd_report_all)) {
    501          case -2:
    502          case -1: break;
    503          case  0: { /* expensive_sanity_check_general */
    504             // Temporarily bump up sanity level to check e.g. the malloc arenas.
    505             const Int save_clo_sanity_level = VG_(clo_sanity_level);
    506             if (VG_(clo_sanity_level) < 4) VG_(clo_sanity_level) = 4;
    507             VG_(sanity_check_general) (/* force_expensive */ True);
    508             VG_(clo_sanity_level) = save_clo_sanity_level;
    509             break;
    510          }
    511          default: tl_assert (0);
    512       }
    513       break;
    514 
    515    default:
    516       vg_assert (0);
    517    }
    518    return ret;
    519 }
    520 
    521 /* handle_gdb_monitor_command handles the provided mon string command,
    522    which can be either a "standard" valgrind monitor command
    523    or a tool specific monitor command.
    524    If command recognised, return 1 else return 0.
    525    Note that in case of ambiguous command, 1 is returned.
    526 */
    527 static
    528 int handle_gdb_monitor_command (char *mon)
    529 {
    530    UWord ret = 0;
    531    UWord tool_ret = 0;
    532    // initially, we assume that when returning, the desired sink is the
    533    // one we have when entering. It can however be changed by the standard
    534    // valgrind command handling.
    535    OutputSink sink_wanted_at_return = VG_(log_output_sink);
    536 
    537    if (!initial_valgrind_sink_saved) {
    538       /* first time we enter here, we save the valgrind default log sink */
    539       initial_valgrind_sink = sink_wanted_at_return;
    540       initial_valgrind_sink_saved = True;
    541    }
    542 
    543    if (!command_output_to_log)
    544       VG_(log_output_sink).fd = -2; /* redirect to monitor_output */
    545 
    546    ret = handle_gdb_valgrind_command (mon, &sink_wanted_at_return);
    547 
    548    /* Even if command was recognised by valgrind core, we call the
    549       tool command handler : this is needed to handle help command
    550       and/or to let the tool do some additional processing of a
    551       valgrind standard command. Note however that if valgrind
    552       recognised the command, we will always return success. */
    553    if (VG_(needs).client_requests) {
    554       /* If the tool reports an error when handling a monitor command,
    555          we need to avoid calling gdbserver during this command
    556          handling. So, we temporarily set VG_(dyn_vgdb_error) to
    557          a huge value to ensure m_errormgr.c does not call gdbserver. */
    558       Int save_dyn_vgdb_error = VG_(dyn_vgdb_error);
    559       UWord arg[2];
    560       VG_(dyn_vgdb_error) = 999999999;
    561       arg[0] = (UWord) VG_USERREQ__GDB_MONITOR_COMMAND;
    562       arg[1] = (UWord) mon;
    563       VG_TDICT_CALL(tool_handle_client_request, VG_(running_tid), arg,
    564                     &tool_ret);
    565       VG_(dyn_vgdb_error) = save_dyn_vgdb_error;
    566    }
    567 
    568    VG_(message_flush) ();
    569 
    570    /* restore or set the desired output */
    571    VG_(log_output_sink).fd = sink_wanted_at_return.fd;
    572    if (ret | tool_ret)
    573       return 1;
    574    else
    575       return 0;
    576 }
    577 
    578 
    579 /* Handle all of the extended 'Q' packets.  */
    580 static
    581 void handle_set (char *arg_own_buf, int *new_packet_len_p)
    582 {
    583    if (strcmp ("QStartNoAckMode", arg_own_buf) == 0) {
    584       noack_mode = True;
    585       write_ok (arg_own_buf);
    586       return;
    587    }
    588 
    589    if (strncmp ("QPassSignals:", arg_own_buf, 13) == 0) {
    590       int i;
    591       char *from, *to;
    592       char *end = arg_own_buf + strlen(arg_own_buf);
    593       CORE_ADDR sig;
    594       for (i = 0; i < TARGET_SIGNAL_LAST; i++)
    595          pass_signals[i] = 0;
    596 
    597       from = arg_own_buf + 13;
    598       while (from < end) {
    599          to = strchr(from, ';');
    600          if (to == NULL) to = end;
    601          decode_address (&sig, from, to - from);
    602          pass_signals[(int)sig] = 1;
    603          dlog(1, "pass_signal gdb_nr %d %s\n",
    604               (int)sig, target_signal_to_name(sig));
    605          from = to;
    606          if (*from == ';') from++;
    607       }
    608       write_ok (arg_own_buf);
    609       return;
    610    }
    611    /* Otherwise we didn't know what packet it was.  Say we didn't
    612       understand it.  */
    613    arg_own_buf[0] = 0;
    614 }
    615 
    616 Bool VG_(client_monitor_command) (HChar *cmd)
    617 {
    618    const Bool connected = remote_connected();
    619    const int saved_command_output_to_log = command_output_to_log;
    620    Bool handled;
    621 
    622    if (!connected)
    623       command_output_to_log = True;
    624    handled = handle_gdb_monitor_command (cmd);
    625    if (!connected) {
    626       // reset the log output unless cmd changed it.
    627       if (command_output_to_log)
    628          command_output_to_log = saved_command_output_to_log;
    629    }
    630    if (handled)
    631       return False; // recognised
    632    else
    633       return True; // not recognised
    634 }
    635 
    636 /* Handle all of the extended 'q' packets.  */
    637 static
    638 void handle_query (char *arg_own_buf, int *new_packet_len_p)
    639 {
    640    static struct inferior_list_entry *thread_ptr;
    641 
    642    /* qRcmd, monitor command handling.  */
    643    if (strncmp ("qRcmd,", arg_own_buf, 6) == 0) {
    644       char *p = arg_own_buf + 6;
    645       int cmdlen = strlen(p)/2;
    646       char cmd[cmdlen+1];
    647 
    648       if (unhexify (cmd, p, cmdlen) != cmdlen) {
    649          write_enn (arg_own_buf);
    650          return;
    651       }
    652       cmd[cmdlen] = '\0';
    653 
    654       if (handle_gdb_monitor_command (cmd)) {
    655          write_ok (arg_own_buf);
    656          return;
    657       } else {
    658          /* cmd not recognised */
    659          VG_(gdb_printf)
    660             ("command '%s' not recognised\n"
    661              "In gdb,     try 'monitor help'\n"
    662              "In a shell, try 'vgdb help'\n",
    663              cmd);
    664          write_ok (arg_own_buf);
    665          return;
    666       }
    667    }
    668 
    669    /* provide some valgrind specific info in return to qThreadExtraInfo. */
    670    if (strncmp ("qThreadExtraInfo,", arg_own_buf, 17) == 0) {
    671       unsigned long gdb_id;
    672       struct thread_info *ti;
    673       ThreadState *tst;
    674       char status[100];
    675 
    676       gdb_id = strtoul (&arg_own_buf[17], NULL, 16);
    677       ti = gdb_id_to_thread (gdb_id);
    678       if (ti != NULL) {
    679          tst = (ThreadState *) inferior_target_data (ti);
    680          /* Additional info is the tid, the thread status and the thread's
    681             name, if any. */
    682          if (tst->thread_name) {
    683             VG_(snprintf) (status, sizeof(status), "tid %d %s %s",
    684                            tst->tid,
    685                            VG_(name_of_ThreadStatus)(tst->status),
    686                            tst->thread_name);
    687          } else {
    688             VG_(snprintf) (status, sizeof(status), "tid %d %s",
    689                            tst->tid,
    690                            VG_(name_of_ThreadStatus)(tst->status));
    691          }
    692          hexify (arg_own_buf, status, strlen(status));
    693          return;
    694       } else {
    695          write_enn (arg_own_buf);
    696          return;
    697       }
    698    }
    699 
    700    if (strcmp ("qAttached", arg_own_buf) == 0) {
    701       /* tell gdb to always detach, never kill the process */
    702       arg_own_buf[0] = '1';
    703       arg_own_buf[1] = 0;
    704       return;
    705    }
    706 
    707    if (strcmp ("qSymbol::", arg_own_buf) == 0) {
    708       /* We have no symbol to read. */
    709       write_ok (arg_own_buf);
    710       return;
    711    }
    712 
    713    if (strcmp ("qfThreadInfo", arg_own_buf) == 0) {
    714       thread_ptr = all_threads.head;
    715       VG_(sprintf) (arg_own_buf, "m%x",
    716                     thread_to_gdb_id ((struct thread_info *)thread_ptr));
    717       thread_ptr = thread_ptr->next;
    718       return;
    719    }
    720 
    721    if (strcmp ("qsThreadInfo", arg_own_buf) == 0) {
    722       if (thread_ptr != NULL) {
    723          VG_(sprintf) (arg_own_buf, "m%x",
    724                        thread_to_gdb_id ((struct thread_info *)thread_ptr));
    725          thread_ptr = thread_ptr->next;
    726          return;
    727       } else {
    728          VG_(sprintf) (arg_own_buf, "l");
    729          return;
    730       }
    731    }
    732 
    733    if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers)) != NULL
    734         && strncmp ("qXfer:features:read:", arg_own_buf, 20) == 0) {
    735       CORE_ADDR ofs;
    736       unsigned int len, doc_len;
    737       const char *annex = NULL;
    738       // First, the annex is extracted from the packet received.
    739       // Then, it is replaced by the corresponding file name.
    740       int fd;
    741 
    742       /* Grab the annex, offset, and length.  */
    743       if (decode_xfer_read (arg_own_buf + 20, &annex, &ofs, &len) < 0) {
    744          strcpy (arg_own_buf, "E00");
    745          return;
    746       }
    747 
    748       if (strcmp (annex, "target.xml") == 0) {
    749          annex = valgrind_target_xml(VG_(clo_vgdb_shadow_registers));
    750          if (annex != NULL && VG_(clo_vgdb_shadow_registers)) {
    751             /* Ensure the shadow registers are initialized. */
    752             initialize_shadow_low(True);
    753          }
    754          if (annex == NULL) {
    755             strcpy (arg_own_buf, "E00");
    756             return;
    757          }
    758       }
    759 
    760       {
    761          char doc[VG_(strlen)(VG_(libdir)) + 1 + VG_(strlen)(annex) + 1];
    762          struct vg_stat stat_doc;
    763          char toread[len];
    764          int len_read;
    765 
    766          VG_(sprintf)(doc, "%s/%s", VG_(libdir), annex);
    767          fd = VG_(fd_open) (doc, VKI_O_RDONLY, 0);
    768          if (fd == -1) {
    769             strcpy (arg_own_buf, "E00");
    770             return;
    771          }
    772          if (VG_(fstat) (fd, &stat_doc) != 0) {
    773             VG_(close) (fd);
    774             strcpy (arg_own_buf, "E00");
    775             return;
    776          }
    777          doc_len = stat_doc.size;
    778 
    779          if (len > PBUFSIZ - POVERHSIZ)
    780             len = PBUFSIZ - POVERHSIZ;
    781 
    782          if (ofs > doc_len) {
    783             write_enn (arg_own_buf);
    784             VG_(close) (fd);
    785             return;
    786          }
    787          VG_(lseek) (fd, ofs, VKI_SEEK_SET);
    788          len_read = VG_(read) (fd, toread, len);
    789          *new_packet_len_p = write_qxfer_response (arg_own_buf, (unsigned char *)toread,
    790                                                    len_read, ofs + len_read < doc_len);
    791          VG_(close) (fd);
    792          return;
    793       }
    794    }
    795 
    796    if (strncmp ("qXfer:auxv:read:", arg_own_buf, 16) == 0) {
    797       unsigned char *data;
    798       int n;
    799       CORE_ADDR ofs;
    800       unsigned int len;
    801       const char *annex;
    802 
    803       /* Reject any annex; grab the offset and length.  */
    804       if (decode_xfer_read (arg_own_buf + 16, &annex, &ofs, &len) < 0
    805           || annex[0] != '\0') {
    806          strcpy (arg_own_buf, "E00");
    807          return;
    808       }
    809 
    810       if (len > PBUFSIZ - 2)
    811          len = PBUFSIZ - 2;
    812       data = malloc (len);
    813 
    814       {
    815          UWord *client_auxv = VG_(client_auxv);
    816          unsigned int client_auxv_len = 0;
    817          while (*client_auxv != 0) {
    818             dlog(4, "auxv %lld %llx\n",
    819                  (ULong)*client_auxv,
    820                  (ULong)*(client_auxv+1));
    821             client_auxv++;
    822             client_auxv++;
    823             client_auxv_len += 2 * sizeof(UWord);
    824          }
    825          client_auxv_len += 2 * sizeof(UWord);
    826          dlog(4, "auxv len %d\n", client_auxv_len);
    827 
    828          if (ofs >= client_auxv_len)
    829             n = -1;
    830          else {
    831             n = client_auxv_len - ofs;
    832             VG_(memcpy) (data, (unsigned char *) VG_(client_auxv), n);
    833          }
    834       }
    835 
    836       if (n < 0)
    837          write_enn (arg_own_buf);
    838       else if (n > len)
    839          *new_packet_len_p = write_qxfer_response (arg_own_buf, data, len, 1);
    840       else
    841          *new_packet_len_p = write_qxfer_response (arg_own_buf, data, n, 0);
    842 
    843       free (data);
    844 
    845       return;
    846    }
    847 
    848 
    849    /* Protocol features query.  */
    850    if (strncmp ("qSupported", arg_own_buf, 10) == 0
    851        && (arg_own_buf[10] == ':' || arg_own_buf[10] == '\0')) {
    852       VG_(sprintf) (arg_own_buf, "PacketSize=%x", PBUFSIZ - 1);
    853       /* Note: max packet size including frame and checksum, but without
    854          trailing null byte, which is not sent/received. */
    855 
    856       strcat (arg_own_buf, ";QStartNoAckMode+");
    857       strcat (arg_own_buf, ";QPassSignals+");
    858       if (VG_(client_auxv))
    859          strcat (arg_own_buf, ";qXfer:auxv:read+");
    860 
    861       if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers)) != NULL) {
    862          strcat (arg_own_buf, ";qXfer:features:read+");
    863          /* if a new gdb connects to us, we have to reset the register
    864             set to the normal register sets to allow this new gdb to
    865             decide to use or not the shadow registers.
    866 
    867             Note that the reset is only done for gdb that are sending
    868             qSupported packets. If a user first connected with a recent
    869             gdb using shadow registers and then with a very old gdb
    870             that does not use qSupported packet, then the old gdb will
    871             not properly connect. */
    872          initialize_shadow_low(False);
    873       }
    874       return;
    875    }
    876 
    877    /* Otherwise we didn't know what packet it was.  Say we didn't
    878       understand it.  */
    879    arg_own_buf[0] = 0;
    880 }
    881 
    882 /* Handle all of the extended 'v' packets.  */
    883 static
    884 void handle_v_requests (char *arg_own_buf, char *status, int *zignal)
    885 {
    886    /* vcont packet code from gdb 6.6 removed */
    887 
    888    /* Otherwise we didn't know what packet it was.  Say we didn't
    889       understand it.  */
    890    arg_own_buf[0] = 0;
    891    return;
    892 }
    893 
    894 static
    895 void myresume (int step, int sig)
    896 {
    897    struct thread_resume resume_info[2];
    898    int n = 0;
    899 
    900    if (step || sig) {
    901       resume_info[0].step = step;
    902       resume_info[0].sig = sig;
    903       n++;
    904    }
    905    resume_info[n].step = 0;
    906    resume_info[n].sig = 0;
    907 
    908    resume_reply_packet_needed = True;
    909    valgrind_resume (resume_info);
    910 }
    911 
    912 /* server_main global variables */
    913 static char *own_buf;
    914 static unsigned char *mem_buf;
    915 
    916 void gdbserver_init (void)
    917 {
    918    dlog(1, "gdbserver_init gdbserver embedded in valgrind: %s\n", version);
    919    noack_mode = False;
    920    valgrind_initialize_target ();
    921    // After a fork, gdbserver_init can be called again.
    922    // We do not have to re-malloc the buffers in such a case.
    923    if (own_buf == NULL)
    924       own_buf = malloc (PBUFSIZ+POVERHSIZ);
    925    if (mem_buf == NULL)
    926       mem_buf = malloc (PBUFSIZ+POVERHSIZ);
    927    // Note: normally, we should only malloc PBUFSIZ. However,
    928    // GDB has a bug, and in some cases, sends e.g. 'm' packets
    929    // asking for slightly more than the PacketSize given at
    930    // connection initialisation. So, we bypass the GDB bug
    931    // by allocating slightly more.
    932 }
    933 
    934 void gdbserver_terminate (void)
    935 {
    936    /* last call to gdbserver is cleanup call */
    937    if (VG_MINIMAL_SETJMP(toplevel)) {
    938       dlog(0, "error caused VG_MINIMAL_LONGJMP to gdbserver_terminate\n");
    939       return;
    940    }
    941    remote_close();
    942 }
    943 
    944 void server_main (void)
    945 {
    946    static char status;
    947    static int zignal;
    948 
    949    char ch;
    950    int i = 0;
    951    unsigned int len;
    952    CORE_ADDR mem_addr;
    953 
    954    zignal = valgrind_wait (&status);
    955    if (VG_MINIMAL_SETJMP(toplevel)) {
    956       dlog(0, "error caused VG_MINIMAL_LONGJMP to server_main\n");
    957    }
    958    while (1) {
    959       unsigned char sig;
    960       int packet_len;
    961       int new_packet_len = -1;
    962 
    963       if (resume_reply_packet_needed) {
    964          /* Send the resume reply to reply to last GDB resume
    965             request. */
    966          resume_reply_packet_needed = False;
    967          prepare_resume_reply (own_buf, status, zignal);
    968          putpkt (own_buf);
    969       }
    970 
    971       /* If we our status is terminal (exit or fatal signal) get out
    972          as quickly as we can. We won't be able to handle any request
    973          anymore.  */
    974       if (status == 'W' || status == 'X') {
    975          return;
    976       }
    977 
    978       packet_len = getpkt (own_buf);
    979       if (packet_len <= 0)
    980          break;
    981 
    982       i = 0;
    983       ch = own_buf[i++];
    984       switch (ch) {
    985       case 'Q':
    986          handle_set (own_buf, &new_packet_len);
    987          break;
    988       case 'q':
    989          handle_query (own_buf, &new_packet_len);
    990          break;
    991       case 'd':
    992          /* set/unset debugging is done through valgrind debug level. */
    993          own_buf[0] = '\0';
    994          break;
    995       case 'D':
    996          reset_valgrind_sink("gdb detaching from process");
    997 
    998          /* When detaching or kill the process, gdb expects to get
    999             an packet OK back.  Any other output will make gdb
   1000             believes detach did not work. */
   1001          write_ok (own_buf);
   1002          putpkt (own_buf);
   1003          remote_finish (reset_after_error);
   1004          remote_open (VG_(clo_vgdb_prefix));
   1005          myresume (0, 0);
   1006          resume_reply_packet_needed = False;
   1007          return;
   1008       case '!':
   1009          /* We can not use the extended protocol with valgrind,
   1010             because we can not restart the running
   1011             program.  So return unrecognized.  */
   1012          own_buf[0] = '\0';
   1013          break;
   1014       case '?':
   1015          prepare_resume_reply (own_buf, status, zignal);
   1016          break;
   1017       case 'H':
   1018          if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's') {
   1019             unsigned long gdb_id, thread_id;
   1020 
   1021             gdb_id = strtoul (&own_buf[2], NULL, 16);
   1022             thread_id = gdb_id_to_thread_id (gdb_id);
   1023             if (thread_id == 0) {
   1024                write_enn (own_buf);
   1025                break;
   1026             }
   1027 
   1028             if (own_buf[1] == 'g') {
   1029                general_thread = thread_id;
   1030                set_desired_inferior (1);
   1031             } else if (own_buf[1] == 'c') {
   1032                cont_thread = thread_id;
   1033             } else if (own_buf[1] == 's') {
   1034                step_thread = thread_id;
   1035             }
   1036 
   1037             write_ok (own_buf);
   1038          } else {
   1039             /* Silently ignore it so that gdb can extend the protocol
   1040                without compatibility headaches.  */
   1041             own_buf[0] = '\0';
   1042          }
   1043          break;
   1044       case 'g':
   1045          set_desired_inferior (1);
   1046          registers_to_string (own_buf);
   1047          break;
   1048       case 'G':
   1049          set_desired_inferior (1);
   1050          registers_from_string (&own_buf[1]);
   1051          write_ok (own_buf);
   1052          break;
   1053       case 'P': {
   1054          int regno;
   1055          char *regbytes;
   1056          Bool mod;
   1057          ThreadState *tst;
   1058          regno = strtol(&own_buf[1], NULL, 16);
   1059          regbytes = strchr(&own_buf[0], '=') + 1;
   1060          set_desired_inferior (1);
   1061          tst = (ThreadState *) inferior_target_data (current_inferior);
   1062          /* Only accept changing registers in "runnable state3.
   1063             In fact, it would be ok to change most of the registers
   1064             except a few "sensitive" registers such as the PC, SP, BP.
   1065             We assume we do not need to very specific here, and that we
   1066             can just refuse all of these. */
   1067          if (tst->status == VgTs_Runnable || tst->status == VgTs_Yielding) {
   1068             supply_register_from_string (regno, regbytes, &mod);
   1069             write_ok (own_buf);
   1070          } else {
   1071             /* at least from gdb 6.6 onwards, an E. error
   1072                reply is shown to the user. So, we do an error
   1073                msg which both is accepted by gdb as an error msg
   1074                and is readable by the user. */
   1075             VG_(sprintf)
   1076                (own_buf,
   1077 "E.\n"
   1078 "ERROR changing register %s regno %d\n"
   1079 "gdb commands changing registers (pc, sp, ...) (e.g. 'jump',\n"
   1080 "set pc, calling from gdb a function in the debugged process, ...)\n"
   1081 "can only be accepted if the thread is VgTs_Runnable or VgTs_Yielding state\n"
   1082 "Thread status is %s\n",
   1083                 find_register_by_number (regno)->name, regno,
   1084                 VG_(name_of_ThreadStatus)(tst->status));
   1085             if (VG_(clo_verbosity) > 1)
   1086                VG_(umsg) ("%s\n", own_buf);
   1087          }
   1088          break;
   1089       }
   1090       case 'm':
   1091          decode_m_packet (&own_buf[1], &mem_addr, &len);
   1092          if (valgrind_read_memory (mem_addr, mem_buf, len) == 0)
   1093             convert_int_to_ascii (mem_buf, own_buf, len);
   1094          else
   1095             write_enn (own_buf);
   1096          break;
   1097       case 'M':
   1098          decode_M_packet (&own_buf[1], &mem_addr, &len, mem_buf);
   1099          if (valgrind_write_memory (mem_addr, mem_buf, len) == 0)
   1100             write_ok (own_buf);
   1101          else
   1102             write_enn (own_buf);
   1103          break;
   1104       case 'X':
   1105          if (decode_X_packet (&own_buf[1], packet_len - 1,
   1106                               &mem_addr, &len, mem_buf) < 0
   1107              || valgrind_write_memory (mem_addr, mem_buf, len) != 0)
   1108             write_enn (own_buf);
   1109          else
   1110             write_ok (own_buf);
   1111          break;
   1112       case 'C':
   1113          convert_ascii_to_int (own_buf + 1, &sig, 1);
   1114          if (target_signal_to_host_p (sig))
   1115             zignal = target_signal_to_host (sig);
   1116          else
   1117             zignal = 0;
   1118          set_desired_inferior (0);
   1119          myresume (0, zignal);
   1120          return; // return control to valgrind
   1121       case 'S':
   1122          convert_ascii_to_int (own_buf + 1, &sig, 1);
   1123          if (target_signal_to_host_p (sig))
   1124             zignal = target_signal_to_host (sig);
   1125          else
   1126             zignal = 0;
   1127          set_desired_inferior (0);
   1128          myresume (1, zignal);
   1129          return; // return control to valgrind
   1130       case 'c':
   1131          set_desired_inferior (0);
   1132          myresume (0, 0);
   1133          return; // return control to valgrind
   1134       case 's':
   1135          set_desired_inferior (0);
   1136          myresume (1, 0);
   1137          return; // return control to valgrind
   1138       case 'Z': {
   1139          char *lenptr;
   1140          char *dataptr;
   1141          CORE_ADDR addr = strtoul (&own_buf[3], &lenptr, 16);
   1142          int zlen = strtol (lenptr + 1, &dataptr, 16);
   1143          char type = own_buf[1];
   1144 
   1145          if (type < '0' || type > '4') {
   1146             /* Watchpoint command type unrecognized. */
   1147             own_buf[0] = '\0';
   1148          } else {
   1149             int res;
   1150 
   1151             res = valgrind_insert_watchpoint (type, addr, zlen);
   1152             if (res == 0)
   1153                write_ok (own_buf);
   1154             else if (res == 1)
   1155                /* Unsupported.  */
   1156                own_buf[0] = '\0';
   1157             else
   1158                write_enn (own_buf);
   1159          }
   1160          break;
   1161       }
   1162       case 'z': {
   1163          char *lenptr;
   1164          char *dataptr;
   1165          CORE_ADDR addr = strtoul (&own_buf[3], &lenptr, 16);
   1166          int zlen = strtol (lenptr + 1, &dataptr, 16);
   1167          char type = own_buf[1];
   1168 
   1169          if (type < '0' || type > '4') {
   1170             /* Watchpoint command type unrecognized. */
   1171             own_buf[0] = '\0';
   1172          } else {
   1173             int res;
   1174 
   1175             res = valgrind_remove_watchpoint (type, addr, zlen);
   1176             if (res == 0)
   1177                write_ok (own_buf);
   1178             else if (res == 1)
   1179                /* Unsupported.  */
   1180                own_buf[0] = '\0';
   1181             else
   1182                write_enn (own_buf);
   1183          }
   1184          break;
   1185       }
   1186       case 'k':
   1187          kill_request("Gdb request to kill this process\n");
   1188          break;
   1189       case 'T': {
   1190          unsigned long gdb_id, thread_id;
   1191 
   1192          gdb_id = strtoul (&own_buf[1], NULL, 16);
   1193          thread_id = gdb_id_to_thread_id (gdb_id);
   1194          if (thread_id == 0) {
   1195             write_enn (own_buf);
   1196             break;
   1197          }
   1198 
   1199          if (valgrind_thread_alive (thread_id))
   1200             write_ok (own_buf);
   1201          else
   1202             write_enn (own_buf);
   1203          break;
   1204       }
   1205       case 'R':
   1206          /* Restarting the inferior is only supported in the
   1207             extended protocol.
   1208             => It is a request we don't understand.  Respond with an
   1209             empty packet so that gdb knows that we don't support this
   1210             request.  */
   1211          own_buf[0] = '\0';
   1212          break;
   1213       case 'v':
   1214          /* Extended (long) request.  */
   1215          handle_v_requests (own_buf, &status, &zignal);
   1216          break;
   1217       default:
   1218          /* It is a request we don't understand.  Respond with an
   1219             empty packet so that gdb knows that we don't support this
   1220             request.  */
   1221          own_buf[0] = '\0';
   1222          break;
   1223       }
   1224 
   1225       if (new_packet_len != -1)
   1226          putpkt_binary (own_buf, new_packet_len);
   1227       else
   1228          putpkt (own_buf);
   1229 
   1230       if (status == 'W')
   1231          VG_(umsg) ("\nChild exited with status %d\n", zignal);
   1232       if (status == 'X')
   1233          VG_(umsg) ("\nChild terminated with signal = 0x%x (%s)\n",
   1234                     target_signal_to_host (zignal),
   1235                     target_signal_to_name (zignal));
   1236       if (status == 'W' || status == 'X') {
   1237          VG_(umsg) ("Process exiting\n");
   1238          VG_(exit) (0);
   1239       }
   1240    }
   1241 
   1242    /* We come here when getpkt fails => close the connection,
   1243       and re-open. Then return control to valgrind.
   1244       We return the control to valgrind as we assume that
   1245       the connection was closed due to vgdb having finished
   1246       to execute a command. */
   1247    if (VG_(clo_verbosity) > 1)
   1248       VG_(umsg) ("Remote side has terminated connection.  "
   1249                  "GDBserver will reopen the connection.\n");
   1250    remote_finish (reset_after_error);
   1251    remote_open (VG_(clo_vgdb_prefix));
   1252    myresume (0, 0);
   1253    resume_reply_packet_needed = False;
   1254    return;
   1255 }
   1256