1 /* Main code for remote server for GDB.
2 Copyright (C) 1989, 1993, 1994, 1995, 1997, 1998, 1999, 2000, 2002, 2003,
4 Free Software Foundation, Inc.
6 This file is part of GDB.
7 It has been modified to integrate it in valgrind
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 Boston, MA 02110-1301, USA. */
26 #include "pub_core_options.h"
27 #include "pub_core_translate.h"
28 #include "pub_core_mallocfree.h"
29 #include "pub_core_initimg.h"
30 #include "pub_core_execontext.h"
31 #include "pub_core_syswrap.h" // VG_(show_open_fds)
32 #include "pub_core_scheduler.h"
33 #include "pub_core_transtab.h"
34 #include "pub_core_debuginfo.h"
35 #include "pub_core_addrinfo.h"
36 #include "pub_core_aspacemgr.h"
38 unsigned long cont_thread
;
39 unsigned long general_thread
;
40 unsigned long step_thread
;
41 unsigned long thread_from_wait
;
42 unsigned long old_thread_from_wait
;
44 int pass_signals
[TARGET_SIGNAL_LAST
]; /* indexed by gdb signal nr */
46 /* for a gdbserver integrated in valgrind, resuming the process consists
47 in returning the control to valgrind.
48 The guess process resumes its execution.
49 Then at the next error or break or ..., valgrind calls gdbserver again.
50 A resume reply packet must then be built to inform GDB that the
51 resume request is finished.
52 resume_reply_packet_needed records the fact that the next call to gdbserver
53 must send a resume packet to gdb. */
54 static Bool resume_reply_packet_needed
= False
;
56 VG_MINIMAL_JMP_BUF(toplevel
);
58 /* Decode a qXfer read request. Return 0 if everything looks OK,
62 int decode_xfer_read (char *buf
, const char **annex
, CORE_ADDR
*ofs
, unsigned int *len
)
64 /* Extract and NUL-terminate the annex. */
66 while (*buf
&& *buf
!= ':')
72 /* After the read/write marker and annex, qXfer looks like a
73 traditional 'm' packet. */
74 decode_m_packet (buf
, ofs
, len
);
79 /* Write the response to a successful qXfer read. Returns the
80 length of the (binary) data stored in BUF, corresponding
81 to as much of DATA/LEN as we could fit. IS_MORE controls
82 the first character of the response. */
84 int write_qxfer_response (char *buf
, unsigned char *data
, int len
, int is_more
)
93 return remote_escape_output (data
, len
, (unsigned char *) buf
+ 1, &out_len
,
94 PBUFSIZ
- POVERHSIZ
- 1) + 1;
97 static Bool initial_valgrind_sink_saved
= False
;
98 /* True <=> valgrind log sink saved in initial_valgrind_sink */
99 static OutputSink initial_valgrind_sink
;
101 static Bool command_output_to_log
= False
;
102 /* True <=> command output goes to log instead of gdb */
104 void reset_valgrind_sink(const char *info
)
106 if (VG_(log_output_sink
).fd
!= initial_valgrind_sink
.fd
107 && initial_valgrind_sink_saved
) {
108 VG_(log_output_sink
).fd
= initial_valgrind_sink
.fd
;
109 VG_(umsg
) ("Reset valgrind output to log (%s)\n",
110 (info
== NULL
? "" : info
));
114 void print_to_initial_valgrind_sink (const char *msg
)
116 vg_assert (initial_valgrind_sink_saved
);
117 VG_(write
) (initial_valgrind_sink
.fd
, msg
, strlen(msg
));
122 void kill_request (const char *msg
)
124 VG_(umsg
) ("%s", msg
);
128 // s is a NULL terminated string made of O or more words (separated by spaces).
129 // Returns a pointer to the Nth word in s.
130 // If Nth word does not exist, return a pointer to the last (0) byte of s.
132 const char *wordn (const char *s
, int n
)
135 Bool searching_word
= True
;
139 searching_word
= True
;
141 if (searching_word
) {
142 searching_word
= False
;
153 void VG_(print_all_stats
) (Bool memory_stats
, Bool tool_stats
)
156 VG_(message
)(Vg_DebugMsg
, "\n");
157 VG_(message
)(Vg_DebugMsg
,
158 "------ Valgrind's internal memory use stats follow ------\n" );
159 VG_(sanity_check_malloc_all
)();
162 "------ %'13llu bytes have already been mmap-ed ANONYMOUS.\n",
163 VG_(am_get_anonsize_total
)());
164 VG_(print_all_arena_stats
)();
165 if (VG_(clo_profile_heap
))
166 VG_(print_arena_cc_analysis
) ();
167 VG_(message
)(Vg_DebugMsg
, "\n");
170 VG_(print_translation_stats
)();
171 VG_(print_tt_tc_stats
)();
172 VG_(print_scheduler_stats
)();
173 VG_(print_ExeContext_stats
)( False
/* with_stacktraces */ );
174 VG_(print_errormgr_stats
)();
175 if (tool_stats
&& VG_(needs
).print_stats
) {
176 VG_TDICT_CALL(tool_print_stats
);
180 /* handle_gdb_valgrind_command handles the provided mon string command.
181 If command is recognised, return 1 else return 0.
182 Note that in case of ambiguous command, 1 is returned.
184 *sink_wanted_at_return is modified if one of the commands
185 'v.set *_output' is handled.
188 int handle_gdb_valgrind_command (char *mon
, OutputSink
*sink_wanted_at_return
)
191 char s
[strlen(mon
)+1]; /* copy for strtok_r */
198 const DiEpoch cur_ep
= VG_(current_DiEpoch
)();
200 vg_assert (initial_valgrind_sink_saved
);
203 wcmd
= strtok_r (s
, " ", &ssaveptr
);
204 /* NB: if possible, avoid introducing a new command below which
205 starts with the same 3 first letters as an already existing
206 command. This ensures a shorter abbreviation for the user. */
207 switch (VG_(keyword_id
) ("help v.set v.info v.wait v.kill v.translate"
209 wcmd
, kwd_report_duplicated_matches
)) {
217 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
221 switch (VG_(keyword_id
) ("debug", wcmd
, kwd_report_all
)) {
222 case -2: int_value
= 0; break;
223 case -1: int_value
= 0; break;
224 case 0: int_value
= 1; break;
225 default: vg_assert (0);
230 "general valgrind monitor commands:\n"
231 " help [debug] : monitor command help. With debug: + debugging commands\n"
232 " v.wait [<ms>] : sleep <ms> (default 0) then continue\n"
233 " v.info all_errors : show all errors found so far\n"
234 " v.info last_error : show last error found\n"
235 " v.info location <addr> : show information about location <addr>\n"
236 " v.info n_errs_found [msg] : show the nr of errors found so far and the given msg\n"
237 " v.info open_fds : show open file descriptors (only if --track-fds=yes)\n"
238 " v.kill : kill the Valgrind process\n"
239 " v.set gdb_output : set valgrind output to gdb\n"
240 " v.set log_output : set valgrind output to log\n"
241 " v.set mixed_output : set valgrind output to log, interactive output to gdb\n"
242 " v.set merge-recursive-frames <num> : merge recursive calls in max <num> frames\n"
243 " v.set vgdb-error <errornr> : debug me at error >= <errornr> \n");
244 if (int_value
) { VG_(gdb_printf
) (
245 "debugging valgrind internals monitor commands:\n"
246 " v.do expensive_sanity_check_general : do an expensive sanity check now\n"
247 " v.info gdbserver_status : show gdbserver status\n"
248 " v.info memory [aspacemgr] : show valgrind heap memory stats\n"
249 " (with aspacemgr arg, also shows valgrind segments on log output)\n"
250 " v.info exectxt : show stacktraces and stats of all execontexts\n"
251 " v.info scheduler : show valgrind thread state and stacktrace\n"
252 " v.info stats : show various valgrind and tool stats\n"
253 " v.info unwind <addr> [<len>] : show unwind debug info for <addr> .. <addr+len>\n"
254 " v.set debuglog <level> : set valgrind debug log level to <level>\n"
255 " v.set hostvisibility [yes*|no] : (en/dis)ables access by gdb/gdbserver to\n"
256 " Valgrind internal host status/memory\n"
257 " v.translate <addr> [<traceflags>] : debug translation of <addr> with <traceflags>\n"
258 " (default traceflags 0b00100000 : show after instrumentation)\n"
259 " An additional flag 0b100000000 allows to show gdbserver instrumentation\n");
264 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
265 switch (kwdid
= VG_(keyword_id
)
266 ("vgdb-error debuglog merge-recursive-frames"
267 " gdb_output log_output mixed_output hostvisibility",
268 wcmd
, kwd_report_all
)) {
272 case 0: /* vgdb-error */
273 case 1: /* debuglog */
274 case 2: /* merge-recursive-frames */
275 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
278 endptr
= "empty"; /* to report an error below */
281 int_value
= strtol (wcmd
, &the_end
, 10);
284 if (*endptr
!= '\0') {
285 VG_(gdb_printf
) ("missing or malformed integer value\n");
286 } else if (kwdid
== 0) {
287 VG_(printf
) ("vgdb-error value changed from %d to %d\n",
288 VG_(dyn_vgdb_error
), int_value
);
289 VG_(dyn_vgdb_error
) = int_value
;
290 } else if (kwdid
== 1) {
291 VG_(printf
) ("debuglog value changed from %d to %d\n",
292 VG_(debugLog_getLevel
)(), int_value
);
293 VG_(debugLog_startup
) (int_value
, "gdbsrv");
294 } else if (kwdid
== 2) {
296 ("merge-recursive-frames value changed from %d to %d\n",
297 VG_(clo_merge_recursive_frames
), int_value
);
298 VG_(clo_merge_recursive_frames
) = int_value
;
303 case 3: /* gdb_output */
304 (*sink_wanted_at_return
).fd
= -2;
305 command_output_to_log
= False
;
306 VG_(gdb_printf
) ("valgrind output will go to gdb\n");
308 case 4: /* log_output */
309 (*sink_wanted_at_return
).fd
= initial_valgrind_sink
.fd
;
310 command_output_to_log
= True
;
311 VG_(gdb_printf
) ("valgrind output will go to log\n");
313 case 5: /* mixed output */
314 (*sink_wanted_at_return
).fd
= initial_valgrind_sink
.fd
;
315 command_output_to_log
= False
;
317 ("valgrind output will go to log, "
318 "interactive output will go to gdb\n");
320 case 6: /* hostvisibility */
321 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
323 switch (VG_(keyword_id
) ("yes no", wcmd
, kwd_report_all
)) {
327 hostvisibility
= True
;
330 hostvisibility
= False
;
332 default: vg_assert (0);
335 hostvisibility
= True
;
337 if (hostvisibility
) {
338 const DebugInfo
*tooldi
339 = VG_(find_DebugInfo
) (cur_ep
, (Addr
)handle_gdb_valgrind_command
);
340 /* Normally, we should always find the tooldi. In case we
341 do not, suggest a 'likely somewhat working' address: */
342 const Addr tool_text_start
344 VG_(DebugInfo_get_text_avma
) (tooldi
) : 0x58000000;
345 const NSegment
*toolseg
347 VG_(am_find_nsegment
) (VG_(DebugInfo_get_text_avma
) (tooldi
))
350 ("Enabled access to Valgrind memory/status by GDB\n"
351 "If not yet done, tell GDB which valgrind file(s) to use, "
353 "add-symbol-file %s %p\n",
354 toolseg
? VG_(am_get_filename
)(toolseg
)
355 : "<toolfile> <address> e.g.",
356 (void*)tool_text_start
);
359 ("Disabled access to Valgrind memory/status by GDB\n");
365 case 2: /* v.info */ {
367 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
368 switch (kwdid
= VG_(keyword_id
)
369 ("all_errors n_errs_found last_error gdbserver_status memory"
370 " scheduler stats open_fds exectxt location unwind",
371 wcmd
, kwd_report_all
)) {
375 case 0: // all_errors
376 // A verbosity of minimum 2 is needed to show the errors.
377 VG_(show_all_errors
)(/* verbosity */ 2, /* xml */ False
);
379 case 1: // n_errs_found
380 VG_(printf
) ("n_errs_found %u n_errs_shown %u (vgdb-error %d) %s\n",
381 VG_(get_n_errs_found
) (),
382 VG_(get_n_errs_shown
) (),
386 case 2: // last_error
387 VG_(show_last_error
)();
389 case 3: // gdbserver_status
390 VG_(gdbserver_status_output
)();
393 VG_(printf
) ("%'13llu bytes have already been mmap-ed ANONYMOUS.\n",
394 VG_(am_get_anonsize_total
)());
395 VG_(print_all_arena_stats
) ();
396 if (VG_(clo_profile_heap
))
397 VG_(print_arena_cc_analysis
) ();
398 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
400 switch (VG_(keyword_id
) ("aspacemgr", wcmd
, kwd_report_all
)) {
404 VG_(am_show_nsegments
) (0, "gdbserver v.info memory aspacemgr");
406 default: vg_assert (0);
412 case 5: /* scheduler */
413 VG_(show_sched_status
) (True
, // host_stacktrace
415 True
); // exited_threads
419 VG_(print_all_stats
)(False
, /* Memory stats */
420 True
/* Tool stats */);
423 case 7: /* open_fds */
424 if (VG_(clo_track_fds
))
425 VG_(show_open_fds
) ("");
428 ("Valgrind must be started with --track-fds=yes"
429 " to show open fds\n");
432 case 8: /* exectxt */
433 VG_(print_ExeContext_stats
) (True
/* with_stacktraces */);
436 case 9: { /* location */
437 /* Note: we prefer 'v.info location' and not 'v.info address' as
438 v.info address is inconsistent with the GDB (native)
439 command 'info address' which gives the address for a symbol.
440 GDB equivalent command of 'v.info location' is 'info symbol'. */
442 SizeT dummy_sz
= 0x1234;
443 if (VG_(strtok_get_address_and_size
) (&address
,
444 &dummy_sz
, &ssaveptr
)) {
445 // If tool provides location information, use that.
446 if (VG_(needs
).info_location
) {
447 VG_TDICT_CALL(tool_info_location
, cur_ep
, address
);
449 // If tool does not provide location info, use the common one.
450 // Also use the common to compare with tool when debug log is set.
451 if (!VG_(needs
).info_location
|| VG_(debugLog_getLevel
)() > 0 ) {
453 ai
.tag
= Addr_Undescribed
;
454 VG_(describe_addr
) (cur_ep
, address
, &ai
);
455 VG_(pp_addrinfo
) (address
, &ai
);
456 VG_(clear_addrinfo
) (&ai
);
462 case 10: { /* unwind */
465 if (VG_(strtok_get_address_and_size
) (&address
,
467 VG_(ppUnwindInfo
) (address
, address
+ sz
- 1);
479 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
481 int_value
= strtol (wcmd
, NULL
, 10);
482 VG_(printf
) ("gdbserver: continuing in %d ms ...\n", int_value
);
483 VG_(poll
)(NULL
, 0, int_value
);
485 VG_(printf
) ("gdbserver: continuing after wait ...\n");
489 kill_request ("monitor command request to kill this process\n");
491 case 5: { /* v.translate */
493 SizeT verbosity
= 0x20;
497 if (VG_(strtok_get_address_and_size
) (&address
, &verbosity
, &ssaveptr
)) {
498 /* we need to force the output to log for the translation trace,
499 as low level VEX tracing cannot be redirected to gdb. */
500 int saved_command_output_to_log
= command_output_to_log
;
501 int saved_fd
= VG_(log_output_sink
).fd
;
502 Bool single_stepping_on_entry
= valgrind_single_stepping();
503 int vex_verbosity
= verbosity
& 0xff;
504 VG_(log_output_sink
).fd
= initial_valgrind_sink
.fd
;
505 if ((verbosity
& 0x100) && !single_stepping_on_entry
) {
506 valgrind_set_single_stepping(True
);
507 // to force gdbserver instrumentation.
509 # if defined(VGA_arm)
510 // on arm, we need to (potentially) convert this address
511 // to the thumb form.
512 address
= thumb_pc (address
);
515 VG_(translate
) ( 0 /* dummy ThreadId; irrelevant due to debugging*/,
520 /*allow redir?*/True
);
521 if ((verbosity
& 0x100) && !single_stepping_on_entry
) {
522 valgrind_set_single_stepping(False
);
523 // reset single stepping.
525 command_output_to_log
= saved_command_output_to_log
;
526 VG_(log_output_sink
).fd
= saved_fd
;
533 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
534 switch (VG_(keyword_id
) ("expensive_sanity_check_general",
535 wcmd
, kwd_report_all
)) {
538 case 0: { /* expensive_sanity_check_general */
539 // Temporarily bump up sanity level to check e.g. the malloc arenas.
540 const Int save_clo_sanity_level
= VG_(clo_sanity_level
);
541 if (VG_(clo_sanity_level
) < 4) VG_(clo_sanity_level
) = 4;
542 VG_(sanity_check_general
) (/* force_expensive */ True
);
543 VG_(clo_sanity_level
) = save_clo_sanity_level
;
546 default: vg_assert (0);
556 /* handle_gdb_monitor_command handles the provided mon string command,
557 which can be either a "standard" valgrind monitor command
558 or a tool specific monitor command.
559 If command recognised, return 1 else return 0.
560 Note that in case of ambiguous command, 1 is returned.
563 int handle_gdb_monitor_command (char *mon
)
567 // initially, we assume that when returning, the desired sink is the
568 // one we have when entering. It can however be changed by the standard
569 // valgrind command handling.
570 OutputSink sink_wanted_at_return
= VG_(log_output_sink
);
571 // When using gdbserver, we temporarily disable xml output.
572 Bool save_clo_xml
= VG_(clo_xml
);
573 VG_(clo_xml
) = False
;
575 if (!initial_valgrind_sink_saved
) {
576 /* first time we enter here, we save the valgrind default log sink */
577 initial_valgrind_sink
= sink_wanted_at_return
;
578 initial_valgrind_sink_saved
= True
;
581 if (!command_output_to_log
)
582 VG_(log_output_sink
).fd
= -2; /* redirect to monitor_output */
584 ret
= handle_gdb_valgrind_command (mon
, &sink_wanted_at_return
);
586 /* Even if command was recognised by valgrind core, we call the
587 tool command handler : this is needed to handle help command
588 and/or to let the tool do some additional processing of a
589 valgrind standard command. Note however that if valgrind
590 recognised the command, we will always return success. */
591 if (VG_(needs
).client_requests
) {
592 /* If the tool reports an error when handling a monitor command,
593 we need to avoid calling gdbserver during this command
594 handling. So, we temporarily set VG_(dyn_vgdb_error) to
595 a huge value to ensure m_errormgr.c does not call gdbserver. */
596 Int save_dyn_vgdb_error
= VG_(dyn_vgdb_error
);
598 VG_(dyn_vgdb_error
) = 999999999;
599 arg
[0] = (UWord
) VG_USERREQ__GDB_MONITOR_COMMAND
;
600 arg
[1] = (UWord
) mon
;
601 VG_TDICT_CALL(tool_handle_client_request
, VG_(running_tid
), arg
,
603 VG_(dyn_vgdb_error
) = save_dyn_vgdb_error
;
606 VG_(message_flush
) ();
608 /* restore or set the desired output */
609 VG_(log_output_sink
).fd
= sink_wanted_at_return
.fd
;
610 VG_(clo_xml
) = save_clo_xml
;
619 /* Handle all of the extended 'Q' packets. */
621 void handle_set (char *arg_own_buf
, int *new_packet_len_p
)
623 if (strcmp ("QStartNoAckMode", arg_own_buf
) == 0) {
625 write_ok (arg_own_buf
);
629 if (strcmp ("QCatchSyscalls:0", arg_own_buf
) == 0) {
630 dlog (3, "catch syscall all off\n");
631 catching_syscalls
= False
;
632 write_ok (arg_own_buf
);
636 const char *q1
= "QCatchSyscalls:1";
637 if (strncmp (q1
, arg_own_buf
, strlen(q1
)) == 0) {
641 if (syscalls_to_catch
!= NULL
) {
642 free (syscalls_to_catch
);
643 syscalls_to_catch
= NULL
;
645 syscalls_to_catch_size
= 0;
646 p
= arg_own_buf
+ strlen(q1
);
649 syscalls_to_catch_size
++;
651 if (syscalls_to_catch_size
> 0) {
655 syscalls_to_catch
= malloc (syscalls_to_catch_size
* sizeof (int));
657 from
= strchr (arg_own_buf
, ';') + 1;
658 for (i
= 0; i
< syscalls_to_catch_size
; i
++) {
659 to
= strchr (from
, ';');
661 to
= arg_own_buf
+ strlen (arg_own_buf
);
662 decode_address (&sysno
, from
, to
- from
);
663 syscalls_to_catch
[i
] = (Int
)sysno
;
664 dlog(4, "catch syscall sysno %d\n", (int)sysno
);
666 if (*from
== ';') from
++;
669 dlog (4, "catch syscall all sysno\n");
670 catching_syscalls
= True
;
671 write_ok (arg_own_buf
);
675 if (strncmp ("QPassSignals:", arg_own_buf
, 13) == 0) {
678 char *end
= arg_own_buf
+ strlen(arg_own_buf
);
680 for (i
= 0; i
< TARGET_SIGNAL_LAST
; i
++)
683 from
= arg_own_buf
+ 13;
685 to
= strchr(from
, ';');
686 if (to
== NULL
) to
= end
;
687 decode_address (&sig
, from
, to
- from
);
688 pass_signals
[(int)sig
] = 1;
689 dlog(3, "pass_signal gdb_nr %d %s\n",
690 (int)sig
, target_signal_to_name(sig
));
692 if (*from
== ';') from
++;
694 write_ok (arg_own_buf
);
697 /* Otherwise we didn't know what packet it was. Say we didn't
702 Bool
VG_(client_monitor_command
) (HChar
*cmd
)
704 const Bool connected
= remote_connected();
705 const int saved_command_output_to_log
= command_output_to_log
;
709 command_output_to_log
= True
;
710 handled
= handle_gdb_monitor_command (cmd
);
712 // reset the log output unless cmd changed it.
713 if (command_output_to_log
)
714 command_output_to_log
= saved_command_output_to_log
;
717 return False
; // recognised
719 return True
; // not recognised
722 /* Handle all of the extended 'q' packets. */
724 void handle_query (char *arg_own_buf
, int *new_packet_len_p
)
726 static struct inferior_list_entry
*thread_ptr
;
728 /* thread local storage query */
729 if (strncmp ("qGetTLSAddr:", arg_own_buf
, 12) == 0) {
731 char *end
= arg_own_buf
+ strlen(arg_own_buf
);
732 unsigned long gdb_id
;
735 struct thread_info
*ti
;
737 from
= arg_own_buf
+ 12;
738 to
= strchr(from
, ',');
740 gdb_id
= strtoul (from
, NULL
, 16);
742 to
= strchr(from
, ',');
743 decode_address (&offset
, from
, to
- from
);
746 decode_address (&lm
, from
, to
- from
);
747 dlog(2, "qGetTLSAddr thread %lu offset %p lm %p\n",
748 gdb_id
, (void*)offset
, (void*)lm
);
750 ti
= gdb_id_to_thread (gdb_id
);
755 tst
= (ThreadState
*) inferior_target_data (ti
);
756 if (valgrind_get_tls_addr(tst
, offset
, lm
, &tls_addr
)) {
757 VG_(sprintf
) (arg_own_buf
, "%lx", tls_addr
);
760 // else we will report we do not support qGetTLSAddr
762 write_enn (arg_own_buf
);
767 /* qRcmd, monitor command handling. */
768 if (strncmp ("qRcmd,", arg_own_buf
, 6) == 0) {
769 char *p
= arg_own_buf
+ 6;
770 int cmdlen
= strlen(p
)/2;
773 if (unhexify (cmd
, p
, cmdlen
) != cmdlen
) {
774 write_enn (arg_own_buf
);
779 if (handle_gdb_monitor_command (cmd
)) {
780 write_ok (arg_own_buf
);
783 /* cmd not recognised */
785 ("command '%s' not recognised\n"
786 "In gdb, try 'monitor help'\n"
787 "In a shell, try 'vgdb help'\n",
789 write_ok (arg_own_buf
);
794 /* provide some valgrind specific info in return to qThreadExtraInfo. */
795 if (strncmp ("qThreadExtraInfo,", arg_own_buf
, 17) == 0) {
796 unsigned long gdb_id
;
797 struct thread_info
*ti
;
800 gdb_id
= strtoul (&arg_own_buf
[17], NULL
, 16);
801 ti
= gdb_id_to_thread (gdb_id
);
803 tst
= (ThreadState
*) inferior_target_data (ti
);
804 /* Additional info is the tid, the thread status and the thread's
806 SizeT len
= strlen(VG_(name_of_ThreadStatus
)(tst
->status
)) + 20;
807 if (tst
->thread_name
) len
+= strlen(tst
->thread_name
);
808 /* As the string will be hexified and copied into own_buf we need
809 to limit the length to avoid buffer overflow. */
810 if (len
* 2 > (PBUFSIZ
+ POVERHSIZ
))
811 len
= (PBUFSIZ
+ POVERHSIZ
) / 2;
813 if (tst
->thread_name
) {
814 VG_(snprintf
) (status
, sizeof(status
), "tid %u %s %s",
816 VG_(name_of_ThreadStatus
)(tst
->status
),
819 VG_(snprintf
) (status
, sizeof(status
), "tid %u %s",
821 VG_(name_of_ThreadStatus
)(tst
->status
));
823 hexify (arg_own_buf
, status
, strlen(status
));
826 write_enn (arg_own_buf
);
831 if (strcmp ("qAttached", arg_own_buf
) == 0) {
832 /* tell gdb to always detach, never kill the process */
833 arg_own_buf
[0] = '1';
838 if (strcmp ("qSymbol::", arg_own_buf
) == 0) {
839 /* We have no symbol to read. */
840 write_ok (arg_own_buf
);
844 if (strcmp ("qC", arg_own_buf
) == 0) {
845 VG_(sprintf
) (arg_own_buf
, "QC%x",
846 thread_to_gdb_id (current_inferior
));
850 if (strcmp ("qfThreadInfo", arg_own_buf
) == 0) {
851 thread_ptr
= all_threads
.head
;
852 VG_(sprintf
) (arg_own_buf
, "m%x",
853 thread_to_gdb_id ((struct thread_info
*)thread_ptr
));
854 thread_ptr
= thread_ptr
->next
;
858 if (strcmp ("qsThreadInfo", arg_own_buf
) == 0) {
859 if (thread_ptr
!= NULL
) {
860 VG_(sprintf
) (arg_own_buf
, "m%x",
861 thread_to_gdb_id ((struct thread_info
*)thread_ptr
));
862 thread_ptr
= thread_ptr
->next
;
865 VG_(sprintf
) (arg_own_buf
, "l");
870 if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers
)) != NULL
871 && strncmp ("qXfer:features:read:", arg_own_buf
, 20) == 0) {
873 unsigned int len
, doc_len
;
874 const char *annex
= NULL
;
875 // First, the annex is extracted from the packet received.
876 // Then, it is replaced by the corresponding file name.
879 /* Grab the annex, offset, and length. */
880 if (decode_xfer_read (arg_own_buf
+ 20, &annex
, &ofs
, &len
) < 0) {
881 strcpy (arg_own_buf
, "E00");
885 if (strcmp (annex
, "target.xml") == 0) {
886 annex
= valgrind_target_xml(VG_(clo_vgdb_shadow_registers
));
887 if (annex
!= NULL
&& VG_(clo_vgdb_shadow_registers
)) {
888 /* Ensure the shadow registers are initialized. */
889 initialize_shadow_low(True
);
892 strcpy (arg_own_buf
, "E00");
898 char doc
[VG_(strlen
)(VG_(libdir
)) + 1 + VG_(strlen
)(annex
) + 1];
899 struct vg_stat stat_doc
;
903 VG_(sprintf
)(doc
, "%s/%s", VG_(libdir
), annex
);
904 fd
= VG_(fd_open
) (doc
, VKI_O_RDONLY
, 0);
906 strcpy (arg_own_buf
, "E00");
909 if (VG_(fstat
) (fd
, &stat_doc
) != 0) {
911 strcpy (arg_own_buf
, "E00");
914 doc_len
= stat_doc
.size
;
916 if (len
> PBUFSIZ
- POVERHSIZ
)
917 len
= PBUFSIZ
- POVERHSIZ
;
920 write_enn (arg_own_buf
);
924 VG_(lseek
) (fd
, ofs
, VKI_SEEK_SET
);
925 len_read
= VG_(read
) (fd
, toread
, len
);
926 *new_packet_len_p
= write_qxfer_response (arg_own_buf
,
927 (unsigned char *)toread
,
929 ofs
+ len_read
< doc_len
);
935 if (strncmp ("qXfer:auxv:read:", arg_own_buf
, 16) == 0) {
942 /* Reject any annex; grab the offset and length. */
943 if (decode_xfer_read (arg_own_buf
+ 16, &annex
, &ofs
, &len
) < 0
944 || annex
[0] != '\0') {
945 strcpy (arg_own_buf
, "E00");
949 if (len
> PBUFSIZ
- POVERHSIZ
)
950 len
= PBUFSIZ
- POVERHSIZ
;
954 UWord
*client_auxv
= VG_(client_auxv
);
955 unsigned int client_auxv_len
= 0;
956 while (*client_auxv
!= 0) {
957 dlog(4, "auxv %llu %llx\n",
959 (ULong
)*(client_auxv
+1));
962 client_auxv_len
+= 2 * sizeof(UWord
);
964 client_auxv_len
+= 2 * sizeof(UWord
);
965 dlog(4, "auxv len %u\n", client_auxv_len
);
967 if (ofs
>= client_auxv_len
)
970 n
= client_auxv_len
- ofs
;
971 VG_(memcpy
) (data
, (unsigned char *) VG_(client_auxv
), n
);
976 write_enn (arg_own_buf
);
978 *new_packet_len_p
= write_qxfer_response (arg_own_buf
, data
, len
, 1);
980 *new_packet_len_p
= write_qxfer_response (arg_own_buf
, data
, n
, 0);
987 if (strncmp ("qXfer:exec-file:read:", arg_own_buf
, 21) == 0) {
996 /* grab the annex, offset and length. */
997 if (decode_xfer_read (arg_own_buf
+ 21, &annex
, &ofs
, &len
) < 0) {
998 strcpy (arg_own_buf
, "E00");
1002 /* Reject any annex with invalid/unexpected pid */
1003 if (strlen(annex
) > 0)
1004 pid
= strtoul (annex
, NULL
, 16);
1007 if ((int)pid
!= VG_(getpid
)() && pid
!= 0) {
1008 VG_(sprintf
) (arg_own_buf
,
1009 "E.Valgrind gdbserver pid is %d."
1010 " Cannot give info for pid %d",
1011 VG_(getpid
)(), (int) pid
);
1015 if (len
> PBUFSIZ
- 2)
1017 data
= malloc (len
);
1019 if (!VG_(resolve_filename
)(VG_(cl_exec_fd
), &name
)) {
1020 VG_(sprintf
) (arg_own_buf
,
1021 "E.Valgrind gdbserver could not"
1022 " resolve pid %d exec filename.",
1027 if (ofs
>= strlen(name
))
1030 n
= strlen(name
) - ofs
;
1031 VG_(memcpy
) (data
, name
, n
);
1035 write_enn (arg_own_buf
);
1037 *new_packet_len_p
= write_qxfer_response (arg_own_buf
, data
, len
, 1);
1039 *new_packet_len_p
= write_qxfer_response (arg_own_buf
, data
, n
, 0);
1046 if (strncmp ("qXfer:siginfo:read:", arg_own_buf
, 19) == 0) {
1053 /* Reject any annex; grab the offset and length. */
1054 if (decode_xfer_read (arg_own_buf
+ 19, &annex
, &ofs
, &len
) < 0
1055 || annex
[0] != '\0') {
1056 strcpy (arg_own_buf
, "E00");
1060 if (len
> PBUFSIZ
- POVERHSIZ
)
1061 len
= PBUFSIZ
- POVERHSIZ
;
1063 gdbserver_pending_signal_to_report(&info
);
1065 if (ofs
>= sizeof(info
))
1068 n
= sizeof(info
) - ofs
;
1071 write_enn (arg_own_buf
);
1073 *new_packet_len_p
= write_qxfer_response (arg_own_buf
,
1074 (unsigned char *)&info
,
1077 *new_packet_len_p
= write_qxfer_response (arg_own_buf
,
1078 (unsigned char *)&info
,
1084 /* Protocol features query. */
1085 if (strncmp ("qSupported", arg_own_buf
, 10) == 0
1086 && (arg_own_buf
[10] == ':' || arg_own_buf
[10] == '\0')) {
1087 VG_(sprintf
) (arg_own_buf
, "PacketSize=%x", (UInt
)PBUFSIZ
- 1);
1088 /* Note: max packet size including frame and checksum, but without
1089 trailing null byte, which is not sent/received. */
1091 strcat (arg_own_buf
, ";QStartNoAckMode+");
1092 strcat (arg_own_buf
, ";QPassSignals+");
1093 strcat (arg_own_buf
, ";QCatchSyscalls+");
1094 if (VG_(client_auxv
))
1095 strcat (arg_own_buf
, ";qXfer:auxv:read+");
1097 if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers
)) != NULL
) {
1098 strcat (arg_own_buf
, ";qXfer:features:read+");
1099 /* if a new gdb connects to us, we have to reset the register
1100 set to the normal register sets to allow this new gdb to
1101 decide to use or not the shadow registers.
1103 Note that the reset is only done for gdb that are sending
1104 qSupported packets. If a user first connected with a recent
1105 gdb using shadow registers and then with a very old gdb
1106 that does not use qSupported packet, then the old gdb will
1107 not properly connect. */
1108 initialize_shadow_low(False
);
1110 strcat (arg_own_buf
, ";qXfer:exec-file:read+");
1111 strcat (arg_own_buf
, ";qXfer:siginfo:read+");
1115 /* Otherwise we didn't know what packet it was. Say we didn't
1120 /* Handle all of the extended 'v' packets. */
1122 void handle_v_requests (char *arg_own_buf
, char *status
, int *zignal
)
1124 /* vcont packet code from gdb 6.6 removed */
1126 /* Otherwise we didn't know what packet it was. Say we didn't
1133 void myresume (int step
, int sig
)
1135 struct thread_resume resume_info
[2];
1139 resume_info
[0].step
= step
;
1140 resume_info
[0].sig
= sig
;
1143 resume_info
[n
].step
= 0;
1144 resume_info
[n
].sig
= 0;
1146 resume_reply_packet_needed
= True
;
1147 valgrind_resume (resume_info
);
1150 /* server_main global variables */
1151 static char *own_buf
;
1152 static unsigned char *mem_buf
;
1154 void gdbserver_init (void)
1156 dlog(1, "gdbserver_init gdbserver embedded in valgrind: %s\n", version
);
1158 valgrind_initialize_target ();
1159 // After a fork, gdbserver_init can be called again.
1160 // We do not have to re-malloc the buffers in such a case.
1161 if (own_buf
== NULL
)
1162 own_buf
= malloc (PBUFSIZ
+POVERHSIZ
);
1163 if (mem_buf
== NULL
)
1164 mem_buf
= malloc (PBUFSIZ
+POVERHSIZ
);
1165 // Note: normally, we should only malloc PBUFSIZ. However,
1166 // GDB has a bug, and in some cases, sends e.g. 'm' packets
1167 // asking for slightly more than the PacketSize given at
1168 // connection initialisation. So, we bypass the GDB bug
1169 // by allocating slightly more.
1172 void gdbserver_terminate (void)
1174 /* last call to gdbserver is cleanup call */
1175 if (VG_MINIMAL_SETJMP(toplevel
)) {
1176 dlog(0, "error caused VG_MINIMAL_LONGJMP to gdbserver_terminate\n");
1182 void server_main (void)
1192 zignal
= valgrind_wait (&status
);
1193 if (VG_MINIMAL_SETJMP(toplevel
)) {
1194 dlog(0, "error caused VG_MINIMAL_LONGJMP to server_main\n");
1199 int new_packet_len
= -1;
1201 if (resume_reply_packet_needed
) {
1202 /* Send the resume reply to reply to last GDB resume
1204 resume_reply_packet_needed
= False
;
1205 prepare_resume_reply (own_buf
, status
, zignal
);
1209 /* If our status is terminal (exit or fatal signal) get out
1210 as quickly as we can. We won't be able to handle any request
1212 if (status
== 'W' || status
== 'X') {
1216 packet_len
= getpkt (own_buf
);
1217 if (packet_len
<= 0)
1224 handle_set (own_buf
, &new_packet_len
);
1227 handle_query (own_buf
, &new_packet_len
);
1230 /* set/unset debugging is done through valgrind debug level. */
1234 reset_valgrind_sink("gdb detaching from process");
1236 /* When detaching or kill the process, gdb expects to get
1237 an packet OK back. Any other output will make gdb
1238 believes detach did not work. */
1241 remote_finish (reset_after_error
);
1242 remote_open (VG_(clo_vgdb_prefix
));
1244 resume_reply_packet_needed
= False
;
1247 /* We can not use the extended protocol with valgrind,
1248 because we can not restart the running
1249 program. So return unrecognized. */
1253 prepare_resume_reply (own_buf
, status
, zignal
);
1256 if (own_buf
[1] == 'c' || own_buf
[1] == 'g' || own_buf
[1] == 's') {
1257 unsigned long gdb_id
, thread_id
;
1259 gdb_id
= strtoul (&own_buf
[2], NULL
, 16);
1260 thread_id
= gdb_id_to_thread_id (gdb_id
);
1261 if (thread_id
== 0) {
1262 write_enn (own_buf
);
1266 if (own_buf
[1] == 'g') {
1267 general_thread
= thread_id
;
1268 set_desired_inferior (1);
1269 } else if (own_buf
[1] == 'c') {
1270 cont_thread
= thread_id
;
1271 } else if (own_buf
[1] == 's') {
1272 step_thread
= thread_id
;
1277 /* Silently ignore it so that gdb can extend the protocol
1278 without compatibility headaches. */
1283 set_desired_inferior (1);
1284 registers_to_string (own_buf
);
1287 set_desired_inferior (1);
1288 registers_from_string (&own_buf
[1]);
1296 regno
= strtol(&own_buf
[1], NULL
, 16);
1297 regbytes
= strchr(&own_buf
[0], '=') + 1;
1298 set_desired_inferior (1);
1299 tst
= (ThreadState
*) inferior_target_data (current_inferior
);
1300 /* Only accept changing registers in "runnable state3.
1301 In fact, it would be ok to change most of the registers
1302 except a few "sensitive" registers such as the PC, SP, BP.
1303 We assume we do not need to very specific here, and that we
1304 can just refuse all of these. */
1305 if (tst
->status
== VgTs_Runnable
|| tst
->status
== VgTs_Yielding
) {
1306 supply_register_from_string (regno
, regbytes
, &mod
);
1309 /* at least from gdb 6.6 onwards, an E. error
1310 reply is shown to the user. So, we do an error
1311 msg which both is accepted by gdb as an error msg
1312 and is readable by the user. */
1316 "ERROR changing register %s regno %d\n"
1317 "gdb commands changing registers (pc, sp, ...) (e.g. 'jump',\n"
1318 "set pc, calling from gdb a function in the debugged process, ...)\n"
1319 "can only be accepted if the thread is VgTs_Runnable or VgTs_Yielding state\n"
1320 "Thread status is %s\n",
1321 find_register_by_number (regno
)->name
, regno
,
1322 VG_(name_of_ThreadStatus
)(tst
->status
));
1323 if (VG_(clo_verbosity
) > 1)
1324 VG_(umsg
) ("%s\n", own_buf
);
1329 decode_m_packet (&own_buf
[1], &mem_addr
, &len
);
1330 if (valgrind_read_memory (mem_addr
, mem_buf
, len
) == 0)
1331 convert_int_to_ascii (mem_buf
, own_buf
, len
);
1333 write_enn (own_buf
);
1336 decode_M_packet (&own_buf
[1], &mem_addr
, &len
, mem_buf
);
1337 if (valgrind_write_memory (mem_addr
, mem_buf
, len
) == 0)
1340 write_enn (own_buf
);
1343 if (decode_X_packet (&own_buf
[1], packet_len
- 1,
1344 &mem_addr
, &len
, mem_buf
) < 0
1345 || valgrind_write_memory (mem_addr
, mem_buf
, len
) != 0)
1346 write_enn (own_buf
);
1351 convert_ascii_to_int (own_buf
+ 1, &sig
, 1);
1352 if (target_signal_to_host_p (sig
))
1353 zignal
= target_signal_to_host (sig
);
1356 set_desired_inferior (0);
1357 myresume (0, zignal
);
1358 return; // return control to valgrind
1360 convert_ascii_to_int (own_buf
+ 1, &sig
, 1);
1361 if (target_signal_to_host_p (sig
))
1362 zignal
= target_signal_to_host (sig
);
1365 set_desired_inferior (0);
1366 myresume (1, zignal
);
1367 return; // return control to valgrind
1369 set_desired_inferior (0);
1371 return; // return control to valgrind
1373 set_desired_inferior (0);
1375 return; // return control to valgrind
1379 CORE_ADDR addr
= strtoul (&own_buf
[3], &lenptr
, 16);
1380 int zlen
= strtol (lenptr
+ 1, &dataptr
, 16);
1381 char type
= own_buf
[1];
1383 if (type
< '0' || type
> '4') {
1384 /* Watchpoint command type unrecognized. */
1389 res
= valgrind_insert_watchpoint (type
, addr
, zlen
);
1396 write_enn (own_buf
);
1403 CORE_ADDR addr
= strtoul (&own_buf
[3], &lenptr
, 16);
1404 int zlen
= strtol (lenptr
+ 1, &dataptr
, 16);
1405 char type
= own_buf
[1];
1407 if (type
< '0' || type
> '4') {
1408 /* Watchpoint command type unrecognized. */
1413 res
= valgrind_remove_watchpoint (type
, addr
, zlen
);
1420 write_enn (own_buf
);
1425 kill_request("Gdb request to kill this process\n");
1428 unsigned long gdb_id
, thread_id
;
1430 gdb_id
= strtoul (&own_buf
[1], NULL
, 16);
1431 thread_id
= gdb_id_to_thread_id (gdb_id
);
1432 if (thread_id
== 0) {
1433 write_enn (own_buf
);
1437 if (valgrind_thread_alive (thread_id
))
1440 write_enn (own_buf
);
1444 /* Restarting the inferior is only supported in the
1446 => It is a request we don't understand. Respond with an
1447 empty packet so that gdb knows that we don't support this
1452 /* Extended (long) request. */
1453 handle_v_requests (own_buf
, &status
, &zignal
);
1456 /* It is a request we don't understand. Respond with an
1457 empty packet so that gdb knows that we don't support this
1463 if (new_packet_len
!= -1)
1464 putpkt_binary (own_buf
, new_packet_len
);
1469 VG_(umsg
) ("\nChild exited with status %d\n", zignal
);
1471 VG_(umsg
) ("\nChild terminated with signal = 0x%x (%s)\n",
1472 (UInt
)target_signal_to_host (zignal
),
1473 target_signal_to_name (zignal
));
1474 if (status
== 'W' || status
== 'X') {
1475 VG_(umsg
) ("Process exiting\n");
1480 /* We come here when getpkt fails => close the connection,
1481 and re-open. Then return control to valgrind.
1482 We return the control to valgrind as we assume that
1483 the connection was closed due to vgdb having finished
1484 to execute a command. */
1485 if (VG_(clo_verbosity
) > 1)
1486 VG_(umsg
) ("Remote side has terminated connection. "
1487 "GDBserver will reopen the connection.\n");
1488 remote_finish (reset_after_error
);
1489 remote_open (VG_(clo_vgdb_prefix
));
1491 resume_reply_packet_needed
= False
;