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