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