Home | History | Annotate | Download | only in m_gdbserver
      1 
      2 /*--------------------------------------------------------------------*/
      3 /*--- Handle remote gdb protocol.                    m_gdbserver.c ---*/
      4 /*--------------------------------------------------------------------*/
      5 
      6 /*
      7    This file is part of Valgrind, a dynamic binary instrumentation
      8    framework.
      9 
     10    Copyright (C) 2011-2012 Philippe Waroquiers
     11 
     12    This program is free software; you can redistribute it and/or
     13    modify it under the terms of the GNU General Public License as
     14    published by the Free Software Foundation; either version 2 of the
     15    License, or (at your option) any later version.
     16 
     17    This program is distributed in the hope that it will be useful, but
     18    WITHOUT ANY WARRANTY; without even the implied warranty of
     19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     20    General Public License for more details.
     21 
     22    You should have received a copy of the GNU General Public License
     23    along with this program; if not, write to the Free Software
     24    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
     25    02111-1307, USA.
     26 
     27    The GNU General Public License is contained in the file COPYING.
     28 */
     29 
     30 #include "pub_core_basics.h"
     31 #include "pub_core_vki.h"
     32 #include "pub_core_debuglog.h"
     33 #include "pub_core_libcproc.h"
     34 #include "pub_core_libcprint.h"
     35 #include "pub_core_mallocfree.h"
     36 #include "pub_core_gdbserver.h"
     37 #include "pub_core_options.h"
     38 #include "pub_core_libcsetjmp.h"
     39 #include "pub_core_threadstate.h"
     40 #include "pub_core_transtab.h"
     41 #include "pub_tool_hashtable.h"
     42 #include "pub_tool_xarray.h"
     43 #include "pub_core_libcassert.h"
     44 #include "pub_tool_libcbase.h"
     45 #include "pub_core_libcsignal.h"
     46 #include "pub_core_signals.h"
     47 #include "pub_tool_machine.h"     // VG_(fnptr_to_fnentry)
     48 #include "pub_tool_debuginfo.h"
     49 #include "pub_core_scheduler.h"
     50 #include "pub_core_syswrap.h"
     51 
     52 #include "server.h"
     53 
     54 Int VG_(dyn_vgdb_error);
     55 
     56 /* forward declarations */
     57 VG_REGPARM(1)
     58 void VG_(helperc_CallDebugger) ( HWord iaddr );
     59 VG_REGPARM(1)
     60 void VG_(helperc_invalidate_if_not_gdbserved) ( Addr addr );
     61 static void invalidate_current_ip (ThreadId tid, char *who);
     62 
     63 /* reasons of call to call_gdbserver. */
     64 typedef
     65    enum {
     66       init_reason,    // initialises gdbserver resources
     67       vgdb_reason,    // gdbserver invocation by vgdb doing ptrace
     68       core_reason,    // gdbserver invocation by core (e.g. error encountered)
     69       break_reason,   // break encountered
     70       watch_reason,   // watchpoint detected by tool
     71       signal_reason}  // signal encountered
     72     CallReason;
     73 
     74 static char* ppCallReason(CallReason reason)
     75 {
     76    switch (reason) {
     77    case init_reason:    return "init_reason";
     78    case vgdb_reason:    return "vgdb_reason";
     79    case core_reason:    return "core_reason";
     80    case break_reason:   return "break_reason";
     81    case watch_reason:   return "watch_reason";
     82    case signal_reason:  return "signal_reason";
     83    default: vg_assert (0);
     84    }
     85 }
     86 
     87 /* An instruction instrumented for gdbserver looks like this:
     88     1. Ist_Mark (0x1234)
     89     2. Put (IP, 0x1234)
     90     3. helperc_CallDebugger (0x1234)
     91          This will give control to gdb if there is a break at 0x1234
     92          or if we are single stepping
     93     4. ... here the real IR for the instruction at 0x1234
     94 
     95     When there is a break at 0x1234:
     96       if user does "continue" or "step" or similar,
     97         then - the call to debugger returns
     98              - valgrind executes at 3. the real IR(s) for 0x1234
     99 
    100       if as part of helperc_CallDebugger, the user calls
    101       some code in gdb e.g print hello_world()
    102         then - gdb prepares a dummy stack frame with a specific
    103                return address (typically it uses _start) and
    104                inserts a break at this address
    105              - gdb then puts in EIP the address of hello_world()
    106              - gdb then continues (so the helperc_CallDebugger
    107                returns)
    108              - call_gdbserver() function will then return the
    109                control to the scheduler (using VG_MINIMAL_LONGJMP)
    110                to allow the block of the new EIP
    111                to be executed.
    112              - hello_world code is executed.
    113              - when hello_world() returns, it returns to
    114                _start and encounters the break at _start.
    115              - gdb then removes this break, put 0x1234 in EIP
    116                and does a "step". This causes to jump from
    117                _start to 0x1234, where the call to
    118                 helperc_CallDebugger is redone.
    119              - This is all ok, the user can then give new gdb
    120                commands.
    121 
    122     However, when continue is given, address 0x1234 is to
    123     be executed: gdb gives a single step, which must not
    124     report again the break at 0x1234. To avoid a 2nd report
    125     of the same break, the below tells that the next
    126     helperc_CallDebugger call must ignore a break/stop at
    127     this address.
    128 */
    129 static Addr ignore_this_break_once = 0;
    130 
    131 
    132 static void call_gdbserver ( ThreadId tid , CallReason reason);
    133 
    134 /* Describes the address addr (for debugging/printing purposes).
    135    Last two results are kept. A third call will replace the
    136    oldest result. */
    137 static char* sym (Addr addr, Bool is_code)
    138 {
    139    static char buf[2][200];
    140    static int w = 0;
    141    PtrdiffT offset;
    142    if (w == 2) w = 0;
    143    buf[w][0] = '\0';
    144    if (is_code) {
    145       VG_(describe_IP) (addr, buf[w], 200);
    146    } else {
    147       VG_(get_datasym_and_offset) (addr, buf[w], 200, &offset);
    148    }
    149    return buf[w++];
    150 }
    151 
    152 /* Each time gdbserver is called, gdbserver_called is incremented
    153    gdbserver_exited is incremented when gdbserver is asked to exit */
    154 static int gdbserver_called = 0;
    155 static int gdbserver_exited = 0;
    156 
    157 /* alloc and free functions for xarray and similar. */
    158 static void* gs_alloc (HChar* cc, SizeT sz)
    159 {
    160    void* res = VG_(arena_malloc)(VG_AR_CORE, cc, sz);
    161    vg_assert (res);
    162    return res;
    163 }
    164 static void gs_free (void* ptr)
    165 {
    166    VG_(arena_free)(VG_AR_CORE, ptr);
    167 }
    168 
    169 typedef
    170    enum {
    171      GS_break,
    172      GS_jump
    173    }
    174    GS_Kind;
    175 
    176 typedef
    177    struct _GS_Address {
    178       struct _GS_Address* next;
    179       Addr    addr;
    180       GS_Kind kind;
    181    }
    182    GS_Address;
    183 
    184 /* gs_addresses contains a list of all addresses that have been invalidated
    185    because they have been (or must be) instrumented for gdbserver.
    186    An entry is added in this table when there is a break at this
    187    address (kind == GS_break) or if this address is the jump target of an
    188    exit of a block that has been instrumented for gdbserver while
    189    single stepping (kind == GS_jump).
    190    When gdbserver is not single stepping anymore, all GS_jump entries
    191    are removed, their translations are invalidated.
    192 
    193    Note for ARM: addr in GS_Address is the value without the thumb bit set.
    194 */
    195 static VgHashTable gs_addresses = NULL;
    196 
    197 // Transform addr in the form stored in the list of addresses.
    198 // For the ARM architecture, we store it with the thumb bit set to 0.
    199 static Addr HT_addr ( Addr addr )
    200 {
    201 #if defined(VGA_arm)
    202   return addr & ~(Addr)1;
    203 #else
    204   return addr;
    205 #endif
    206 }
    207 
    208 static void add_gs_address (Addr addr, GS_Kind kind, char* from)
    209 {
    210    GS_Address *p;
    211 
    212    p = VG_(arena_malloc)(VG_AR_CORE, from, sizeof(GS_Address));
    213    p->addr = HT_addr (addr);
    214    p->kind = kind;
    215    VG_(HT_add_node)(gs_addresses, p);
    216    /* It should be sufficient to discard a range of 1.
    217       We use 2 to ensure the below is not sensitive to the presence
    218       of thumb bit in the range of addresses to discard. */
    219    VG_(discard_translations) (addr, 2, from);
    220 }
    221 
    222 static void remove_gs_address (GS_Address* g, char* from)
    223 {
    224    VG_(HT_remove) (gs_addresses, g->addr);
    225    // See add_gs_address for the explanation for the range 2 below.
    226    VG_(discard_translations) (g->addr, 2, from);
    227    VG_(arena_free) (VG_AR_CORE, g);
    228 }
    229 
    230 char* VG_(ppPointKind) (PointKind kind)
    231 {
    232    switch(kind) {
    233    case software_breakpoint: return "software_breakpoint";
    234    case hardware_breakpoint: return "hardware_breakpoint";
    235    case write_watchpoint:    return "write_watchpoint";
    236    case read_watchpoint:     return "read_watchpoint";
    237    case access_watchpoint:   return "access_watchpoint";
    238    default:                  return "???wrong PointKind";
    239    }
    240 }
    241 
    242 typedef
    243    struct _GS_Watch {
    244       Addr    addr;
    245       SizeT   len;
    246       PointKind kind;
    247    }
    248    GS_Watch;
    249 
    250 /* gs_watches contains a list of all addresses+len+kind that are being
    251    watched. */
    252 static XArray* gs_watches = NULL;
    253 
    254 static inline GS_Watch* index_gs_watches(Word i)
    255 {
    256    return *(GS_Watch **) VG_(indexXA) (gs_watches, i);
    257 }
    258 
    259 /* Returns the GS_Watch matching addr/len/kind and sets *g_ix to its
    260    position in gs_watches.
    261    If no matching GS_Watch is found, returns NULL and sets g_ix to -1. */
    262 static GS_Watch* lookup_gs_watch (Addr addr, SizeT len, PointKind kind,
    263                                   Word* g_ix)
    264 {
    265    const Word n_elems = VG_(sizeXA) (gs_watches);
    266    Word i;
    267    GS_Watch *g;
    268 
    269    /* Linear search. If we have many watches, this might be optimised
    270       by having the array sorted and using VG_(lookupXA) */
    271    for (i = 0; i < n_elems; i++) {
    272       g = index_gs_watches(i);
    273       if (g->addr == addr && g->len == len && g->kind == kind) {
    274          // Found.
    275          *g_ix = i;
    276          return g;
    277       }
    278    }
    279 
    280    // Not found.
    281    *g_ix = -1;
    282    return NULL;
    283 }
    284 
    285 
    286 /* protocol spec tells the below must be idempotent. */
    287 static void breakpoint (Bool insert, CORE_ADDR addr)
    288 {
    289    GS_Address *g;
    290 
    291    g = VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(addr));
    292    if (insert) {
    293       /* insert a breakpoint at addr or upgrade its kind */
    294       if (g == NULL) {
    295          add_gs_address (addr, GS_break, "m_gdbserver breakpoint insert");
    296       } else {
    297          /* already gdbserved. Normally, it must be because of a jump.
    298             However, due to idempotent or if connection with gdb was
    299             lost (kept breaks from the previous gdb), if already existing,
    300             we just upgrade its kind. */
    301          g->kind = GS_break;
    302       }
    303    } else {
    304       /* delete a breakpoint at addr or downgrade its kind */
    305       if (g != NULL && g->kind == GS_break) {
    306          if (valgrind_single_stepping()) {
    307             /* keep gdbserved instrumentation while single stepping */
    308             g->kind = GS_jump;
    309          } else {
    310             remove_gs_address (g, "m_gdbserver breakpoint remove");
    311          }
    312       } else {
    313          dlog (1, "remove break addr %p %s\n",
    314                C2v(addr), (g == NULL ?
    315                            "NULL" :
    316                            (g->kind == GS_jump ? "GS_jump" : "GS_break")));
    317       }
    318    }
    319 }
    320 
    321 static Bool (*tool_watchpoint) (PointKind kind,
    322                                 Bool insert,
    323                                 Addr addr,
    324                                 SizeT len) = NULL;
    325 void VG_(needs_watchpoint) (Bool (*watchpoint) (PointKind kind,
    326                                                 Bool insert,
    327                                                 Addr addr,
    328                                                 SizeT len))
    329 {
    330    tool_watchpoint = watchpoint;
    331 }
    332 
    333 Bool VG_(gdbserver_point) (PointKind kind, Bool insert,
    334                            CORE_ADDR addr, int len)
    335 {
    336    Bool res;
    337    GS_Watch *g;
    338    Word g_ix;
    339    Bool is_code = kind == software_breakpoint || kind == hardware_breakpoint;
    340 
    341    dlog(1, "%s %s at addr %p %s\n",
    342         (insert ? "insert" : "remove"),
    343         VG_(ppPointKind) (kind),
    344         C2v(addr),
    345         sym(addr, is_code));
    346 
    347    if (is_code) {
    348       breakpoint (insert, addr);
    349       return True;
    350    }
    351 
    352    vg_assert (kind == access_watchpoint
    353               || kind == read_watchpoint
    354               || kind == write_watchpoint);
    355 
    356    if (tool_watchpoint == NULL)
    357       return False;
    358 
    359    res = (*tool_watchpoint) (kind, insert, addr, len);
    360    if (!res)
    361       return False; /* error or unsupported */
    362 
    363    // Protocol says insert/remove must be idempotent.
    364    // So, we just ignore double insert or (supposed) double delete.
    365 
    366    g = lookup_gs_watch (addr, len, kind, &g_ix);
    367    if (insert) {
    368       if (g == NULL) {
    369          g = VG_(arena_malloc)(VG_AR_CORE, "gdbserver_point watchpoint",
    370                                sizeof(GS_Watch));
    371          g->addr = addr;
    372          g->len  = len;
    373          g->kind = kind;
    374          VG_(addToXA)(gs_watches, &g);
    375       } else {
    376          dlog(1,
    377               "VG_(gdbserver_point) addr %p len %d kind %s already inserted\n",
    378                C2v(addr), len, VG_(ppPointKind) (kind));
    379       }
    380    } else {
    381       if (g != NULL) {
    382          VG_(removeIndexXA) (gs_watches, g_ix);
    383          VG_(arena_free) (VG_AR_CORE, g);
    384       } else {
    385          dlog(1,
    386               "VG_(gdbserver_point) addr %p len %d kind %s already deleted?\n",
    387               C2v(addr), len, VG_(ppPointKind) (kind));
    388       }
    389    }
    390    return True;
    391 }
    392 
    393 Bool VG_(is_watched)(PointKind kind, Addr addr, Int szB)
    394 {
    395    Word n_elems;
    396    GS_Watch* g;
    397    Word i;
    398    Bool watched = False;
    399    const ThreadId tid = VG_(running_tid);
    400 
    401    if (!gdbserver_called)
    402       return False;
    403 
    404    n_elems = VG_(sizeXA) (gs_watches);
    405 
    406    Addr to = addr + szB; // semi-open interval [addr, to[
    407 
    408    vg_assert (kind == access_watchpoint
    409               || kind == read_watchpoint
    410               || kind == write_watchpoint);
    411    dlog(1, "tid %d VG_(is_watched) %s addr %p szB %d\n",
    412         tid, VG_(ppPointKind) (kind), C2v(addr), szB);
    413 
    414    for (i = 0; i < n_elems; i++) {
    415       g = index_gs_watches(i);
    416       switch (g->kind) {
    417       case software_breakpoint:
    418       case hardware_breakpoint:
    419          break;
    420       case access_watchpoint:
    421       case read_watchpoint:
    422       case write_watchpoint:
    423          if (to <= g->addr || addr >= (g->addr + g->len))
    424             /* If no overlap, examine next watchpoint: */
    425             continue;
    426 
    427          watched = True; /* We have an overlap */
    428 
    429          /* call gdbserver if access kind reported by the tool
    430             matches the watchpoint kind. */
    431          if (kind == access_watchpoint
    432              || g->kind == access_watchpoint
    433              || g->kind == kind) {
    434             /* Watchpoint encountered.
    435                If this is a read watchpoint, we directly call gdbserver
    436                to report it to gdb.
    437                Otherwise, for a write watchpoint, we have to finish
    438                the instruction so as to modify the value.
    439                If we do not finish the instruction, then gdb sees no
    440                value change and continues.
    441                For a read watchpoint, we better call gdbserver directly:
    442                in case the current block is not gdbserved, Valgrind
    443                will execute instructions till the next block. */
    444 
    445             /* set the watchpoint stop address to the first read or written. */
    446             if (g->addr <= addr) {
    447                VG_(set_watchpoint_stop_address) (addr);
    448             } else {
    449                VG_(set_watchpoint_stop_address) (g->addr);
    450             }
    451 
    452             if (kind == write_watchpoint) {
    453                /* Let Valgrind stop as early as possible after this instruction
    454                   by switching to Single Stepping mode. */
    455                valgrind_set_single_stepping (True);
    456                invalidate_current_ip (tid, "m_gdbserver write watchpoint");
    457             } else {
    458                call_gdbserver (tid, watch_reason);
    459                VG_(set_watchpoint_stop_address) ((Addr) 0);
    460             }
    461             return True; // we are watched here.
    462          }
    463          break;
    464       default:
    465          vg_assert (0);
    466       }
    467    }
    468    return watched;
    469 }
    470 
    471 /* Returns the reason for which gdbserver instrumentation is needed */
    472 static VgVgdb VG_(gdbserver_instrumentation_needed) (VexGuestExtents* vge)
    473 {
    474    GS_Address* g;
    475    int e;
    476 
    477    if (!gdbserver_called)
    478       return Vg_VgdbNo;
    479 
    480    if (valgrind_single_stepping()) {
    481       dlog(2, "gdbserver_instrumentation_needed due to single stepping\n");
    482       return Vg_VgdbYes;
    483    }
    484 
    485    if (VG_(clo_vgdb) == Vg_VgdbYes && VG_(HT_count_nodes) (gs_addresses) == 0)
    486       return Vg_VgdbNo;
    487 
    488    /* We assume we do not have a huge nr of breakpoints.
    489       Otherwise, we need something more efficient e.g.
    490       a sorted list of breakpoints or associate extents to it or ...
    491    */
    492    VG_(HT_ResetIter) (gs_addresses);
    493    while ((g = VG_(HT_Next) (gs_addresses))) {
    494       for (e = 0; e < vge->n_used; e++) {
    495          if (g->addr >= HT_addr(vge->base[e])
    496              && g->addr < HT_addr(vge->base[e]) + vge->len[e]) {
    497             dlog(2,
    498                  "gdbserver_instrumentation_needed %p %s reason %s\n",
    499                  C2v(g->addr), sym(g->addr, /* is_code */ True),
    500                  (g->kind == GS_jump ? "GS_jump" : "GS_break"));
    501             return Vg_VgdbYes;
    502          }
    503       }
    504    }
    505 
    506    if (VG_(clo_vgdb) == Vg_VgdbFull) {
    507       dlog(4, "gdbserver_instrumentation_needed"
    508            " due to VG_(clo_vgdb) == Vg_VgdbFull\n");
    509       return Vg_VgdbFull;
    510    }
    511 
    512 
    513    return Vg_VgdbNo;
    514 }
    515 
    516 // Clear gdbserved_addresses in gs_addresses.
    517 // If clear_only_jumps, clears only the addresses that are served
    518 // for jump reasons.
    519 // Otherwise, clear all the addresses.
    520 // Cleared addresses are invalidated so as to have them re-translated.
    521 static void clear_gdbserved_addresses(Bool clear_only_jumps)
    522 {
    523    GS_Address** ag;
    524    UInt n_elems;
    525    int i;
    526 
    527    dlog(1,
    528         "clear_gdbserved_addresses: scanning hash table nodes %d\n",
    529         VG_(HT_count_nodes) (gs_addresses));
    530    ag = (GS_Address**) VG_(HT_to_array) (gs_addresses, &n_elems);
    531    for (i = 0; i < n_elems; i++)
    532       if (!clear_only_jumps || ag[i]->kind == GS_jump)
    533          remove_gs_address (ag[i], "clear_gdbserved_addresses");
    534    VG_(free) (ag);
    535 }
    536 
    537 // Clear watched addressed in gs_watches, delete gs_watches.
    538 static void clear_watched_addresses(void)
    539 {
    540    GS_Watch* g;
    541    const Word n_elems = VG_(sizeXA) (gs_watches);
    542    Word i;
    543 
    544    dlog(1,
    545         "clear_watched_addresses: %ld elements\n",
    546         n_elems);
    547 
    548    for (i = 0; i < n_elems; i++) {
    549       g = index_gs_watches(i);
    550       if (!VG_(gdbserver_point) (g->kind,
    551                                  /* insert */ False,
    552                                  g->addr,
    553                                  g->len)) {
    554          vg_assert (0);
    555       }
    556    }
    557 
    558    VG_(deleteXA) (gs_watches);
    559    gs_watches = NULL;
    560 }
    561 
    562 static void invalidate_if_jump_not_yet_gdbserved (Addr addr, char* from)
    563 {
    564    if (VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(addr)))
    565       return;
    566    add_gs_address (addr, GS_jump, from);
    567 }
    568 
    569 static void invalidate_current_ip (ThreadId tid, char *who)
    570 {
    571    invalidate_if_jump_not_yet_gdbserved (VG_(get_IP) (tid), who);
    572 }
    573 
    574 void VG_(gdbserver_prerun_action) (ThreadId tid)
    575 {
    576    // Using VG_(dyn_vgdb_error) allows the user to control if gdbserver
    577    // stops after a fork.
    578    if (VG_(dyn_vgdb_error) == 0) {
    579       /* The below call allows gdb to attach at startup
    580          before the first guest instruction is executed. */
    581       VG_(umsg)("(action at startup) vgdb me ... \n");
    582       VG_(gdbserver)(tid);
    583    } else {
    584       /* User has activated gdbserver => initialize now the FIFOs
    585          to let vgdb/gdb contact us either via the scheduler poll
    586          mechanism or via vgdb ptrace-ing valgrind. */
    587       if (VG_(gdbserver_activity) (tid))
    588          VG_(gdbserver) (tid);
    589    }
    590 }
    591 
    592 /* when fork is done, various cleanup is needed in the child process.
    593    In particular, child must have its own connection to avoid stealing
    594    data from its parent */
    595 static void gdbserver_cleanup_in_child_after_fork(ThreadId me)
    596 {
    597    dlog(1, "thread %d gdbserver_cleanup_in_child_after_fork pid %d\n",
    598         me, VG_(getpid) ());
    599 
    600    /* finish connection inheritated from parent */
    601    remote_finish(reset_after_fork);
    602 
    603    /* ensure next call to gdbserver will be considered as a brand
    604       new call that will initialize a fresh gdbserver. */
    605    if (gdbserver_called) {
    606       gdbserver_called = 0;
    607       vg_assert (gs_addresses != NULL);
    608       vg_assert (gs_watches != NULL);
    609       clear_gdbserved_addresses(/* clear only jumps */ False);
    610       VG_(HT_destruct) (gs_addresses, VG_(free));
    611       gs_addresses = NULL;
    612       clear_watched_addresses();
    613    } else {
    614       vg_assert (gs_addresses == NULL);
    615       vg_assert (gs_watches == NULL);
    616    }
    617 
    618 
    619    if (VG_(clo_trace_children)) {
    620       VG_(gdbserver_prerun_action) (me);
    621    }
    622 }
    623 
    624 /* If reason is init_reason, creates the connection resources (e.g.
    625       the FIFOs) to allow a gdb connection to be detected by polling
    626       using remote_desc_activity.
    627    Otherwise (other reasons):
    628        If connection with gdb not yet opened, opens the connection with gdb.
    629        reads gdb remote protocol packets and executes the requested commands.
    630 */
    631 static void call_gdbserver ( ThreadId tid , CallReason reason)
    632 {
    633    ThreadState*     tst = VG_(get_ThreadState)(tid);
    634    int stepping;
    635    Addr saved_pc;
    636 
    637    dlog(1,
    638         "entering call_gdbserver %s ... pid %d tid %d status %s "
    639         "sched_jmpbuf_valid %d\n",
    640         ppCallReason (reason),
    641         VG_(getpid) (), tid, VG_(name_of_ThreadStatus)(tst->status),
    642         tst->sched_jmpbuf_valid);
    643 
    644    vg_assert(VG_(is_valid_tid)(tid));
    645    saved_pc = VG_(get_IP) (tid);
    646 
    647    if (gdbserver_exited) {
    648       dlog(0, "call_gdbserver called when gdbserver_exited %d\n",
    649            gdbserver_exited);
    650       return;
    651    }
    652 
    653    if (gdbserver_called == 0) {
    654       vg_assert (gs_addresses == NULL);
    655       vg_assert (gs_watches == NULL);
    656       gs_addresses = VG_(HT_construct)( "gdbserved_addresses" );
    657       gs_watches = VG_(newXA)(gs_alloc,
    658                               "gdbserved_watches",
    659                               gs_free,
    660                               sizeof(GS_Watch*));
    661       VG_(atfork)(NULL, NULL, gdbserver_cleanup_in_child_after_fork);
    662    }
    663    vg_assert (gs_addresses != NULL);
    664    vg_assert (gs_watches != NULL);
    665 
    666    gdbserver_called++;
    667 
    668    /* call gdbserver_init if this is the first call to gdbserver. */
    669    if (gdbserver_called == 1)
    670       gdbserver_init();
    671 
    672    if (reason == init_reason || gdbserver_called == 1)
    673       remote_open(VG_(clo_vgdb_prefix));
    674 
    675    /* if the call reason is to initialize, then return control to
    676       valgrind. After this initialization, gdbserver will be called
    677       again either if there is an error detected by valgrind or
    678       if vgdb sends data to the valgrind process. */
    679    if (reason == init_reason) {
    680       return;
    681    }
    682 
    683    stepping = valgrind_single_stepping();
    684 
    685    server_main();
    686 
    687    ignore_this_break_once = valgrind_get_ignore_break_once();
    688    if (ignore_this_break_once)
    689       dlog(1, "!!! will ignore_this_break_once %s\n",
    690            sym(ignore_this_break_once, /* is_code */ True));
    691 
    692 
    693    if (valgrind_single_stepping()) {
    694       /* we are single stepping. If we were not stepping on entry,
    695          then invalidate the current program counter so as to properly
    696          do single step. In case the program counter was changed by
    697          gdb, this will also invalidate the target address we will
    698          jump to. */
    699       if (!stepping && tid != 0) {
    700          invalidate_current_ip (tid, "m_gdbserver single step");
    701       }
    702    } else {
    703       /* We are not single stepping.  If we were stepping on entry,
    704          then clear the gdbserved addresses.  This will cause all
    705          these gdbserved blocks to be invalidated so that they can be
    706          re-translated without being gdbserved. */
    707       if (stepping)
    708          clear_gdbserved_addresses(/* clear only jumps */ True);
    709    }
    710 
    711    /* can't do sanity check at beginning. At least the stack
    712       check is not yet possible. */
    713    if (gdbserver_called > 1)
    714       VG_(sanity_check_general) (/* force_expensive */ False);
    715 
    716    /* If the PC has been changed by gdb, then we VG_MINIMAL_LONGJMP to
    717       the scheduler to execute the block of the new PC.
    718       Otherwise we just return to continue executing the
    719       current block. */
    720    if (VG_(get_IP) (tid) != saved_pc) {
    721       dlog(1, "tid %d %s PC changed from %s to %s\n",
    722            tid, VG_(name_of_ThreadStatus) (tst->status),
    723            sym(saved_pc, /* is_code */ True),
    724            sym(VG_(get_IP) (tid), /* is_code */ True));
    725       if (tst->status == VgTs_Yielding) {
    726          SysRes sres;
    727          VG_(memset)(&sres, 0, sizeof(SysRes));
    728          VG_(acquire_BigLock)(tid, "gdbsrv VG_MINIMAL_LONGJMP");
    729       }
    730       if (tst->sched_jmpbuf_valid) {
    731          /* resume scheduler */
    732          VG_MINIMAL_LONGJMP(tst->sched_jmpbuf);
    733       }
    734       /* else continue to run */
    735    }
    736    /* continue to run */
    737 }
    738 
    739 /* busy > 0 when gdbserver is currently being called.
    740    busy is used to to avoid vgdb invoking gdbserver
    741    while gdbserver by Valgrind. */
    742 static volatile int busy = 0;
    743 
    744 void VG_(gdbserver) ( ThreadId tid )
    745 {
    746    busy++;
    747    /* called by the rest of valgrind for
    748          --vgdb-error=0 reason
    749       or by scheduler "poll/debug/interrupt" reason
    750       or to terminate. */
    751    if (tid != 0) {
    752       call_gdbserver (tid, core_reason);
    753    } else {
    754       if (gdbserver_called == 0) {
    755          dlog(1, "VG_(gdbserver) called to terminate, nothing to terminate\n");
    756       } else if (gdbserver_exited) {
    757          dlog(0, "VG_(gdbserver) called to terminate again %d\n",
    758               gdbserver_exited);
    759       } else {
    760          gdbserver_terminate();
    761          gdbserver_exited++;
    762       }
    763    }
    764    busy--;
    765 }
    766 
    767 // nr of invoke_gdbserver while gdbserver is already executing.
    768 static int interrupts_while_busy = 0;
    769 
    770 // nr of invoke_gdbserver while gdbserver is not executing.
    771 static int interrupts_non_busy = 0;
    772 
    773 // nr of invoke_gdbserver when some threads are not interruptible.
    774 static int interrupts_non_interruptible = 0;
    775 
    776 /* When all threads are blocked in a system call, the Valgrind
    777    scheduler cannot poll the shared memory for gdbserver activity.  In
    778    such a case, vgdb will force the invokation of gdbserver using
    779    ptrace. To do that, vgdb 'pushes' a call to invoke_gdbserver
    780    on the stack using ptrace. invoke_gdbserver must not return.
    781    Instead, it must call give_control_back_to_vgdb.
    782    vgdb expects to receive a SIGSTOP, which this function generates.
    783    When vgdb gets this SIGSTOP, it knows invoke_gdbserver call
    784    is finished and can reset the Valgrind process in the state prior to
    785    the 'pushed call' (using ptrace again).
    786    This all works well. However, the user must avoid
    787    'kill-9ing' vgdb during such a pushed call, otherwise
    788    the SIGSTOP generated below will be seen by the Valgrind core,
    789    instead of being handled by vgdb. The OS will then handle the SIGSTOP
    790    by stopping the Valgrind process.
    791    We use SIGSTOP as this process cannot be masked. */
    792 
    793 static void give_control_back_to_vgdb(void)
    794 {
    795    /* cause a SIGSTOP to be sent to ourself, so that vgdb takes control.
    796       vgdb will then restore the stack so as to resume the activity
    797       before the ptrace (typically do_syscall_WRK). */
    798    if (VG_(kill)(VG_(getpid)(), VKI_SIGSTOP) != 0)
    799       vg_assert2(0, "SIGSTOP for vgdb could not be generated\n");
    800 
    801    /* If we arrive here, it means a call was pushed on the stack
    802       by vgdb, but during this call, vgdb and/or connection
    803       died. Alternatively, it is a bug in the vgdb<=>Valgrind gdbserver
    804       ptrace handling. */
    805    vg_assert2(0,
    806               "vgdb did not took control. Did you kill vgdb ?\n"
    807               "busy %d vgdb_interrupted_tid %d\n",
    808               busy, vgdb_interrupted_tid);
    809 }
    810 
    811 /* Using ptrace calls, vgdb will force an invocation of gdbserver.
    812    VG_(invoke_gdbserver) is the entry point called through the
    813    vgdb ptrace technique. */
    814 void VG_(invoke_gdbserver) ( int check )
    815 {
    816    /* ******* Avoid non-reentrant function call from here .....
    817       till the ".... till here" below. */
    818 
    819    /* We need to determine the state of the various threads to decide
    820       if we directly invoke gdbserver or if we rather indicate to the
    821       scheduler to invoke the gdbserver.  To decide that, it is
    822       critical to avoid any "coregrind" function call as the ptrace
    823       might have stopped the process in the middle of this (possibly)
    824       non-rentrant function.  So, it is only when all threads are in
    825       an "interruptible" state that we can safely invoke
    826       gdbserver. Otherwise, we let the valgrind scheduler invoke
    827       gdbserver at the next poll.  This poll will be made very soon
    828       thanks to a call to VG_(force_vgdb_poll). */
    829    int n_tid;
    830 
    831    vg_assert (check == 0x8BADF00D);
    832 
    833    if (busy) {
    834       interrupts_while_busy++;
    835       give_control_back_to_vgdb();
    836    }
    837    interrupts_non_busy++;
    838 
    839    /* check if all threads are in an "interruptible" state.  If yes,
    840       we invoke gdbserver. Otherwise, we tell the scheduler to wake up
    841       asap. */
    842    for (n_tid = 1; n_tid < VG_N_THREADS; n_tid++) {
    843       switch (VG_(threads)[n_tid].status) {
    844       /* interruptible states. */
    845       case VgTs_WaitSys:
    846       case VgTs_Yielding:
    847          if (vgdb_interrupted_tid == 0) vgdb_interrupted_tid = n_tid;
    848          break;
    849 
    850       case VgTs_Empty:
    851       case VgTs_Zombie:
    852          break;
    853 
    854       /* non interruptible states. */
    855       case VgTs_Init:
    856       case VgTs_Runnable:
    857          interrupts_non_interruptible++;
    858          VG_(force_vgdb_poll) ();
    859          give_control_back_to_vgdb();
    860 
    861       default:             vg_assert(0);
    862       }
    863    }
    864 
    865    /* .... till here.
    866       From here onwards, function calls are ok: it is
    867       safe to call valgrind core functions: all threads are blocked in
    868       a system call or are yielding or ... */
    869    dlog(1, "invoke_gdbserver running_tid %d vgdb_interrupted_tid %d\n",
    870         VG_(running_tid), vgdb_interrupted_tid);
    871    call_gdbserver (vgdb_interrupted_tid, vgdb_reason);
    872    vgdb_interrupted_tid = 0;
    873    dlog(1,
    874         "exit invoke_gdbserver running_tid %d\n", VG_(running_tid));
    875    give_control_back_to_vgdb();
    876 
    877    vg_assert2(0, "end of invoke_gdbserver reached");
    878 
    879 }
    880 
    881 Bool VG_(gdbserver_activity) (ThreadId tid)
    882 {
    883    Bool ret;
    884    busy++;
    885    if (!gdbserver_called)
    886       call_gdbserver (tid, init_reason);
    887    switch (remote_desc_activity("VG_(gdbserver_activity)")) {
    888    case 0: ret = False; break;
    889    case 1: ret = True; break;
    890    case 2: call_gdbserver (tid, init_reason); ret = False; break;
    891    default: vg_assert (0);
    892    }
    893    busy--;
    894    return ret;
    895 }
    896 
    897 Bool VG_(gdbserver_report_signal) (Int vki_sigNo, ThreadId tid)
    898 {
    899    dlog(1, "VG core calling VG_(gdbserver_report_signal) "
    900         "vki_nr %d %s gdb_nr %d %s tid %d\n",
    901         vki_sigNo, VG_(signame)(vki_sigNo),
    902         target_signal_from_host (vki_sigNo),
    903         target_signal_to_name(target_signal_from_host (vki_sigNo)),
    904         tid);
    905 
    906    /* if gdbserver is currently not connected, then signal
    907       is to be given to the process */
    908    if (!remote_connected()) {
    909       dlog(1, "not connected => pass\n");
    910       return True;
    911    }
    912    /* if gdb has informed gdbserver that this signal can be
    913       passed directly without informing gdb, then signal is
    914       to be given to the process. */
    915    if (pass_signals[target_signal_from_host(vki_sigNo)]) {
    916       dlog(1, "pass_signals => pass\n");
    917       return True;
    918    }
    919 
    920    /* indicate to gdbserver that there is a signal */
    921    gdbserver_signal_encountered (vki_sigNo);
    922 
    923    /* let gdbserver do some work, e.g. show the signal to the user */
    924    call_gdbserver (tid, signal_reason);
    925 
    926    /* ask gdbserver what is the final decision */
    927    if (gdbserver_deliver_signal (vki_sigNo)) {
    928       dlog(1, "gdbserver deliver signal\n");
    929       return True;
    930    } else {
    931       dlog(1, "gdbserver ignore signal\n");
    932       return False;
    933    }
    934 }
    935 
    936 // Check if single_stepping or if there is a break requested at iaddr.
    937 // If yes, call debugger
    938 VG_REGPARM(1)
    939 void VG_(helperc_CallDebugger) ( HWord iaddr )
    940 {
    941    GS_Address* g;
    942 
    943    // For Vg_VgdbFull, after a fork, we might have calls to this helper
    944    // while gdbserver is not yet initialized.
    945    if (!gdbserver_called)
    946       return;
    947 
    948    if (valgrind_single_stepping() ||
    949        ((g = VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(iaddr))) &&
    950         (g->kind == GS_break))) {
    951       if (iaddr == HT_addr(ignore_this_break_once)) {
    952          dlog(1, "ignoring ignore_this_break_once %s\n",
    953               sym(ignore_this_break_once, /* is_code */ True));
    954          ignore_this_break_once = 0;
    955       } else {
    956          call_gdbserver (VG_(get_running_tid)(), break_reason);
    957       }
    958    }
    959 }
    960 
    961 /* software_breakpoint support --------------------------------------*/
    962 /* When a block is instrumented for gdbserver, single step and breaks
    963    will be obeyed in this block.  However, if a jump to another block
    964    is executed while single_stepping is active, we must ensure that
    965    this block is also instrumented. For this, when a block is
    966    instrumented for gdbserver while single_stepping, the target of all
    967    the Jump instructions in this block will be checked to verify if
    968    the block is already instrumented for gdbserver.  The below will
    969    ensure that if not already instrumented for gdbserver, the target
    970    block translation containing addr will be invalidated.  The list of
    971    gdbserved Addr will also be kept so that translations can be
    972    dropped automatically by gdbserver when going out of single step
    973    mode.
    974 
    975    Call the below at translation time if the jump target is a constant.
    976    Otherwise, rather use VG_(add_stmt_call_invalidate_if_not_gdbserved).
    977 
    978    To instrument the target exit statement, you can call
    979    VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved) rather
    980    than check the kind of target exit. */
    981 static void VG_(invalidate_if_not_gdbserved) (Addr addr)
    982 {
    983    if (valgrind_single_stepping())
    984       invalidate_if_jump_not_yet_gdbserved
    985          (addr, "gdbserver target jump (instrument)");
    986 }
    987 
    988 // same as VG_(invalidate_if_not_gdbserved) but is intended to be called
    989 // at runtime (only difference is the invalidate reason which traces
    990 // it is at runtime)
    991 VG_REGPARM(1)
    992 void VG_(helperc_invalidate_if_not_gdbserved) ( Addr addr )
    993 {
    994    if (valgrind_single_stepping())
    995       invalidate_if_jump_not_yet_gdbserved
    996          (addr, "gdbserver target jump (runtime)");
    997 }
    998 
    999 static void VG_(add_stmt_call_invalidate_if_not_gdbserved)
   1000      ( IRSB* sb_in,
   1001        VexGuestLayout* layout,
   1002        VexGuestExtents* vge,
   1003        IRTemp jmp,
   1004        IRSB* irsb)
   1005 {
   1006 
   1007    void*    fn;
   1008    HChar*   nm;
   1009    IRExpr** args;
   1010    Int      nargs;
   1011    IRDirty* di;
   1012 
   1013    fn    = &VG_(helperc_invalidate_if_not_gdbserved);
   1014    nm    = "VG_(helperc_invalidate_if_not_gdbserved)";
   1015    args  = mkIRExprVec_1(IRExpr_RdTmp (jmp));
   1016    nargs = 1;
   1017 
   1018    di = unsafeIRDirty_0_N( nargs/*regparms*/, nm,
   1019                            VG_(fnptr_to_fnentry)( fn ), args );
   1020 
   1021    di->nFxState = 0;
   1022 
   1023    addStmtToIRSB(irsb, IRStmt_Dirty(di));
   1024 }
   1025 
   1026 /* software_breakpoint support --------------------------------------*/
   1027 /* If a tool wants to allow gdbserver to do something at Addr, then
   1028    VG_(add_stmt_call_gdbserver) will add in IRSB a call to a helper
   1029    function.  This helper function will check if the process must be
   1030    stopped at the instruction Addr: either there is a break at Addr or
   1031    the process is being single-stepped.  Typical usage of the below is to
   1032    instrument an Ist_IMark to allow the debugger to interact at any
   1033    instruction being executed.  As soon as there is one break in a block,
   1034    then to allow single stepping in this block (and possible insertions
   1035    of other breaks in the same sb_in while the process is stopped), a
   1036    debugger statement will be inserted for all instructions of a block. */
   1037 static void VG_(add_stmt_call_gdbserver)
   1038      (IRSB* sb_in,                /* block being translated */
   1039       VexGuestLayout* layout,
   1040       VexGuestExtents* vge,
   1041       IRType gWordTy, IRType hWordTy,
   1042       Addr  iaddr,                /* Addr of instruction being instrumented */
   1043       UChar delta,                /* delta to add to iaddr to obtain IP */
   1044       IRSB* irsb)                 /* irsb block to which call is added */
   1045 {
   1046    void*    fn;
   1047    HChar*   nm;
   1048    IRExpr** args;
   1049    Int      nargs;
   1050    IRDirty* di;
   1051 
   1052    /* first store the address in the program counter so that the check
   1053       done by VG_(helperc_CallDebugger) will be based on the correct
   1054       program counter.  We might make this more efficient by rather
   1055       searching for assignement to program counter and instrumenting
   1056       that but the below is easier and I guess that the optimiser will
   1057       remove the redundant store. And in any case, when debugging a
   1058       piece of code, the efficiency requirement is not critical: very
   1059       few blocks will be instrumented for debugging. */
   1060 
   1061    /* For platforms on which the IP can differ from the addr of the instruction
   1062       being executed, we need to add the delta to obtain the IP.
   1063       This IP will be given to gdb (e.g. if a breakpoint is put at iaddr).
   1064 
   1065       For ARM, this delta will ensure that the thumb bit is set in the
   1066       IP when executing thumb code. gdb uses this thumb bit a.o.
   1067       to properly guess the next IP for the 'step' and 'stepi' commands. */
   1068    vg_assert(delta <= 1);
   1069    addStmtToIRSB(irsb, IRStmt_Put(layout->offset_IP ,
   1070                                   mkIRExpr_HWord(iaddr + (Addr)delta)));
   1071 
   1072    fn    = &VG_(helperc_CallDebugger);
   1073    nm    = "VG_(helperc_CallDebugger)";
   1074    args  = mkIRExprVec_1(mkIRExpr_HWord (iaddr));
   1075    nargs = 1;
   1076 
   1077    di = unsafeIRDirty_0_N( nargs/*regparms*/, nm,
   1078                            VG_(fnptr_to_fnentry)( fn ), args );
   1079 
   1080    /* Note: in fact, a debugger call can read whatever register
   1081       or memory. It can also write whatever register or memory.
   1082       So, in theory, we have to indicate the whole universe
   1083       can be read and modified. It is however not critical
   1084       to indicate precisely what is being read/written
   1085       as such indications are needed for tool error detection
   1086       and we do not want to have errors being detected for
   1087       gdb interactions. */
   1088 
   1089    di->nFxState = 2;
   1090    di->fxState[0].fx        = Ifx_Read;
   1091    di->fxState[0].offset    = layout->offset_SP;
   1092    di->fxState[0].size      = layout->sizeof_SP;
   1093    di->fxState[0].nRepeats  = 0;
   1094    di->fxState[0].repeatLen = 0;
   1095    di->fxState[1].fx        = Ifx_Modify;
   1096    di->fxState[1].offset    = layout->offset_IP;
   1097    di->fxState[1].size      = layout->sizeof_IP;
   1098    di->fxState[1].nRepeats  = 0;
   1099    di->fxState[1].repeatLen = 0;
   1100 
   1101    addStmtToIRSB(irsb, IRStmt_Dirty(di));
   1102 
   1103 }
   1104 
   1105 
   1106 /* Invalidate the target of the exit if needed:
   1107    If target is constant, it is invalidated at translation time.
   1108    Otherwise, a call to a helper function is generated to invalidate
   1109    the translation at run time.
   1110    The below is thus calling either VG_(invalidate_if_not_gdbserved)
   1111    or VG_(add_stmt_call_invalidate_if_not_gdbserved).  */
   1112 static void VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved)
   1113    (IRSB* sb_in,
   1114     VexGuestLayout* layout,
   1115     VexGuestExtents* vge,
   1116     IRType gWordTy,
   1117     IRSB* irsb)
   1118 {
   1119    if (sb_in->next->tag == Iex_Const) {
   1120      VG_(invalidate_if_not_gdbserved) (gWordTy == Ity_I64 ?
   1121                                        sb_in->next->Iex.Const.con->Ico.U64
   1122                                        : sb_in->next->Iex.Const.con->Ico.U32);
   1123    } else if (sb_in->next->tag == Iex_RdTmp) {
   1124      VG_(add_stmt_call_invalidate_if_not_gdbserved)
   1125        (sb_in, layout, vge, sb_in->next->Iex.RdTmp.tmp, irsb);
   1126    } else {
   1127      vg_assert (0); /* unexpected expression tag in exit. */
   1128    }
   1129 }
   1130 
   1131 IRSB* VG_(instrument_for_gdbserver_if_needed)
   1132      (IRSB* sb_in,
   1133       VexGuestLayout* layout,
   1134       VexGuestExtents* vge,
   1135       IRType gWordTy, IRType hWordTy)
   1136 {
   1137    IRSB* sb_out;
   1138    Int i;
   1139    const VgVgdb instr_needed = VG_(gdbserver_instrumentation_needed) (vge);
   1140 
   1141    if (instr_needed == Vg_VgdbNo)
   1142      return sb_in;
   1143 
   1144 
   1145    /* here, we need to instrument for gdbserver */
   1146    sb_out = deepCopyIRSBExceptStmts(sb_in);
   1147 
   1148    for (i = 0; i < sb_in->stmts_used; i++) {
   1149       IRStmt* st = sb_in->stmts[i];
   1150 
   1151       if (!st || st->tag == Ist_NoOp) continue;
   1152 
   1153       if (st->tag == Ist_Exit && instr_needed == Vg_VgdbYes) {
   1154         VG_(invalidate_if_not_gdbserved)
   1155           (hWordTy == Ity_I64 ?
   1156            st->Ist.Exit.dst->Ico.U64 :
   1157            st->Ist.Exit.dst->Ico.U32);
   1158       }
   1159       addStmtToIRSB( sb_out, st );
   1160       if (st->tag == Ist_IMark) {
   1161          /* For an Ist_Mark, add a call to debugger. */
   1162          switch (instr_needed) {
   1163          case Vg_VgdbNo: vg_assert (0);
   1164          case Vg_VgdbYes:
   1165          case Vg_VgdbFull:
   1166             VG_(add_stmt_call_gdbserver) ( sb_in, layout, vge,
   1167                                            gWordTy, hWordTy,
   1168                                            st->Ist.IMark.addr,
   1169                                            st->Ist.IMark.delta,
   1170                                            sb_out);
   1171             /* There is an optimisation possible here for Vg_VgdbFull:
   1172                Put a guard ensuring we only call gdbserver if 'FullCallNeeded'.
   1173                FullCallNeeded would be set to 1 we have just switched on
   1174                Single Stepping or have just encountered a watchpoint
   1175                or have just inserted a breakpoint.
   1176                (as gdb by default removes and re-insert breakpoints), we would
   1177                need to also implement the notion of 'breakpoint pending removal'
   1178                to remove at the next 'continue/step' packet. */
   1179             break;
   1180          default: vg_assert (0);
   1181          }
   1182       }
   1183    }
   1184 
   1185    if (instr_needed == Vg_VgdbYes) {
   1186       VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved) (sb_in,
   1187                                                                   layout, vge,
   1188                                                                   gWordTy,
   1189                                                                   sb_out);
   1190    }
   1191 
   1192    return sb_out;
   1193 }
   1194 
   1195 struct mon_out_buf {
   1196    char buf[DATASIZ+1];
   1197    int next;
   1198    UInt ret;
   1199 };
   1200 
   1201 static void mon_out (HChar c, void *opaque)
   1202 {
   1203    struct mon_out_buf *b = (struct mon_out_buf *) opaque;
   1204    b->ret++;
   1205    b->buf[b->next] = c;
   1206    b->next++;
   1207    if (b->next == DATASIZ) {
   1208       b->buf[b->next] = '\0';
   1209       monitor_output(b->buf);
   1210       b->next = 0;
   1211    }
   1212 }
   1213 UInt VG_(gdb_printf) ( const HChar *format, ... )
   1214 {
   1215    struct mon_out_buf b;
   1216 
   1217    b.next = 0;
   1218    b.ret = 0;
   1219 
   1220    va_list vargs;
   1221    va_start(vargs, format);
   1222    VG_(vcbprintf) (mon_out, &b, format, vargs);
   1223    va_end(vargs);
   1224 
   1225    if (b.next > 0) {
   1226       b.buf[b.next] = '\0';
   1227       monitor_output(b.buf);
   1228    }
   1229    return b.ret;
   1230 }
   1231 
   1232 Int VG_(keyword_id) (Char* keywords, Char* input_word, kwd_report_error report)
   1233 {
   1234    const Int il = (input_word == NULL ? 0 : VG_(strlen) (input_word));
   1235    Char  iw[il+1];
   1236    Char  kwds[VG_(strlen)(keywords)+1];
   1237    Char  *kwdssaveptr;
   1238 
   1239    Char* kw; /* current keyword, its length, its position */
   1240    Int   kwl;
   1241    Int   kpos = -1;
   1242 
   1243    Int pass;
   1244    /* pass 0 = search, optional pass 1 = output message multiple matches */
   1245 
   1246    Int pass1needed = 0;
   1247 
   1248    Int partial_match = -1;
   1249    Int full_match = -1;
   1250 
   1251    if (input_word == NULL) {
   1252       iw[0] = 0;
   1253       partial_match = 0; /* to force an empty string to cause an error */
   1254    } else {
   1255       VG_(strcpy) (iw, input_word);
   1256    }
   1257 
   1258    for (pass = 0; pass < 2; pass++) {
   1259       VG_(strcpy) (kwds, keywords);
   1260       if (pass == 1)
   1261          VG_(gdb_printf) ("%s can match",
   1262                           (il == 0 ? "<empty string>" : (char *) iw));
   1263       for (kw = VG_(strtok_r) (kwds, " ", &kwdssaveptr);
   1264            kw != NULL;
   1265            kw = VG_(strtok_r) (NULL, " ", &kwdssaveptr)) {
   1266          kwl = VG_(strlen) (kw);
   1267          kpos++;
   1268 
   1269          if (il > kwl) {
   1270             ; /* ishtar !~ is */
   1271          } else if (il == kwl) {
   1272             if (VG_(strcmp) (kw, iw) == 0) {
   1273                /* exact match */
   1274                if (pass == 1)
   1275                   VG_(gdb_printf) (" %s", kw);
   1276                if (full_match != -1)
   1277                   pass1needed++;
   1278                full_match = kpos;
   1279             }
   1280          } else {
   1281             /* il < kwl */
   1282             if (VG_(strncmp) (iw, kw, il) == 0) {
   1283                /* partial match */
   1284                if (pass == 1)
   1285                   VG_(gdb_printf) (" %s", kw);
   1286                if (partial_match != -1)
   1287                   pass1needed++;
   1288                partial_match = kpos;
   1289             }
   1290          }
   1291       }
   1292       /* check for success or for no match at all */
   1293       if (pass1needed == 0) {
   1294          if (full_match != -1) {
   1295             return full_match;
   1296          } else {
   1297             if (report == kwd_report_all && partial_match == -1) {
   1298                VG_(gdb_printf) ("%s does not match any of '%s'\n",
   1299                                 iw, keywords);
   1300             }
   1301             return partial_match;
   1302          }
   1303       }
   1304 
   1305       /* here we have duplicated match error */
   1306       if (pass == 1 || report == kwd_report_none) {
   1307          if (report != kwd_report_none) {
   1308             VG_(gdb_printf) ("\n");
   1309          }
   1310          if (partial_match != -1 || full_match != -1)
   1311             return -2;
   1312          else
   1313             return -1;
   1314       }
   1315    }
   1316    /* UNREACHED */
   1317    vg_assert (0);
   1318 }
   1319 
   1320 /* True if string can be a 0x number */
   1321 static Bool is_zero_x (Char *s)
   1322 {
   1323    if (strlen (s) >= 3 && s[0] == '0' && s[1] == 'x')
   1324       return True;
   1325    else
   1326       return False;
   1327 }
   1328 
   1329 /* True if string can be a 0b number */
   1330 static Bool is_zero_b (Char *s)
   1331 {
   1332    if (strlen (s) >= 3 && s[0] == '0' && s[1] == 'b')
   1333       return True;
   1334    else
   1335       return False;
   1336 }
   1337 
   1338 void VG_(strtok_get_address_and_size) (Addr* address,
   1339                                        SizeT* szB,
   1340                                        Char **ssaveptr)
   1341 {
   1342    Char* wa;
   1343    Char* ws;
   1344    Char* endptr;
   1345    UChar *ppc;
   1346 
   1347    wa = VG_(strtok_r) (NULL, " ", ssaveptr);
   1348    ppc = wa;
   1349    if (ppc == NULL || !VG_(parse_Addr) (&ppc, address)) {
   1350       VG_(gdb_printf) ("missing or malformed address\n");
   1351       *address = (Addr) 0;
   1352       *szB = 0;
   1353       return;
   1354    }
   1355    ws = VG_(strtok_r) (NULL, " ", ssaveptr);
   1356    if (ws == NULL) {
   1357       /* Do nothing, i.e. keep current value of szB. */ ;
   1358    } else if (is_zero_x (ws)) {
   1359       *szB = VG_(strtoull16) (ws, &endptr);
   1360    } else if (is_zero_b (ws)) {
   1361       Int j;
   1362       Char *parsews = ws;
   1363       Int n_bits = VG_(strlen) (ws) - 2;
   1364       *szB = 0;
   1365       ws = NULL; // assume the below loop gives a correct nr.
   1366       for (j = 0; j < n_bits; j++) {
   1367          if      ('0' == parsews[j+2]) { /* do nothing */ }
   1368          else if ('1' == parsews[j+2]) *szB |= (1 << (n_bits-j-1));
   1369          else {
   1370             /* report malformed binary integer */
   1371             ws = parsews;
   1372             endptr = ws + j + 2;
   1373             break;
   1374          }
   1375       }
   1376    } else {
   1377       *szB = VG_(strtoull10) (ws, &endptr);
   1378    }
   1379 
   1380    if (ws != NULL && *endptr != '\0') {
   1381       VG_(gdb_printf) ("malformed integer, expecting "
   1382                        "hex 0x..... or dec ...... or binary .....b\n");
   1383       *address = (Addr) 0;
   1384       *szB = 0;
   1385       return;
   1386    }
   1387 }
   1388 
   1389 void VG_(gdbserver_status_output)(void)
   1390 {
   1391    const int nr_gdbserved_addresses
   1392       = (gs_addresses == NULL ? -1 : VG_(HT_count_nodes) (gs_addresses));
   1393    const int nr_watchpoints
   1394       = (gs_watches == NULL ? -1 : (int) VG_(sizeXA) (gs_watches));
   1395    remote_utils_output_status();
   1396    VG_(umsg)
   1397       ("nr of calls to gdbserver: %d\n"
   1398        "single stepping %d\n"
   1399        "interrupts intr_tid %d gs_non_busy %d gs_busy %d tid_non_intr %d\n"
   1400        "gdbserved addresses %d (-1 = not initialized)\n"
   1401        "watchpoints %d (-1 = not initialized)\n"
   1402        "vgdb-error %d\n",
   1403        gdbserver_called,
   1404        valgrind_single_stepping(),
   1405 
   1406        vgdb_interrupted_tid,
   1407        interrupts_non_busy,
   1408        interrupts_while_busy,
   1409        interrupts_non_interruptible,
   1410 
   1411        nr_gdbserved_addresses,
   1412        nr_watchpoints,
   1413        VG_(dyn_vgdb_error));
   1414 }
   1415