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|all])\n"
238 " v.kill : kill the Valgrind process\n"
239 " v.clo <clo_option>... : changes one or more dynamic command line options\n"
240 " with no clo_option, show the dynamically changeable options.\n"
241 " v.set gdb_output : set valgrind output to gdb\n"
242 " v.set log_output : set valgrind output to log\n"
243 " v.set mixed_output : set valgrind output to log, interactive output to gdb\n"
244 " v.set merge-recursive-frames <num> : merge recursive calls in max <num> frames\n"
245 " v.set vgdb-error <errornr> : debug me at error >= <errornr> \n");
246 if (int_value
) { VG_(gdb_printf
) (
247 "debugging valgrind internals monitor commands:\n"
248 " v.do expensive_sanity_check_general : do an expensive sanity check now\n"
249 " v.info gdbserver_status : show gdbserver status\n"
250 " v.info memory [aspacemgr] : show valgrind heap memory stats\n"
251 " (with aspacemgr arg, also shows valgrind segments on log output)\n"
252 " v.info exectxt : show stacktraces and stats of all execontexts\n"
253 " v.info scheduler : show valgrind thread state and stacktrace\n"
254 " v.info stats : show various valgrind and tool stats\n"
255 " v.info unwind <addr> [<len>] : show unwind debug info for <addr> .. <addr+len>\n"
256 " v.set debuglog <level> : set valgrind debug log level to <level>\n"
257 " v.set hostvisibility [yes*|no] : (en/dis)ables access by gdb/gdbserver to\n"
258 " Valgrind internal host status/memory\n"
259 " v.translate <addr> [<traceflags>] : debug translation of <addr> with <traceflags>\n"
260 " (default traceflags 0b00100000 : show after instrumentation)\n"
261 " An additional flag 0b100000000 allows one to show gdbserver instrumentation\n");
266 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
267 switch (kwdid
= VG_(keyword_id
)
268 ("vgdb-error debuglog merge-recursive-frames"
269 " gdb_output log_output mixed_output hostvisibility",
270 wcmd
, kwd_report_all
)) {
274 case 0: /* vgdb-error */
275 case 1: /* debuglog */
276 case 2: /* merge-recursive-frames */
277 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
280 endptr
= "empty"; /* to report an error below */
283 int_value
= strtol (wcmd
, &the_end
, 10);
286 if (*endptr
!= '\0') {
287 VG_(gdb_printf
) ("missing or malformed integer value\n");
288 } else if (kwdid
== 0) {
289 VG_(printf
) ("vgdb-error value changed from %d to %d\n",
290 VG_(clo_vgdb_error
), int_value
);
291 VG_(clo_vgdb_error
) = int_value
;
292 } else if (kwdid
== 1) {
293 VG_(printf
) ("debuglog value changed from %d to %d\n",
294 VG_(debugLog_getLevel
)(), int_value
);
295 VG_(debugLog_startup
) (int_value
, "gdbsrv");
296 } else if (kwdid
== 2) {
298 ("merge-recursive-frames value changed from %d to %d\n",
299 VG_(clo_merge_recursive_frames
), int_value
);
300 VG_(clo_merge_recursive_frames
) = int_value
;
305 case 3: /* gdb_output */
306 (*sink_wanted_at_return
).fd
= -2;
307 command_output_to_log
= False
;
308 VG_(gdb_printf
) ("valgrind output will go to gdb\n");
310 case 4: /* log_output */
311 (*sink_wanted_at_return
).fd
= initial_valgrind_sink
.fd
;
312 command_output_to_log
= True
;
313 VG_(gdb_printf
) ("valgrind output will go to log\n");
315 case 5: /* mixed output */
316 (*sink_wanted_at_return
).fd
= initial_valgrind_sink
.fd
;
317 command_output_to_log
= False
;
319 ("valgrind output will go to log, "
320 "interactive output will go to gdb\n");
322 case 6: /* hostvisibility */
323 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
325 switch (VG_(keyword_id
) ("yes no", wcmd
, kwd_report_all
)) {
329 hostvisibility
= True
;
332 hostvisibility
= False
;
334 default: vg_assert (0);
337 hostvisibility
= True
;
339 if (hostvisibility
) {
340 const DebugInfo
*tooldi
341 = VG_(find_DebugInfo
) (cur_ep
, (Addr
)handle_gdb_valgrind_command
);
342 /* Normally, we should always find the tooldi. In case we
343 do not, suggest a 'likely somewhat working' address: */
344 const Addr tool_text_start
346 VG_(DebugInfo_get_text_avma
) (tooldi
) : 0x58000000;
347 const NSegment
*toolseg
349 VG_(am_find_nsegment
) (VG_(DebugInfo_get_text_avma
) (tooldi
))
352 ("Enabled access to Valgrind memory/status by GDB\n"
353 "If not yet done, tell GDB which valgrind file(s) to use, "
355 "add-symbol-file %s %p\n",
356 toolseg
? VG_(am_get_filename
)(toolseg
)
357 : "<toolfile> <address> e.g.",
358 (void*)tool_text_start
);
361 ("Disabled access to Valgrind memory/status by GDB\n");
367 case 2: /* v.info */ {
369 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
370 switch (kwdid
= VG_(keyword_id
)
371 ("all_errors n_errs_found last_error gdbserver_status memory"
372 " scheduler stats open_fds exectxt location unwind",
373 wcmd
, kwd_report_all
)) {
377 case 0: // all_errors
378 // A verbosity of minimum 2 is needed to show the errors.
379 VG_(show_all_errors
)(/* verbosity */ 2, /* xml */ False
);
381 case 1: // n_errs_found
382 VG_(printf
) ("n_errs_found %u n_errs_shown %u (vgdb-error %d) %s\n",
383 VG_(get_n_errs_found
) (),
384 VG_(get_n_errs_shown
) (),
388 case 2: // last_error
389 VG_(show_last_error
)();
391 case 3: // gdbserver_status
392 VG_(gdbserver_status_output
)();
395 VG_(printf
) ("%'13llu bytes have already been mmap-ed ANONYMOUS.\n",
396 VG_(am_get_anonsize_total
)());
397 VG_(print_all_arena_stats
) ();
398 if (VG_(clo_profile_heap
))
399 VG_(print_arena_cc_analysis
) ();
400 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
402 switch (VG_(keyword_id
) ("aspacemgr", wcmd
, kwd_report_all
)) {
406 VG_(am_show_nsegments
) (0, "gdbserver v.info memory aspacemgr");
408 default: vg_assert (0);
414 case 5: /* scheduler */
415 VG_(show_sched_status
) (True
, // host_stacktrace
417 True
); // exited_threads
421 VG_(print_all_stats
)(False
, /* Memory stats */
422 True
/* Tool stats */);
425 case 7: /* open_fds */
426 if (VG_(clo_track_fds
))
427 VG_(show_open_fds
) ("");
430 ("Valgrind must be started with --track-fds=[yes|all]"
431 " to show open fds\n");
434 case 8: /* exectxt */
435 VG_(print_ExeContext_stats
) (True
/* with_stacktraces */);
438 case 9: { /* location */
439 /* Note: we prefer 'v.info location' and not 'v.info address' as
440 v.info address is inconsistent with the GDB (native)
441 command 'info address' which gives the address for a symbol.
442 GDB equivalent command of 'v.info location' is 'info symbol'. */
444 SizeT dummy_sz
= 0x1234;
445 if (VG_(strtok_get_address_and_size
) (&address
,
446 &dummy_sz
, &ssaveptr
)) {
447 // If tool provides location information, use that.
448 if (VG_(needs
).info_location
) {
449 VG_TDICT_CALL(tool_info_location
, cur_ep
, address
);
451 // If tool does not provide location info, use the common one.
452 // Also use the common to compare with tool when debug log is set.
453 if (!VG_(needs
).info_location
|| VG_(debugLog_getLevel
)() > 0 ) {
455 ai
.tag
= Addr_Undescribed
;
456 VG_(describe_addr
) (cur_ep
, address
, &ai
);
457 VG_(pp_addrinfo
) (address
, &ai
);
458 VG_(clear_addrinfo
) (&ai
);
464 case 10: { /* unwind */
467 if (VG_(strtok_get_address_and_size
) (&address
,
469 VG_(ppUnwindInfo
) (address
, address
+ sz
- 1);
481 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
483 int_value
= strtol (wcmd
, NULL
, 10);
484 VG_(printf
) ("gdbserver: continuing in %d ms ...\n", int_value
);
485 VG_(poll
)(NULL
, 0, int_value
);
487 VG_(printf
) ("gdbserver: continuing after wait ...\n");
491 kill_request ("monitor command request to kill this process\n");
493 case 5: { /* v.translate */
495 SizeT verbosity
= 0x20;
499 if (VG_(strtok_get_address_and_size
) (&address
, &verbosity
, &ssaveptr
)) {
500 /* we need to force the output to log for the translation trace,
501 as low level VEX tracing cannot be redirected to gdb. */
502 int saved_command_output_to_log
= command_output_to_log
;
503 int saved_fd
= VG_(log_output_sink
).fd
;
504 Bool single_stepping_on_entry
= valgrind_single_stepping();
505 int vex_verbosity
= verbosity
& 0xff;
506 VG_(log_output_sink
).fd
= initial_valgrind_sink
.fd
;
507 if ((verbosity
& 0x100) && !single_stepping_on_entry
) {
508 valgrind_set_single_stepping(True
);
509 // to force gdbserver instrumentation.
511 # if defined(VGA_arm)
512 // on arm, we need to (potentially) convert this address
513 // to the thumb form.
514 address
= thumb_pc (address
);
517 VG_(translate
) ( 0 /* dummy ThreadId; irrelevant due to debugging*/,
522 /*allow redir?*/True
);
523 if ((verbosity
& 0x100) && !single_stepping_on_entry
) {
524 valgrind_set_single_stepping(False
);
525 // reset single stepping.
527 command_output_to_log
= saved_command_output_to_log
;
528 VG_(log_output_sink
).fd
= saved_fd
;
535 wcmd
= strtok_r (NULL
, " ", &ssaveptr
);
536 switch (VG_(keyword_id
) ("expensive_sanity_check_general",
537 wcmd
, kwd_report_all
)) {
540 case 0: { /* expensive_sanity_check_general */
541 // Temporarily bump up sanity level to check e.g. the malloc arenas.
542 const Int save_clo_sanity_level
= VG_(clo_sanity_level
);
543 if (VG_(clo_sanity_level
) < 4) VG_(clo_sanity_level
) = 4;
544 VG_(sanity_check_general
) (/* force_expensive */ True
);
545 VG_(clo_sanity_level
) = save_clo_sanity_level
;
548 default: vg_assert (0);
554 for (wcmd
= VG_(strtok_r
)(NULL
, " ", &ssaveptr
);
556 wcmd
= VG_(strtok_r
)(NULL
, " ", &ssaveptr
)) {
558 VG_(process_dynamic_option
) (cloD
, wcmd
);
561 VG_(list_dynamic_options
) ();
571 /* handle_gdb_monitor_command handles the provided mon string command,
572 which can be either a "standard" valgrind monitor command
573 or a tool specific monitor command.
574 If command recognised, return 1 else return 0.
575 Note that in case of ambiguous command, 1 is returned.
578 int handle_gdb_monitor_command (char *mon
)
582 // initially, we assume that when returning, the desired sink is the
583 // one we have when entering. It can however be changed by the standard
584 // valgrind command handling.
585 OutputSink sink_wanted_at_return
= VG_(log_output_sink
);
586 // When using gdbserver, we temporarily disable xml output.
587 Bool save_clo_xml
= VG_(clo_xml
);
588 VG_(clo_xml
) = False
;
590 if (!initial_valgrind_sink_saved
) {
591 /* first time we enter here, we save the valgrind default log sink */
592 initial_valgrind_sink
= sink_wanted_at_return
;
593 initial_valgrind_sink_saved
= True
;
596 if (!command_output_to_log
)
597 VG_(log_output_sink
).fd
= -2; /* redirect to monitor_output */
599 ret
= handle_gdb_valgrind_command (mon
, &sink_wanted_at_return
);
601 /* Even if command was recognised by valgrind core, we call the
602 tool command handler : this is needed to handle help command
603 and/or to let the tool do some additional processing of a
604 valgrind standard command. Note however that if valgrind
605 recognised the command, we will always return success. */
606 if (VG_(needs
).client_requests
) {
607 /* If the tool reports an error when handling a monitor command,
608 we need to avoid calling gdbserver during this command
609 handling. So, we temporarily set VG_(clo_vgdb_error) to
610 a huge value to ensure m_errormgr.c does not call gdbserver. */
611 Int save_clo_vgdb_error
= VG_(clo_vgdb_error
);
613 VG_(clo_vgdb_error
) = 999999999;
614 arg
[0] = (UWord
) VG_USERREQ__GDB_MONITOR_COMMAND
;
615 arg
[1] = (UWord
) mon
;
616 VG_TDICT_CALL(tool_handle_client_request
, VG_(running_tid
), arg
,
618 VG_(clo_vgdb_error
) = save_clo_vgdb_error
;
621 VG_(message_flush
) ();
623 /* restore or set the desired output */
624 VG_(log_output_sink
).fd
= sink_wanted_at_return
.fd
;
625 VG_(clo_xml
) = save_clo_xml
;
634 /* Handle all of the extended 'Q' packets. */
636 void handle_set (char *arg_own_buf
, int *new_packet_len_p
)
638 if (strcmp ("QStartNoAckMode", arg_own_buf
) == 0) {
640 write_ok (arg_own_buf
);
644 if (strcmp ("QCatchSyscalls:0", arg_own_buf
) == 0) {
645 dlog (3, "catch syscall all off\n");
646 catching_syscalls
= False
;
647 write_ok (arg_own_buf
);
651 const char *q1
= "QCatchSyscalls:1";
652 if (strncmp (q1
, arg_own_buf
, strlen(q1
)) == 0) {
656 if (syscalls_to_catch
!= NULL
) {
657 free (syscalls_to_catch
);
658 syscalls_to_catch
= NULL
;
660 syscalls_to_catch_size
= 0;
661 p
= arg_own_buf
+ strlen(q1
);
664 syscalls_to_catch_size
++;
666 if (syscalls_to_catch_size
> 0) {
670 syscalls_to_catch
= malloc (syscalls_to_catch_size
* sizeof (int));
672 from
= strchr (arg_own_buf
, ';') + 1;
673 for (i
= 0; i
< syscalls_to_catch_size
; i
++) {
674 to
= strchr (from
, ';');
676 to
= arg_own_buf
+ strlen (arg_own_buf
);
677 decode_address (&sysno
, from
, to
- from
);
678 syscalls_to_catch
[i
] = (Int
)sysno
;
679 dlog(4, "catch syscall sysno %d\n", (int)sysno
);
681 if (*from
== ';') from
++;
684 dlog (4, "catch syscall all sysno\n");
685 catching_syscalls
= True
;
686 write_ok (arg_own_buf
);
690 if (strncmp ("QPassSignals:", arg_own_buf
, 13) == 0) {
693 char *end
= arg_own_buf
+ strlen(arg_own_buf
);
695 for (i
= 0; i
< TARGET_SIGNAL_LAST
; i
++)
698 from
= arg_own_buf
+ 13;
700 to
= strchr(from
, ';');
701 if (to
== NULL
) to
= end
;
702 decode_address (&sig
, from
, to
- from
);
703 pass_signals
[(int)sig
] = 1;
704 dlog(3, "pass_signal gdb_nr %d %s\n",
705 (int)sig
, target_signal_to_name(sig
));
707 if (*from
== ';') from
++;
709 write_ok (arg_own_buf
);
712 /* Otherwise we didn't know what packet it was. Say we didn't
717 Bool
VG_(client_monitor_command
) (HChar
*cmd
)
719 const Bool connected
= remote_connected();
720 const int saved_command_output_to_log
= command_output_to_log
;
724 command_output_to_log
= True
;
725 handled
= handle_gdb_monitor_command (cmd
);
727 // reset the log output unless cmd changed it.
728 if (command_output_to_log
)
729 command_output_to_log
= saved_command_output_to_log
;
732 return False
; // recognised
734 return True
; // not recognised
737 /* Handle all of the extended 'q' packets. */
739 void handle_query (char *arg_own_buf
, int *new_packet_len_p
)
741 static struct inferior_list_entry
*thread_ptr
;
743 /* thread local storage query */
744 if (strncmp ("qGetTLSAddr:", arg_own_buf
, 12) == 0) {
746 char *end
= arg_own_buf
+ strlen(arg_own_buf
);
747 unsigned long gdb_id
;
750 struct thread_info
*ti
;
752 from
= arg_own_buf
+ 12;
753 to
= strchr(from
, ',');
755 gdb_id
= strtoul (from
, NULL
, 16);
757 to
= strchr(from
, ',');
758 decode_address (&offset
, from
, to
- from
);
761 decode_address (&lm
, from
, to
- from
);
762 dlog(2, "qGetTLSAddr thread %lu offset %p lm %p\n",
763 gdb_id
, (void*)offset
, (void*)lm
);
765 ti
= gdb_id_to_thread (gdb_id
);
770 tst
= (ThreadState
*) inferior_target_data (ti
);
771 if (valgrind_get_tls_addr(tst
, offset
, lm
, &tls_addr
)) {
772 VG_(sprintf
) (arg_own_buf
, "%lx", tls_addr
);
775 // else we will report we do not support qGetTLSAddr
777 write_enn (arg_own_buf
);
782 /* qRcmd, monitor command handling. */
783 if (strncmp ("qRcmd,", arg_own_buf
, 6) == 0) {
784 char *p
= arg_own_buf
+ 6;
785 int cmdlen
= strlen(p
)/2;
788 if (unhexify (cmd
, p
, cmdlen
) != cmdlen
) {
789 write_enn (arg_own_buf
);
794 if (handle_gdb_monitor_command (cmd
)) {
795 write_ok (arg_own_buf
);
798 /* cmd not recognised */
800 ("command '%s' not recognised\n"
801 "In gdb, try 'monitor help'\n"
802 "In a shell, try 'vgdb help'\n",
804 write_ok (arg_own_buf
);
809 /* provide some valgrind specific info in return to qThreadExtraInfo. */
810 if (strncmp ("qThreadExtraInfo,", arg_own_buf
, 17) == 0) {
811 unsigned long gdb_id
;
812 struct thread_info
*ti
;
815 gdb_id
= strtoul (&arg_own_buf
[17], NULL
, 16);
816 ti
= gdb_id_to_thread (gdb_id
);
818 tst
= (ThreadState
*) inferior_target_data (ti
);
819 /* Additional info is the tid, the thread status and the thread's
821 SizeT len
= strlen(VG_(name_of_ThreadStatus
)(tst
->status
)) + 20;
822 if (tst
->thread_name
) len
+= strlen(tst
->thread_name
);
823 /* As the string will be hexified and copied into own_buf we need
824 to limit the length to avoid buffer overflow. */
825 if (len
* 2 > (PBUFSIZ
+ POVERHSIZ
))
826 len
= (PBUFSIZ
+ POVERHSIZ
) / 2;
828 if (tst
->thread_name
) {
829 VG_(snprintf
) (status
, sizeof(status
), "tid %u %s %s",
831 VG_(name_of_ThreadStatus
)(tst
->status
),
834 VG_(snprintf
) (status
, sizeof(status
), "tid %u %s",
836 VG_(name_of_ThreadStatus
)(tst
->status
));
838 hexify (arg_own_buf
, status
, strlen(status
));
841 write_enn (arg_own_buf
);
846 /* Without argument, traditional remote protocol. */
847 if (strcmp ("qAttached", arg_own_buf
) == 0) {
848 /* tell gdb to always detach, never kill the process */
849 arg_own_buf
[0] = '1';
854 /* With argument, extended-remote protocol. */
855 if (strncmp ("qAttached:", arg_own_buf
, strlen ("qAttached:")) == 0) {
856 /* We just created this process */
857 arg_own_buf
[0] = '0';
862 if (strcmp ("qSymbol::", arg_own_buf
) == 0) {
863 /* We have no symbol to read. */
864 write_ok (arg_own_buf
);
868 if (strcmp ("qC", arg_own_buf
) == 0) {
869 VG_(sprintf
) (arg_own_buf
, "QC%x",
870 thread_to_gdb_id (current_inferior
));
874 if (strcmp ("qfThreadInfo", arg_own_buf
) == 0) {
875 thread_ptr
= all_threads
.head
;
876 VG_(sprintf
) (arg_own_buf
, "m%x",
877 thread_to_gdb_id ((struct thread_info
*)thread_ptr
));
878 thread_ptr
= thread_ptr
->next
;
882 if (strcmp ("qsThreadInfo", arg_own_buf
) == 0) {
883 if (thread_ptr
!= NULL
) {
884 VG_(sprintf
) (arg_own_buf
, "m%x",
885 thread_to_gdb_id ((struct thread_info
*)thread_ptr
));
886 thread_ptr
= thread_ptr
->next
;
889 VG_(sprintf
) (arg_own_buf
, "l");
894 if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers
)) != NULL
895 && strncmp ("qXfer:features:read:", arg_own_buf
, 20) == 0) {
897 unsigned int len
, doc_len
;
898 const char *annex
= NULL
;
899 // First, the annex is extracted from the packet received.
900 // Then, it is replaced by the corresponding file name.
903 /* Grab the annex, offset, and length. */
904 if (decode_xfer_read (arg_own_buf
+ 20, &annex
, &ofs
, &len
) < 0) {
905 strcpy (arg_own_buf
, "E00");
909 if (strcmp (annex
, "target.xml") == 0) {
910 annex
= valgrind_target_xml(VG_(clo_vgdb_shadow_registers
));
911 if (annex
!= NULL
&& VG_(clo_vgdb_shadow_registers
)) {
912 /* Ensure the shadow registers are initialized. */
913 initialize_shadow_low(True
);
916 strcpy (arg_own_buf
, "E00");
922 char doc
[VG_(strlen
)(VG_(libdir
)) + 1 + VG_(strlen
)(annex
) + 1];
923 struct vg_stat stat_doc
;
927 VG_(sprintf
)(doc
, "%s/%s", VG_(libdir
), annex
);
928 fd
= VG_(fd_open
) (doc
, VKI_O_RDONLY
, 0);
930 strcpy (arg_own_buf
, "E00");
933 if (VG_(fstat
) (fd
, &stat_doc
) != 0) {
935 strcpy (arg_own_buf
, "E00");
938 doc_len
= stat_doc
.size
;
940 if (len
> PBUFSIZ
- POVERHSIZ
)
941 len
= PBUFSIZ
- POVERHSIZ
;
944 write_enn (arg_own_buf
);
948 VG_(lseek
) (fd
, ofs
, VKI_SEEK_SET
);
949 len_read
= VG_(read
) (fd
, toread
, len
);
950 *new_packet_len_p
= write_qxfer_response (arg_own_buf
,
951 (unsigned char *)toread
,
953 ofs
+ len_read
< doc_len
);
959 if (strncmp ("qXfer:auxv:read:", arg_own_buf
, 16) == 0) {
966 /* Reject any annex; grab the offset and length. */
967 if (decode_xfer_read (arg_own_buf
+ 16, &annex
, &ofs
, &len
) < 0
968 || annex
[0] != '\0') {
969 strcpy (arg_own_buf
, "E00");
973 if (len
> PBUFSIZ
- POVERHSIZ
)
974 len
= PBUFSIZ
- POVERHSIZ
;
978 UWord
*client_auxv
= VG_(client_auxv
);
979 unsigned int client_auxv_len
= 0;
980 while (*client_auxv
!= 0) {
981 dlog(4, "auxv %llu %llx\n",
983 (ULong
)*(client_auxv
+1));
986 client_auxv_len
+= 2 * sizeof(UWord
);
988 client_auxv_len
+= 2 * sizeof(UWord
);
989 dlog(4, "auxv len %u\n", client_auxv_len
);
991 if (ofs
>= client_auxv_len
)
994 n
= client_auxv_len
- ofs
;
995 VG_(memcpy
) (data
, (unsigned char *) VG_(client_auxv
), n
);
1000 write_enn (arg_own_buf
);
1002 *new_packet_len_p
= write_qxfer_response (arg_own_buf
, data
, len
, 1);
1004 *new_packet_len_p
= write_qxfer_response (arg_own_buf
, data
, n
, 0);
1011 if (strncmp ("qXfer:exec-file:read:", arg_own_buf
, 21) == 0) {
1012 unsigned char *data
;
1020 /* grab the annex, offset and length. */
1021 if (decode_xfer_read (arg_own_buf
+ 21, &annex
, &ofs
, &len
) < 0) {
1022 strcpy (arg_own_buf
, "E00");
1026 /* Reject any annex with invalid/unexpected pid */
1027 if (strlen(annex
) > 0)
1028 pid
= strtoul (annex
, NULL
, 16);
1031 if ((int)pid
!= VG_(getpid
)() && pid
!= 0) {
1032 VG_(sprintf
) (arg_own_buf
,
1033 "E.Valgrind gdbserver pid is %d."
1034 " Cannot give info for pid %d",
1035 VG_(getpid
)(), (int) pid
);
1039 if (len
> PBUFSIZ
- 2)
1041 data
= malloc (len
);
1043 if (!VG_(resolve_filename
)(VG_(cl_exec_fd
), &name
)) {
1044 VG_(sprintf
) (arg_own_buf
,
1045 "E.Valgrind gdbserver could not"
1046 " resolve pid %d exec filename.",
1051 if (ofs
>= strlen(name
))
1054 n
= strlen(name
) - ofs
;
1055 VG_(memcpy
) (data
, name
, n
);
1059 write_enn (arg_own_buf
);
1061 *new_packet_len_p
= write_qxfer_response (arg_own_buf
, data
, len
, 1);
1063 *new_packet_len_p
= write_qxfer_response (arg_own_buf
, data
, n
, 0);
1070 if (strncmp ("qXfer:siginfo:read:", arg_own_buf
, 19) == 0) {
1077 /* Reject any annex; grab the offset and length. */
1078 if (decode_xfer_read (arg_own_buf
+ 19, &annex
, &ofs
, &len
) < 0
1079 || annex
[0] != '\0') {
1080 strcpy (arg_own_buf
, "E00");
1084 if (len
> PBUFSIZ
- POVERHSIZ
)
1085 len
= PBUFSIZ
- POVERHSIZ
;
1087 gdbserver_pending_signal_to_report(&info
);
1089 if (ofs
>= sizeof(info
))
1092 n
= sizeof(info
) - ofs
;
1095 write_enn (arg_own_buf
);
1097 *new_packet_len_p
= write_qxfer_response (arg_own_buf
,
1098 (unsigned char *)&info
,
1101 *new_packet_len_p
= write_qxfer_response (arg_own_buf
,
1102 (unsigned char *)&info
,
1108 /* Protocol features query. */
1109 if (strncmp ("qSupported", arg_own_buf
, 10) == 0
1110 && (arg_own_buf
[10] == ':' || arg_own_buf
[10] == '\0')) {
1111 VG_(sprintf
) (arg_own_buf
, "PacketSize=%x", (UInt
)PBUFSIZ
- 1);
1112 /* Note: max packet size including frame and checksum, but without
1113 trailing null byte, which is not sent/received. */
1115 strcat (arg_own_buf
, ";QStartNoAckMode+");
1116 strcat (arg_own_buf
, ";QPassSignals+");
1117 strcat (arg_own_buf
, ";QCatchSyscalls+");
1118 if (VG_(client_auxv
))
1119 strcat (arg_own_buf
, ";qXfer:auxv:read+");
1121 if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers
)) != NULL
) {
1122 strcat (arg_own_buf
, ";qXfer:features:read+");
1123 /* if a new gdb connects to us, we have to reset the register
1124 set to the normal register sets to allow this new gdb to
1125 decide to use or not the shadow registers.
1127 Note that the reset is only done for gdb that are sending
1128 qSupported packets. If a user first connected with a recent
1129 gdb using shadow registers and then with a very old gdb
1130 that does not use qSupported packet, then the old gdb will
1131 not properly connect. */
1132 initialize_shadow_low(False
);
1134 strcat (arg_own_buf
, ";qXfer:exec-file:read+");
1135 strcat (arg_own_buf
, ";qXfer:siginfo:read+");
1139 /* Otherwise we didn't know what packet it was. Say we didn't
1144 /* Handle all of the extended 'v' packets. */
1146 void handle_v_requests (char *arg_own_buf
, char *status
, int *zignal
)
1148 /* vcont packet code from gdb 6.6 removed */
1150 /* Otherwise we didn't know what packet it was. Say we didn't
1157 void myresume (int step
, int sig
)
1159 struct thread_resume resume_info
[2];
1163 resume_info
[0].step
= step
;
1164 resume_info
[0].sig
= sig
;
1167 resume_info
[n
].step
= 0;
1168 resume_info
[n
].sig
= 0;
1170 resume_reply_packet_needed
= True
;
1171 valgrind_resume (resume_info
);
1174 /* server_main global variables */
1175 static char *own_buf
;
1176 static unsigned char *mem_buf
;
1178 void gdbserver_init (void)
1180 dlog(1, "gdbserver_init gdbserver embedded in valgrind: %s\n", version
);
1182 valgrind_initialize_target ();
1183 // After a fork, gdbserver_init can be called again.
1184 // We do not have to re-malloc the buffers in such a case.
1185 if (own_buf
== NULL
)
1186 own_buf
= malloc (PBUFSIZ
+POVERHSIZ
);
1187 if (mem_buf
== NULL
)
1188 mem_buf
= malloc (PBUFSIZ
+POVERHSIZ
);
1189 // Note: normally, we should only malloc PBUFSIZ. However,
1190 // GDB has a bug, and in some cases, sends e.g. 'm' packets
1191 // asking for slightly more than the PacketSize given at
1192 // connection initialisation. So, we bypass the GDB bug
1193 // by allocating slightly more.
1196 void gdbserver_terminate (void)
1198 /* last call to gdbserver is cleanup call */
1199 if (VG_MINIMAL_SETJMP(toplevel
)) {
1200 dlog(0, "error caused VG_MINIMAL_LONGJMP to gdbserver_terminate\n");
1206 void server_main (void)
1216 zignal
= valgrind_wait (&status
);
1217 if (VG_MINIMAL_SETJMP(toplevel
)) {
1218 dlog(0, "error caused VG_MINIMAL_LONGJMP to server_main\n");
1223 int new_packet_len
= -1;
1225 if (resume_reply_packet_needed
) {
1226 /* Send the resume reply to reply to last GDB resume
1228 resume_reply_packet_needed
= False
;
1229 prepare_resume_reply (own_buf
, status
, zignal
);
1233 /* If our status is terminal (exit or fatal signal) get out
1234 as quickly as we can. We won't be able to handle any request
1236 if (status
== 'W' || status
== 'X') {
1240 packet_len
= getpkt (own_buf
);
1241 if (packet_len
<= 0)
1248 handle_set (own_buf
, &new_packet_len
);
1251 handle_query (own_buf
, &new_packet_len
);
1254 /* set/unset debugging is done through valgrind debug level. */
1258 reset_valgrind_sink("gdb detaching from process");
1260 /* When detaching or kill the process, gdb expects to get
1261 an packet OK back. Any other output will make gdb
1262 believes detach did not work. */
1265 remote_finish (reset_after_error
);
1266 remote_open (VG_(clo_vgdb_prefix
));
1268 resume_reply_packet_needed
= False
;
1271 /* We can not use the extended protocol with valgrind,
1272 because we can not restart the running
1273 program. So return unrecognized. */
1277 prepare_resume_reply (own_buf
, status
, zignal
);
1280 if (own_buf
[1] == 'c' || own_buf
[1] == 'g' || own_buf
[1] == 's') {
1281 unsigned long gdb_id
, thread_id
;
1283 gdb_id
= strtoul (&own_buf
[2], NULL
, 16);
1284 thread_id
= gdb_id_to_thread_id (gdb_id
);
1285 if (thread_id
== 0) {
1286 write_enn (own_buf
);
1290 if (own_buf
[1] == 'g') {
1291 general_thread
= thread_id
;
1292 set_desired_inferior (1);
1293 } else if (own_buf
[1] == 'c') {
1294 cont_thread
= thread_id
;
1295 } else if (own_buf
[1] == 's') {
1296 step_thread
= thread_id
;
1301 /* Silently ignore it so that gdb can extend the protocol
1302 without compatibility headaches. */
1307 set_desired_inferior (1);
1308 registers_to_string (own_buf
);
1311 set_desired_inferior (1);
1312 registers_from_string (&own_buf
[1]);
1319 regno
= strtol(&own_buf
[1], NULL
, 16);
1320 regbytes
= strchr(&own_buf
[0], '=') + 1;
1321 set_desired_inferior (1);
1322 tst
= (ThreadState
*) inferior_target_data (current_inferior
);
1323 /* Only accept changing registers in "runnable state3.
1324 In fact, it would be ok to change most of the registers
1325 except a few "sensitive" registers such as the PC, SP, BP.
1326 We assume we do not need to very specific here, and that we
1327 can just refuse all of these. */
1328 if (tst
->status
== VgTs_Runnable
|| tst
->status
== VgTs_Yielding
) {
1329 supply_register_from_string (regno
, regbytes
);
1332 /* at least from gdb 6.6 onwards, an E. error
1333 reply is shown to the user. So, we do an error
1334 msg which both is accepted by gdb as an error msg
1335 and is readable by the user. */
1339 "ERROR changing register %s regno %d\n"
1340 "gdb commands changing registers (pc, sp, ...) (e.g. 'jump',\n"
1341 "set pc, calling from gdb a function in the debugged process, ...)\n"
1342 "can only be accepted if the thread is VgTs_Runnable or VgTs_Yielding state\n"
1343 "Thread status is %s\n",
1344 find_register_by_number (regno
)->name
, regno
,
1345 VG_(name_of_ThreadStatus
)(tst
->status
));
1346 if (VG_(clo_verbosity
) > 1)
1347 VG_(umsg
) ("%s\n", own_buf
);
1352 decode_m_packet (&own_buf
[1], &mem_addr
, &len
);
1353 if (valgrind_read_memory (mem_addr
, mem_buf
, len
) == 0)
1354 convert_int_to_ascii (mem_buf
, own_buf
, len
);
1356 write_enn (own_buf
);
1359 decode_M_packet (&own_buf
[1], &mem_addr
, &len
, mem_buf
);
1360 if (valgrind_write_memory (mem_addr
, mem_buf
, len
) == 0)
1363 write_enn (own_buf
);
1366 if (decode_X_packet (&own_buf
[1], packet_len
- 1,
1367 &mem_addr
, &len
, mem_buf
) < 0
1368 || valgrind_write_memory (mem_addr
, mem_buf
, len
) != 0)
1369 write_enn (own_buf
);
1374 convert_ascii_to_int (own_buf
+ 1, &sig
, 1);
1375 if (target_signal_to_host_p (sig
))
1376 zignal
= target_signal_to_host (sig
);
1379 set_desired_inferior (0);
1380 myresume (0, zignal
);
1381 return; // return control to valgrind
1383 convert_ascii_to_int (own_buf
+ 1, &sig
, 1);
1384 if (target_signal_to_host_p (sig
))
1385 zignal
= target_signal_to_host (sig
);
1388 set_desired_inferior (0);
1389 myresume (1, zignal
);
1390 return; // return control to valgrind
1392 set_desired_inferior (0);
1394 return; // return control to valgrind
1396 set_desired_inferior (0);
1398 return; // return control to valgrind
1402 CORE_ADDR addr
= strtoul (&own_buf
[3], &lenptr
, 16);
1403 int zlen
= strtol (lenptr
+ 1, &dataptr
, 16);
1404 char type
= own_buf
[1];
1406 if (type
< '0' || type
> '4') {
1407 /* Watchpoint command type unrecognized. */
1412 res
= valgrind_insert_watchpoint (type
, addr
, zlen
);
1419 write_enn (own_buf
);
1426 CORE_ADDR addr
= strtoul (&own_buf
[3], &lenptr
, 16);
1427 int zlen
= strtol (lenptr
+ 1, &dataptr
, 16);
1428 char type
= own_buf
[1];
1430 if (type
< '0' || type
> '4') {
1431 /* Watchpoint command type unrecognized. */
1436 res
= valgrind_remove_watchpoint (type
, addr
, zlen
);
1443 write_enn (own_buf
);
1448 kill_request("Gdb request to kill this process\n");
1451 unsigned long gdb_id
, thread_id
;
1453 gdb_id
= strtoul (&own_buf
[1], NULL
, 16);
1454 thread_id
= gdb_id_to_thread_id (gdb_id
);
1455 if (thread_id
== 0) {
1456 write_enn (own_buf
);
1460 if (valgrind_thread_alive (thread_id
))
1463 write_enn (own_buf
);
1467 /* Restarting the inferior is only supported in the
1469 => It is a request we don't understand. Respond with an
1470 empty packet so that gdb knows that we don't support this
1475 /* Extended (long) request. */
1476 handle_v_requests (own_buf
, &status
, &zignal
);
1479 /* It is a request we don't understand. Respond with an
1480 empty packet so that gdb knows that we don't support this
1486 if (new_packet_len
!= -1)
1487 putpkt_binary (own_buf
, new_packet_len
);
1492 VG_(umsg
) ("\nChild exited with status %d\n", zignal
);
1494 VG_(umsg
) ("\nChild terminated with signal = 0x%x (%s)\n",
1495 (UInt
)target_signal_to_host (zignal
),
1496 target_signal_to_name (zignal
));
1497 if (status
== 'W' || status
== 'X') {
1498 VG_(umsg
) ("Process exiting\n");
1503 /* We come here when getpkt fails => close the connection,
1504 and re-open. Then return control to valgrind.
1505 We return the control to valgrind as we assume that
1506 the connection was closed due to vgdb having finished
1507 to execute a command. */
1508 if (VG_(clo_verbosity
) > 1)
1509 VG_(umsg
) ("Remote side has terminated connection. "
1510 "GDBserver will reopen the connection.\n");
1511 remote_finish (reset_after_error
);
1512 remote_open (VG_(clo_vgdb_prefix
));
1514 resume_reply_packet_needed
= False
;