FreeBSD regtest: add fakes for FreeBSD < 13
[valgrind.git] / coregrind / m_gdbserver / m_gdbserver.c
blob5d0973e9ed8b8fd3e9364e1e49c803198a86a5a3
2 /*--------------------------------------------------------------------*/
3 /*--- Handle remote gdb protocol. m_gdbserver.c ---*/
4 /*--------------------------------------------------------------------*/
6 /*
7 This file is part of Valgrind, a dynamic binary instrumentation
8 framework.
10 Copyright (C) 2011-2017 Philippe Waroquiers
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.
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.
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, see <http://www.gnu.org/licenses/>.
25 The GNU General Public License is contained in the file COPYING.
28 #include "pub_core_basics.h"
29 #include "pub_core_vki.h"
30 #include "pub_core_debuglog.h"
31 #include "pub_core_libcproc.h"
32 #include "pub_core_libcprint.h"
33 #include "pub_core_mallocfree.h"
34 #include "pub_core_threadstate.h"
35 #include "pub_core_gdbserver.h"
36 #include "pub_core_options.h"
37 #include "pub_core_transtab.h"
38 #include "pub_core_hashtable.h"
39 #include "pub_core_xarray.h"
40 #include "pub_core_libcassert.h"
41 #include "pub_core_libcbase.h"
42 #include "pub_core_libcsignal.h"
43 #include "pub_core_signals.h"
44 #include "pub_core_machine.h" // VG_(fnptr_to_fnentry)
45 #include "pub_core_debuginfo.h"
46 #include "pub_core_scheduler.h"
47 #include "pub_core_syswrap.h"
49 #include "server.h"
51 /* forward declarations */
52 VG_REGPARM(1)
53 void VG_(helperc_CallDebugger) ( HWord iaddr );
54 VG_REGPARM(1)
55 void VG_(helperc_invalidate_if_not_gdbserved) ( Addr addr );
56 static void invalidate_current_ip (ThreadId tid, const HChar *who);
58 /* reasons of call to call_gdbserver. */
59 typedef
60 enum {
61 init_reason, // initialises gdbserver resources
62 vgdb_reason, // gdbserver invocation by vgdb doing ptrace
63 core_reason, // gdbserver invocation by core (e.g. error encountered)
64 break_reason, // break encountered
65 watch_reason, // watchpoint detected by tool
66 signal_reason, // signal encountered
67 exit_reason} // process terminated
68 CallReason;
70 static const HChar* ppCallReason(CallReason reason)
72 switch (reason) {
73 case init_reason: return "init_reason";
74 case vgdb_reason: return "vgdb_reason";
75 case core_reason: return "core_reason";
76 case break_reason: return "break_reason";
77 case watch_reason: return "watch_reason";
78 case signal_reason: return "signal_reason";
79 case exit_reason: return "exit_reason";
80 default: vg_assert (0);
84 /* An instruction instrumented for gdbserver looks like this:
85 1. Ist_Mark (0x1234)
86 2. Put (IP, 0x1234)
87 3. helperc_CallDebugger (0x1234)
88 This will give control to gdb if there is a break at 0x1234
89 or if we are single stepping
90 4. ... here the real IR for the instruction at 0x1234
92 When there is a break at 0x1234:
93 if user does "continue" or "step" or similar,
94 then - the call to debugger returns
95 - valgrind executes at 3. the real IR(s) for 0x1234
97 if as part of helperc_CallDebugger, the user calls
98 some code in gdb e.g print hello_world()
99 then - gdb prepares a dummy stack frame with a specific
100 return address (typically it uses _start) and
101 inserts a break at this address
102 - gdb then puts in EIP the address of hello_world()
103 - gdb then continues (so the helperc_CallDebugger
104 returns)
105 - call_gdbserver() function will then return the
106 control to the scheduler (using VG_MINIMAL_LONGJMP)
107 to allow the block of the new EIP
108 to be executed.
109 - hello_world code is executed.
110 - when hello_world() returns, it returns to
111 _start and encounters the break at _start.
112 - gdb then removes this break, put 0x1234 in EIP
113 and does a "step". This causes to jump from
114 _start to 0x1234, where the call to
115 helperc_CallDebugger is redone.
116 - This is all ok, the user can then give new gdb
117 commands.
119 However, when continue is given, address 0x1234 is to
120 be executed: gdb gives a single step, which must not
121 report again the break at 0x1234. To avoid a 2nd report
122 of the same break, the below tells that the next
123 helperc_CallDebugger call must ignore a break/stop at
124 this address.
126 static Addr ignore_this_break_once = 0;
129 static void call_gdbserver ( ThreadId tid , CallReason reason);
131 /* Describes the address addr (for debugging/printing purposes).
132 Last two results are kept. A third call will replace the
133 oldest result. */
134 static HChar* sym (Addr addr, Bool is_code)
136 static HChar *buf[2];
137 static int w = 0;
138 PtrdiffT offset;
139 if (w == 2) w = 0;
141 // sym is used for debugging/tracing, so cur_ep is a reasonable choice.
142 const DiEpoch cur_ep = VG_(current_DiEpoch)();
144 if (is_code) {
145 const HChar *name;
146 name = VG_(describe_IP) (cur_ep, addr, NULL);
147 if (buf[w]) VG_(free)(buf[w]);
148 buf[w] = VG_(strdup)("gdbserver sym", name);
149 } else {
150 const HChar *name;
151 VG_(get_datasym_and_offset) (cur_ep, addr, &name, &offset);
152 if (buf[w]) VG_(free)(buf[w]);
153 buf[w] = VG_(strdup)("gdbserver sym", name);
155 return buf[w++];
158 /* Each time gdbserver is called, gdbserver_called is incremented
159 gdbserver_exited is incremented when gdbserver is asked to exit */
160 static int gdbserver_called = 0;
161 static int gdbserver_exited = 0;
163 /* alloc and free functions for xarray and similar. */
164 static void* gs_alloc (const HChar* cc, SizeT sz)
166 return VG_(malloc)(cc, sz);
168 static void gs_free (void* ptr)
170 VG_(free)(ptr);
173 typedef
174 enum {
175 GS_break,
176 GS_jump
178 GS_Kind;
180 typedef
181 struct _GS_Address {
182 struct _GS_Address* next;
183 Addr addr;
184 GS_Kind kind;
186 GS_Address;
188 /* gs_addresses contains a list of all addresses that have been invalidated
189 because they have been (or must be) instrumented for gdbserver.
190 An entry is added in this table when there is a break at this
191 address (kind == GS_break) or if this address is the jump target of an
192 exit of a block that has been instrumented for gdbserver while
193 single stepping (kind == GS_jump).
194 When gdbserver is not single stepping anymore, all GS_jump entries
195 are removed, their translations are invalidated.
197 Note for ARM: addr in GS_Address is the value without the thumb bit set.
199 static VgHashTable *gs_addresses = NULL;
201 // Transform addr in the form stored in the list of addresses.
202 // For the ARM architecture, we store it with the thumb bit set to 0.
203 static Addr HT_addr ( Addr addr )
205 #if defined(VGA_arm)
206 return addr & ~(Addr)1;
207 #else
208 return addr;
209 #endif
212 static void add_gs_address (Addr addr, GS_Kind kind, const HChar* from)
214 GS_Address *p;
216 p = VG_(malloc)(from, sizeof(GS_Address));
217 p->addr = HT_addr (addr);
218 p->kind = kind;
219 VG_(HT_add_node)(gs_addresses, p);
220 /* It should be sufficient to discard a range of 1.
221 We use 2 to ensure the below is not sensitive to the presence
222 of thumb bit in the range of addresses to discard.
223 No need to discard translations for Vg_VgdbFull as all
224 instructions are in any case vgdb-instrumented. */
225 if (VG_(clo_vgdb) != Vg_VgdbFull)
226 VG_(discard_translations) (addr, 2, from);
229 static void remove_gs_address (GS_Address* g, const HChar* from)
231 VG_(HT_remove) (gs_addresses, g->addr);
232 // See add_gs_address for the explanation for condition and the range 2 below.
233 if (VG_(clo_vgdb) != Vg_VgdbFull)
234 VG_(discard_translations) (g->addr, 2, from);
235 VG_(free) (g);
238 const HChar* VG_(ppPointKind) (PointKind kind)
240 switch(kind) {
241 case software_breakpoint: return "software_breakpoint";
242 case hardware_breakpoint: return "hardware_breakpoint";
243 case write_watchpoint: return "write_watchpoint";
244 case read_watchpoint: return "read_watchpoint";
245 case access_watchpoint: return "access_watchpoint";
246 default: return "???wrong PointKind";
250 typedef
251 struct _GS_Watch {
252 Addr addr;
253 SizeT len;
254 PointKind kind;
256 GS_Watch;
258 /* gs_watches contains a list of all addresses+len+kind that are being
259 watched. */
260 static XArray* gs_watches = NULL;
262 static inline GS_Watch* index_gs_watches(Word i)
264 return *(GS_Watch **) VG_(indexXA) (gs_watches, i);
267 /* Returns the GS_Watch matching addr/len/kind and sets *g_ix to its
268 position in gs_watches.
269 If no matching GS_Watch is found, returns NULL and sets g_ix to -1. */
270 static GS_Watch* lookup_gs_watch (Addr addr, SizeT len, PointKind kind,
271 Word* g_ix)
273 const Word n_elems = VG_(sizeXA) (gs_watches);
274 Word i;
275 GS_Watch *g;
277 /* Linear search. If we have many watches, this might be optimised
278 by having the array sorted and using VG_(lookupXA) */
279 for (i = 0; i < n_elems; i++) {
280 g = index_gs_watches(i);
281 if (g->addr == addr && g->len == len && g->kind == kind) {
282 // Found.
283 *g_ix = i;
284 return g;
288 // Not found.
289 *g_ix = -1;
290 return NULL;
294 /* protocol spec tells the below must be idempotent. */
295 static void breakpoint (Bool insert, CORE_ADDR addr)
297 GS_Address *g;
299 g = VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(addr));
300 if (insert) {
301 /* insert a breakpoint at addr or upgrade its kind */
302 if (g == NULL) {
303 add_gs_address (addr, GS_break, "m_gdbserver breakpoint insert");
304 } else {
305 /* already gdbserved. Normally, it must be because of a jump.
306 However, due to idempotent or if connection with gdb was
307 lost (kept breaks from the previous gdb), if already existing,
308 we just upgrade its kind. */
309 g->kind = GS_break;
311 } else {
312 /* delete a breakpoint at addr or downgrade its kind */
313 if (g != NULL && g->kind == GS_break) {
314 if (valgrind_single_stepping()) {
315 /* keep gdbserved instrumentation while single stepping */
316 g->kind = GS_jump;
317 } else {
318 remove_gs_address (g, "m_gdbserver breakpoint remove");
320 } else {
321 dlog (1, "remove break addr %p %s\n",
322 C2v(addr), (g == NULL ?
323 "NULL" :
324 (g->kind == GS_jump ? "GS_jump" : "GS_break")));
329 static Bool (*tool_watchpoint) (PointKind kind,
330 Bool insert,
331 Addr addr,
332 SizeT len) = NULL;
333 void VG_(needs_watchpoint) (Bool (*watchpoint) (PointKind kind,
334 Bool insert,
335 Addr addr,
336 SizeT len))
338 tool_watchpoint = watchpoint;
341 Bool VG_(gdbserver_point) (PointKind kind, Bool insert,
342 CORE_ADDR addr, int len)
344 Bool res;
345 GS_Watch *g;
346 Word g_ix;
347 Bool is_code = kind == software_breakpoint || kind == hardware_breakpoint;
349 dlog(1, "%s %s at addr %p %s\n",
350 (insert ? "insert" : "remove"),
351 VG_(ppPointKind) (kind),
352 C2v(addr),
353 sym(addr, is_code));
355 if (is_code) {
356 breakpoint (insert, addr);
357 return True;
360 vg_assert (kind == access_watchpoint
361 || kind == read_watchpoint
362 || kind == write_watchpoint);
364 if (tool_watchpoint == NULL)
365 return False;
367 res = (*tool_watchpoint) (kind, insert, addr, len);
368 if (!res)
369 return False; /* error or unsupported */
371 // Protocol says insert/remove must be idempotent.
372 // So, we just ignore double insert or (supposed) double delete.
374 g = lookup_gs_watch (addr, len, kind, &g_ix);
375 if (insert) {
376 if (g == NULL) {
377 g = VG_(malloc)("gdbserver_point watchpoint", sizeof(GS_Watch));
378 g->addr = addr;
379 g->len = len;
380 g->kind = kind;
381 VG_(addToXA)(gs_watches, &g);
382 } else {
383 dlog(1,
384 "VG_(gdbserver_point) addr %p len %d kind %s already inserted\n",
385 C2v(addr), len, VG_(ppPointKind) (kind));
387 } else {
388 if (g != NULL) {
389 VG_(removeIndexXA) (gs_watches, g_ix);
390 VG_(free) (g);
391 } else {
392 dlog(1,
393 "VG_(gdbserver_point) addr %p len %d kind %s already deleted?\n",
394 C2v(addr), len, VG_(ppPointKind) (kind));
397 return True;
400 Bool VG_(has_gdbserver_breakpoint) (Addr addr)
402 GS_Address *g;
403 if (!gdbserver_called)
404 return False;
405 g = VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(addr));
406 return (g != NULL && g->kind == GS_break);
409 Bool VG_(is_watched)(PointKind kind, Addr addr, Int szB)
411 Word n_elems;
412 GS_Watch* g;
413 Word i;
414 Bool watched = False;
415 const ThreadId tid = VG_(running_tid);
417 if (!gdbserver_called)
418 return False;
420 n_elems = VG_(sizeXA) (gs_watches);
422 Addr to = addr + szB; // semi-open interval [addr, to[
424 vg_assert (kind == access_watchpoint
425 || kind == read_watchpoint
426 || kind == write_watchpoint);
427 dlog(1, "tid %u VG_(is_watched) %s addr %p szB %d\n",
428 tid, VG_(ppPointKind) (kind), C2v(addr), szB);
430 for (i = 0; i < n_elems; i++) {
431 g = index_gs_watches(i);
432 switch (g->kind) {
433 case software_breakpoint:
434 case hardware_breakpoint:
435 break;
436 case access_watchpoint:
437 case read_watchpoint:
438 case write_watchpoint:
439 if (to <= g->addr || addr >= (g->addr + g->len))
440 /* If no overlap, examine next watchpoint: */
441 continue;
443 watched = True; /* We have an overlap */
445 /* call gdbserver if access kind reported by the tool
446 matches the watchpoint kind. */
447 if (kind == access_watchpoint
448 || g->kind == access_watchpoint
449 || g->kind == kind) {
450 /* Watchpoint encountered.
451 If this is a read watchpoint, we directly call gdbserver
452 to report it to gdb.
453 Otherwise, for a write watchpoint, we have to finish
454 the instruction so as to modify the value.
455 If we do not finish the instruction, then gdb sees no
456 value change and continues.
457 For a read watchpoint, we better call gdbserver directly:
458 in case the current block is not gdbserved, Valgrind
459 will execute instructions till the next block. */
461 /* set the watchpoint stop address to the first read or written. */
462 if (g->addr <= addr) {
463 VG_(set_watchpoint_stop_address) (addr);
464 } else {
465 VG_(set_watchpoint_stop_address) (g->addr);
468 if (kind == write_watchpoint) {
469 /* Let Valgrind stop as early as possible after this instruction
470 by switching to Single Stepping mode. */
471 valgrind_set_single_stepping (True);
472 invalidate_current_ip (tid, "m_gdbserver write watchpoint");
473 } else {
474 call_gdbserver (tid, watch_reason);
475 VG_(set_watchpoint_stop_address) ((Addr) 0);
477 return True; // we are watched here.
479 break;
480 default:
481 vg_assert (0);
484 return watched;
487 /* Returns the reason for which gdbserver instrumentation is needed */
488 static VgVgdb VG_(gdbserver_instrumentation_needed) (const VexGuestExtents* vge)
490 GS_Address* g;
491 int e;
493 if (!gdbserver_called)
494 return Vg_VgdbNo;
496 if (valgrind_single_stepping()) {
497 dlog(2, "gdbserver_instrumentation_needed due to single stepping\n");
498 return Vg_VgdbYes;
501 if (VG_(clo_vgdb) == Vg_VgdbYes && VG_(HT_count_nodes) (gs_addresses) == 0)
502 return Vg_VgdbNo;
504 /* We assume we do not have a huge nr of breakpoints.
505 Otherwise, we need something more efficient e.g.
506 a sorted list of breakpoints or associate extents to it or ...
508 VG_(HT_ResetIter) (gs_addresses);
509 while ((g = VG_(HT_Next) (gs_addresses))) {
510 for (e = 0; e < vge->n_used; e++) {
511 if (g->addr >= HT_addr(vge->base[e])
512 && g->addr < HT_addr(vge->base[e]) + vge->len[e]) {
513 dlog(2,
514 "gdbserver_instrumentation_needed %p %s reason %s\n",
515 C2v(g->addr), sym(g->addr, /* is_code */ True),
516 (g->kind == GS_jump ? "GS_jump" : "GS_break"));
517 return Vg_VgdbYes;
522 if (VG_(clo_vgdb) == Vg_VgdbFull) {
523 dlog(4, "gdbserver_instrumentation_needed"
524 " due to VG_(clo_vgdb) == Vg_VgdbFull\n");
525 return Vg_VgdbFull;
529 return Vg_VgdbNo;
532 // Clear gdbserved_addresses in gs_addresses.
533 // If clear_only_jumps, clears only the addresses that are served
534 // for jump reasons.
535 // Otherwise, clear all the addresses.
536 // Cleared addresses are invalidated so as to have them re-translated.
537 static void clear_gdbserved_addresses(Bool clear_only_jumps)
539 GS_Address** ag;
540 UInt n_elems;
541 int i;
543 dlog(1,
544 "clear_gdbserved_addresses: scanning hash table nodes %u\n",
545 VG_(HT_count_nodes) (gs_addresses));
546 ag = (GS_Address**) VG_(HT_to_array) (gs_addresses, &n_elems);
547 for (i = 0; i < n_elems; i++)
548 if (!clear_only_jumps || ag[i]->kind == GS_jump)
549 remove_gs_address (ag[i], "clear_gdbserved_addresses");
550 VG_(free) (ag);
553 // Clear watched addressed in gs_watches, delete gs_watches.
554 static void clear_watched_addresses(void)
556 GS_Watch* g;
557 const Word n_elems = VG_(sizeXA) (gs_watches);
558 Word i;
560 dlog(1,
561 "clear_watched_addresses: %ld elements\n",
562 n_elems);
564 for (i = 0; i < n_elems; i++) {
565 g = index_gs_watches(i);
566 if (!VG_(gdbserver_point) (g->kind,
567 /* insert */ False,
568 g->addr,
569 g->len)) {
570 vg_assert (0);
574 VG_(deleteXA) (gs_watches);
575 gs_watches = NULL;
578 static void invalidate_if_jump_not_yet_gdbserved (Addr addr, const HChar* from)
580 if (VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(addr)))
581 return;
582 add_gs_address (addr, GS_jump, from);
585 static void invalidate_current_ip (ThreadId tid, const HChar *who)
587 invalidate_if_jump_not_yet_gdbserved (VG_(get_IP) (tid), who);
590 Bool VG_(gdbserver_init_done) (void)
592 return gdbserver_called > 0;
595 Bool VG_(gdbserver_stop_at) (VgdbStopAt stopat)
597 return gdbserver_called > 0 && VgdbStopAtiS(stopat, VG_(clo_vgdb_stop_at));
600 void VG_(gdbserver_prerun_action) (ThreadId tid)
602 // Using VG_(clo_vgdb_error) allows the user to control if gdbserver
603 // stops after a fork.
604 if ((VG_(clo_vgdb_error) == 0
605 || (VgdbStopAtiS(VgdbStopAt_Startup, VG_(clo_vgdb_stop_at))))) {
606 /* The below call allows gdb to attach at startup
607 before the first guest instruction is executed. */
608 if (!(VG_(clo_launched_with_multi)))
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);
620 /* when fork is done, various cleanup is needed in the child process.
621 In particular, child must have its own connection to avoid stealing
622 data from its parent */
623 static void gdbserver_cleanup_in_child_after_fork(ThreadId me)
625 dlog(1, "thread %u gdbserver_cleanup_in_child_after_fork pid %d\n",
626 me, VG_(getpid) ());
628 /* finish connection inheritated from parent */
629 remote_finish(reset_after_fork);
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);
647 if (VG_(clo_trace_children)) {
648 VG_(gdbserver_prerun_action) (me);
649 } else {
650 /* After fork, if we do not trace the children, disable vgdb
651 poll to avoid gdbserver being called unexpectedly. */
652 VG_(disable_vgdb_poll) ();
656 /* If reason is init_reason, creates the connection resources (e.g.
657 the FIFOs) to allow a gdb connection to be detected by polling
658 using remote_desc_activity.
659 Otherwise (other reasons):
660 If connection with gdb not yet opened, opens the connection with gdb.
661 reads gdb remote protocol packets and executes the requested commands.
663 static void call_gdbserver ( ThreadId tid , CallReason reason)
665 ThreadState* tst = VG_(get_ThreadState)(tid);
666 int stepping;
667 Addr saved_pc;
669 dlog(1,
670 "entering call_gdbserver %s ... pid %d tid %u status %s "
671 "sched_jmpbuf_valid %d\n",
672 ppCallReason (reason),
673 VG_(getpid) (), tid, VG_(name_of_ThreadStatus)(tst->status),
674 tst->sched_jmpbuf_valid);
676 /* If we are about to die, then just run server_main() once to get
677 the resume reply out and return immediately because most of the state
678 of this tid and process is about to be torn down. */
679 if (reason == exit_reason) {
680 server_main();
681 return;
684 vg_assert(VG_(is_valid_tid)(tid));
685 saved_pc = VG_(get_IP) (tid);
687 if (gdbserver_exited) {
688 dlog(0, "call_gdbserver called when gdbserver_exited %d\n",
689 gdbserver_exited);
690 return;
693 if (gdbserver_called == 0) {
694 vg_assert (gs_addresses == NULL);
695 vg_assert (gs_watches == NULL);
696 gs_addresses = VG_(HT_construct)( "gdbserved_addresses" );
697 gs_watches = VG_(newXA)(gs_alloc,
698 "gdbserved_watches",
699 gs_free,
700 sizeof(GS_Watch*));
701 VG_(atfork)(NULL, NULL, gdbserver_cleanup_in_child_after_fork);
703 vg_assert (gs_addresses != NULL);
704 vg_assert (gs_watches != NULL);
706 gdbserver_called++;
708 /* call gdbserver_init if this is the first call to gdbserver. */
709 if (gdbserver_called == 1)
710 gdbserver_init();
712 if (reason == init_reason || gdbserver_called == 1)
713 remote_open(VG_(clo_vgdb_prefix));
715 /* if the call reason is to initialize, then return control to
716 valgrind. After this initialization, gdbserver will be called
717 again either if there is an error detected by valgrind or
718 if vgdb sends data to the valgrind process. */
719 if (reason == init_reason) {
720 return;
723 stepping = valgrind_single_stepping();
725 server_main();
727 ignore_this_break_once = valgrind_get_ignore_break_once();
728 if (ignore_this_break_once)
729 dlog(1, "!!! will ignore_this_break_once %s\n",
730 sym(ignore_this_break_once, /* is_code */ True));
733 if (valgrind_single_stepping()) {
734 /* we are single stepping. If we were not stepping on entry,
735 then invalidate the current program counter so as to properly
736 do single step. In case the program counter was changed by
737 gdb, this will also invalidate the target address we will
738 jump to. */
739 if (!stepping && tid != 0) {
740 invalidate_current_ip (tid, "m_gdbserver single step");
742 } else {
743 /* We are not single stepping. If we were stepping on entry,
744 then clear the gdbserved addresses. This will cause all
745 these gdbserved blocks to be invalidated so that they can be
746 re-translated without being gdbserved. */
747 if (stepping)
748 clear_gdbserved_addresses(/* clear only jumps */ True);
751 /* can't do sanity check at beginning. At least the stack
752 check is not yet possible. */
753 if (gdbserver_called > 1)
754 VG_(sanity_check_general) (/* force_expensive */ False);
756 /* If the PC has been changed by gdb, then we VG_MINIMAL_LONGJMP to
757 the scheduler to execute the block of the new PC.
758 Otherwise we just return to continue executing the
759 current block. */
760 if (VG_(get_IP) (tid) != saved_pc) {
761 dlog(1, "tid %u %s PC changed from %s to %s\n",
762 tid, VG_(name_of_ThreadStatus) (tst->status),
763 sym(saved_pc, /* is_code */ True),
764 sym(VG_(get_IP) (tid), /* is_code */ True));
765 if (tst->status == VgTs_Yielding) {
766 SysRes sres;
767 VG_(memset)(&sres, 0, sizeof(SysRes));
768 VG_(acquire_BigLock)(tid, "gdbsrv VG_MINIMAL_LONGJMP");
770 if (tst->sched_jmpbuf_valid) {
771 /* resume scheduler */
772 VG_MINIMAL_LONGJMP(tst->sched_jmpbuf);
774 /* else continue to run */
776 /* continue to run */
779 /* busy > 0 when gdbserver is currently being called.
780 busy is used to avoid vgdb invoking gdbserver
781 while gdbserver by Valgrind. */
782 static volatile int busy = 0;
784 void VG_(gdbserver) ( ThreadId tid )
786 busy++;
787 /* called by the rest of valgrind for
788 --vgdb-error=0 reason
789 or by scheduler "poll/debug/interrupt" reason
790 or to terminate. */
791 if (tid != 0) {
792 call_gdbserver (tid, core_reason);
793 } else {
794 if (gdbserver_called == 0) {
795 dlog(1, "VG_(gdbserver) called to terminate, nothing to terminate\n");
796 } else if (gdbserver_exited) {
797 dlog(1, "VG_(gdbserver) called to terminate again %d\n",
798 gdbserver_exited);
799 } else {
800 gdbserver_terminate();
801 gdbserver_exited++;
804 busy--;
807 // nr of invoke_gdbserver while gdbserver is already executing.
808 static int interrupts_while_busy = 0;
810 // nr of invoke_gdbserver while gdbserver is not executing.
811 static int interrupts_non_busy = 0;
813 // nr of invoke_gdbserver when some threads are not interruptible.
814 static int interrupts_non_interruptible = 0;
816 /* When all threads are blocked in a system call, the Valgrind
817 scheduler cannot poll the shared memory for gdbserver activity. In
818 such a case, vgdb will force the invocation of gdbserver using
819 ptrace. To do that, vgdb 'pushes' a call to invoke_gdbserver
820 on the stack using ptrace. invoke_gdbserver must not return.
821 Instead, it must call give_control_back_to_vgdb.
822 vgdb expects to receive a SIGSTOP, which this function generates.
823 When vgdb gets this SIGSTOP, it knows invoke_gdbserver call
824 is finished and can reset the Valgrind process in the state prior to
825 the 'pushed call' (using ptrace again).
826 This all works well. However, the user must avoid
827 'kill-9ing' vgdb during such a pushed call, otherwise
828 the SIGSTOP generated below will be seen by the Valgrind core,
829 instead of being handled by vgdb. The OS will then handle the SIGSTOP
830 by stopping the Valgrind process.
831 We use SIGSTOP as this process cannot be masked. */
833 static void give_control_back_to_vgdb(void)
835 #if !defined(VGO_solaris)
836 /* cause a SIGSTOP to be sent to ourself, so that vgdb takes control.
837 vgdb will then restore the stack so as to resume the activity
838 before the ptrace (typically do_syscall_WRK). */
839 if (VG_(kill)(VG_(getpid)(), VKI_SIGSTOP) != 0)
840 vg_assert2(0, "SIGSTOP for vgdb could not be generated\n");
842 /* If we arrive here, it means a call was pushed on the stack
843 by vgdb, but during this call, vgdb and/or connection
844 died. Alternatively, it is a bug in the vgdb<=>Valgrind gdbserver
845 ptrace handling. */
846 vg_assert2(0,
847 "vgdb did not took control. Did you kill vgdb ?\n"
848 "busy %d vgdb_interrupted_tid %u\n",
849 busy, vgdb_interrupted_tid);
850 #else /* defined(VGO_solaris) */
851 /* On Solaris, this code is run within the context of an agent thread
852 (see vgdb-invoker-solaris.c and "PCAGENT" control message in
853 proc(4)). Exit the agent thread now.
855 SysRes sres = VG_(do_syscall0)(SYS_lwp_exit);
856 if (sr_isError(sres))
857 vg_assert2(0, "The agent thread could not be exited\n");
858 #endif /* !defined(VGO_solaris) */
861 /* Using ptrace calls, vgdb will force an invocation of gdbserver.
862 VG_(invoke_gdbserver) is the entry point called through the
863 vgdb ptrace technique. */
864 void VG_(invoke_gdbserver) ( int check )
866 /* ******* Avoid non-reentrant function call from here .....
867 till the ".... till here" below. */
869 /* We need to determine the state of the various threads to decide
870 if we directly invoke gdbserver or if we rather indicate to the
871 scheduler to invoke the gdbserver. To decide that, it is
872 critical to avoid any "coregrind" function call as the ptrace
873 might have stopped the process in the middle of this (possibly)
874 non-rentrant function. So, it is only when all threads are in
875 an "interruptible" state that we can safely invoke
876 gdbserver. Otherwise, we let the valgrind scheduler invoke
877 gdbserver at the next poll. This poll will be made very soon
878 thanks to a call to VG_(force_vgdb_poll). */
879 int n_tid, vgdb_interrupted_tid_local = 0;
881 vg_assert (check == 0x8BADF00D);
883 if (busy) {
884 interrupts_while_busy++;
885 give_control_back_to_vgdb();
887 interrupts_non_busy++;
889 /* check if all threads are in an "interruptible" state. If yes,
890 we invoke gdbserver. Otherwise, we tell the scheduler to wake up
891 asap. */
892 for (n_tid = 1; n_tid < VG_N_THREADS; n_tid++) {
893 switch (VG_(threads)[n_tid].status) {
894 /* interruptible states. */
895 case VgTs_WaitSys:
896 case VgTs_Yielding:
897 if (vgdb_interrupted_tid_local == 0)
898 vgdb_interrupted_tid_local = n_tid;
899 break;
901 case VgTs_Empty:
902 case VgTs_Zombie:
903 break;
905 /* non interruptible states. */
906 case VgTs_Init:
907 case VgTs_Runnable:
908 interrupts_non_interruptible++;
909 VG_(force_vgdb_poll) ();
910 give_control_back_to_vgdb();
911 /* If give_control_back_to_vgdb returns in an non interruptable
912 state something went horribly wrong, fallthrough to vg_assert. */
913 default: vg_assert(0);
917 vgdb_interrupted_tid = vgdb_interrupted_tid_local;
919 /* .... till here.
920 From here onwards, function calls are ok: it is
921 safe to call valgrind core functions: all threads are blocked in
922 a system call or are yielding or ... */
923 dlog(1, "invoke_gdbserver running_tid %u vgdb_interrupted_tid %u\n",
924 VG_(running_tid), vgdb_interrupted_tid);
925 call_gdbserver (vgdb_interrupted_tid, vgdb_reason);
926 vgdb_interrupted_tid = 0;
927 dlog(1,
928 "exit invoke_gdbserver running_tid %u\n", VG_(running_tid));
929 give_control_back_to_vgdb();
931 vg_assert2(0, "end of invoke_gdbserver reached");
935 Bool VG_(gdbserver_activity) (ThreadId tid)
937 Bool ret;
938 busy++;
939 if (!gdbserver_called)
940 call_gdbserver (tid, init_reason);
941 switch (remote_desc_activity("VG_(gdbserver_activity)")) {
942 case 0: ret = False; break;
943 case 1: ret = True; break;
944 case 2:
945 remote_finish(reset_after_error);
946 call_gdbserver (tid, init_reason);
947 ret = False;
948 break;
949 default: vg_assert (0);
951 busy--;
952 return ret;
955 static void dlog_signal (const HChar *who, const vki_siginfo_t *info,
956 ThreadId tid)
958 dlog(1, "VG core calling %s "
959 "vki_nr %d %s gdb_nr %u %s tid %u\n",
960 who,
961 info->si_signo, VG_(signame)(info->si_signo),
962 target_signal_from_host (info->si_signo),
963 target_signal_to_name(target_signal_from_host (info->si_signo)),
964 tid);
968 void VG_(gdbserver_report_fatal_signal) (const vki_siginfo_t *info,
969 ThreadId tid)
971 dlog_signal("VG_(gdbserver_report_fatal_signal)", info, tid);
973 if (remote_connected()) {
974 dlog(1, "already connected, assuming already reported\n");
975 return;
978 if (!(VG_(clo_launched_with_multi)))
979 VG_(umsg)("(action on fatal signal) vgdb me ... \n");
981 /* indicate to gdbserver that there is a signal */
982 gdbserver_signal_encountered (info);
984 /* let gdbserver do some work, e.g. show the signal to the user */
985 call_gdbserver (tid, signal_reason);
989 Bool VG_(gdbserver_report_signal) (vki_siginfo_t *info, ThreadId tid)
991 dlog_signal("VG_(gdbserver_report_signal)", info, tid);
993 /* if gdbserver is currently not connected, then signal
994 is to be given to the process */
995 if (!remote_connected()) {
996 dlog(1, "not connected => pass\n");
997 return True;
999 /* if gdb has informed gdbserver that this signal can be
1000 passed directly without informing gdb, then signal is
1001 to be given to the process. */
1002 if (pass_signals[target_signal_from_host(info->si_signo)]) {
1003 dlog(1, "pass_signals => pass\n");
1004 return True;
1007 /* indicate to gdbserver that there is a signal */
1008 gdbserver_signal_encountered (info);
1010 /* let gdbserver do some work, e.g. show the signal to the user.
1011 User can also decide to ignore the signal or change the signal. */
1012 call_gdbserver (tid, signal_reason);
1014 /* ask gdbserver what is the final decision */
1015 if (gdbserver_deliver_signal (info)) {
1016 dlog(1, "gdbserver deliver signal\n");
1017 return True;
1018 } else {
1019 dlog(1, "gdbserver ignore signal\n");
1020 return False;
1024 Bool catching_syscalls = False; // True if catching all or some syscalls.
1025 /* If catching_syscalls is True, then syscalls_to_catch_size == 0 means
1026 to catch all syscalls. Otherwise, it is the size of the syscalls_to_catch
1027 array. */
1028 Int syscalls_to_catch_size = 0;
1029 Int *syscalls_to_catch;
1030 static Bool catch_this_syscall (Int sysno)
1032 Int i;
1034 if (syscalls_to_catch_size == 0)
1035 return True;
1037 for (i = 0; i < syscalls_to_catch_size; i++)
1038 if (syscalls_to_catch[i] == sysno)
1039 return True;
1041 return False;
1044 void VG_(gdbserver_report_syscall) (Bool before, UWord sysno, ThreadId tid)
1046 dlog(4, "VG_(gdbserver_report_syscall) before %d sysno %lu tid %u\n",
1047 before, sysno, tid);
1049 if (UNLIKELY(catching_syscalls)) {
1050 if (!remote_connected()) {
1051 dlog(2, "not connected => no report\n");
1054 if (catch_this_syscall ((Int)sysno)) {
1055 /* let gdbserver do some work */
1056 gdbserver_syscall_encountered (before, (Int)sysno);
1057 call_gdbserver (tid, signal_reason);
1062 void VG_(gdbserver_exit) (ThreadId tid, VgSchedReturnCode tids_schedretcode)
1064 dlog(1, "VG core calling VG_(gdbserver_exit) tid %u will exit\n", tid);
1065 if (remote_connected()) {
1066 /* Make sure vgdb knows we are about to die and why. */
1067 switch(tids_schedretcode) {
1068 case VgSrc_None:
1069 vg_assert (0);
1070 case VgSrc_ExitThread:
1071 case VgSrc_ExitProcess:
1072 gdbserver_process_exit_encountered
1073 ('W', VG_(threads)[tid].os_state.exitcode);
1074 call_gdbserver (tid, exit_reason);
1075 break;
1076 case VgSrc_FatalSig:
1077 gdbserver_process_exit_encountered
1078 ('X', VG_(threads)[tid].os_state.fatalsig);
1079 call_gdbserver (tid, exit_reason);
1080 break;
1081 default:
1082 vg_assert(0);
1084 } else {
1085 dlog(1, "not connected\n");
1088 /* Tear down the connection if it still exists. */
1089 VG_(gdbserver) (0);
1092 // Check if single_stepping or if there is a break requested at iaddr.
1093 // If yes, call debugger
1094 VG_REGPARM(1)
1095 void VG_(helperc_CallDebugger) ( HWord iaddr )
1097 GS_Address* g;
1099 // For Vg_VgdbFull, after a fork, we might have calls to this helper
1100 // while gdbserver is not yet initialized.
1101 if (!gdbserver_called)
1102 return;
1104 if (valgrind_single_stepping() ||
1105 ((g = VG_(HT_lookup) (gs_addresses, (UWord)HT_addr(iaddr))) &&
1106 (g->kind == GS_break))) {
1107 if (iaddr == HT_addr(ignore_this_break_once)) {
1108 dlog(1, "ignoring ignore_this_break_once %s\n",
1109 sym(ignore_this_break_once, /* is_code */ True));
1110 ignore_this_break_once = 0;
1111 } else {
1112 call_gdbserver (VG_(get_running_tid)(), break_reason);
1117 /* software_breakpoint support --------------------------------------*/
1118 /* When a block is instrumented for gdbserver, single step and breaks
1119 will be obeyed in this block. However, if a jump to another block
1120 is executed while single_stepping is active, we must ensure that
1121 this block is also instrumented. For this, when a block is
1122 instrumented for gdbserver while single_stepping, the target of all
1123 the Jump instructions in this block will be checked to verify if
1124 the block is already instrumented for gdbserver. The below will
1125 ensure that if not already instrumented for gdbserver, the target
1126 block translation containing addr will be invalidated. The list of
1127 gdbserved Addr will also be kept so that translations can be
1128 dropped automatically by gdbserver when going out of single step
1129 mode.
1131 Call the below at translation time if the jump target is a constant.
1132 Otherwise, rather use VG_(add_stmt_call_invalidate_if_not_gdbserved).
1134 To instrument the target exit statement, you can call
1135 VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved) rather
1136 than check the kind of target exit. */
1137 static void VG_(invalidate_if_not_gdbserved) (Addr addr)
1139 if (valgrind_single_stepping())
1140 invalidate_if_jump_not_yet_gdbserved
1141 (addr, "gdbserver target jump (instrument)");
1144 // same as VG_(invalidate_if_not_gdbserved) but is intended to be called
1145 // at runtime (only difference is the invalidate reason which traces
1146 // it is at runtime)
1147 VG_REGPARM(1)
1148 void VG_(helperc_invalidate_if_not_gdbserved) ( Addr addr )
1150 if (valgrind_single_stepping())
1151 invalidate_if_jump_not_yet_gdbserved
1152 (addr, "gdbserver target jump (runtime)");
1155 static void VG_(add_stmt_call_invalidate_if_not_gdbserved)
1156 ( IRSB* sb_in,
1157 const VexGuestLayout* layout,
1158 const VexGuestExtents* vge,
1159 IRTemp jmp,
1160 IRSB* irsb)
1163 void* fn;
1164 const HChar* nm;
1165 IRExpr** args;
1166 Int nargs;
1167 IRDirty* di;
1169 fn = &VG_(helperc_invalidate_if_not_gdbserved);
1170 nm = "VG_(helperc_invalidate_if_not_gdbserved)";
1171 args = mkIRExprVec_1(IRExpr_RdTmp (jmp));
1172 nargs = 1;
1174 di = unsafeIRDirty_0_N( nargs/*regparms*/, nm,
1175 VG_(fnptr_to_fnentry)( fn ), args );
1177 di->nFxState = 0;
1179 addStmtToIRSB(irsb, IRStmt_Dirty(di));
1182 /* software_breakpoint support --------------------------------------*/
1183 /* If a tool wants to allow gdbserver to do something at Addr, then
1184 VG_(add_stmt_call_gdbserver) will add in IRSB a call to a helper
1185 function. This helper function will check if the process must be
1186 stopped at the instruction Addr: either there is a break at Addr or
1187 the process is being single-stepped. Typical usage of the below is to
1188 instrument an Ist_IMark to allow the debugger to interact at any
1189 instruction being executed. As soon as there is one break in a block,
1190 then to allow single stepping in this block (and possible insertions
1191 of other breaks in the same sb_in while the process is stopped), a
1192 debugger statement will be inserted for all instructions of a block. */
1193 static void VG_(add_stmt_call_gdbserver)
1194 (IRSB* sb_in, /* block being translated */
1195 const VexGuestLayout* layout,
1196 const VexGuestExtents* vge,
1197 IRType gWordTy, IRType hWordTy,
1198 Addr iaddr, /* Addr of instruction being instrumented */
1199 UChar delta, /* delta to add to iaddr to obtain IP */
1200 IRSB* irsb) /* irsb block to which call is added */
1202 void* fn;
1203 const HChar* nm;
1204 IRExpr** args;
1205 Int nargs;
1206 IRDirty* di;
1208 /* first store the address in the program counter so that the check
1209 done by VG_(helperc_CallDebugger) will be based on the correct
1210 program counter. We might make this more efficient by rather
1211 searching for assignement to program counter and instrumenting
1212 that but the below is easier and I guess that the optimiser will
1213 remove the redundant store. And in any case, when debugging a
1214 piece of code, the efficiency requirement is not critical: very
1215 few blocks will be instrumented for debugging. */
1217 /* For platforms on which the IP can differ from the addr of the instruction
1218 being executed, we need to add the delta to obtain the IP.
1219 This IP will be given to gdb (e.g. if a breakpoint is put at iaddr).
1221 For ARM, this delta will ensure that the thumb bit is set in the
1222 IP when executing thumb code. gdb uses this thumb bit a.o.
1223 to properly guess the next IP for the 'step' and 'stepi' commands. */
1224 vg_assert(delta <= 1);
1225 addStmtToIRSB(irsb, IRStmt_Put(layout->offset_IP ,
1226 mkIRExpr_HWord(iaddr + (Addr)delta)));
1228 fn = &VG_(helperc_CallDebugger);
1229 nm = "VG_(helperc_CallDebugger)";
1230 args = mkIRExprVec_1(mkIRExpr_HWord (iaddr));
1231 nargs = 1;
1233 di = unsafeIRDirty_0_N( nargs/*regparms*/, nm,
1234 VG_(fnptr_to_fnentry)( fn ), args );
1236 /* Note: in fact, a debugger call can read whatever register
1237 or memory. It can also write whatever register or memory.
1238 So, in theory, we have to indicate the whole universe
1239 can be read and modified. It is however not critical
1240 to indicate precisely what is being read/written
1241 as such indications are needed for tool error detection
1242 and we do not want to have errors being detected for
1243 gdb interactions. */
1245 di->nFxState = 2;
1246 di->fxState[0].fx = Ifx_Read;
1247 di->fxState[0].offset = layout->offset_SP;
1248 di->fxState[0].size = layout->sizeof_SP;
1249 di->fxState[0].nRepeats = 0;
1250 di->fxState[0].repeatLen = 0;
1251 di->fxState[1].fx = Ifx_Modify;
1252 di->fxState[1].offset = layout->offset_IP;
1253 di->fxState[1].size = layout->sizeof_IP;
1254 di->fxState[1].nRepeats = 0;
1255 di->fxState[1].repeatLen = 0;
1257 addStmtToIRSB(irsb, IRStmt_Dirty(di));
1262 /* Invalidate the target of the exit if needed:
1263 If target is constant, it is invalidated at translation time.
1264 Otherwise, a call to a helper function is generated to invalidate
1265 the translation at run time.
1266 The below is thus calling either VG_(invalidate_if_not_gdbserved)
1267 or VG_(add_stmt_call_invalidate_if_not_gdbserved). */
1268 static void VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved)
1269 (IRSB* sb_in,
1270 const VexGuestLayout* layout,
1271 const VexGuestExtents* vge,
1272 IRType gWordTy,
1273 IRSB* irsb)
1275 if (sb_in->next->tag == Iex_Const) {
1276 VG_(invalidate_if_not_gdbserved) (gWordTy == Ity_I64 ?
1277 sb_in->next->Iex.Const.con->Ico.U64
1278 : sb_in->next->Iex.Const.con->Ico.U32);
1279 } else if (sb_in->next->tag == Iex_RdTmp) {
1280 VG_(add_stmt_call_invalidate_if_not_gdbserved)
1281 (sb_in, layout, vge, sb_in->next->Iex.RdTmp.tmp, irsb);
1282 } else {
1283 vg_assert (0); /* unexpected expression tag in exit. */
1287 IRSB* VG_(instrument_for_gdbserver_if_needed)
1288 (IRSB* sb_in,
1289 const VexGuestLayout* layout,
1290 const VexGuestExtents* vge,
1291 IRType gWordTy, IRType hWordTy)
1293 IRSB* sb_out;
1294 Int i;
1295 const VgVgdb instr_needed = VG_(gdbserver_instrumentation_needed) (vge);
1297 if (instr_needed == Vg_VgdbNo)
1298 return sb_in;
1301 /* here, we need to instrument for gdbserver */
1302 sb_out = deepCopyIRSBExceptStmts(sb_in);
1304 for (i = 0; i < sb_in->stmts_used; i++) {
1305 IRStmt* st = sb_in->stmts[i];
1307 if (!st || st->tag == Ist_NoOp) continue;
1309 if (st->tag == Ist_Exit && instr_needed == Vg_VgdbYes) {
1310 VG_(invalidate_if_not_gdbserved)
1311 (hWordTy == Ity_I64 ?
1312 st->Ist.Exit.dst->Ico.U64 :
1313 st->Ist.Exit.dst->Ico.U32);
1315 addStmtToIRSB( sb_out, st );
1316 if (st->tag == Ist_IMark) {
1317 /* For an Ist_Mark, add a call to debugger. */
1318 switch (instr_needed) {
1319 case Vg_VgdbNo: vg_assert (0);
1320 case Vg_VgdbYes:
1321 case Vg_VgdbFull:
1322 VG_(add_stmt_call_gdbserver) ( sb_in, layout, vge,
1323 gWordTy, hWordTy,
1324 st->Ist.IMark.addr,
1325 st->Ist.IMark.delta,
1326 sb_out);
1327 /* There is an optimisation possible here for Vg_VgdbFull:
1328 Put a guard ensuring we only call gdbserver if 'FullCallNeeded'.
1329 FullCallNeeded would be set to 1 we have just switched on
1330 Single Stepping or have just encountered a watchpoint
1331 or have just inserted a breakpoint.
1332 (as gdb by default removes and re-insert breakpoints), we would
1333 need to also implement the notion of 'breakpoint pending removal'
1334 to remove at the next 'continue/step' packet. */
1335 break;
1336 default: vg_assert (0);
1341 if (instr_needed == Vg_VgdbYes) {
1342 VG_(add_stmt_call_invalidate_exit_target_if_not_gdbserved) (sb_in,
1343 layout, vge,
1344 gWordTy,
1345 sb_out);
1348 return sb_out;
1351 struct mon_out_buf {
1352 HChar buf[DATASIZ+1];
1353 int next;
1354 UInt ret;
1357 static void mon_out (HChar c, void *opaque)
1359 struct mon_out_buf *b = (struct mon_out_buf *) opaque;
1360 b->ret++;
1361 b->buf[b->next] = c;
1362 b->next++;
1363 if (b->next == DATASIZ) {
1364 b->buf[b->next] = '\0';
1365 monitor_output(b->buf);
1366 b->next = 0;
1369 UInt VG_(gdb_printf) ( const HChar *format, ... )
1371 struct mon_out_buf b;
1373 b.next = 0;
1374 b.ret = 0;
1376 va_list vargs;
1377 va_start(vargs, format);
1378 VG_(vcbprintf) (mon_out, &b, format, vargs);
1379 va_end(vargs);
1381 if (b.next > 0) {
1382 b.buf[b.next] = '\0';
1383 monitor_output(b.buf);
1385 return b.ret;
1388 Int VG_(keyword_id) (const HChar* keywords, const HChar* input_word,
1389 kwd_report_error report)
1391 const Int il = (input_word == NULL ? 0 : VG_(strlen) (input_word));
1392 HChar iw[il+1];
1393 HChar kwds[VG_(strlen)(keywords)+1];
1394 HChar *kwdssaveptr;
1396 HChar* kw; /* current keyword, its length, its position */
1397 Int kwl;
1398 Int kpos = -1;
1400 Int pass;
1401 /* pass 0 = search, optional pass 1 = output message multiple matches */
1403 Int pass1needed = 0;
1405 Int partial_match = -1;
1406 Int full_match = -1;
1408 if (input_word == NULL) {
1409 iw[0] = 0;
1410 partial_match = 0; /* to force an empty string to cause an error */
1411 } else {
1412 VG_(strcpy) (iw, input_word);
1415 for (pass = 0; pass < 2; pass++) {
1416 VG_(strcpy) (kwds, keywords);
1417 if (pass == 1)
1418 VG_(gdb_printf) ("%s can match",
1419 (il == 0 ? "<empty string>" : iw));
1420 for (kw = VG_(strtok_r) (kwds, " ", &kwdssaveptr);
1421 kw != NULL;
1422 kw = VG_(strtok_r) (NULL, " ", &kwdssaveptr)) {
1423 kwl = VG_(strlen) (kw);
1424 kpos++;
1426 if (il > kwl) {
1427 ; /* ishtar !~ is */
1428 } else if (il == kwl) {
1429 if (VG_(strcmp) (kw, iw) == 0) {
1430 /* exact match */
1431 if (pass == 1)
1432 VG_(gdb_printf) (" %s", kw);
1433 if (full_match != -1)
1434 pass1needed++;
1435 full_match = kpos;
1437 } else {
1438 /* il < kwl */
1439 if (VG_(strncmp) (iw, kw, il) == 0) {
1440 /* partial match */
1441 if (pass == 1)
1442 VG_(gdb_printf) (" %s", kw);
1443 if (partial_match != -1)
1444 pass1needed++;
1445 partial_match = kpos;
1449 /* check for success or for no match at all */
1450 if (pass1needed == 0) {
1451 if (full_match != -1) {
1452 return full_match;
1453 } else {
1454 if (report == kwd_report_all && partial_match == -1) {
1455 VG_(gdb_printf) ("%s does not match any of '%s'\n",
1456 iw, keywords);
1458 return partial_match;
1462 /* here we have duplicated match error */
1463 if (pass == 1 || report == kwd_report_none) {
1464 if (report != kwd_report_none) {
1465 VG_(gdb_printf) ("\n");
1467 if (partial_match != -1 || full_match != -1)
1468 return -2;
1469 else
1470 return -1;
1473 /* UNREACHED */
1474 vg_assert (0);
1477 /* True if string can be a 0x number */
1478 static Bool is_zero_x (const HChar *s)
1480 if (strlen (s) >= 3 && s[0] == '0' && s[1] == 'x')
1481 return True;
1482 else
1483 return False;
1486 /* True if string can be a 0b number */
1487 static Bool is_zero_b (const HChar *s)
1489 if (strlen (s) >= 3 && s[0] == '0' && s[1] == 'b')
1490 return True;
1491 else
1492 return False;
1495 Bool VG_(strtok_get_address_and_size) (Addr* address,
1496 SizeT* szB,
1497 HChar **ssaveptr)
1499 HChar* wa;
1500 HChar* ws;
1501 HChar* endptr;
1502 const HChar *ppc;
1504 wa = VG_(strtok_r) (NULL, " [", ssaveptr);
1505 ppc = wa;
1506 if (ppc == NULL || !VG_(parse_Addr) (&ppc, address)) {
1507 VG_(gdb_printf) ("missing or malformed address\n");
1508 *address = (Addr) 0;
1509 *szB = 0;
1510 return False;
1512 ws = VG_(strtok_r) (NULL, " ]", ssaveptr);
1513 if (ws == NULL) {
1514 /* Do nothing, i.e. keep current value of szB. */ ;
1515 } else if (is_zero_x (ws)) {
1516 *szB = VG_(strtoull16) (ws, &endptr);
1517 } else if (is_zero_b (ws)) {
1518 Int j;
1519 HChar *parsews = ws;
1520 Int n_bits = VG_(strlen) (ws) - 2;
1521 *szB = 0;
1522 ws = NULL; // assume the below loop gives a correct nr.
1523 for (j = 0; j < n_bits; j++) {
1524 if ('0' == parsews[j+2]) { /* do nothing */ }
1525 else if ('1' == parsews[j+2]) *szB |= (1 << (n_bits-j-1));
1526 else {
1527 /* report malformed binary integer */
1528 ws = parsews;
1529 endptr = ws + j + 2;
1530 break;
1533 } else {
1534 *szB = VG_(strtoull10) (ws, &endptr);
1537 if (ws != NULL && *endptr != '\0') {
1538 VG_(gdb_printf) ("malformed integer, expecting "
1539 "hex 0x..... or dec ...... or binary 0b.....\n");
1540 *address = (Addr) 0;
1541 *szB = 0;
1542 return False;
1545 return True;
1548 void VG_(gdbserver_status_output)(void)
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(),
1566 vgdb_interrupted_tid,
1567 interrupts_non_busy,
1568 interrupts_while_busy,
1569 interrupts_non_interruptible,
1571 nr_gdbserved_addresses,
1572 nr_watchpoints,
1573 VG_(clo_vgdb_error),
1574 hostvisibility ? "yes" : "no");