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