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-2015 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_threadstate.h"
37 #include "pub_core_gdbserver.h"
38 #include "pub_core_options.h"
39 #include "pub_core_transtab.h"
40 #include "pub_core_hashtable.h"
41 #include "pub_core_xarray.h"
42 #include "pub_core_libcassert.h"
43 #include "pub_core_libcbase.h"
44 #include "pub_core_libcsignal.h"
45 #include "pub_core_signals.h"
46 #include "pub_core_machine.h"     // VG_(fnptr_to_fnentry)
47 #include "pub_core_debuginfo.h"
48 #include "pub_core_scheduler.h"
49 #include "pub_core_syswrap.h"
50 
51 #include "server.h"
52 
53 Int VG_(dyn_vgdb_error);
54 
55 /* forward declarations */
56 VG_REGPARM(1)
57 void VG_(helperc_CallDebugger) ( HWord iaddr );
58 VG_REGPARM(1)
59 void VG_(helperc_invalidate_if_not_gdbserved) ( Addr addr );
60 static void invalidate_current_ip (ThreadId tid, const HChar *who);
61 
62 /* reasons of call to call_gdbserver. */
63 typedef
64    enum {
65       init_reason,    // initialises gdbserver resources
66       vgdb_reason,    // gdbserver invocation by vgdb doing ptrace
67       core_reason,    // gdbserver invocation by core (e.g. error encountered)
68       break_reason,   // break encountered
69       watch_reason,   // watchpoint detected by tool
70       signal_reason,  // signal encountered
71       exit_reason}    // process terminated
72     CallReason;
73 
ppCallReason(CallReason reason)74 static const HChar* ppCallReason(CallReason reason)
75 {
76    switch (reason) {
77    case init_reason:    return "init_reason";
78    case vgdb_reason:    return "vgdb_reason";
79    case core_reason:    return "core_reason";
80    case break_reason:   return "break_reason";
81    case watch_reason:   return "watch_reason";
82    case signal_reason:  return "signal_reason";
83    case exit_reason:    return "exit_reason";
84    default: vg_assert (0);
85    }
86 }
87 
88 /* An instruction instrumented for gdbserver looks like this:
89     1. Ist_Mark (0x1234)
90     2. Put (IP, 0x1234)
91     3. helperc_CallDebugger (0x1234)
92          This will give control to gdb if there is a break at 0x1234
93          or if we are single stepping
94     4. ... here the real IR for the instruction at 0x1234
95 
96     When there is a break at 0x1234:
97       if user does "continue" or "step" or similar,
98         then - the call to debugger returns
99              - valgrind executes at 3. the real IR(s) for 0x1234
100 
101       if as part of helperc_CallDebugger, the user calls
102       some code in gdb e.g print hello_world()
103         then - gdb prepares a dummy stack frame with a specific
104                return address (typically it uses _start) and
105                inserts a break at this address
106              - gdb then puts in EIP the address of hello_world()
107              - gdb then continues (so the helperc_CallDebugger
108                returns)
109              - call_gdbserver() function will then return the
110                control to the scheduler (using VG_MINIMAL_LONGJMP)
111                to allow the block of the new EIP
112                to be executed.
113              - hello_world code is executed.
114              - when hello_world() returns, it returns to
115                _start and encounters the break at _start.
116              - gdb then removes this break, put 0x1234 in EIP
117                and does a "step". This causes to jump from
118                _start to 0x1234, where the call to
119                 helperc_CallDebugger is redone.
120              - This is all ok, the user can then give new gdb
121                commands.
122 
123     However, when continue is given, address 0x1234 is to
124     be executed: gdb gives a single step, which must not
125     report again the break at 0x1234. To avoid a 2nd report
126     of the same break, the below tells that the next
127     helperc_CallDebugger call must ignore a break/stop at
128     this address.
129 */
130 static Addr ignore_this_break_once = 0;
131 
132 
133 static void call_gdbserver ( ThreadId tid , CallReason reason);
134 
135 /* Describes the address addr (for debugging/printing purposes).
136    Last two results are kept. A third call will replace the
137    oldest result. */
sym(Addr addr,Bool is_code)138 static HChar* sym (Addr addr, Bool is_code)
139 {
140    static HChar *buf[2];
141    static int w = 0;
142    PtrdiffT offset;
143    if (w == 2) w = 0;
144 
145    if (is_code) {
146       const HChar *name;
147       name = VG_(describe_IP) (addr, NULL);
148       if (buf[w]) VG_(free)(buf[w]);
149       buf[w] = VG_(strdup)("gdbserver sym", name);
150    } else {
151       const HChar *name;
152       VG_(get_datasym_and_offset) (addr, &name, &offset);
153       if (buf[w]) VG_(free)(buf[w]);
154       buf[w] = VG_(strdup)("gdbserver sym", name);
155    }
156    return buf[w++];
157 }
158 
159 /* Each time gdbserver is called, gdbserver_called is incremented
160    gdbserver_exited is incremented when gdbserver is asked to exit */
161 static int gdbserver_called = 0;
162 static int gdbserver_exited = 0;
163 
164 /* alloc and free functions for xarray and similar. */
gs_alloc(const HChar * cc,SizeT sz)165 static void* gs_alloc (const HChar* cc, SizeT sz)
166 {
167    return VG_(malloc)(cc, sz);
168 }
gs_free(void * ptr)169 static void gs_free (void* ptr)
170 {
171    VG_(free)(ptr);
172 }
173 
174 typedef
175    enum {
176      GS_break,
177      GS_jump
178    }
179    GS_Kind;
180 
181 typedef
182    struct _GS_Address {
183       struct _GS_Address* next;
184       Addr    addr;
185       GS_Kind kind;
186    }
187    GS_Address;
188 
189 /* gs_addresses contains a list of all addresses that have been invalidated
190    because they have been (or must be) instrumented for gdbserver.
191    An entry is added in this table when there is a break at this
192    address (kind == GS_break) or if this address is the jump target of an
193    exit of a block that has been instrumented for gdbserver while
194    single stepping (kind == GS_jump).
195    When gdbserver is not single stepping anymore, all GS_jump entries
196    are removed, their translations are invalidated.
197 
198    Note for ARM: addr in GS_Address is the value without the thumb bit set.
199 */
200 static VgHashTable *gs_addresses = NULL;
201 
202 // Transform addr in the form stored in the list of addresses.
203 // For the ARM architecture, we store it with the thumb bit set to 0.
HT_addr(Addr addr)204 static Addr HT_addr ( Addr addr )
205 {
206 #if defined(VGA_arm)
207   return addr & ~(Addr)1;
208 #else
209   return addr;
210 #endif
211 }
212 
add_gs_address(Addr addr,GS_Kind kind,const HChar * from)213 static void add_gs_address (Addr addr, GS_Kind kind, const HChar* from)
214 {
215    GS_Address *p;
216 
217    p = VG_(malloc)(from, sizeof(GS_Address));
218    p->addr = HT_addr (addr);
219    p->kind = kind;
220    VG_(HT_add_node)(gs_addresses, p);
221    /* It should be sufficient to discard a range of 1.
222       We use 2 to ensure the below is not sensitive to the presence
223       of thumb bit in the range of addresses to discard.
224       No need to discard translations for Vg_VgdbFull as all
225       instructions are in any case vgdb-instrumented. */
226    if (VG_(clo_vgdb) != Vg_VgdbFull)
227       VG_(discard_translations) (addr, 2, from);
228 }
229 
remove_gs_address(GS_Address * g,const HChar * from)230 static void remove_gs_address (GS_Address* g, const HChar* from)
231 {
232    VG_(HT_remove) (gs_addresses, g->addr);
233    // See add_gs_address for the explanation for condition and the range 2 below.
234    if (VG_(clo_vgdb) != Vg_VgdbFull)
235       VG_(discard_translations) (g->addr, 2, from);
236    VG_(free) (g);
237 }
238 
VG_(ppPointKind)239 const HChar* VG_(ppPointKind) (PointKind kind)
240 {
241    switch(kind) {
242    case software_breakpoint: return "software_breakpoint";
243    case hardware_breakpoint: return "hardware_breakpoint";
244    case write_watchpoint:    return "write_watchpoint";
245    case read_watchpoint:     return "read_watchpoint";
246    case access_watchpoint:   return "access_watchpoint";
247    default:                  return "???wrong PointKind";
248    }
249 }
250 
251 typedef
252    struct _GS_Watch {
253       Addr    addr;
254       SizeT   len;
255       PointKind kind;
256    }
257    GS_Watch;
258 
259 /* gs_watches contains a list of all addresses+len+kind that are being
260    watched. */
261 static XArray* gs_watches = NULL;
262 
index_gs_watches(Word i)263 static inline GS_Watch* index_gs_watches(Word i)
264 {
265    return *(GS_Watch **) VG_(indexXA) (gs_watches, i);
266 }
267 
268 /* Returns the GS_Watch matching addr/len/kind and sets *g_ix to its
269    position in gs_watches.
270    If no matching GS_Watch is found, returns NULL and sets g_ix to -1. */
lookup_gs_watch(Addr addr,SizeT len,PointKind kind,Word * g_ix)271 static GS_Watch* lookup_gs_watch (Addr addr, SizeT len, PointKind kind,
272                                   Word* g_ix)
273 {
274    const Word n_elems = VG_(sizeXA) (gs_watches);
275    Word i;
276    GS_Watch *g;
277 
278    /* Linear search. If we have many watches, this might be optimised
279       by having the array sorted and using VG_(lookupXA) */
280    for (i = 0; i < n_elems; i++) {
281       g = index_gs_watches(i);
282       if (g->addr == addr && g->len == len && g->kind == kind) {
283          // Found.
284          *g_ix = i;
285          return g;
286       }
287    }
288 
289    // Not found.
290    *g_ix = -1;
291    return NULL;
292 }
293 
294 
295 /* protocol spec tells the below must be idempotent. */
breakpoint(Bool insert,CORE_ADDR addr)296 static void breakpoint (Bool insert, CORE_ADDR addr)
297 {
298    GS_Address *g;
299 
300    g = VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(addr));
301    if (insert) {
302       /* insert a breakpoint at addr or upgrade its kind */
303       if (g == NULL) {
304          add_gs_address (addr, GS_break, "m_gdbserver breakpoint insert");
305       } else {
306          /* already gdbserved. Normally, it must be because of a jump.
307             However, due to idempotent or if connection with gdb was
308             lost (kept breaks from the previous gdb), if already existing,
309             we just upgrade its kind. */
310          g->kind = GS_break;
311       }
312    } else {
313       /* delete a breakpoint at addr or downgrade its kind */
314       if (g != NULL && g->kind == GS_break) {
315          if (valgrind_single_stepping()) {
316             /* keep gdbserved instrumentation while single stepping */
317             g->kind = GS_jump;
318          } else {
319             remove_gs_address (g, "m_gdbserver breakpoint remove");
320          }
321       } else {
322          dlog (1, "remove break addr %p %s\n",
323                C2v(addr), (g == NULL ?
324                            "NULL" :
325                            (g->kind == GS_jump ? "GS_jump" : "GS_break")));
326       }
327    }
328 }
329 
330 static Bool (*tool_watchpoint) (PointKind kind,
331                                 Bool insert,
332                                 Addr addr,
333                                 SizeT len) = NULL;
VG_(needs_watchpoint)334 void VG_(needs_watchpoint) (Bool (*watchpoint) (PointKind kind,
335                                                 Bool insert,
336                                                 Addr addr,
337                                                 SizeT len))
338 {
339    tool_watchpoint = watchpoint;
340 }
341 
VG_(gdbserver_point)342 Bool VG_(gdbserver_point) (PointKind kind, Bool insert,
343                            CORE_ADDR addr, int len)
344 {
345    Bool res;
346    GS_Watch *g;
347    Word g_ix;
348    Bool is_code = kind == software_breakpoint || kind == hardware_breakpoint;
349 
350    dlog(1, "%s %s at addr %p %s\n",
351         (insert ? "insert" : "remove"),
352         VG_(ppPointKind) (kind),
353         C2v(addr),
354         sym(addr, is_code));
355 
356    if (is_code) {
357       breakpoint (insert, addr);
358       return True;
359    }
360 
361    vg_assert (kind == access_watchpoint
362               || kind == read_watchpoint
363               || kind == write_watchpoint);
364 
365    if (tool_watchpoint == NULL)
366       return False;
367 
368    res = (*tool_watchpoint) (kind, insert, addr, len);
369    if (!res)
370       return False; /* error or unsupported */
371 
372    // Protocol says insert/remove must be idempotent.
373    // So, we just ignore double insert or (supposed) double delete.
374 
375    g = lookup_gs_watch (addr, len, kind, &g_ix);
376    if (insert) {
377       if (g == NULL) {
378          g = VG_(malloc)("gdbserver_point watchpoint", 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_(free) (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 
VG_(has_gdbserver_breakpoint)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 
VG_(is_watched)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 %u 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 */
VG_(gdbserver_instrumentation_needed)489 static VgVgdb VG_(gdbserver_instrumentation_needed) (const 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.
clear_gdbserved_addresses(Bool clear_only_jumps)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 %u\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.
clear_watched_addresses(void)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 
invalidate_if_jump_not_yet_gdbserved(Addr addr,const HChar * from)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 
invalidate_current_ip(ThreadId tid,const HChar * who)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 
VG_(gdbserver_init_done)591 Bool VG_(gdbserver_init_done) (void)
592 {
593    return gdbserver_called > 0;
594 }
595 
VG_(gdbserver_stop_at)596 Bool VG_(gdbserver_stop_at) (VgdbStopAt stopat)
597 {
598    return gdbserver_called > 0 && VgdbStopAtiS(stopat, VG_(clo_vgdb_stop_at));
599 }
600 
VG_(gdbserver_prerun_action)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 */
gdbserver_cleanup_in_child_after_fork(ThreadId me)623 static void gdbserver_cleanup_in_child_after_fork(ThreadId me)
624 {
625    dlog(1, "thread %u 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 */
call_gdbserver(ThreadId tid,CallReason reason)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 %u 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 %u %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 avoid vgdb invoking gdbserver
777    while gdbserver by Valgrind. */
778 static volatile int busy = 0;
779 
VG_(gdbserver)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(1, "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 
give_control_back_to_vgdb(void)829 static void give_control_back_to_vgdb(void)
830 {
831 #if !defined(VGO_solaris)
832    /* cause a SIGSTOP to be sent to ourself, so that vgdb takes control.
833       vgdb will then restore the stack so as to resume the activity
834       before the ptrace (typically do_syscall_WRK). */
835    if (VG_(kill)(VG_(getpid)(), VKI_SIGSTOP) != 0)
836       vg_assert2(0, "SIGSTOP for vgdb could not be generated\n");
837 
838    /* If we arrive here, it means a call was pushed on the stack
839       by vgdb, but during this call, vgdb and/or connection
840       died. Alternatively, it is a bug in the vgdb<=>Valgrind gdbserver
841       ptrace handling. */
842    vg_assert2(0,
843               "vgdb did not took control. Did you kill vgdb ?\n"
844               "busy %d vgdb_interrupted_tid %u\n",
845               busy, vgdb_interrupted_tid);
846 #else /* defined(VGO_solaris) */
847    /* On Solaris, this code is run within the context of an agent thread
848       (see vgdb-invoker-solaris.c and "PCAGENT" control message in
849       proc(4)). Exit the agent thread now.
850     */
851    SysRes sres = VG_(do_syscall0)(SYS_lwp_exit);
852    if (sr_isError(sres))
853       vg_assert2(0, "The agent thread could not be exited\n");
854 #endif /* !defined(VGO_solaris) */
855 }
856 
857 /* Using ptrace calls, vgdb will force an invocation of gdbserver.
858    VG_(invoke_gdbserver) is the entry point called through the
859    vgdb ptrace technique. */
VG_(invoke_gdbserver)860 void VG_(invoke_gdbserver) ( int check )
861 {
862    /* ******* Avoid non-reentrant function call from here .....
863       till the ".... till here" below. */
864 
865    /* We need to determine the state of the various threads to decide
866       if we directly invoke gdbserver or if we rather indicate to the
867       scheduler to invoke the gdbserver.  To decide that, it is
868       critical to avoid any "coregrind" function call as the ptrace
869       might have stopped the process in the middle of this (possibly)
870       non-rentrant function.  So, it is only when all threads are in
871       an "interruptible" state that we can safely invoke
872       gdbserver. Otherwise, we let the valgrind scheduler invoke
873       gdbserver at the next poll.  This poll will be made very soon
874       thanks to a call to VG_(force_vgdb_poll). */
875    int n_tid;
876 
877    vg_assert (check == 0x8BADF00D);
878 
879    if (busy) {
880       interrupts_while_busy++;
881       give_control_back_to_vgdb();
882    }
883    interrupts_non_busy++;
884 
885    /* check if all threads are in an "interruptible" state.  If yes,
886       we invoke gdbserver. Otherwise, we tell the scheduler to wake up
887       asap. */
888    for (n_tid = 1; n_tid < VG_N_THREADS; n_tid++) {
889       switch (VG_(threads)[n_tid].status) {
890       /* interruptible states. */
891       case VgTs_WaitSys:
892       case VgTs_Yielding:
893          if (vgdb_interrupted_tid == 0) vgdb_interrupted_tid = n_tid;
894          break;
895 
896       case VgTs_Empty:
897       case VgTs_Zombie:
898          break;
899 
900       /* non interruptible states. */
901       case VgTs_Init:
902       case VgTs_Runnable:
903          interrupts_non_interruptible++;
904          VG_(force_vgdb_poll) ();
905          give_control_back_to_vgdb();
906 
907       default:             vg_assert(0);
908       }
909    }
910 
911    /* .... till here.
912       From here onwards, function calls are ok: it is
913       safe to call valgrind core functions: all threads are blocked in
914       a system call or are yielding or ... */
915    dlog(1, "invoke_gdbserver running_tid %u vgdb_interrupted_tid %u\n",
916         VG_(running_tid), vgdb_interrupted_tid);
917    call_gdbserver (vgdb_interrupted_tid, vgdb_reason);
918    vgdb_interrupted_tid = 0;
919    dlog(1,
920         "exit invoke_gdbserver running_tid %u\n", VG_(running_tid));
921    give_control_back_to_vgdb();
922 
923    vg_assert2(0, "end of invoke_gdbserver reached");
924 
925 }
926 
VG_(gdbserver_activity)927 Bool VG_(gdbserver_activity) (ThreadId tid)
928 {
929    Bool ret;
930    busy++;
931    if (!gdbserver_called)
932       call_gdbserver (tid, init_reason);
933    switch (remote_desc_activity("VG_(gdbserver_activity)")) {
934    case 0: ret = False; break;
935    case 1: ret = True; break;
936    case 2:
937       remote_finish(reset_after_error);
938       call_gdbserver (tid, init_reason);
939       ret = False;
940       break;
941    default: vg_assert (0);
942    }
943    busy--;
944    return ret;
945 }
946 
dlog_signal(const HChar * who,const vki_siginfo_t * info,ThreadId tid)947 static void dlog_signal (const HChar *who, const vki_siginfo_t *info,
948                          ThreadId tid)
949 {
950    dlog(1, "VG core calling %s "
951         "vki_nr %d %s gdb_nr %u %s tid %u\n",
952         who,
953         info->si_signo, VG_(signame)(info->si_signo),
954         target_signal_from_host (info->si_signo),
955         target_signal_to_name(target_signal_from_host (info->si_signo)),
956         tid);
957 
958 }
959 
VG_(gdbserver_report_fatal_signal)960 void VG_(gdbserver_report_fatal_signal) (const vki_siginfo_t *info,
961                                          ThreadId tid)
962 {
963    dlog_signal("VG_(gdbserver_report_fatal_signal)", info, tid);
964 
965    if (remote_connected()) {
966       dlog(1, "already connected, assuming already reported\n");
967       return;
968    }
969 
970    VG_(umsg)("(action on fatal signal) vgdb me ... \n");
971 
972    /* indicate to gdbserver that there is a signal */
973    gdbserver_signal_encountered (info);
974 
975    /* let gdbserver do some work, e.g. show the signal to the user */
976    call_gdbserver (tid, signal_reason);
977 
978 }
979 
VG_(gdbserver_report_signal)980 Bool VG_(gdbserver_report_signal) (vki_siginfo_t *info, ThreadId tid)
981 {
982    dlog_signal("VG_(gdbserver_report_signal)", info, tid);
983 
984    /* if gdbserver is currently not connected, then signal
985       is to be given to the process */
986    if (!remote_connected()) {
987       dlog(1, "not connected => pass\n");
988       return True;
989    }
990    /* if gdb has informed gdbserver that this signal can be
991       passed directly without informing gdb, then signal is
992       to be given to the process. */
993    if (pass_signals[target_signal_from_host(info->si_signo)]) {
994       dlog(1, "pass_signals => pass\n");
995       return True;
996    }
997 
998    /* indicate to gdbserver that there is a signal */
999    gdbserver_signal_encountered (info);
1000 
1001    /* let gdbserver do some work, e.g. show the signal to the user.
1002       User can also decide to ignore the signal or change the signal. */
1003    call_gdbserver (tid, signal_reason);
1004 
1005    /* ask gdbserver what is the final decision */
1006    if (gdbserver_deliver_signal (info)) {
1007       dlog(1, "gdbserver deliver signal\n");
1008       return True;
1009    } else {
1010       dlog(1, "gdbserver ignore signal\n");
1011       return False;
1012    }
1013 }
1014 
VG_(gdbserver_exit)1015 void VG_(gdbserver_exit) (ThreadId tid, VgSchedReturnCode tids_schedretcode)
1016 {
1017    dlog(1, "VG core calling VG_(gdbserver_exit) tid %u will exit\n", tid);
1018    if (remote_connected()) {
1019       /* Make sure vgdb knows we are about to die and why. */
1020       switch(tids_schedretcode) {
1021       case VgSrc_None:
1022          vg_assert (0);
1023       case VgSrc_ExitThread:
1024       case VgSrc_ExitProcess:
1025          gdbserver_process_exit_encountered ('W', VG_(threads)[tid].os_state.exitcode);
1026          call_gdbserver (tid, exit_reason);
1027          break;
1028       case VgSrc_FatalSig:
1029          gdbserver_process_exit_encountered ('X', VG_(threads)[tid].os_state.fatalsig);
1030          call_gdbserver (tid, exit_reason);
1031          break;
1032       default:
1033          vg_assert(0);
1034       }
1035    } else {
1036       dlog(1, "not connected\n");
1037    }
1038 
1039    /* Tear down the connection if it still exists. */
1040    VG_(gdbserver) (0);
1041 }
1042 
1043 // Check if single_stepping or if there is a break requested at iaddr.
1044 // If yes, call debugger
1045 VG_REGPARM(1)
VG_(helperc_CallDebugger)1046 void VG_(helperc_CallDebugger) ( HWord iaddr )
1047 {
1048    GS_Address* g;
1049 
1050    // For Vg_VgdbFull, after a fork, we might have calls to this helper
1051    // while gdbserver is not yet initialized.
1052    if (!gdbserver_called)
1053       return;
1054 
1055    if (valgrind_single_stepping() ||
1056        ((g = VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(iaddr))) &&
1057         (g->kind == GS_break))) {
1058       if (iaddr == HT_addr(ignore_this_break_once)) {
1059          dlog(1, "ignoring ignore_this_break_once %s\n",
1060               sym(ignore_this_break_once, /* is_code */ True));
1061          ignore_this_break_once = 0;
1062       } else {
1063          call_gdbserver (VG_(get_running_tid)(), break_reason);
1064       }
1065    }
1066 }
1067 
1068 /* software_breakpoint support --------------------------------------*/
1069 /* When a block is instrumented for gdbserver, single step and breaks
1070    will be obeyed in this block.  However, if a jump to another block
1071    is executed while single_stepping is active, we must ensure that
1072    this block is also instrumented. For this, when a block is
1073    instrumented for gdbserver while single_stepping, the target of all
1074    the Jump instructions in this block will be checked to verify if
1075    the block is already instrumented for gdbserver.  The below will
1076    ensure that if not already instrumented for gdbserver, the target
1077    block translation containing addr will be invalidated.  The list of
1078    gdbserved Addr will also be kept so that translations can be
1079    dropped automatically by gdbserver when going out of single step
1080    mode.
1081 
1082    Call the below at translation time if the jump target is a constant.
1083    Otherwise, rather use VG_(add_stmt_call_invalidate_if_not_gdbserved).
1084 
1085    To instrument the target exit statement, you can call
1086    VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved) rather
1087    than check the kind of target exit. */
VG_(invalidate_if_not_gdbserved)1088 static void VG_(invalidate_if_not_gdbserved) (Addr addr)
1089 {
1090    if (valgrind_single_stepping())
1091       invalidate_if_jump_not_yet_gdbserved
1092          (addr, "gdbserver target jump (instrument)");
1093 }
1094 
1095 // same as VG_(invalidate_if_not_gdbserved) but is intended to be called
1096 // at runtime (only difference is the invalidate reason which traces
1097 // it is at runtime)
1098 VG_REGPARM(1)
VG_(helperc_invalidate_if_not_gdbserved)1099 void VG_(helperc_invalidate_if_not_gdbserved) ( Addr addr )
1100 {
1101    if (valgrind_single_stepping())
1102       invalidate_if_jump_not_yet_gdbserved
1103          (addr, "gdbserver target jump (runtime)");
1104 }
1105 
VG_(add_stmt_call_invalidate_if_not_gdbserved)1106 static void VG_(add_stmt_call_invalidate_if_not_gdbserved)
1107      ( IRSB* sb_in,
1108        const VexGuestLayout* layout,
1109        const VexGuestExtents* vge,
1110        IRTemp jmp,
1111        IRSB* irsb)
1112 {
1113 
1114    void*    fn;
1115    const HChar*   nm;
1116    IRExpr** args;
1117    Int      nargs;
1118    IRDirty* di;
1119 
1120    fn    = &VG_(helperc_invalidate_if_not_gdbserved);
1121    nm    = "VG_(helperc_invalidate_if_not_gdbserved)";
1122    args  = mkIRExprVec_1(IRExpr_RdTmp (jmp));
1123    nargs = 1;
1124 
1125    di = unsafeIRDirty_0_N( nargs/*regparms*/, nm,
1126                            VG_(fnptr_to_fnentry)( fn ), args );
1127 
1128    di->nFxState = 0;
1129 
1130    addStmtToIRSB(irsb, IRStmt_Dirty(di));
1131 }
1132 
1133 /* software_breakpoint support --------------------------------------*/
1134 /* If a tool wants to allow gdbserver to do something at Addr, then
1135    VG_(add_stmt_call_gdbserver) will add in IRSB a call to a helper
1136    function.  This helper function will check if the process must be
1137    stopped at the instruction Addr: either there is a break at Addr or
1138    the process is being single-stepped.  Typical usage of the below is to
1139    instrument an Ist_IMark to allow the debugger to interact at any
1140    instruction being executed.  As soon as there is one break in a block,
1141    then to allow single stepping in this block (and possible insertions
1142    of other breaks in the same sb_in while the process is stopped), a
1143    debugger statement will be inserted for all instructions of a block. */
VG_(add_stmt_call_gdbserver)1144 static void VG_(add_stmt_call_gdbserver)
1145      (IRSB* sb_in,                /* block being translated */
1146       const VexGuestLayout* layout,
1147       const VexGuestExtents* vge,
1148       IRType gWordTy, IRType hWordTy,
1149       Addr  iaddr,                /* Addr of instruction being instrumented */
1150       UChar delta,                /* delta to add to iaddr to obtain IP */
1151       IRSB* irsb)                 /* irsb block to which call is added */
1152 {
1153    void*    fn;
1154    const HChar*   nm;
1155    IRExpr** args;
1156    Int      nargs;
1157    IRDirty* di;
1158 
1159    /* first store the address in the program counter so that the check
1160       done by VG_(helperc_CallDebugger) will be based on the correct
1161       program counter.  We might make this more efficient by rather
1162       searching for assignement to program counter and instrumenting
1163       that but the below is easier and I guess that the optimiser will
1164       remove the redundant store. And in any case, when debugging a
1165       piece of code, the efficiency requirement is not critical: very
1166       few blocks will be instrumented for debugging. */
1167 
1168    /* For platforms on which the IP can differ from the addr of the instruction
1169       being executed, we need to add the delta to obtain the IP.
1170       This IP will be given to gdb (e.g. if a breakpoint is put at iaddr).
1171 
1172       For ARM, this delta will ensure that the thumb bit is set in the
1173       IP when executing thumb code. gdb uses this thumb bit a.o.
1174       to properly guess the next IP for the 'step' and 'stepi' commands. */
1175    vg_assert(delta <= 1);
1176    addStmtToIRSB(irsb, IRStmt_Put(layout->offset_IP ,
1177                                   mkIRExpr_HWord(iaddr + (Addr)delta)));
1178 
1179    fn    = &VG_(helperc_CallDebugger);
1180    nm    = "VG_(helperc_CallDebugger)";
1181    args  = mkIRExprVec_1(mkIRExpr_HWord (iaddr));
1182    nargs = 1;
1183 
1184    di = unsafeIRDirty_0_N( nargs/*regparms*/, nm,
1185                            VG_(fnptr_to_fnentry)( fn ), args );
1186 
1187    /* Note: in fact, a debugger call can read whatever register
1188       or memory. It can also write whatever register or memory.
1189       So, in theory, we have to indicate the whole universe
1190       can be read and modified. It is however not critical
1191       to indicate precisely what is being read/written
1192       as such indications are needed for tool error detection
1193       and we do not want to have errors being detected for
1194       gdb interactions. */
1195 
1196    di->nFxState = 2;
1197    di->fxState[0].fx        = Ifx_Read;
1198    di->fxState[0].offset    = layout->offset_SP;
1199    di->fxState[0].size      = layout->sizeof_SP;
1200    di->fxState[0].nRepeats  = 0;
1201    di->fxState[0].repeatLen = 0;
1202    di->fxState[1].fx        = Ifx_Modify;
1203    di->fxState[1].offset    = layout->offset_IP;
1204    di->fxState[1].size      = layout->sizeof_IP;
1205    di->fxState[1].nRepeats  = 0;
1206    di->fxState[1].repeatLen = 0;
1207 
1208    addStmtToIRSB(irsb, IRStmt_Dirty(di));
1209 
1210 }
1211 
1212 
1213 /* Invalidate the target of the exit if needed:
1214    If target is constant, it is invalidated at translation time.
1215    Otherwise, a call to a helper function is generated to invalidate
1216    the translation at run time.
1217    The below is thus calling either VG_(invalidate_if_not_gdbserved)
1218    or VG_(add_stmt_call_invalidate_if_not_gdbserved).  */
VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved)1219 static void VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved)
1220    (IRSB* sb_in,
1221     const VexGuestLayout* layout,
1222     const VexGuestExtents* vge,
1223     IRType gWordTy,
1224     IRSB* irsb)
1225 {
1226    if (sb_in->next->tag == Iex_Const) {
1227      VG_(invalidate_if_not_gdbserved) (gWordTy == Ity_I64 ?
1228                                        sb_in->next->Iex.Const.con->Ico.U64
1229                                        : sb_in->next->Iex.Const.con->Ico.U32);
1230    } else if (sb_in->next->tag == Iex_RdTmp) {
1231      VG_(add_stmt_call_invalidate_if_not_gdbserved)
1232        (sb_in, layout, vge, sb_in->next->Iex.RdTmp.tmp, irsb);
1233    } else {
1234      vg_assert (0); /* unexpected expression tag in exit. */
1235    }
1236 }
1237 
VG_(instrument_for_gdbserver_if_needed)1238 IRSB* VG_(instrument_for_gdbserver_if_needed)
1239      (IRSB* sb_in,
1240       const VexGuestLayout* layout,
1241       const VexGuestExtents* vge,
1242       IRType gWordTy, IRType hWordTy)
1243 {
1244    IRSB* sb_out;
1245    Int i;
1246    const VgVgdb instr_needed = VG_(gdbserver_instrumentation_needed) (vge);
1247 
1248    if (instr_needed == Vg_VgdbNo)
1249      return sb_in;
1250 
1251 
1252    /* here, we need to instrument for gdbserver */
1253    sb_out = deepCopyIRSBExceptStmts(sb_in);
1254 
1255    for (i = 0; i < sb_in->stmts_used; i++) {
1256       IRStmt* st = sb_in->stmts[i];
1257 
1258       if (!st || st->tag == Ist_NoOp) continue;
1259 
1260       if (st->tag == Ist_Exit && instr_needed == Vg_VgdbYes) {
1261         VG_(invalidate_if_not_gdbserved)
1262           (hWordTy == Ity_I64 ?
1263            st->Ist.Exit.dst->Ico.U64 :
1264            st->Ist.Exit.dst->Ico.U32);
1265       }
1266       addStmtToIRSB( sb_out, st );
1267       if (st->tag == Ist_IMark) {
1268          /* For an Ist_Mark, add a call to debugger. */
1269          switch (instr_needed) {
1270          case Vg_VgdbNo: vg_assert (0);
1271          case Vg_VgdbYes:
1272          case Vg_VgdbFull:
1273             VG_(add_stmt_call_gdbserver) ( sb_in, layout, vge,
1274                                            gWordTy, hWordTy,
1275                                            st->Ist.IMark.addr,
1276                                            st->Ist.IMark.delta,
1277                                            sb_out);
1278             /* There is an optimisation possible here for Vg_VgdbFull:
1279                Put a guard ensuring we only call gdbserver if 'FullCallNeeded'.
1280                FullCallNeeded would be set to 1 we have just switched on
1281                Single Stepping or have just encountered a watchpoint
1282                or have just inserted a breakpoint.
1283                (as gdb by default removes and re-insert breakpoints), we would
1284                need to also implement the notion of 'breakpoint pending removal'
1285                to remove at the next 'continue/step' packet. */
1286             break;
1287          default: vg_assert (0);
1288          }
1289       }
1290    }
1291 
1292    if (instr_needed == Vg_VgdbYes) {
1293       VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved) (sb_in,
1294                                                                   layout, vge,
1295                                                                   gWordTy,
1296                                                                   sb_out);
1297    }
1298 
1299    return sb_out;
1300 }
1301 
1302 struct mon_out_buf {
1303    HChar buf[DATASIZ+1];
1304    int next;
1305    UInt ret;
1306 };
1307 
mon_out(HChar c,void * opaque)1308 static void mon_out (HChar c, void *opaque)
1309 {
1310    struct mon_out_buf *b = (struct mon_out_buf *) opaque;
1311    b->ret++;
1312    b->buf[b->next] = c;
1313    b->next++;
1314    if (b->next == DATASIZ) {
1315       b->buf[b->next] = '\0';
1316       monitor_output(b->buf);
1317       b->next = 0;
1318    }
1319 }
VG_(gdb_printf)1320 UInt VG_(gdb_printf) ( const HChar *format, ... )
1321 {
1322    struct mon_out_buf b;
1323 
1324    b.next = 0;
1325    b.ret = 0;
1326 
1327    va_list vargs;
1328    va_start(vargs, format);
1329    VG_(vcbprintf) (mon_out, &b, format, vargs);
1330    va_end(vargs);
1331 
1332    if (b.next > 0) {
1333       b.buf[b.next] = '\0';
1334       monitor_output(b.buf);
1335    }
1336    return b.ret;
1337 }
1338 
VG_(keyword_id)1339 Int VG_(keyword_id) (const HChar* keywords, const HChar* input_word,
1340                      kwd_report_error report)
1341 {
1342    const Int il = (input_word == NULL ? 0 : VG_(strlen) (input_word));
1343    HChar  iw[il+1];
1344    HChar  kwds[VG_(strlen)(keywords)+1];
1345    HChar  *kwdssaveptr;
1346 
1347    HChar* kw; /* current keyword, its length, its position */
1348    Int   kwl;
1349    Int   kpos = -1;
1350 
1351    Int pass;
1352    /* pass 0 = search, optional pass 1 = output message multiple matches */
1353 
1354    Int pass1needed = 0;
1355 
1356    Int partial_match = -1;
1357    Int full_match = -1;
1358 
1359    if (input_word == NULL) {
1360       iw[0] = 0;
1361       partial_match = 0; /* to force an empty string to cause an error */
1362    } else {
1363       VG_(strcpy) (iw, input_word);
1364    }
1365 
1366    for (pass = 0; pass < 2; pass++) {
1367       VG_(strcpy) (kwds, keywords);
1368       if (pass == 1)
1369          VG_(gdb_printf) ("%s can match",
1370                           (il == 0 ? "<empty string>" : iw));
1371       for (kw = VG_(strtok_r) (kwds, " ", &kwdssaveptr);
1372            kw != NULL;
1373            kw = VG_(strtok_r) (NULL, " ", &kwdssaveptr)) {
1374          kwl = VG_(strlen) (kw);
1375          kpos++;
1376 
1377          if (il > kwl) {
1378             ; /* ishtar !~ is */
1379          } else if (il == kwl) {
1380             if (VG_(strcmp) (kw, iw) == 0) {
1381                /* exact match */
1382                if (pass == 1)
1383                   VG_(gdb_printf) (" %s", kw);
1384                if (full_match != -1)
1385                   pass1needed++;
1386                full_match = kpos;
1387             }
1388          } else {
1389             /* il < kwl */
1390             if (VG_(strncmp) (iw, kw, il) == 0) {
1391                /* partial match */
1392                if (pass == 1)
1393                   VG_(gdb_printf) (" %s", kw);
1394                if (partial_match != -1)
1395                   pass1needed++;
1396                partial_match = kpos;
1397             }
1398          }
1399       }
1400       /* check for success or for no match at all */
1401       if (pass1needed == 0) {
1402          if (full_match != -1) {
1403             return full_match;
1404          } else {
1405             if (report == kwd_report_all && partial_match == -1) {
1406                VG_(gdb_printf) ("%s does not match any of '%s'\n",
1407                                 iw, keywords);
1408             }
1409             return partial_match;
1410          }
1411       }
1412 
1413       /* here we have duplicated match error */
1414       if (pass == 1 || report == kwd_report_none) {
1415          if (report != kwd_report_none) {
1416             VG_(gdb_printf) ("\n");
1417          }
1418          if (partial_match != -1 || full_match != -1)
1419             return -2;
1420          else
1421             return -1;
1422       }
1423    }
1424    /* UNREACHED */
1425    vg_assert (0);
1426 }
1427 
1428 /* True if string can be a 0x number */
is_zero_x(const HChar * s)1429 static Bool is_zero_x (const HChar *s)
1430 {
1431    if (strlen (s) >= 3 && s[0] == '0' && s[1] == 'x')
1432       return True;
1433    else
1434       return False;
1435 }
1436 
1437 /* True if string can be a 0b number */
is_zero_b(const HChar * s)1438 static Bool is_zero_b (const HChar *s)
1439 {
1440    if (strlen (s) >= 3 && s[0] == '0' && s[1] == 'b')
1441       return True;
1442    else
1443       return False;
1444 }
1445 
VG_(strtok_get_address_and_size)1446 Bool VG_(strtok_get_address_and_size) (Addr* address,
1447                                        SizeT* szB,
1448                                        HChar **ssaveptr)
1449 {
1450    HChar* wa;
1451    HChar* ws;
1452    HChar* endptr;
1453    const HChar *ppc;
1454 
1455    wa = VG_(strtok_r) (NULL, " ", ssaveptr);
1456    ppc = wa;
1457    if (ppc == NULL || !VG_(parse_Addr) (&ppc, address)) {
1458       VG_(gdb_printf) ("missing or malformed address\n");
1459       *address = (Addr) 0;
1460       *szB = 0;
1461       return False;
1462    }
1463    ws = VG_(strtok_r) (NULL, " ", ssaveptr);
1464    if (ws == NULL) {
1465       /* Do nothing, i.e. keep current value of szB. */ ;
1466    } else if (is_zero_x (ws)) {
1467       *szB = VG_(strtoull16) (ws, &endptr);
1468    } else if (is_zero_b (ws)) {
1469       Int j;
1470       HChar *parsews = ws;
1471       Int n_bits = VG_(strlen) (ws) - 2;
1472       *szB = 0;
1473       ws = NULL; // assume the below loop gives a correct nr.
1474       for (j = 0; j < n_bits; j++) {
1475          if      ('0' == parsews[j+2]) { /* do nothing */ }
1476          else if ('1' == parsews[j+2]) *szB |= (1 << (n_bits-j-1));
1477          else {
1478             /* report malformed binary integer */
1479             ws = parsews;
1480             endptr = ws + j + 2;
1481             break;
1482          }
1483       }
1484    } else {
1485       *szB = VG_(strtoull10) (ws, &endptr);
1486    }
1487 
1488    if (ws != NULL && *endptr != '\0') {
1489       VG_(gdb_printf) ("malformed integer, expecting "
1490                        "hex 0x..... or dec ...... or binary .....b\n");
1491       *address = (Addr) 0;
1492       *szB = 0;
1493       return False;
1494    }
1495    return True;
1496 }
1497 
VG_(gdbserver_status_output)1498 void VG_(gdbserver_status_output)(void)
1499 {
1500    const int nr_gdbserved_addresses
1501       = (gs_addresses == NULL ? -1 : VG_(HT_count_nodes) (gs_addresses));
1502    const int nr_watchpoints
1503       = (gs_watches == NULL ? -1 : (int) VG_(sizeXA) (gs_watches));
1504    remote_utils_output_status();
1505    VG_(umsg)
1506       ("nr of calls to gdbserver: %d\n"
1507        "single stepping %d\n"
1508        "interrupts intr_tid %u gs_non_busy %d gs_busy %d tid_non_intr %d\n"
1509        "gdbserved addresses %d (-1 = not initialized)\n"
1510        "watchpoints %d (-1 = not initialized)\n"
1511        "vgdb-error %d\n"
1512        "hostvisibility %s\n",
1513        gdbserver_called,
1514        valgrind_single_stepping(),
1515 
1516        vgdb_interrupted_tid,
1517        interrupts_non_busy,
1518        interrupts_while_busy,
1519        interrupts_non_interruptible,
1520 
1521        nr_gdbserved_addresses,
1522        nr_watchpoints,
1523        VG_(dyn_vgdb_error),
1524        hostvisibility ? "yes" : "no");
1525 }
1526