1
2/*--------------------------------------------------------------------*/
3/*--- Handle remote gdb protocol.                    m_gdbserver.c ---*/
4/*--------------------------------------------------------------------*/
5
6/*
7   This file is part of Valgrind, a dynamic binary instrumentation
8   framework.
9
10   Copyright (C) 2011-2013 Philippe Waroquiers
11
12   This program is free software; you can redistribute it and/or
13   modify it under the terms of the GNU General Public License as
14   published by the Free Software Foundation; either version 2 of the
15   License, or (at your option) any later version.
16
17   This program is distributed in the hope that it will be useful, but
18   WITHOUT ANY WARRANTY; without even the implied warranty of
19   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20   General Public License for more details.
21
22   You should have received a copy of the GNU General Public License
23   along with this program; if not, write to the Free Software
24   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
25   02111-1307, USA.
26
27   The GNU General Public License is contained in the file COPYING.
28*/
29
30#include "pub_core_basics.h"
31#include "pub_core_vki.h"
32#include "pub_core_debuglog.h"
33#include "pub_core_libcproc.h"
34#include "pub_core_libcprint.h"
35#include "pub_core_mallocfree.h"
36#include "pub_core_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
53Int VG_(dyn_vgdb_error);
54
55/* forward declarations */
56VG_REGPARM(1)
57void VG_(helperc_CallDebugger) ( HWord iaddr );
58VG_REGPARM(1)
59void VG_(helperc_invalidate_if_not_gdbserved) ( Addr addr );
60static void invalidate_current_ip (ThreadId tid, const HChar *who);
61
62/* reasons of call to call_gdbserver. */
63typedef
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
74static 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*/
130static Addr ignore_this_break_once = 0;
131
132
133static 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. */
138static 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 */
161static int gdbserver_called = 0;
162static int gdbserver_exited = 0;
163
164/* alloc and free functions for xarray and similar. */
165static void* gs_alloc (const HChar* cc, SizeT sz)
166{
167   return VG_(malloc)(cc, sz);
168}
169static void gs_free (void* ptr)
170{
171   VG_(free)(ptr);
172}
173
174typedef
175   enum {
176     GS_break,
177     GS_jump
178   }
179   GS_Kind;
180
181typedef
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*/
200static 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.
204static 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
213static 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
230static 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
239const 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
251typedef
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. */
261static XArray* gs_watches = NULL;
262
263static 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. */
271static 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. */
296static 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
330static Bool (*tool_watchpoint) (PointKind kind,
331                                Bool insert,
332                                Addr addr,
333                                SizeT len) = NULL;
334void VG_(needs_watchpoint) (Bool (*watchpoint) (PointKind kind,
335                                                Bool insert,
336                                                Addr addr,
337                                                SizeT len))
338{
339   tool_watchpoint = watchpoint;
340}
341
342Bool 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
401Bool 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
410Bool VG_(is_watched)(PointKind kind, Addr addr, Int szB)
411{
412   Word n_elems;
413   GS_Watch* g;
414   Word i;
415   Bool watched = False;
416   const ThreadId tid = VG_(running_tid);
417
418   if (!gdbserver_called)
419      return False;
420
421   n_elems = VG_(sizeXA) (gs_watches);
422
423   Addr to = addr + szB; // semi-open interval [addr, to[
424
425   vg_assert (kind == access_watchpoint
426              || kind == read_watchpoint
427              || kind == write_watchpoint);
428   dlog(1, "tid %d VG_(is_watched) %s addr %p szB %d\n",
429        tid, VG_(ppPointKind) (kind), C2v(addr), szB);
430
431   for (i = 0; i < n_elems; i++) {
432      g = index_gs_watches(i);
433      switch (g->kind) {
434      case software_breakpoint:
435      case hardware_breakpoint:
436         break;
437      case access_watchpoint:
438      case read_watchpoint:
439      case write_watchpoint:
440         if (to <= g->addr || addr >= (g->addr + g->len))
441            /* If no overlap, examine next watchpoint: */
442            continue;
443
444         watched = True; /* We have an overlap */
445
446         /* call gdbserver if access kind reported by the tool
447            matches the watchpoint kind. */
448         if (kind == access_watchpoint
449             || g->kind == access_watchpoint
450             || g->kind == kind) {
451            /* Watchpoint encountered.
452               If this is a read watchpoint, we directly call gdbserver
453               to report it to gdb.
454               Otherwise, for a write watchpoint, we have to finish
455               the instruction so as to modify the value.
456               If we do not finish the instruction, then gdb sees no
457               value change and continues.
458               For a read watchpoint, we better call gdbserver directly:
459               in case the current block is not gdbserved, Valgrind
460               will execute instructions till the next block. */
461
462            /* set the watchpoint stop address to the first read or written. */
463            if (g->addr <= addr) {
464               VG_(set_watchpoint_stop_address) (addr);
465            } else {
466               VG_(set_watchpoint_stop_address) (g->addr);
467            }
468
469            if (kind == write_watchpoint) {
470               /* Let Valgrind stop as early as possible after this instruction
471                  by switching to Single Stepping mode. */
472               valgrind_set_single_stepping (True);
473               invalidate_current_ip (tid, "m_gdbserver write watchpoint");
474            } else {
475               call_gdbserver (tid, watch_reason);
476               VG_(set_watchpoint_stop_address) ((Addr) 0);
477            }
478            return True; // we are watched here.
479         }
480         break;
481      default:
482         vg_assert (0);
483      }
484   }
485   return watched;
486}
487
488/* Returns the reason for which gdbserver instrumentation is needed */
489static 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.
538static void clear_gdbserved_addresses(Bool clear_only_jumps)
539{
540   GS_Address** ag;
541   UInt n_elems;
542   int i;
543
544   dlog(1,
545        "clear_gdbserved_addresses: scanning hash table nodes %d\n",
546        VG_(HT_count_nodes) (gs_addresses));
547   ag = (GS_Address**) VG_(HT_to_array) (gs_addresses, &n_elems);
548   for (i = 0; i < n_elems; i++)
549      if (!clear_only_jumps || ag[i]->kind == GS_jump)
550         remove_gs_address (ag[i], "clear_gdbserved_addresses");
551   VG_(free) (ag);
552}
553
554// Clear watched addressed in gs_watches, delete gs_watches.
555static 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
579static 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
586static void invalidate_current_ip (ThreadId tid, const HChar *who)
587{
588   invalidate_if_jump_not_yet_gdbserved (VG_(get_IP) (tid), who);
589}
590
591Bool VG_(gdbserver_init_done) (void)
592{
593   return gdbserver_called > 0;
594}
595
596Bool VG_(gdbserver_stop_at) (VgdbStopAt stopat)
597{
598   return gdbserver_called > 0 && VgdbStopAtiS(stopat, VG_(clo_vgdb_stop_at));
599}
600
601void 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 */
623static void gdbserver_cleanup_in_child_after_fork(ThreadId me)
624{
625   dlog(1, "thread %d gdbserver_cleanup_in_child_after_fork pid %d\n",
626        me, VG_(getpid) ());
627
628   /* finish connection inheritated from parent */
629   remote_finish(reset_after_fork);
630
631   /* ensure next call to gdbserver will be considered as a brand
632      new call that will initialize a fresh gdbserver. */
633   if (gdbserver_called) {
634      gdbserver_called = 0;
635      vg_assert (gs_addresses != NULL);
636      vg_assert (gs_watches != NULL);
637      clear_gdbserved_addresses(/* clear only jumps */ False);
638      VG_(HT_destruct) (gs_addresses, VG_(free));
639      gs_addresses = NULL;
640      clear_watched_addresses();
641   } else {
642      vg_assert (gs_addresses == NULL);
643      vg_assert (gs_watches == NULL);
644   }
645
646
647   if (VG_(clo_trace_children)) {
648      VG_(gdbserver_prerun_action) (me);
649   }
650}
651
652/* If reason is init_reason, creates the connection resources (e.g.
653      the FIFOs) to allow a gdb connection to be detected by polling
654      using remote_desc_activity.
655   Otherwise (other reasons):
656       If connection with gdb not yet opened, opens the connection with gdb.
657       reads gdb remote protocol packets and executes the requested commands.
658*/
659static void call_gdbserver ( ThreadId tid , CallReason reason)
660{
661   ThreadState*     tst = VG_(get_ThreadState)(tid);
662   int stepping;
663   Addr saved_pc;
664
665   dlog(1,
666        "entering call_gdbserver %s ... pid %d tid %d status %s "
667        "sched_jmpbuf_valid %d\n",
668        ppCallReason (reason),
669        VG_(getpid) (), tid, VG_(name_of_ThreadStatus)(tst->status),
670        tst->sched_jmpbuf_valid);
671
672   /* If we are about to die, then just run server_main() once to get
673      the resume reply out and return immediately because most of the state
674      of this tid and process is about to be torn down. */
675   if (reason == exit_reason) {
676      server_main();
677      return;
678   }
679
680   vg_assert(VG_(is_valid_tid)(tid));
681   saved_pc = VG_(get_IP) (tid);
682
683   if (gdbserver_exited) {
684      dlog(0, "call_gdbserver called when gdbserver_exited %d\n",
685           gdbserver_exited);
686      return;
687   }
688
689   if (gdbserver_called == 0) {
690      vg_assert (gs_addresses == NULL);
691      vg_assert (gs_watches == NULL);
692      gs_addresses = VG_(HT_construct)( "gdbserved_addresses" );
693      gs_watches = VG_(newXA)(gs_alloc,
694                              "gdbserved_watches",
695                              gs_free,
696                              sizeof(GS_Watch*));
697      VG_(atfork)(NULL, NULL, gdbserver_cleanup_in_child_after_fork);
698   }
699   vg_assert (gs_addresses != NULL);
700   vg_assert (gs_watches != NULL);
701
702   gdbserver_called++;
703
704   /* call gdbserver_init if this is the first call to gdbserver. */
705   if (gdbserver_called == 1)
706      gdbserver_init();
707
708   if (reason == init_reason || gdbserver_called == 1)
709      remote_open(VG_(clo_vgdb_prefix));
710
711   /* if the call reason is to initialize, then return control to
712      valgrind. After this initialization, gdbserver will be called
713      again either if there is an error detected by valgrind or
714      if vgdb sends data to the valgrind process. */
715   if (reason == init_reason) {
716      return;
717   }
718
719   stepping = valgrind_single_stepping();
720
721   server_main();
722
723   ignore_this_break_once = valgrind_get_ignore_break_once();
724   if (ignore_this_break_once)
725      dlog(1, "!!! will ignore_this_break_once %s\n",
726           sym(ignore_this_break_once, /* is_code */ True));
727
728
729   if (valgrind_single_stepping()) {
730      /* we are single stepping. If we were not stepping on entry,
731         then invalidate the current program counter so as to properly
732         do single step. In case the program counter was changed by
733         gdb, this will also invalidate the target address we will
734         jump to. */
735      if (!stepping && tid != 0) {
736         invalidate_current_ip (tid, "m_gdbserver single step");
737      }
738   } else {
739      /* We are not single stepping.  If we were stepping on entry,
740         then clear the gdbserved addresses.  This will cause all
741         these gdbserved blocks to be invalidated so that they can be
742         re-translated without being gdbserved. */
743      if (stepping)
744         clear_gdbserved_addresses(/* clear only jumps */ True);
745   }
746
747   /* can't do sanity check at beginning. At least the stack
748      check is not yet possible. */
749   if (gdbserver_called > 1)
750      VG_(sanity_check_general) (/* force_expensive */ False);
751
752   /* If the PC has been changed by gdb, then we VG_MINIMAL_LONGJMP to
753      the scheduler to execute the block of the new PC.
754      Otherwise we just return to continue executing the
755      current block. */
756   if (VG_(get_IP) (tid) != saved_pc) {
757      dlog(1, "tid %d %s PC changed from %s to %s\n",
758           tid, VG_(name_of_ThreadStatus) (tst->status),
759           sym(saved_pc, /* is_code */ True),
760           sym(VG_(get_IP) (tid), /* is_code */ True));
761      if (tst->status == VgTs_Yielding) {
762         SysRes sres;
763         VG_(memset)(&sres, 0, sizeof(SysRes));
764         VG_(acquire_BigLock)(tid, "gdbsrv VG_MINIMAL_LONGJMP");
765      }
766      if (tst->sched_jmpbuf_valid) {
767         /* resume scheduler */
768         VG_MINIMAL_LONGJMP(tst->sched_jmpbuf);
769      }
770      /* else continue to run */
771   }
772   /* continue to run */
773}
774
775/* busy > 0 when gdbserver is currently being called.
776   busy is used to to avoid vgdb invoking gdbserver
777   while gdbserver by Valgrind. */
778static volatile int busy = 0;
779
780void VG_(gdbserver) ( ThreadId tid )
781{
782   busy++;
783   /* called by the rest of valgrind for
784         --vgdb-error=0 reason
785      or by scheduler "poll/debug/interrupt" reason
786      or to terminate. */
787   if (tid != 0) {
788      call_gdbserver (tid, core_reason);
789   } else {
790      if (gdbserver_called == 0) {
791         dlog(1, "VG_(gdbserver) called to terminate, nothing to terminate\n");
792      } else if (gdbserver_exited) {
793         dlog(0, "VG_(gdbserver) called to terminate again %d\n",
794              gdbserver_exited);
795      } else {
796         gdbserver_terminate();
797         gdbserver_exited++;
798      }
799   }
800   busy--;
801}
802
803// nr of invoke_gdbserver while gdbserver is already executing.
804static int interrupts_while_busy = 0;
805
806// nr of invoke_gdbserver while gdbserver is not executing.
807static int interrupts_non_busy = 0;
808
809// nr of invoke_gdbserver when some threads are not interruptible.
810static 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
829static void give_control_back_to_vgdb(void)
830{
831   /* cause a SIGSTOP to be sent to ourself, so that vgdb takes control.
832      vgdb will then restore the stack so as to resume the activity
833      before the ptrace (typically do_syscall_WRK). */
834   if (VG_(kill)(VG_(getpid)(), VKI_SIGSTOP) != 0)
835      vg_assert2(0, "SIGSTOP for vgdb could not be generated\n");
836
837   /* If we arrive here, it means a call was pushed on the stack
838      by vgdb, but during this call, vgdb and/or connection
839      died. Alternatively, it is a bug in the vgdb<=>Valgrind gdbserver
840      ptrace handling. */
841   vg_assert2(0,
842              "vgdb did not took control. Did you kill vgdb ?\n"
843              "busy %d vgdb_interrupted_tid %d\n",
844              busy, vgdb_interrupted_tid);
845}
846
847/* Using ptrace calls, vgdb will force an invocation of gdbserver.
848   VG_(invoke_gdbserver) is the entry point called through the
849   vgdb ptrace technique. */
850void VG_(invoke_gdbserver) ( int check )
851{
852   /* ******* Avoid non-reentrant function call from here .....
853      till the ".... till here" below. */
854
855   /* We need to determine the state of the various threads to decide
856      if we directly invoke gdbserver or if we rather indicate to the
857      scheduler to invoke the gdbserver.  To decide that, it is
858      critical to avoid any "coregrind" function call as the ptrace
859      might have stopped the process in the middle of this (possibly)
860      non-rentrant function.  So, it is only when all threads are in
861      an "interruptible" state that we can safely invoke
862      gdbserver. Otherwise, we let the valgrind scheduler invoke
863      gdbserver at the next poll.  This poll will be made very soon
864      thanks to a call to VG_(force_vgdb_poll). */
865   int n_tid;
866
867   vg_assert (check == 0x8BADF00D);
868
869   if (busy) {
870      interrupts_while_busy++;
871      give_control_back_to_vgdb();
872   }
873   interrupts_non_busy++;
874
875   /* check if all threads are in an "interruptible" state.  If yes,
876      we invoke gdbserver. Otherwise, we tell the scheduler to wake up
877      asap. */
878   for (n_tid = 1; n_tid < VG_N_THREADS; n_tid++) {
879      switch (VG_(threads)[n_tid].status) {
880      /* interruptible states. */
881      case VgTs_WaitSys:
882      case VgTs_Yielding:
883         if (vgdb_interrupted_tid == 0) vgdb_interrupted_tid = n_tid;
884         break;
885
886      case VgTs_Empty:
887      case VgTs_Zombie:
888         break;
889
890      /* non interruptible states. */
891      case VgTs_Init:
892      case VgTs_Runnable:
893         interrupts_non_interruptible++;
894         VG_(force_vgdb_poll) ();
895         give_control_back_to_vgdb();
896
897      default:             vg_assert(0);
898      }
899   }
900
901   /* .... till here.
902      From here onwards, function calls are ok: it is
903      safe to call valgrind core functions: all threads are blocked in
904      a system call or are yielding or ... */
905   dlog(1, "invoke_gdbserver running_tid %d vgdb_interrupted_tid %d\n",
906        VG_(running_tid), vgdb_interrupted_tid);
907   call_gdbserver (vgdb_interrupted_tid, vgdb_reason);
908   vgdb_interrupted_tid = 0;
909   dlog(1,
910        "exit invoke_gdbserver running_tid %d\n", VG_(running_tid));
911   give_control_back_to_vgdb();
912
913   vg_assert2(0, "end of invoke_gdbserver reached");
914
915}
916
917Bool VG_(gdbserver_activity) (ThreadId tid)
918{
919   Bool ret;
920   busy++;
921   if (!gdbserver_called)
922      call_gdbserver (tid, init_reason);
923   switch (remote_desc_activity("VG_(gdbserver_activity)")) {
924   case 0: ret = False; break;
925   case 1: ret = True; break;
926   case 2:
927      remote_finish(reset_after_error);
928      call_gdbserver (tid, init_reason);
929      ret = False;
930      break;
931   default: vg_assert (0);
932   }
933   busy--;
934   return ret;
935}
936
937static void dlog_signal (const HChar *who, const vki_siginfo_t *info,
938                         ThreadId tid)
939{
940   dlog(1, "VG core calling %s "
941        "vki_nr %d %s gdb_nr %d %s tid %d\n",
942        who,
943        info->si_signo, VG_(signame)(info->si_signo),
944        target_signal_from_host (info->si_signo),
945        target_signal_to_name(target_signal_from_host (info->si_signo)),
946        tid);
947
948}
949
950void VG_(gdbserver_report_fatal_signal) (const vki_siginfo_t *info,
951                                         ThreadId tid)
952{
953   dlog_signal("VG_(gdbserver_report_fatal_signal)", info, tid);
954
955   if (remote_connected()) {
956      dlog(1, "already connected, assuming already reported\n");
957      return;
958   }
959
960   VG_(umsg)("(action on fatal signal) vgdb me ... \n");
961
962   /* indicate to gdbserver that there is a signal */
963   gdbserver_signal_encountered (info);
964
965   /* let gdbserver do some work, e.g. show the signal to the user */
966   call_gdbserver (tid, signal_reason);
967
968}
969
970Bool VG_(gdbserver_report_signal) (vki_siginfo_t *info, ThreadId tid)
971{
972   dlog_signal("VG_(gdbserver_report_signal)", info, tid);
973
974   /* if gdbserver is currently not connected, then signal
975      is to be given to the process */
976   if (!remote_connected()) {
977      dlog(1, "not connected => pass\n");
978      return True;
979   }
980   /* if gdb has informed gdbserver that this signal can be
981      passed directly without informing gdb, then signal is
982      to be given to the process. */
983   if (pass_signals[target_signal_from_host(info->si_signo)]) {
984      dlog(1, "pass_signals => pass\n");
985      return True;
986   }
987
988   /* indicate to gdbserver that there is a signal */
989   gdbserver_signal_encountered (info);
990
991   /* let gdbserver do some work, e.g. show the signal to the user.
992      User can also decide to ignore the signal or change the signal. */
993   call_gdbserver (tid, signal_reason);
994
995   /* ask gdbserver what is the final decision */
996   if (gdbserver_deliver_signal (info)) {
997      dlog(1, "gdbserver deliver signal\n");
998      return True;
999   } else {
1000      dlog(1, "gdbserver ignore signal\n");
1001      return False;
1002   }
1003}
1004
1005void VG_(gdbserver_exit) (ThreadId tid, VgSchedReturnCode tids_schedretcode)
1006{
1007   dlog(1, "VG core calling VG_(gdbserver_exit) tid %d will exit\n", tid);
1008   if (remote_connected()) {
1009      /* Make sure vgdb knows we are about to die and why. */
1010      switch(tids_schedretcode) {
1011      case VgSrc_None:
1012         vg_assert (0);
1013      case VgSrc_ExitThread:
1014      case VgSrc_ExitProcess:
1015         gdbserver_process_exit_encountered ('W', VG_(threads)[tid].os_state.exitcode);
1016         call_gdbserver (tid, exit_reason);
1017         break;
1018      case VgSrc_FatalSig:
1019         gdbserver_process_exit_encountered ('X', VG_(threads)[tid].os_state.fatalsig);
1020         call_gdbserver (tid, exit_reason);
1021         break;
1022      default:
1023         vg_assert(0);
1024      }
1025   } else {
1026      dlog(1, "not connected\n");
1027   }
1028
1029   /* Tear down the connection if it still exists. */
1030   VG_(gdbserver) (0);
1031}
1032
1033// Check if single_stepping or if there is a break requested at iaddr.
1034// If yes, call debugger
1035VG_REGPARM(1)
1036void VG_(helperc_CallDebugger) ( HWord iaddr )
1037{
1038   GS_Address* g;
1039
1040   // For Vg_VgdbFull, after a fork, we might have calls to this helper
1041   // while gdbserver is not yet initialized.
1042   if (!gdbserver_called)
1043      return;
1044
1045   if (valgrind_single_stepping() ||
1046       ((g = VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(iaddr))) &&
1047        (g->kind == GS_break))) {
1048      if (iaddr == HT_addr(ignore_this_break_once)) {
1049         dlog(1, "ignoring ignore_this_break_once %s\n",
1050              sym(ignore_this_break_once, /* is_code */ True));
1051         ignore_this_break_once = 0;
1052      } else {
1053         call_gdbserver (VG_(get_running_tid)(), break_reason);
1054      }
1055   }
1056}
1057
1058/* software_breakpoint support --------------------------------------*/
1059/* When a block is instrumented for gdbserver, single step and breaks
1060   will be obeyed in this block.  However, if a jump to another block
1061   is executed while single_stepping is active, we must ensure that
1062   this block is also instrumented. For this, when a block is
1063   instrumented for gdbserver while single_stepping, the target of all
1064   the Jump instructions in this block will be checked to verify if
1065   the block is already instrumented for gdbserver.  The below will
1066   ensure that if not already instrumented for gdbserver, the target
1067   block translation containing addr will be invalidated.  The list of
1068   gdbserved Addr will also be kept so that translations can be
1069   dropped automatically by gdbserver when going out of single step
1070   mode.
1071
1072   Call the below at translation time if the jump target is a constant.
1073   Otherwise, rather use VG_(add_stmt_call_invalidate_if_not_gdbserved).
1074
1075   To instrument the target exit statement, you can call
1076   VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved) rather
1077   than check the kind of target exit. */
1078static void VG_(invalidate_if_not_gdbserved) (Addr addr)
1079{
1080   if (valgrind_single_stepping())
1081      invalidate_if_jump_not_yet_gdbserved
1082         (addr, "gdbserver target jump (instrument)");
1083}
1084
1085// same as VG_(invalidate_if_not_gdbserved) but is intended to be called
1086// at runtime (only difference is the invalidate reason which traces
1087// it is at runtime)
1088VG_REGPARM(1)
1089void VG_(helperc_invalidate_if_not_gdbserved) ( Addr addr )
1090{
1091   if (valgrind_single_stepping())
1092      invalidate_if_jump_not_yet_gdbserved
1093         (addr, "gdbserver target jump (runtime)");
1094}
1095
1096static void VG_(add_stmt_call_invalidate_if_not_gdbserved)
1097     ( IRSB* sb_in,
1098       const VexGuestLayout* layout,
1099       const VexGuestExtents* vge,
1100       IRTemp jmp,
1101       IRSB* irsb)
1102{
1103
1104   void*    fn;
1105   const HChar*   nm;
1106   IRExpr** args;
1107   Int      nargs;
1108   IRDirty* di;
1109
1110   fn    = &VG_(helperc_invalidate_if_not_gdbserved);
1111   nm    = "VG_(helperc_invalidate_if_not_gdbserved)";
1112   args  = mkIRExprVec_1(IRExpr_RdTmp (jmp));
1113   nargs = 1;
1114
1115   di = unsafeIRDirty_0_N( nargs/*regparms*/, nm,
1116                           VG_(fnptr_to_fnentry)( fn ), args );
1117
1118   di->nFxState = 0;
1119
1120   addStmtToIRSB(irsb, IRStmt_Dirty(di));
1121}
1122
1123/* software_breakpoint support --------------------------------------*/
1124/* If a tool wants to allow gdbserver to do something at Addr, then
1125   VG_(add_stmt_call_gdbserver) will add in IRSB a call to a helper
1126   function.  This helper function will check if the process must be
1127   stopped at the instruction Addr: either there is a break at Addr or
1128   the process is being single-stepped.  Typical usage of the below is to
1129   instrument an Ist_IMark to allow the debugger to interact at any
1130   instruction being executed.  As soon as there is one break in a block,
1131   then to allow single stepping in this block (and possible insertions
1132   of other breaks in the same sb_in while the process is stopped), a
1133   debugger statement will be inserted for all instructions of a block. */
1134static void VG_(add_stmt_call_gdbserver)
1135     (IRSB* sb_in,                /* block being translated */
1136      const VexGuestLayout* layout,
1137      const VexGuestExtents* vge,
1138      IRType gWordTy, IRType hWordTy,
1139      Addr  iaddr,                /* Addr of instruction being instrumented */
1140      UChar delta,                /* delta to add to iaddr to obtain IP */
1141      IRSB* irsb)                 /* irsb block to which call is added */
1142{
1143   void*    fn;
1144   const HChar*   nm;
1145   IRExpr** args;
1146   Int      nargs;
1147   IRDirty* di;
1148
1149   /* first store the address in the program counter so that the check
1150      done by VG_(helperc_CallDebugger) will be based on the correct
1151      program counter.  We might make this more efficient by rather
1152      searching for assignement to program counter and instrumenting
1153      that but the below is easier and I guess that the optimiser will
1154      remove the redundant store. And in any case, when debugging a
1155      piece of code, the efficiency requirement is not critical: very
1156      few blocks will be instrumented for debugging. */
1157
1158   /* For platforms on which the IP can differ from the addr of the instruction
1159      being executed, we need to add the delta to obtain the IP.
1160      This IP will be given to gdb (e.g. if a breakpoint is put at iaddr).
1161
1162      For ARM, this delta will ensure that the thumb bit is set in the
1163      IP when executing thumb code. gdb uses this thumb bit a.o.
1164      to properly guess the next IP for the 'step' and 'stepi' commands. */
1165   vg_assert(delta <= 1);
1166   addStmtToIRSB(irsb, IRStmt_Put(layout->offset_IP ,
1167                                  mkIRExpr_HWord(iaddr + (Addr)delta)));
1168
1169   fn    = &VG_(helperc_CallDebugger);
1170   nm    = "VG_(helperc_CallDebugger)";
1171   args  = mkIRExprVec_1(mkIRExpr_HWord (iaddr));
1172   nargs = 1;
1173
1174   di = unsafeIRDirty_0_N( nargs/*regparms*/, nm,
1175                           VG_(fnptr_to_fnentry)( fn ), args );
1176
1177   /* Note: in fact, a debugger call can read whatever register
1178      or memory. It can also write whatever register or memory.
1179      So, in theory, we have to indicate the whole universe
1180      can be read and modified. It is however not critical
1181      to indicate precisely what is being read/written
1182      as such indications are needed for tool error detection
1183      and we do not want to have errors being detected for
1184      gdb interactions. */
1185
1186   di->nFxState = 2;
1187   di->fxState[0].fx        = Ifx_Read;
1188   di->fxState[0].offset    = layout->offset_SP;
1189   di->fxState[0].size      = layout->sizeof_SP;
1190   di->fxState[0].nRepeats  = 0;
1191   di->fxState[0].repeatLen = 0;
1192   di->fxState[1].fx        = Ifx_Modify;
1193   di->fxState[1].offset    = layout->offset_IP;
1194   di->fxState[1].size      = layout->sizeof_IP;
1195   di->fxState[1].nRepeats  = 0;
1196   di->fxState[1].repeatLen = 0;
1197
1198   addStmtToIRSB(irsb, IRStmt_Dirty(di));
1199
1200}
1201
1202
1203/* Invalidate the target of the exit if needed:
1204   If target is constant, it is invalidated at translation time.
1205   Otherwise, a call to a helper function is generated to invalidate
1206   the translation at run time.
1207   The below is thus calling either VG_(invalidate_if_not_gdbserved)
1208   or VG_(add_stmt_call_invalidate_if_not_gdbserved).  */
1209static void VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved)
1210   (IRSB* sb_in,
1211    const VexGuestLayout* layout,
1212    const VexGuestExtents* vge,
1213    IRType gWordTy,
1214    IRSB* irsb)
1215{
1216   if (sb_in->next->tag == Iex_Const) {
1217     VG_(invalidate_if_not_gdbserved) (gWordTy == Ity_I64 ?
1218                                       sb_in->next->Iex.Const.con->Ico.U64
1219                                       : sb_in->next->Iex.Const.con->Ico.U32);
1220   } else if (sb_in->next->tag == Iex_RdTmp) {
1221     VG_(add_stmt_call_invalidate_if_not_gdbserved)
1222       (sb_in, layout, vge, sb_in->next->Iex.RdTmp.tmp, irsb);
1223   } else {
1224     vg_assert (0); /* unexpected expression tag in exit. */
1225   }
1226}
1227
1228IRSB* VG_(instrument_for_gdbserver_if_needed)
1229     (IRSB* sb_in,
1230      const VexGuestLayout* layout,
1231      const VexGuestExtents* vge,
1232      IRType gWordTy, IRType hWordTy)
1233{
1234   IRSB* sb_out;
1235   Int i;
1236   const VgVgdb instr_needed = VG_(gdbserver_instrumentation_needed) (vge);
1237
1238   if (instr_needed == Vg_VgdbNo)
1239     return sb_in;
1240
1241
1242   /* here, we need to instrument for gdbserver */
1243   sb_out = deepCopyIRSBExceptStmts(sb_in);
1244
1245   for (i = 0; i < sb_in->stmts_used; i++) {
1246      IRStmt* st = sb_in->stmts[i];
1247
1248      if (!st || st->tag == Ist_NoOp) continue;
1249
1250      if (st->tag == Ist_Exit && instr_needed == Vg_VgdbYes) {
1251        VG_(invalidate_if_not_gdbserved)
1252          (hWordTy == Ity_I64 ?
1253           st->Ist.Exit.dst->Ico.U64 :
1254           st->Ist.Exit.dst->Ico.U32);
1255      }
1256      addStmtToIRSB( sb_out, st );
1257      if (st->tag == Ist_IMark) {
1258         /* For an Ist_Mark, add a call to debugger. */
1259         switch (instr_needed) {
1260         case Vg_VgdbNo: vg_assert (0);
1261         case Vg_VgdbYes:
1262         case Vg_VgdbFull:
1263            VG_(add_stmt_call_gdbserver) ( sb_in, layout, vge,
1264                                           gWordTy, hWordTy,
1265                                           st->Ist.IMark.addr,
1266                                           st->Ist.IMark.delta,
1267                                           sb_out);
1268            /* There is an optimisation possible here for Vg_VgdbFull:
1269               Put a guard ensuring we only call gdbserver if 'FullCallNeeded'.
1270               FullCallNeeded would be set to 1 we have just switched on
1271               Single Stepping or have just encountered a watchpoint
1272               or have just inserted a breakpoint.
1273               (as gdb by default removes and re-insert breakpoints), we would
1274               need to also implement the notion of 'breakpoint pending removal'
1275               to remove at the next 'continue/step' packet. */
1276            break;
1277         default: vg_assert (0);
1278         }
1279      }
1280   }
1281
1282   if (instr_needed == Vg_VgdbYes) {
1283      VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved) (sb_in,
1284                                                                  layout, vge,
1285                                                                  gWordTy,
1286                                                                  sb_out);
1287   }
1288
1289   return sb_out;
1290}
1291
1292struct mon_out_buf {
1293   HChar buf[DATASIZ+1];
1294   int next;
1295   UInt ret;
1296};
1297
1298static void mon_out (HChar c, void *opaque)
1299{
1300   struct mon_out_buf *b = (struct mon_out_buf *) opaque;
1301   b->ret++;
1302   b->buf[b->next] = c;
1303   b->next++;
1304   if (b->next == DATASIZ) {
1305      b->buf[b->next] = '\0';
1306      monitor_output(b->buf);
1307      b->next = 0;
1308   }
1309}
1310UInt VG_(gdb_printf) ( const HChar *format, ... )
1311{
1312   struct mon_out_buf b;
1313
1314   b.next = 0;
1315   b.ret = 0;
1316
1317   va_list vargs;
1318   va_start(vargs, format);
1319   VG_(vcbprintf) (mon_out, &b, format, vargs);
1320   va_end(vargs);
1321
1322   if (b.next > 0) {
1323      b.buf[b.next] = '\0';
1324      monitor_output(b.buf);
1325   }
1326   return b.ret;
1327}
1328
1329Int VG_(keyword_id) (const HChar* keywords, const HChar* input_word,
1330                     kwd_report_error report)
1331{
1332   const Int il = (input_word == NULL ? 0 : VG_(strlen) (input_word));
1333   HChar  iw[il+1];
1334   HChar  kwds[VG_(strlen)(keywords)+1];
1335   HChar  *kwdssaveptr;
1336
1337   HChar* kw; /* current keyword, its length, its position */
1338   Int   kwl;
1339   Int   kpos = -1;
1340
1341   Int pass;
1342   /* pass 0 = search, optional pass 1 = output message multiple matches */
1343
1344   Int pass1needed = 0;
1345
1346   Int partial_match = -1;
1347   Int full_match = -1;
1348
1349   if (input_word == NULL) {
1350      iw[0] = 0;
1351      partial_match = 0; /* to force an empty string to cause an error */
1352   } else {
1353      VG_(strcpy) (iw, input_word);
1354   }
1355
1356   for (pass = 0; pass < 2; pass++) {
1357      VG_(strcpy) (kwds, keywords);
1358      if (pass == 1)
1359         VG_(gdb_printf) ("%s can match",
1360                          (il == 0 ? "<empty string>" : iw));
1361      for (kw = VG_(strtok_r) (kwds, " ", &kwdssaveptr);
1362           kw != NULL;
1363           kw = VG_(strtok_r) (NULL, " ", &kwdssaveptr)) {
1364         kwl = VG_(strlen) (kw);
1365         kpos++;
1366
1367         if (il > kwl) {
1368            ; /* ishtar !~ is */
1369         } else if (il == kwl) {
1370            if (VG_(strcmp) (kw, iw) == 0) {
1371               /* exact match */
1372               if (pass == 1)
1373                  VG_(gdb_printf) (" %s", kw);
1374               if (full_match != -1)
1375                  pass1needed++;
1376               full_match = kpos;
1377            }
1378         } else {
1379            /* il < kwl */
1380            if (VG_(strncmp) (iw, kw, il) == 0) {
1381               /* partial match */
1382               if (pass == 1)
1383                  VG_(gdb_printf) (" %s", kw);
1384               if (partial_match != -1)
1385                  pass1needed++;
1386               partial_match = kpos;
1387            }
1388         }
1389      }
1390      /* check for success or for no match at all */
1391      if (pass1needed == 0) {
1392         if (full_match != -1) {
1393            return full_match;
1394         } else {
1395            if (report == kwd_report_all && partial_match == -1) {
1396               VG_(gdb_printf) ("%s does not match any of '%s'\n",
1397                                iw, keywords);
1398            }
1399            return partial_match;
1400         }
1401      }
1402
1403      /* here we have duplicated match error */
1404      if (pass == 1 || report == kwd_report_none) {
1405         if (report != kwd_report_none) {
1406            VG_(gdb_printf) ("\n");
1407         }
1408         if (partial_match != -1 || full_match != -1)
1409            return -2;
1410         else
1411            return -1;
1412      }
1413   }
1414   /* UNREACHED */
1415   vg_assert (0);
1416}
1417
1418/* True if string can be a 0x number */
1419static Bool is_zero_x (const HChar *s)
1420{
1421   if (strlen (s) >= 3 && s[0] == '0' && s[1] == 'x')
1422      return True;
1423   else
1424      return False;
1425}
1426
1427/* True if string can be a 0b number */
1428static Bool is_zero_b (const HChar *s)
1429{
1430   if (strlen (s) >= 3 && s[0] == '0' && s[1] == 'b')
1431      return True;
1432   else
1433      return False;
1434}
1435
1436Bool VG_(strtok_get_address_and_size) (Addr* address,
1437                                       SizeT* szB,
1438                                       HChar **ssaveptr)
1439{
1440   HChar* wa;
1441   HChar* ws;
1442   HChar* endptr;
1443   const HChar *ppc;
1444
1445   wa = VG_(strtok_r) (NULL, " ", ssaveptr);
1446   ppc = wa;
1447   if (ppc == NULL || !VG_(parse_Addr) (&ppc, address)) {
1448      VG_(gdb_printf) ("missing or malformed address\n");
1449      *address = (Addr) 0;
1450      *szB = 0;
1451      return False;
1452   }
1453   ws = VG_(strtok_r) (NULL, " ", ssaveptr);
1454   if (ws == NULL) {
1455      /* Do nothing, i.e. keep current value of szB. */ ;
1456   } else if (is_zero_x (ws)) {
1457      *szB = VG_(strtoull16) (ws, &endptr);
1458   } else if (is_zero_b (ws)) {
1459      Int j;
1460      HChar *parsews = ws;
1461      Int n_bits = VG_(strlen) (ws) - 2;
1462      *szB = 0;
1463      ws = NULL; // assume the below loop gives a correct nr.
1464      for (j = 0; j < n_bits; j++) {
1465         if      ('0' == parsews[j+2]) { /* do nothing */ }
1466         else if ('1' == parsews[j+2]) *szB |= (1 << (n_bits-j-1));
1467         else {
1468            /* report malformed binary integer */
1469            ws = parsews;
1470            endptr = ws + j + 2;
1471            break;
1472         }
1473      }
1474   } else {
1475      *szB = VG_(strtoull10) (ws, &endptr);
1476   }
1477
1478   if (ws != NULL && *endptr != '\0') {
1479      VG_(gdb_printf) ("malformed integer, expecting "
1480                       "hex 0x..... or dec ...... or binary .....b\n");
1481      *address = (Addr) 0;
1482      *szB = 0;
1483      return False;
1484   }
1485   return True;
1486}
1487
1488void VG_(gdbserver_status_output)(void)
1489{
1490   const int nr_gdbserved_addresses
1491      = (gs_addresses == NULL ? -1 : VG_(HT_count_nodes) (gs_addresses));
1492   const int nr_watchpoints
1493      = (gs_watches == NULL ? -1 : (int) VG_(sizeXA) (gs_watches));
1494   remote_utils_output_status();
1495   VG_(umsg)
1496      ("nr of calls to gdbserver: %d\n"
1497       "single stepping %d\n"
1498       "interrupts intr_tid %d gs_non_busy %d gs_busy %d tid_non_intr %d\n"
1499       "gdbserved addresses %d (-1 = not initialized)\n"
1500       "watchpoints %d (-1 = not initialized)\n"
1501       "vgdb-error %d\n"
1502       "hostvisibility %s\n",
1503       gdbserver_called,
1504       valgrind_single_stepping(),
1505
1506       vgdb_interrupted_tid,
1507       interrupts_non_busy,
1508       interrupts_while_busy,
1509       interrupts_non_interruptible,
1510
1511       nr_gdbserved_addresses,
1512       nr_watchpoints,
1513       VG_(dyn_vgdb_error),
1514       hostvisibility ? "yes" : "no");
1515}
1516