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 
     31 unsigned long cont_thread;
     32 unsigned long general_thread;
     33 unsigned long step_thread;
     34 unsigned long thread_from_wait;
     35 unsigned long old_thread_from_wait;
     36 
     37 int pass_signals[TARGET_SIGNAL_LAST]; /* indexed by gdb signal nr */
     38 
     39 /* for a gdbserver integrated in valgrind, resuming the process consists
     40    in returning the control to valgrind.
     41    The guess process resumes its execution.
     42    Then at the next error or break or ..., valgrind calls gdbserver again.
     43    A resume reply packet must then be built to inform GDB that the
     44    resume request is finished.
     45    resume_reply_packet_needed records the fact that the next call to gdbserver
     46    must send a resume packet to gdb. */
     47 static Bool resume_reply_packet_needed = False;
     48 
     49 VG_MINIMAL_JMP_BUF(toplevel);
     50 
     51 /* Decode a qXfer read request.  Return 0 if everything looks OK,
     52    or -1 otherwise.  */
     53 
     54 static
     55 int decode_xfer_read (char *buf, char **annex, CORE_ADDR *ofs, unsigned int *len)
     56 {
     57    /* Extract and NUL-terminate the annex.  */
     58    *annex = buf;
     59    while (*buf && *buf != ':')
     60       buf++;
     61    if (*buf == '\0')
     62       return -1;
     63    *buf++ = 0;
     64 
     65    /* After the read/write marker and annex, qXfer looks like a
     66       traditional 'm' packet.  */
     67    decode_m_packet (buf, ofs, len);
     68 
     69    return 0;
     70 }
     71 
     72 /* Write the response to a successful qXfer read.  Returns the
     73    length of the (binary) data stored in BUF, corresponding
     74    to as much of DATA/LEN as we could fit.  IS_MORE controls
     75    the first character of the response.  */
     76 static
     77 int write_qxfer_response (char *buf, unsigned char *data, int len, int is_more)
     78 {
     79    int out_len;
     80 
     81    if (is_more)
     82       buf[0] = 'm';
     83    else
     84       buf[0] = 'l';
     85 
     86    return remote_escape_output (data, len, (unsigned char *) buf + 1, &out_len,
     87                                 PBUFSIZ - POVERHSIZ - 1) + 1;
     88 }
     89 
     90 static Bool initial_valgrind_sink_saved = False;
     91 /* True <=> valgrind log sink saved in initial_valgrind_sink */
     92 static OutputSink initial_valgrind_sink;
     93 
     94 static Bool command_output_to_log = False;
     95 /* True <=> command output goes to log instead of gdb */
     96 
     97 void reset_valgrind_sink(char *info)
     98 {
     99    if (VG_(log_output_sink).fd != initial_valgrind_sink.fd
    100        && initial_valgrind_sink_saved) {
    101       VG_(log_output_sink).fd = initial_valgrind_sink.fd;
    102       VG_(umsg) ("Reset valgrind output to log (%s)\n",
    103                  (info = NULL ? "" : info));
    104    }
    105 }
    106 
    107 static
    108 void kill_request (char *msg)
    109 {
    110    VG_(umsg) ("%s", msg);
    111    remote_close();
    112    VG_(exit) (0);
    113 }
    114 
    115 /* handle_gdb_valgrind_command handles the provided mon string command.
    116    If command is recognised, return 1 else return 0.
    117    Note that in case of ambiguous command, 1 is returned.
    118 
    119    *sink_wanted_at_return is modified if one of the commands
    120    'v.set *_output' is handled.
    121 */
    122 static
    123 int handle_gdb_valgrind_command (char* mon, OutputSink* sink_wanted_at_return)
    124 {
    125    UWord ret = 0;
    126    char s[strlen(mon)+1]; /* copy for strtok_r */
    127    char* wcmd;
    128    Char* ssaveptr;
    129    char* endptr;
    130    int   kwdid;
    131    int int_value;
    132 
    133    vg_assert (initial_valgrind_sink_saved);
    134 
    135    strcpy (s, mon);
    136    wcmd = strtok_r (s, " ", &ssaveptr);
    137    /* NB: if possible, avoid introducing a new command below which
    138       starts with the same 3 first letters as an already existing
    139       command. This ensures a shorter abbreviation for the user. */
    140    switch (VG_(keyword_id) ("help v.set v.info v.wait v.kill v.translate",
    141                             wcmd, kwd_report_duplicated_matches)) {
    142    case -2:
    143       ret = 1;
    144       break;
    145    case -1:
    146       break;
    147    case  0: /* help */
    148       ret = 1;
    149       wcmd = strtok_r (NULL, " ", &ssaveptr);
    150       if (wcmd == NULL) {
    151          int_value = 0;
    152       } else {
    153          switch (VG_(keyword_id) ("debug", wcmd, kwd_report_all)) {
    154          case -2: int_value = 0; break;
    155          case -1: int_value = 0; break;
    156          case  0: int_value = 1; break;
    157          default: tl_assert (0);
    158          }
    159       }
    160 
    161       VG_(gdb_printf) (
    162 "general valgrind monitor commands:\n"
    163 "  help [debug]             : monitor command help. With debug: + debugging commands\n"
    164 "  v.wait [<ms>]           : sleep <ms> (default 0) then continue\n"
    165 "  v.info all_errors       : show all errors found so far\n"
    166 "  v.info last_error       : show last error found\n"
    167 "  v.info n_errs_found     : show the nr of errors found so far\n"
    168 "  v.kill                  : kill the Valgrind process\n"
    169 "  v.set gdb_output        : set valgrind output to gdb\n"
    170 "  v.set log_output        : set valgrind output to log\n"
    171 "  v.set mixed_output      : set valgrind output to log, interactive output to gdb\n"
    172 "  v.set vgdb-error <errornr> : debug me at error >= <errornr> \n");
    173       if (int_value) { VG_(gdb_printf) (
    174 "debugging valgrind internals monitor commands:\n"
    175 "  v.info gdbserver_status : show gdbserver status\n"
    176 "  v.info memory [aspacemgr] : show valgrind heap memory stats\n"
    177 "     (with aspacemgr arg, also shows valgrind segments on log ouput)\n"
    178 "  v.info scheduler        : show valgrind thread state and stacktrace\n"
    179 "  v.set debuglog <level>  : set valgrind debug log level to <level>\n"
    180 "  v.translate <addr> [<traceflags>]  : debug translation of <addr> with <traceflags>\n"
    181 "    (default traceflags 0b00100000 : show after instrumentation)\n"
    182 "   An additional flag  0b100000000 allows to show gdbserver instrumentation\n");
    183       }
    184       break;
    185    case  1: /* v.set */
    186       ret = 1;
    187       wcmd = strtok_r (NULL, " ", &ssaveptr);
    188       switch (kwdid = VG_(keyword_id)
    189               ("vgdb-error debuglog gdb_output log_output mixed_output",
    190                wcmd, kwd_report_all)) {
    191       case -2:
    192       case -1:
    193          break;
    194       case 0: /* vgdb-error */
    195       case 1: /* debuglog */
    196          wcmd = strtok_r (NULL, " ", &ssaveptr);
    197          if (wcmd == NULL) {
    198             int_value = 0;
    199             endptr = "empty"; /* to report an error below */
    200          } else {
    201             int_value = strtol (wcmd, &endptr, 10);
    202          }
    203          if (*endptr != '\0') {
    204             VG_(gdb_printf) ("missing or malformed integer value\n");
    205          } else if (kwdid == 0) {
    206             VG_(gdb_printf) ("vgdb-error value changed from %d to %d\n",
    207                              VG_(dyn_vgdb_error), int_value);
    208             VG_(dyn_vgdb_error) = int_value;
    209          } else if (kwdid == 1) {
    210             VG_(gdb_printf) ("debuglog value changed from %d to %d\n",
    211                              VG_(debugLog_getLevel)(), int_value);
    212             VG_(debugLog_startup) (int_value, "gdbsrv");
    213          } else {
    214             vg_assert (0);
    215          }
    216          break;
    217       case 2: /* gdb_output */
    218          (*sink_wanted_at_return).fd = -2;
    219          command_output_to_log = False;
    220          VG_(gdb_printf) ("valgrind output will go to gdb\n");
    221          break;
    222       case 3: /* log_output */
    223          (*sink_wanted_at_return).fd = initial_valgrind_sink.fd;
    224          command_output_to_log = True;
    225          VG_(gdb_printf) ("valgrind output will go to log\n");
    226          break;
    227       case 4: /* mixed output */
    228          (*sink_wanted_at_return).fd = initial_valgrind_sink.fd;
    229          command_output_to_log = False;
    230          VG_(gdb_printf)
    231             ("valgrind output will go to log, interactive output will go to gdb\n");
    232          break;
    233       default:
    234          vg_assert (0);
    235       }
    236       break;
    237    case  2: /* v.info */ {
    238       ret = 1;
    239       wcmd = strtok_r (NULL, " ", &ssaveptr);
    240       switch (kwdid = VG_(keyword_id)
    241               ("all_errors n_errs_found last_error gdbserver_status memory"
    242                " scheduler",
    243                wcmd, kwd_report_all)) {
    244       case -2:
    245       case -1:
    246          break;
    247       case 0: // all_errors
    248          // A verbosity of minimum 2 is needed to show the errors.
    249          VG_(show_all_errors)(/* verbosity */ 2, /* xml */ False);
    250          break;
    251       case  1: // n_errs_found
    252          VG_(gdb_printf) ("n_errs_found %d n_errs_shown %d (vgdb-error %d)\n",
    253                           VG_(get_n_errs_found) (),
    254                           VG_(get_n_errs_shown) (),
    255                           VG_(dyn_vgdb_error));
    256          break;
    257       case 2: // last_error
    258          VG_(show_last_error)();
    259          break;
    260       case  3: // gdbserver_status
    261          VG_(gdbserver_status_output)();
    262          break;
    263       case  4: /* memory */
    264          VG_(print_all_arena_stats) ();
    265          if (VG_(clo_profile_heap))
    266             VG_(print_arena_cc_analysis) ();
    267          wcmd = strtok_r (NULL, " ", &ssaveptr);
    268          if (wcmd != NULL) {
    269             switch (VG_(keyword_id) ("aspacemgr", wcmd, kwd_report_all)) {
    270             case -2:
    271             case -1: break;
    272             case  0:
    273                VG_(am_show_nsegments) (0, "gdbserver v.info memory aspacemgr");
    274                break;
    275             default: tl_assert (0);
    276             }
    277          }
    278 
    279          ret = 1;
    280          break;
    281       case  5: /* scheduler */
    282          VG_(show_sched_status) ();
    283          ret = 1;
    284          break;
    285       default:
    286          vg_assert(0);
    287       }
    288       break;
    289    }
    290    case  3: /* v.wait */
    291       wcmd = strtok_r (NULL, " ", &ssaveptr);
    292       if (wcmd != NULL) {
    293          int_value = strtol (wcmd, &endptr, 10);
    294          VG_(gdb_printf) ("gdbserver: continuing in %d ms ...\n", int_value);
    295          VG_(poll)(NULL, 0, int_value);
    296       }
    297       VG_(gdb_printf) ("gdbserver: continuing after wait ...\n");
    298       ret = 1;
    299       break;
    300    case  4: /* v.kill */
    301       kill_request ("monitor command request to kill this process\n");
    302       break;
    303    case  5: { /* v.translate */
    304       Addr address;
    305       SizeT verbosity = 0x20;
    306 
    307       ret = 1;
    308 
    309       VG_(strtok_get_address_and_size) (&address, &verbosity, &ssaveptr);
    310       if (address != (Addr) 0 || verbosity != 0) {
    311          /* we need to force the output to log for the translation trace,
    312             as low level VEX tracing cannot be redirected to gdb. */
    313          int saved_command_output_to_log = command_output_to_log;
    314          int saved_fd = VG_(log_output_sink).fd;
    315          Bool single_stepping_on_entry = valgrind_single_stepping();
    316          int vex_verbosity = verbosity & 0xff;
    317          VG_(log_output_sink).fd = initial_valgrind_sink.fd;
    318          if ((verbosity & 0x100) && !single_stepping_on_entry) {
    319             valgrind_set_single_stepping(True);
    320             // to force gdbserver instrumentation.
    321          }
    322 #        if defined(VGA_arm)
    323          // on arm, we need to (potentially) convert this address
    324          // to the thumb form.
    325          address = thumb_pc (address);
    326 #        endif
    327 
    328          VG_(translate) ( 0 /* dummy ThreadId; irrelevant due to debugging*/,
    329                           address,
    330                           /*debugging*/True,
    331                           (Int) vex_verbosity,
    332                           /*bbs_done*/0,
    333                           /*allow redir?*/True);
    334          if ((verbosity & 0x100) && !single_stepping_on_entry) {
    335             valgrind_set_single_stepping(False);
    336             // reset single stepping.
    337          }
    338          command_output_to_log = saved_command_output_to_log;
    339          VG_(log_output_sink).fd = saved_fd;
    340       }
    341       break;
    342    }
    343 
    344    default:
    345       vg_assert (0);
    346    }
    347    return ret;
    348 }
    349 
    350 /* handle_gdb_monitor_command handles the provided mon string command,
    351    which can be either a "standard" valgrind monitor command
    352    or a tool specific monitor command.
    353    If command recognised, return 1 else return 0.
    354    Note that in case of ambiguous command, 1 is returned.
    355 */
    356 static
    357 int handle_gdb_monitor_command (char* mon)
    358 {
    359    UWord ret = 0;
    360    UWord tool_ret = 0;
    361    // initially, we assume that when returning, the desired sink is the
    362    // one we have when entering. It can however be changed by the standard
    363    // valgrind command handling.
    364    OutputSink sink_wanted_at_return = VG_(log_output_sink);
    365 
    366    if (!initial_valgrind_sink_saved) {
    367       /* first time we enter here, we save the valgrind default log sink */
    368       initial_valgrind_sink = sink_wanted_at_return;
    369       initial_valgrind_sink_saved = True;
    370    }
    371 
    372    if (!command_output_to_log)
    373       VG_(log_output_sink).fd = -2; /* redirect to monitor_output */
    374 
    375    ret = handle_gdb_valgrind_command (mon, &sink_wanted_at_return);
    376 
    377    /* Even if command was recognised by valgrind core, we call the
    378       tool command handler : this is needed to handle help command
    379       and/or to let the tool do some additional processing of a
    380       valgrind standard command. Note however that if valgrind
    381       recognised the command, we will always return success. */
    382    if (VG_(needs).client_requests) {
    383       /* If the tool reports an error when handling a monitor command,
    384          we need to avoid calling gdbserver during this command
    385          handling. So, we temporarily set VG_(dyn_vgdb_error) to
    386          a huge value to ensure m_errormgr.c does not call gdbserver. */
    387       Int save_dyn_vgdb_error = VG_(dyn_vgdb_error);
    388       UWord arg[2];
    389       VG_(dyn_vgdb_error) = 999999999;
    390       arg[0] = (UWord) VG_USERREQ__GDB_MONITOR_COMMAND;
    391       arg[1] = (UWord) mon;
    392       VG_TDICT_CALL(tool_handle_client_request, VG_(running_tid), arg,
    393                     &tool_ret);
    394       VG_(dyn_vgdb_error) = save_dyn_vgdb_error;
    395    }
    396 
    397    /* restore or set the desired output */
    398    VG_(log_output_sink).fd = sink_wanted_at_return.fd;
    399    if (ret | tool_ret)
    400       return 1;
    401    else
    402       return 0;
    403 }
    404 
    405 
    406 /* Handle all of the extended 'Q' packets.  */
    407 static
    408 void handle_set (char *arg_own_buf, int *new_packet_len_p)
    409 {
    410    if (strcmp ("QStartNoAckMode", arg_own_buf) == 0) {
    411       noack_mode = True;
    412       write_ok (arg_own_buf);
    413       return;
    414    }
    415 
    416    if (strncmp ("QPassSignals:", arg_own_buf, 13) == 0) {
    417       int i;
    418       char *from, *to;
    419       char *end = arg_own_buf + strlen(arg_own_buf);
    420       CORE_ADDR sig;
    421       for (i = 0; i < TARGET_SIGNAL_LAST; i++)
    422          pass_signals[i] = 0;
    423 
    424       from = arg_own_buf + 13;
    425       while (from < end) {
    426          to = strchr(from, ';');
    427          if (to == NULL) to = end;
    428          decode_address (&sig, from, to - from);
    429          pass_signals[(int)sig] = 1;
    430          dlog(1, "pass_signal gdb_nr %d %s\n",
    431               (int)sig, target_signal_to_name(sig));
    432          from = to;
    433          if (*from == ';') from++;
    434       }
    435       write_ok (arg_own_buf);
    436       return;
    437    }
    438    /* Otherwise we didn't know what packet it was.  Say we didn't
    439       understand it.  */
    440    arg_own_buf[0] = 0;
    441 }
    442 
    443 /* Handle all of the extended 'q' packets.  */
    444 static
    445 void handle_query (char *arg_own_buf, int *new_packet_len_p)
    446 {
    447    static struct inferior_list_entry *thread_ptr;
    448 
    449    /* qRcmd, monitor command handling.  */
    450    if (strncmp ("qRcmd,", arg_own_buf, 6) == 0) {
    451       char *p = arg_own_buf + 6;
    452       int cmdlen = strlen(p)/2;
    453       char cmd[cmdlen+1];
    454 
    455       if (unhexify (cmd, p, cmdlen) != cmdlen) {
    456          write_enn (arg_own_buf);
    457          return;
    458       }
    459       cmd[cmdlen] = '\0';
    460 
    461       if (handle_gdb_monitor_command (cmd)) {
    462          /* In case the command is from a standalone vgdb,
    463             connection will be closed soon => flush the output. */
    464          VG_(message_flush) ();
    465          write_ok (arg_own_buf);
    466          return;
    467       } else {
    468          /* cmd not recognised */
    469          VG_(gdb_printf)
    470             ("command '%s' not recognised\n"
    471              "In gdb,     try 'monitor help'\n"
    472              "In a shell, try 'vgdb help'\n",
    473              cmd);
    474          write_ok (arg_own_buf);
    475          return;
    476       }
    477    }
    478 
    479    /* provide some valgrind specific info in return to qThreadExtraInfo. */
    480    if (strncmp ("qThreadExtraInfo,", arg_own_buf, 17) == 0) {
    481       unsigned long gdb_id;
    482       struct thread_info *ti;
    483       ThreadState *tst;
    484       char status[100];
    485 
    486       gdb_id = strtoul (&arg_own_buf[17], NULL, 16);
    487       ti = gdb_id_to_thread (gdb_id);
    488       if (ti != NULL) {
    489          tst = (ThreadState *) inferior_target_data (ti);
    490          /* Additional info is the tid and the thread status. */
    491          VG_(snprintf) (status, sizeof(status), "tid %d %s",
    492                         tst->tid,
    493                         VG_(name_of_ThreadStatus)(tst->status));
    494          hexify (arg_own_buf, status, strlen(status));
    495          return;
    496       } else {
    497          write_enn (arg_own_buf);
    498          return;
    499       }
    500    }
    501 
    502    if (strcmp ("qAttached", arg_own_buf) == 0) {
    503       /* tell gdb to always detach, never kill the process */
    504       arg_own_buf[0] = '1';
    505       arg_own_buf[1] = 0;
    506       return;
    507    }
    508 
    509    if (strcmp ("qSymbol::", arg_own_buf) == 0) {
    510       /* We have no symbol to read. */
    511       write_ok (arg_own_buf);
    512       return;
    513    }
    514 
    515    if (strcmp ("qfThreadInfo", arg_own_buf) == 0) {
    516       thread_ptr = all_threads.head;
    517       VG_(sprintf) (arg_own_buf, "m%x",
    518                     thread_to_gdb_id ((struct thread_info *)thread_ptr));
    519       thread_ptr = thread_ptr->next;
    520       return;
    521    }
    522 
    523    if (strcmp ("qsThreadInfo", arg_own_buf) == 0) {
    524       if (thread_ptr != NULL) {
    525          VG_(sprintf) (arg_own_buf, "m%x",
    526                        thread_to_gdb_id ((struct thread_info *)thread_ptr));
    527          thread_ptr = thread_ptr->next;
    528          return;
    529       } else {
    530          VG_(sprintf) (arg_own_buf, "l");
    531          return;
    532       }
    533    }
    534 
    535    if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers)) != NULL
    536         && strncmp ("qXfer:features:read:", arg_own_buf, 20) == 0) {
    537       CORE_ADDR ofs;
    538       unsigned int len, doc_len;
    539       char *annex = NULL;
    540       // First, the annex is extracted from the packet received.
    541       // Then, it is replaced by the corresponding file name.
    542       int fd;
    543 
    544       /* Grab the annex, offset, and length.  */
    545       if (decode_xfer_read (arg_own_buf + 20, &annex, &ofs, &len) < 0) {
    546          strcpy (arg_own_buf, "E00");
    547          return;
    548       }
    549 
    550       if (strcmp (annex, "target.xml") == 0) {
    551          annex = valgrind_target_xml(VG_(clo_vgdb_shadow_registers));
    552          if (annex != NULL && VG_(clo_vgdb_shadow_registers)) {
    553             /* Ensure the shadow registers are initialized. */
    554             initialize_shadow_low(True);
    555          }
    556          if (annex == NULL) {
    557             strcpy (arg_own_buf, "E00");
    558             return;
    559          }
    560       }
    561 
    562       {
    563          char doc[VG_(strlen)(VG_(libdir)) + 1 + VG_(strlen)(annex) + 1];
    564          struct vg_stat stat_doc;
    565          char toread[len];
    566          int len_read;
    567 
    568          VG_(sprintf)(doc, "%s/%s", VG_(libdir), annex);
    569          fd = VG_(fd_open) (doc, VKI_O_RDONLY, 0);
    570          if (fd == -1) {
    571             strcpy (arg_own_buf, "E00");
    572             return;
    573          }
    574          if (VG_(fstat) (fd, &stat_doc) != 0) {
    575             VG_(close) (fd);
    576             strcpy (arg_own_buf, "E00");
    577             return;
    578          }
    579          doc_len = stat_doc.size;
    580 
    581          if (len > PBUFSIZ - POVERHSIZ)
    582             len = PBUFSIZ - POVERHSIZ;
    583 
    584          if (ofs > doc_len) {
    585             write_enn (arg_own_buf);
    586             VG_(close) (fd);
    587             return;
    588          }
    589          VG_(lseek) (fd, ofs, VKI_SEEK_SET);
    590          len_read = VG_(read) (fd, toread, len);
    591          *new_packet_len_p = write_qxfer_response (arg_own_buf, toread,
    592                                                    len_read, ofs + len_read < doc_len);
    593          VG_(close) (fd);
    594          return;
    595       }
    596    }
    597 
    598    if (strncmp ("qXfer:auxv:read:", arg_own_buf, 16) == 0) {
    599       unsigned char *data;
    600       int n;
    601       CORE_ADDR ofs;
    602       unsigned int len;
    603       char *annex;
    604 
    605       /* Reject any annex; grab the offset and length.  */
    606       if (decode_xfer_read (arg_own_buf + 16, &annex, &ofs, &len) < 0
    607           || annex[0] != '\0') {
    608          strcpy (arg_own_buf, "E00");
    609          return;
    610       }
    611 
    612       if (len > PBUFSIZ - 2)
    613          len = PBUFSIZ - 2;
    614       data = malloc (len);
    615 
    616       {
    617          UWord *client_auxv = VG_(client_auxv);
    618          unsigned int client_auxv_len = 0;
    619          while (*client_auxv != 0) {
    620             dlog(4, "auxv %lld %llx\n",
    621                  (ULong)*client_auxv,
    622                  (ULong)*(client_auxv+1));
    623             client_auxv++;
    624             client_auxv++;
    625             client_auxv_len += 2 * sizeof(UWord);
    626          }
    627          client_auxv_len += 2 * sizeof(UWord);
    628          dlog(4, "auxv len %d\n", client_auxv_len);
    629 
    630          if (ofs >= client_auxv_len)
    631             n = -1;
    632          else {
    633             n = client_auxv_len - ofs;
    634             VG_(memcpy) (data, (unsigned char *) VG_(client_auxv), n);
    635          }
    636       }
    637 
    638       if (n < 0)
    639          write_enn (arg_own_buf);
    640       else if (n > len)
    641          *new_packet_len_p = write_qxfer_response (arg_own_buf, data, len, 1);
    642       else
    643          *new_packet_len_p = write_qxfer_response (arg_own_buf, data, n, 0);
    644 
    645       free (data);
    646 
    647       return;
    648    }
    649 
    650 
    651    /* Protocol features query.  */
    652    if (strncmp ("qSupported", arg_own_buf, 10) == 0
    653        && (arg_own_buf[10] == ':' || arg_own_buf[10] == '\0')) {
    654       VG_(sprintf) (arg_own_buf, "PacketSize=%x", PBUFSIZ - 1);
    655       /* Note: max packet size including frame and checksum, but without
    656          trailing null byte, which is not sent/received. */
    657 
    658       strcat (arg_own_buf, ";QStartNoAckMode+");
    659       strcat (arg_own_buf, ";QPassSignals+");
    660       if (VG_(client_auxv))
    661          strcat (arg_own_buf, ";qXfer:auxv:read+");
    662 
    663       if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers)) != NULL) {
    664          strcat (arg_own_buf, ";qXfer:features:read+");
    665          /* if a new gdb connects to us, we have to reset the register
    666             set to the normal register sets to allow this new gdb to
    667             decide to use or not the shadow registers.
    668 
    669             Note that the reset is only done for gdb that are sending
    670             qSupported packets. If a user first connected with a recent
    671             gdb using shadow registers and then with a very old gdb
    672             that does not use qSupported packet, then the old gdb will
    673             not properly connect. */
    674          initialize_shadow_low(False);
    675       }
    676       return;
    677    }
    678 
    679    /* Otherwise we didn't know what packet it was.  Say we didn't
    680       understand it.  */
    681    arg_own_buf[0] = 0;
    682 }
    683 
    684 /* Handle all of the extended 'v' packets.  */
    685 static
    686 void handle_v_requests (char *arg_own_buf, char *status, int *zignal)
    687 {
    688    /* vcont packet code from gdb 6.6 removed */
    689 
    690    /* Otherwise we didn't know what packet it was.  Say we didn't
    691       understand it.  */
    692    arg_own_buf[0] = 0;
    693    return;
    694 }
    695 
    696 static
    697 void myresume (int step, int sig)
    698 {
    699    struct thread_resume resume_info[2];
    700    int n = 0;
    701 
    702    if (step || sig) {
    703       resume_info[0].step = step;
    704       resume_info[0].sig = sig;
    705       n++;
    706    }
    707    resume_info[n].step = 0;
    708    resume_info[n].sig = 0;
    709 
    710    resume_reply_packet_needed = True;
    711    valgrind_resume (resume_info);
    712 }
    713 
    714 /* server_main global variables */
    715 static char *own_buf;
    716 static unsigned char *mem_buf;
    717 
    718 void gdbserver_init (void)
    719 {
    720    dlog(1, "gdbserver_init gdbserver embedded in valgrind: %s\n", version);
    721    noack_mode = False;
    722    valgrind_initialize_target ();
    723    // After a fork, gdbserver_init can be called again.
    724    // We do not have to re-malloc the buffers in such a case.
    725    if (own_buf == NULL)
    726       own_buf = malloc (PBUFSIZ);
    727    if (mem_buf == NULL)
    728       mem_buf = malloc (PBUFSIZ);
    729 }
    730 
    731 void gdbserver_terminate (void)
    732 {
    733    /* last call to gdbserver is cleanup call */
    734    if (VG_MINIMAL_SETJMP(toplevel)) {
    735       dlog(0, "error caused VG_MINIMAL_LONGJMP to gdbserver_terminate\n");
    736       return;
    737    }
    738    remote_close();
    739 }
    740 
    741 void server_main (void)
    742 {
    743    static char status;
    744    static int zignal;
    745 
    746    char ch;
    747    int i = 0;
    748    unsigned int len;
    749    CORE_ADDR mem_addr;
    750 
    751    zignal = valgrind_wait (&status);
    752    if (VG_MINIMAL_SETJMP(toplevel)) {
    753       dlog(0, "error caused VG_MINIMAL_LONGJMP to server_main\n");
    754    }
    755    while (1) {
    756       unsigned char sig;
    757       int packet_len;
    758       int new_packet_len = -1;
    759 
    760       if (resume_reply_packet_needed) {
    761          /* Send the resume reply to reply to last GDB resume
    762             request. */
    763          resume_reply_packet_needed = False;
    764          prepare_resume_reply (own_buf, status, zignal);
    765          putpkt (own_buf);
    766       }
    767 
    768       packet_len = getpkt (own_buf);
    769       if (packet_len <= 0)
    770          break;
    771 
    772       i = 0;
    773       ch = own_buf[i++];
    774       switch (ch) {
    775       case 'Q':
    776          handle_set (own_buf, &new_packet_len);
    777          break;
    778       case 'q':
    779          handle_query (own_buf, &new_packet_len);
    780          break;
    781       case 'd':
    782          /* set/unset debugging is done through valgrind debug level. */
    783          own_buf[0] = '\0';
    784          break;
    785       case 'D':
    786          reset_valgrind_sink("gdb detaching from process");
    787 
    788          /* When detaching or kill the process, gdb expects to get
    789             an packet OK back.  Any other output will make gdb
    790             believes detach did not work. */
    791          write_ok (own_buf);
    792          putpkt (own_buf);
    793          remote_finish (reset_after_error);
    794          remote_open (VG_(clo_vgdb_prefix));
    795          myresume (0, 0);
    796          resume_reply_packet_needed = False;
    797          return;
    798       case '!':
    799          /* We can not use the extended protocol with valgrind,
    800             because we can not restart the running
    801             program.  So return unrecognized.  */
    802          own_buf[0] = '\0';
    803          break;
    804       case '?':
    805          prepare_resume_reply (own_buf, status, zignal);
    806          break;
    807       case 'H':
    808          if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's') {
    809             unsigned long gdb_id, thread_id;
    810 
    811             gdb_id = strtoul (&own_buf[2], NULL, 16);
    812             thread_id = gdb_id_to_thread_id (gdb_id);
    813             if (thread_id == 0) {
    814                write_enn (own_buf);
    815                break;
    816             }
    817 
    818             if (own_buf[1] == 'g') {
    819                general_thread = thread_id;
    820                set_desired_inferior (1);
    821             } else if (own_buf[1] == 'c') {
    822                cont_thread = thread_id;
    823             } else if (own_buf[1] == 's') {
    824                step_thread = thread_id;
    825             }
    826 
    827             write_ok (own_buf);
    828          } else {
    829             /* Silently ignore it so that gdb can extend the protocol
    830                without compatibility headaches.  */
    831             own_buf[0] = '\0';
    832          }
    833          break;
    834       case 'g':
    835          set_desired_inferior (1);
    836          registers_to_string (own_buf);
    837          break;
    838       case 'G':
    839          set_desired_inferior (1);
    840          registers_from_string (&own_buf[1]);
    841          write_ok (own_buf);
    842          break;
    843       case 'P': {
    844          int regno;
    845          char *regbytes;
    846          Bool mod;
    847          ThreadState *tst;
    848          regno = strtol(&own_buf[1], NULL, 16);
    849          regbytes = strchr(&own_buf[0], '=') + 1;
    850          set_desired_inferior (1);
    851          tst = (ThreadState *) inferior_target_data (current_inferior);
    852          /* Only accept changing registers in "runnable state3.
    853             In fact, it would be ok to change most of the registers
    854             except a few "sensitive" registers such as the PC, SP, BP.
    855             We assume we do not need to very specific here, and that we
    856             can just refuse all of these. */
    857          if (tst->status == VgTs_Runnable || tst->status == VgTs_Yielding) {
    858             supply_register_from_string (regno, regbytes, &mod);
    859             write_ok (own_buf);
    860          } else {
    861             /* at least from gdb 6.6 onwards, an E. error
    862                reply is shown to the user. So, we do an error
    863                msg which both is accepted by gdb as an error msg
    864                and is readable by the user. */
    865             VG_(sprintf)
    866                (own_buf,
    867 "E.\n"
    868 "ERROR changing register %s regno %d\n"
    869 "gdb commands changing registers (pc, sp, ...) (e.g. 'jump',\n"
    870 "set pc, calling from gdb a function in the debugged process, ...)\n"
    871 "can only be accepted if the thread is VgTs_Runnable or VgTs_Yielding state\n"
    872 "Thread status is %s\n",
    873                 find_register_by_number (regno)->name, regno,
    874                 VG_(name_of_ThreadStatus)(tst->status));
    875             if (VG_(clo_verbosity) > 1)
    876                VG_(umsg) ("%s\n", own_buf);
    877          }
    878          break;
    879       }
    880       case 'm':
    881          decode_m_packet (&own_buf[1], &mem_addr, &len);
    882          if (valgrind_read_memory (mem_addr, mem_buf, len) == 0)
    883             convert_int_to_ascii (mem_buf, own_buf, len);
    884          else
    885             write_enn (own_buf);
    886          break;
    887       case 'M':
    888          decode_M_packet (&own_buf[1], &mem_addr, &len, mem_buf);
    889          if (valgrind_write_memory (mem_addr, mem_buf, len) == 0)
    890             write_ok (own_buf);
    891          else
    892             write_enn (own_buf);
    893          break;
    894       case 'X':
    895          if (decode_X_packet (&own_buf[1], packet_len - 1,
    896                               &mem_addr, &len, mem_buf) < 0
    897              || valgrind_write_memory (mem_addr, mem_buf, len) != 0)
    898             write_enn (own_buf);
    899          else
    900             write_ok (own_buf);
    901          break;
    902       case 'C':
    903          convert_ascii_to_int (own_buf + 1, &sig, 1);
    904          if (target_signal_to_host_p (sig))
    905             zignal = target_signal_to_host (sig);
    906          else
    907             zignal = 0;
    908          set_desired_inferior (0);
    909          myresume (0, zignal);
    910          return; // return control to valgrind
    911       case 'S':
    912          convert_ascii_to_int (own_buf + 1, &sig, 1);
    913          if (target_signal_to_host_p (sig))
    914             zignal = target_signal_to_host (sig);
    915          else
    916             zignal = 0;
    917          set_desired_inferior (0);
    918          myresume (1, zignal);
    919          return; // return control to valgrind
    920       case 'c':
    921          set_desired_inferior (0);
    922          myresume (0, 0);
    923          return; // return control to valgrind
    924       case 's':
    925          set_desired_inferior (0);
    926          myresume (1, 0);
    927          return; // return control to valgrind
    928       case 'Z': {
    929          char *lenptr;
    930          char *dataptr;
    931          CORE_ADDR addr = strtoul (&own_buf[3], &lenptr, 16);
    932          int zlen = strtol (lenptr + 1, &dataptr, 16);
    933          char type = own_buf[1];
    934 
    935          if (type < '0' || type > '4') {
    936             /* Watchpoint command type unrecognized. */
    937             own_buf[0] = '\0';
    938          } else {
    939             int res;
    940 
    941             res = valgrind_insert_watchpoint (type, addr, zlen);
    942             if (res == 0)
    943                write_ok (own_buf);
    944             else if (res == 1)
    945                /* Unsupported.  */
    946                own_buf[0] = '\0';
    947             else
    948                write_enn (own_buf);
    949          }
    950          break;
    951       }
    952       case 'z': {
    953          char *lenptr;
    954          char *dataptr;
    955          CORE_ADDR addr = strtoul (&own_buf[3], &lenptr, 16);
    956          int zlen = strtol (lenptr + 1, &dataptr, 16);
    957          char type = own_buf[1];
    958 
    959          if (type < '0' || type > '4') {
    960             /* Watchpoint command type unrecognized. */
    961             own_buf[0] = '\0';
    962          } else {
    963             int res;
    964 
    965             res = valgrind_remove_watchpoint (type, addr, zlen);
    966             if (res == 0)
    967                write_ok (own_buf);
    968             else if (res == 1)
    969                /* Unsupported.  */
    970                own_buf[0] = '\0';
    971             else
    972                write_enn (own_buf);
    973          }
    974          break;
    975       }
    976       case 'k':
    977          kill_request("Gdb request to kill this process\n");
    978          break;
    979       case 'T': {
    980          unsigned long gdb_id, thread_id;
    981 
    982          gdb_id = strtoul (&own_buf[1], NULL, 16);
    983          thread_id = gdb_id_to_thread_id (gdb_id);
    984          if (thread_id == 0) {
    985             write_enn (own_buf);
    986             break;
    987          }
    988 
    989          if (valgrind_thread_alive (thread_id))
    990             write_ok (own_buf);
    991          else
    992             write_enn (own_buf);
    993          break;
    994       }
    995       case 'R':
    996          /* Restarting the inferior is only supported in the
    997             extended protocol.
    998             => It is a request we don't understand.  Respond with an
    999             empty packet so that gdb knows that we don't support this
   1000             request.  */
   1001          own_buf[0] = '\0';
   1002          break;
   1003       case 'v':
   1004          /* Extended (long) request.  */
   1005          handle_v_requests (own_buf, &status, &zignal);
   1006          break;
   1007       default:
   1008          /* It is a request we don't understand.  Respond with an
   1009             empty packet so that gdb knows that we don't support this
   1010             request.  */
   1011          own_buf[0] = '\0';
   1012          break;
   1013       }
   1014 
   1015       if (new_packet_len != -1)
   1016          putpkt_binary (own_buf, new_packet_len);
   1017       else
   1018          putpkt (own_buf);
   1019 
   1020       if (status == 'W')
   1021          VG_(umsg) ("\nChild exited with status %d\n", zignal);
   1022       if (status == 'X')
   1023          VG_(umsg) ("\nChild terminated with signal = 0x%x (%s)\n",
   1024                     target_signal_to_host (zignal),
   1025                     target_signal_to_name (zignal));
   1026       if (status == 'W' || status == 'X') {
   1027          VG_(umsg) ("Process exiting\n");
   1028          VG_(exit) (0);
   1029       }
   1030    }
   1031 
   1032    /* We come here when getpkt fails => close the connection,
   1033       and re-open. Then return control to valgrind.
   1034       We return the control to valgrind as we assume that
   1035       the connection was closed due to vgdb having finished
   1036       to execute a command. */
   1037    if (VG_(clo_verbosity) > 1)
   1038       VG_(umsg) ("Remote side has terminated connection.  "
   1039                  "GDBserver will reopen the connection.\n");
   1040    remote_finish (reset_after_error);
   1041    remote_open (VG_(clo_vgdb_prefix));
   1042    myresume (0, 0);
   1043    resume_reply_packet_needed = False;
   1044    return;
   1045 }
   1046