1 /* Remote utility routines for the remote server for GDB.
2 Copyright (C) 1986, 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2011
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. */
24 #include "pub_core_basics.h"
25 #include "pub_core_vki.h"
26 #include "pub_core_vkiscnums.h"
27 #include "pub_core_libcsignal.h"
28 #include "pub_core_options.h"
29 #include "pub_core_aspacemgr.h"
30 #include "pub_core_syswrap.h"
34 # if defined(VGO_linux)
35 #include <sys/prctl.h>
38 /* Calls sr_perror with msg.
39 Outputs more information about Valgrind state if verbosity > 0
40 or debuglog_getlevel > 0. */
42 void sr_extended_perror (SysRes sr
, const HChar
*msg
)
44 sr_perror (sr
, "%s", msg
);
45 if (VG_(clo_verbosity
) > 0 || VG_(debugLog_getLevel
)() >= 1) {
47 vki_sigset_t cursigset
;
48 VG_(show_sched_status
) (True
, // host_stacktrace
50 True
); // exited_threads
51 VG_(sigprocmask
) (0, // dummy how.
52 NULL
, // do not change the sigmask
54 VG_(dmsg
)("current sigmask value { ");
55 for (i
= 1; i
<= _VKI_NSIG
; i
++) {
56 if (VG_(sigismember
)(&cursigset
, i
))
63 /* Calls VG_(poll) with given arguments. If VG_(poll) fails due to EINTR,
65 Normally, VG_(poll) gdbsrv syscalls are not supposed to be interrupted :
66 either gdbsrv has been called by the scheduler (so all async signals
68 or gdbsrv has been forced invoked by vgdb+ptrace, and vgdb is queuing
71 However, on old kernels (such as on RHEL5.5 2.6.18), when vgdb+ptrace
72 intercepts and queues an async signal, the poll syscall is not properly
73 restarted. Instead, it returns EINTR even if no signal was effectively
74 received by the ptraced process.
75 See red-hat "Bug 679129 - Change in behaviour between RH5.5 and RH6
76 with ptrace and syscalls bugzilla"
77 e.g. "Why rhel5 differs? Because unlike in rhel6, sys_poll() returns
78 -EINTR if interrupted, that is all. This old implementation does
79 not support the restart-if-eintr-is-spurious."
81 So in case VG_(poll) fails with EINTR, we retry. */
82 static SysRes
VG_(poll_no_eintr
) (struct vki_pollfd
*fds
, Int nfds
, Int timeout
)
84 const HChar
* msg
= "VG_(poll) failed (old kernel ?) retrying ... \n";
87 sr
= VG_(poll
) (fds
, nfds
, timeout
);
88 if (!sr_isError(sr
) || sr_Err(sr
) != VKI_EINTR
)
90 sr_perror (sr
, "%s", msg
);
91 if (VG_(debugLog_getLevel
)() >= 1) {
92 sr_extended_perror (sr
, msg
);
100 static int readchar (int single
);
102 void remote_utils_output_status(void);
104 #define INVALID_DESCRIPTOR -1
105 static int remote_desc
= INVALID_DESCRIPTOR
;
107 static VgdbShared
*shared
;
108 static int last_looked_cntr
= -1;
109 static struct vki_pollfd remote_desc_pollfdread_activity
;
111 /* for a gdbserver embedded in valgrind, we read from a FIFO and write
112 to another FIFO So, we need two descriptors */
113 static int write_remote_desc
= INVALID_DESCRIPTOR
;
114 static int pid_from_to_creator
;
115 /* only this pid will remove the FIFOs: if an exec fails, we must avoid
116 that the exiting child believes it has to remove the FIFOs of its parent */
117 static int mknod_done
= 0;
119 static char *from_gdb
= NULL
;
120 static char *to_gdb
= NULL
;
121 static char *shared_mem
= NULL
;
124 int open_fifo (const char *side
, const char *path
, int flags
)
128 dlog(1, "Opening %s side %s\n", side
, path
);
129 o
= VG_(open
) (path
, flags
, 0);
130 if (sr_isError (o
)) {
131 sr_perror(o
, "open fifo %s\n", path
);
132 fatal ("valgrind: fatal error: vgdb FIFO cannot be opened.\n");
135 dlog(1, "result fd %d\n", fd
);
137 fd
= VG_(safe_fd
)(fd
);
138 dlog(1, "result safe_fd %d\n", fd
);
140 fatal("safe_fd for vgdb FIFO failed\n");
144 void remote_utils_output_status(void)
147 VG_(umsg
)("remote communication not initialized\n");
149 VG_(umsg
)("shared->written_by_vgdb %d shared->seen_by_valgrind %d\n",
150 shared
->written_by_vgdb
, shared
->seen_by_valgrind
);
153 /* Returns 0 if vgdb and connection state looks good,
154 otherwise returns an int value telling which check failed. */
156 int vgdb_state_looks_bad(const char* where
)
158 if (VG_(kill
)(shared
->vgdb_pid
, 0) != 0)
159 return 1; // vgdb process does not exist anymore.
161 if (remote_desc_activity(where
) == 2)
162 return 2; // check for error on remote desc shows a problem
164 if (remote_desc
== INVALID_DESCRIPTOR
)
165 return 3; // after check, remote_desc not ok anymore
167 return 0; // all is ok.
170 void VG_(set_ptracer
)(void)
172 #ifdef PR_SET_PTRACER
174 const char *ptrace_scope_setting_file
= "/proc/sys/kernel/yama/ptrace_scope";
179 o
= VG_(open
) (ptrace_scope_setting_file
, VKI_O_RDONLY
, 0);
181 if (VG_(debugLog_getLevel
)() >= 1) {
182 sr_perror(o
, "error VG_(open) %s\n", ptrace_scope_setting_file
);
184 /* can't read setting. Assuming ptrace can be called by vgdb. */
188 if (VG_(read
) (fd
, &ptrace_scope
, 1) == 1) {
189 dlog(1, "ptrace_scope %c\n", ptrace_scope
);
190 if (ptrace_scope
!= '0') {
191 /* insufficient default ptrace_scope.
192 Indicate to the kernel that we accept to be ptraced. */
193 #ifdef PR_SET_PTRACER_ANY
194 ret
= VG_(prctl
) (PR_SET_PTRACER
, PR_SET_PTRACER_ANY
, 0, 0, 0);
195 dlog(1, "set_ptracer to PR_SET_PTRACER_ANY result %d\n", ret
);
197 ret
= VG_(prctl
) (PR_SET_PTRACER
, 1, 0, 0, 0);
198 dlog(1, "set_ptracer to 1 result %d\n", ret
);
201 VG_(umsg
)("error calling PR_SET_PTRACER, vgdb might block\n");
204 dlog(0, "Could not read the ptrace_scope setting from %s\n",
205 ptrace_scope_setting_file
);
212 /* returns 1 if one or more poll "errors" is set.
213 Errors are: VKI_POLLERR or VKI_POLLHUP or VKI_POLLNAL */
215 int poll_cond (short revents
)
217 return (revents
& (VKI_POLLERR
| VKI_POLLHUP
| VKI_POLLNVAL
));
220 /* Ensures we have a valid write file descriptor.
221 Returns 1 if we have a valid write file descriptor,
222 0 if the write fd is not valid/cannot be opened. */
224 int ensure_write_remote_desc(void)
226 struct vki_pollfd write_remote_desc_ok
;
228 if (write_remote_desc
!= INVALID_DESCRIPTOR
) {
229 write_remote_desc_ok
.fd
= write_remote_desc
;
230 write_remote_desc_ok
.events
= VKI_POLLOUT
;
231 write_remote_desc_ok
.revents
= 0;
232 ret
= VG_(poll_no_eintr
)(&write_remote_desc_ok
, 1, 0);
234 || (sr_Res(ret
) > 0 && poll_cond(write_remote_desc_ok
.revents
))) {
235 if (sr_isError(ret
)) {
236 sr_extended_perror(ret
, "ensure_write_remote_desc: poll error\n");
238 dlog(0, "POLLcond %d closing write_remote_desc %d\n",
239 write_remote_desc_ok
.revents
, write_remote_desc
);
241 VG_(close
) (write_remote_desc
);
242 write_remote_desc
= INVALID_DESCRIPTOR
;
245 if (write_remote_desc
== INVALID_DESCRIPTOR
) {
246 /* open_fifo write will block if the receiving vgdb
247 process is dead. So, let's check for vgdb state to
248 be reasonably sure someone is reading on the other
250 if (!vgdb_state_looks_bad("bad?@ensure_write_remote_desc")) {
251 write_remote_desc
= open_fifo ("write", to_gdb
, VKI_O_WRONLY
);
255 return (write_remote_desc
!= INVALID_DESCRIPTOR
);
258 #if defined(VGO_darwin)
259 #define VKI_S_IFIFO 0010000
262 void safe_mknod (char *nod
)
265 m
= VG_(mknod
) (nod
, VKI_S_IFIFO
|0600, 0);
266 if (sr_isError (m
)) {
267 if (sr_Err (m
) == VKI_EEXIST
) {
268 if (VG_(clo_verbosity
) > 1) {
269 VG_(umsg
)("%s already created\n", nod
);
272 sr_perror(m
, "mknod %s\n", nod
);
273 VG_(umsg
) ("valgrind: fatal error: vgdb FIFOs cannot be created.\n");
279 /* If remote_desc is not opened, open it.
280 Setup remote_desc_pollfdread_activity. */
281 static void setup_remote_desc_for_reading (void)
283 int save_fcntl_flags
;
285 if (remote_desc
== INVALID_DESCRIPTOR
) {
286 /* we open the read side FIFO in non blocking mode
287 We then set the fd in blocking mode.
288 Opening in non-blocking read mode always succeeds while opening
289 in non-blocking write mode succeeds only if the fifo is already
290 opened in read mode. So, we wait till we have read the first
291 character from the read side before opening the write side. */
292 remote_desc
= open_fifo ("read", from_gdb
, VKI_O_RDONLY
|VKI_O_NONBLOCK
);
293 save_fcntl_flags
= VG_(fcntl
) (remote_desc
, VKI_F_GETFL
, 0);
294 VG_(fcntl
) (remote_desc
, VKI_F_SETFL
, save_fcntl_flags
& ~VKI_O_NONBLOCK
);
296 remote_desc_pollfdread_activity
.fd
= remote_desc
;
297 remote_desc_pollfdread_activity
.events
= VKI_POLLIN
;
298 remote_desc_pollfdread_activity
.revents
= 0;
301 /* Open a connection to a remote debugger.
302 NAME is the filename used for communication.
303 For Valgrind, name is the prefix for the two read and write FIFOs
304 The two FIFOs names will be build by appending
305 -from-vgdb-to-pid-by-user-on-host and -to-vgdb-from-pid-by-user-on-host
306 with pid being the pidnr of the valgrind process These two FIFOs
307 will be created if not existing yet. They will be removed when
308 the gdbserver connection is closed or the process exits */
310 void remote_open (const HChar
*name
)
312 const HChar
*user
, *host
;
315 const int pid
= VG_(getpid
)();
318 int shared_mem_fd
= INVALID_DESCRIPTOR
;
320 VG_(memset
) (&vgdbinit
, 0, sizeof (VgdbShared
));
321 vgdbinit
= (VgdbShared
)
322 {0, 0, (Addr
) VG_(invoke_gdbserver
),
323 (Addr
) VG_(threads
), VG_N_THREADS
, sizeof(ThreadState
),
324 offsetof(ThreadState
, status
),
325 offsetof(ThreadState
, os_state
) + offsetof(ThreadOSstate
, lwpid
),
327 #if VEX_HOST_WORDSIZE == 8
332 user
= VG_(getenv
)("LOGNAME");
333 if (user
== NULL
) user
= VG_(getenv
)("USER");
334 if (user
== NULL
) user
= "???";
335 if (VG_(strchr
)(user
, '/')) user
= "???";
337 host
= VG_(getenv
)("HOST");
338 if (host
== NULL
) host
= VG_(getenv
)("HOSTNAME");
339 if (host
== NULL
) host
= "???";
340 if (VG_(strchr
)(host
, '/')) host
= "???";
342 len
= strlen(name
) + strlen(user
) + strlen(host
) + 40;
344 if (from_gdb
!= NULL
)
346 from_gdb
= malloc (len
);
349 to_gdb
= malloc (len
);
350 if (shared_mem
!= NULL
)
352 shared_mem
= malloc (len
);
353 /* below 3 lines must match the equivalent in vgdb.c */
354 VG_(sprintf
) (from_gdb
, "%s-from-vgdb-to-%d-by-%s-on-%s", name
,
356 VG_(sprintf
) (to_gdb
, "%s-to-vgdb-from-%d-by-%s-on-%s", name
,
358 VG_(sprintf
) (shared_mem
, "%s-shared-mem-vgdb-%d-by-%s-on-%s", name
,
360 if (VG_(clo_verbosity
) > 1) {
361 VG_(umsg
)("embedded gdbserver: reading from %s\n", from_gdb
);
362 VG_(umsg
)("embedded gdbserver: writing to %s\n", to_gdb
);
363 VG_(umsg
)("embedded gdbserver: shared mem %s\n", shared_mem
);
365 VG_(umsg
)("TO CONTROL THIS PROCESS USING vgdb (which you probably\n"
366 "don't want to do, unless you know exactly what you're doing,\n"
367 "or are doing some strange experiment):\n"
368 " %s/../../bin/vgdb%s%s --pid=%d ...command...\n",
370 (VG_(arg_vgdb_prefix
) ? " " : ""),
371 (VG_(arg_vgdb_prefix
) ? VG_(arg_vgdb_prefix
) : ""),
374 if (VG_(clo_verbosity
) > 1
375 || ((VG_(clo_vgdb_error
) < 999999999
376 || VG_(clo_vgdb_stop_at
) != 0)
377 && !(VG_(clo_launched_with_multi
)))) {
380 "TO DEBUG THIS PROCESS USING GDB: start GDB like this\n"
382 "and then give GDB the following command\n"
383 " target remote | %s/../../bin/vgdb%s%s --pid=%d\n",
384 VG_(args_the_exename
),
386 (VG_(arg_vgdb_prefix
) ? " " : ""),
387 (VG_(arg_vgdb_prefix
) ? VG_(arg_vgdb_prefix
) : ""),
390 VG_(umsg
)("--pid is optional if only one valgrind process is running\n");
398 * Unlink just in case a previous process with the same PID had been
399 * killed and hence Valgrind hasn't had the chance yet to remove these.
401 VG_(unlink
)(from_gdb
);
403 VG_(unlink
)(shared_mem
);
405 o
= VG_(open
) (shared_mem
, VKI_O_CREAT
|VKI_O_RDWR
, 0600);
406 if (sr_isError (o
)) {
407 sr_perror(o
, "cannot create shared_mem file %s\n", shared_mem
);
408 fatal("Cannot recover from previous error. Good-bye.");
410 shared_mem_fd
= sr_Res(o
);
413 if (VG_(write
)(shared_mem_fd
, &vgdbinit
, sizeof(VgdbShared
))
414 != sizeof(VgdbShared
)) {
415 fatal("error writing %d bytes to shared mem %s\n",
416 (int) sizeof(VgdbShared
), shared_mem
);
419 SysRes res
= VG_(am_shared_mmap_file_float_valgrind
)
420 (sizeof(VgdbShared
), VKI_PROT_READ
|VKI_PROT_WRITE
,
421 shared_mem_fd
, (Off64T
)0);
422 if (sr_isError(res
)) {
423 sr_perror(res
, "error VG_(am_shared_mmap_file_float_valgrind) %s\n",
425 fatal("Cannot recover from previous error. Good-bye.");
427 addr_shared
= sr_Res (res
);
429 shared
= (VgdbShared
*) addr_shared
;
430 VG_(close
) (shared_mem_fd
);
433 safe_mknod(from_gdb
);
434 /* from_gdb is the last resource created: vgdb searches such FIFOs
435 to detect the presence of a valgrind process.
436 So, we better create this resource when all the rest needed by
437 vgdb is ready : the other FIFO and the shared memory. */
439 pid_from_to_creator
= pid
;
442 setup_remote_desc_for_reading ();
445 /* sync_gdb_connection wait a time long enough to let the connection
446 be properly closed if needed when closing the connection (in case
447 of detach or error), if we reopen it too quickly, it seems there
448 are some events queued in the kernel concerning the "old"
449 connection/remote_desc which are discovered with poll or select on
450 the "new" connection/remote_desc. We bypass this by waiting some
451 time to let a proper cleanup to be donex */
452 void sync_gdb_connection(void)
455 ret
= VG_(poll_no_eintr
)(0, 0, 100);
457 sr_extended_perror(ret
, "sync_gdb_connection: poll error\n");
461 const char * ppFinishReason (FinishReason reason
)
464 case orderly_finish
: return "orderly_finish";
465 case reset_after_error
: return "reset_after_error";
466 case reset_after_fork
: return "reset_after_fork";
467 default: vg_assert (0);
471 void remote_finish (FinishReason reason
)
473 dlog(1, "remote_finish (reason %s) %d %d\n",
474 ppFinishReason(reason
), remote_desc
, write_remote_desc
);
475 reset_valgrind_sink(ppFinishReason(reason
));
476 if (write_remote_desc
!= INVALID_DESCRIPTOR
)
477 VG_(close
) (write_remote_desc
);
478 write_remote_desc
= INVALID_DESCRIPTOR
;
480 if (remote_desc
!= INVALID_DESCRIPTOR
) {
481 /* Fully close the connection, either due to orderly_finish or
482 to reset_after_fork or reset_after_error. For
483 reset_after_error, the FIFO will be re-opened soon. This
484 leaves a small window during which a race condition can
485 happen between vgdb and a forking process: Just after fork,
486 both the parent and the child have the FIFO open. The child
487 will close it asap (as part of the 'after fork cleanup'). If
488 2 vgdbs are launched very quickly just after the fork, the
489 parent will close its FIFO when the 1st vgdb exits. Then if
490 the 2nd vgdb is started before the parent has the time to
491 re-open the FIFO, the 2nd vgdb will be able to open the FIFO
492 (as it is still opened by the child). The 2nd vgdb can then
493 have a 'write' error when the child closes the FIFO. After
494 the 1st vgdb closes its FIFO write side, the parent gets EOF
495 on its reading FIFO till it is closed and re-opened. Opening
496 a 2nd time the FIFO before closing the 'previous fd' solves
497 this race condition, but causes other (not understood)
498 problems due to too early re-invocation of gdbsrv. Rather
499 than to handle this race condition in gdbsrv side, we put a
500 'retry' loop in vgdb for the initial write on the write
502 remote_desc_pollfdread_activity
.fd
= INVALID_DESCRIPTOR
;
503 remote_desc_pollfdread_activity
.events
= 0;
504 remote_desc_pollfdread_activity
.revents
= 0;
505 VG_(close
) (remote_desc
);
506 remote_desc
= INVALID_DESCRIPTOR
;
510 /* ensure the child will create its own FIFOs */
511 if (reason
== reset_after_fork
)
514 if (reason
== reset_after_error
)
515 sync_gdb_connection();
518 /* orderly close, cleans up everything */
519 void remote_close (void)
521 const int pid
= VG_(getpid
)();
522 remote_finish(orderly_finish
);
523 dlog(1, "%d (creator %d) maybe unlinking \n %s\n %s\n %s\n",
524 pid
, pid_from_to_creator
,
525 from_gdb
? from_gdb
: "NULL",
526 to_gdb
? to_gdb
: "NULL",
527 shared_mem
? shared_mem
: "NULL");
529 // PJF this is not ideal
530 // if the guest enters capability mode then the unlink calls will fail
531 // this may well also apply to Linux and seccomp
532 // I don't have any thoughts on how to fix it, other than forking early on
533 // having the child run the guest and the parent wait()ing and then
534 // the parent doing the cleanup
536 Bool unlinkPossible
= True
;
537 #if defined(VGO_freebsd)
538 unlinkPossible
= (VG_(get_capability_mode
)() == False
);
541 if (unlinkPossible
== True
) {
542 if (pid
== pid_from_to_creator
&& from_gdb
&& VG_(unlink
) (from_gdb
) == -1)
543 warning ("could not unlink %s\n", from_gdb
);
544 if (pid
== pid_from_to_creator
&& to_gdb
&& VG_(unlink
) (to_gdb
) == -1)
545 warning ("could not unlink %s\n", to_gdb
);
546 if (pid
== pid_from_to_creator
&& shared_mem
&& VG_(unlink
) (shared_mem
) == -1)
547 warning ("could not unlink %s\n", shared_mem
);
549 VG_(debugLog
)(1, "remote close",
550 "cannot unlink gdb pipes\n");
560 Bool
remote_connected(void)
562 return write_remote_desc
!= INVALID_DESCRIPTOR
;
565 /* cleanup after an error detected by poll_cond */
567 void error_poll_cond(void)
569 /* if we will close the connection, we assume either that
570 all characters have been seen or that they will be dropped. */
571 shared
->seen_by_valgrind
= shared
->written_by_vgdb
;
572 remote_finish(reset_after_error
);
575 /* remote_desc_activity might be used at high frequency if the user
576 gives a small value to --vgdb-poll. So, the function avoids
577 doing repetitively system calls by rather looking at the
578 counter values maintained in shared memory by vgdb. */
579 int remote_desc_activity(const char *msg
)
583 const int looking_at
= shared
->written_by_vgdb
;
584 if (shared
->seen_by_valgrind
== looking_at
)
586 if (remote_desc
== INVALID_DESCRIPTOR
)
589 /* poll the remote desc */
590 remote_desc_pollfdread_activity
.revents
= 0;
591 ret
= VG_(poll_no_eintr
) (&remote_desc_pollfdread_activity
, 1, 0);
593 || (sr_Res(ret
) && poll_cond(remote_desc_pollfdread_activity
.revents
))) {
594 if (sr_isError(ret
)) {
595 sr_extended_perror(ret
, "remote_desc_activity: poll error\n");
597 dlog(0, "POLLcond %d remote_desc_pollfdread %d\n",
598 remote_desc_pollfdread_activity
.revents
, remote_desc
);
603 retval
= sr_Res(ret
);
606 "remote_desc_activity %s %d last_looked_cntr %d looking_at %d"
607 " shared->written_by_vgdb %d shared->seen_by_valgrind %d"
609 msg
, remote_desc
, last_looked_cntr
, looking_at
,
610 shared
->written_by_vgdb
, shared
->seen_by_valgrind
,
612 /* if no error from poll, indicate we have "seen" up to looking_at */
614 last_looked_cntr
= looking_at
;
618 /* Convert hex digit A to a number. */
623 if (a
>= '0' && a
<= '9')
625 else if (a
>= 'a' && a
<= 'f')
628 error ("Reply contains invalid hex digit 0x%x\n", (unsigned)a
);
632 int unhexify (char *bin
, const char *hex
, int count
)
636 for (i
= 0; i
< count
; i
++) {
637 if (hex
[0] == 0 || hex
[1] == 0) {
638 /* Hex string is short, or of uneven length.
639 Return the count that has been converted so far. */
642 *bin
++ = fromhex (hex
[0]) * 16 + fromhex (hex
[1]);
648 void decode_address (CORE_ADDR
*addrp
, const char *start
, int len
)
655 for (i
= 0; i
< len
; i
++) {
658 addr
= addr
| (fromhex (ch
) & 0x0f);
663 /* builds an image of bin according to byte order of the architecture
664 Useful for register and int image */
665 char* heximage (char *buf
, const char *bin
, int count
)
667 #if (VKI_LITTLE_ENDIAN)
669 /* note: no need for trailing \0, length is known with count */
671 for (i
= 0; i
< count
; i
++)
672 rev
[i
] = bin
[count
- i
- 1];
673 hexify (buf
, rev
, count
);
675 hexify (buf
, bin
, count
);
680 void* C2v(CORE_ADDR addr
)
686 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
687 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
688 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
689 (which may be more than *OUT_LEN due to escape characters). The
690 total number of bytes in the output buffer will be at most
694 remote_escape_output (const gdb_byte
*buffer
, int len
,
695 gdb_byte
*out_buf
, int *out_len
,
698 int input_index
, output_index
;
701 for (input_index
= 0; input_index
< len
; input_index
++) {
702 gdb_byte b
= buffer
[input_index
];
704 if (b
== '$' || b
== '#' || b
== '}' || b
== '*') {
705 /* These must be escaped. */
706 if (output_index
+ 2 > out_maxlen
)
708 out_buf
[output_index
++] = '}';
709 out_buf
[output_index
++] = b
^ 0x20;
711 if (output_index
+ 1 > out_maxlen
)
713 out_buf
[output_index
++] = b
;
717 *out_len
= input_index
;
721 /* Convert BUFFER, escaped data LEN bytes long, into binary data
722 in OUT_BUF. Return the number of bytes written to OUT_BUF.
723 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
725 This function reverses remote_escape_output. It allows more
726 escaped characters than that function does, in particular because
727 '*' must be escaped to avoid the run-length encoding processing
728 in reading packets. */
731 int remote_unescape_input (const gdb_byte
*buffer
, int len
,
732 gdb_byte
*out_buf
, int out_maxlen
)
734 int input_index
, output_index
;
739 for (input_index
= 0; input_index
< len
; input_index
++) {
740 gdb_byte b
= buffer
[input_index
];
742 if (output_index
+ 1 > out_maxlen
)
743 error ("Received too much data (len %d) from the target.\n", len
);
746 out_buf
[output_index
++] = b
^ 0x20;
748 } else if (b
== '}') {
751 out_buf
[output_index
++] = b
;
756 error ("Unmatched escape character in target response.\n");
761 /* Look for a sequence of characters which can be run-length encoded.
762 If there are any, update *CSUM and *P. Otherwise, output the
763 single character. Return the number of characters consumed. */
766 int try_rle (char *buf
, int remaining
, unsigned char *csum
, char **p
)
770 /* Always output the character. */
774 /* Don't go past '~'. */
778 for (n
= 1; n
< remaining
; n
++)
779 if (buf
[n
] != buf
[0])
782 /* N is the index of the first character not the same as buf[0].
783 buf[0] is counted twice, so by decrementing N, we get the number
784 of characters the RLE sequence will replace. */
790 /* Skip the frame characters. The manual says to skip '+' and '-'
791 also, but there's no reason to. Unfortunately these two unusable
792 characters double the encoded length of a four byte zero
794 while (n
+ 29 == '$' || n
+ 29 == '#')
805 /* Send a packet to the remote machine, with error checking.
806 The data of the packet is in BUF, and the length of the
807 packet is in CNT. Returns >= 0 on success, -1 otherwise. */
809 int putpkt_binary (char *buf
, int cnt
)
812 unsigned char csum
= 0;
817 buf2
= malloc (PBUFSIZ
+POVERHSIZ
);
818 // should malloc PBUFSIZ, but bypass GDB bug (see gdbserver_init in server.c)
819 vg_assert (5 == POVERHSIZ
);
820 vg_assert (cnt
<= PBUFSIZ
); // be tolerant for GDB bug.
822 /* Copy the packet into buffer BUF2, encapsulating it
823 and giving it a checksum. */
828 for (i
= 0; i
< cnt
;)
829 i
+= try_rle (buf
+ i
, cnt
- i
, &csum
, &p
);
832 *p
++ = tohex ((csum
>> 4) & 0xf);
833 *p
++ = tohex (csum
& 0xf);
837 /* we might have to write a pkt when out FIFO not yet/anymore opened */
838 if (!ensure_write_remote_desc()) {
839 warning ("putpkt(write) error: no write_remote_desc\n");
844 /* Send it once (noack_mode)
845 or send it over and over until we get a positive ack. */
848 if (VG_(write
) (write_remote_desc
, buf2
, p
- buf2
) != p
- buf2
) {
849 warning ("putpkt(write) error\n");
854 if (VG_(debugLog_getLevel
)() >= 3) {
855 char *tracebuf
= malloc(4 * (p
- buf2
) + 1); // worst case
858 for (UInt npr
= 0; npr
< p
- buf2
; npr
++) {
859 UChar uc
= (unsigned char)buf2
[npr
];
860 if (uc
> 31 && uc
< 127) {
864 VG_(sprintf
)(tr
, "%03o", uc
);
869 dlog(3, "putpkt (\"%s\"); (%slen %d) %s\n", tracebuf
,
870 strlen(tracebuf
) == p
- buf2
? "binary " : "",
872 noack_mode
? "[no ack]" : "[looking for ack]");
881 dlog(3, "[received '%c' (0x%x)]\n", cc
, (unsigned)cc
);
885 dlog(1, "putpkt(read): Got EOF\n");
887 warning ("putpkt(read) error\n");
893 /* Check for an input interrupt while we're here. */
895 dlog(1, "Received 0x03 character (SIGINT)\n");
900 return 1; /* Success! */
903 /* Send a packet to the remote machine, with error checking. The data
904 of the packet is in BUF, and the packet should be a NUL-terminated
905 string. Returns >= 0 on success, -1 otherwise. */
907 int putpkt (char *buf
)
909 return putpkt_binary (buf
, strlen (buf
));
912 void monitor_output (char *s
)
914 if (remote_connected()) {
915 const int len
= strlen(s
);
916 char *buf
= malloc(1 + 2*len
+ 1);
919 hexify(buf
+1, s
, len
);
920 if (putpkt (buf
) < 0) {
921 /* We probably have lost the connection with vgdb. */
922 reset_valgrind_sink("Error writing monitor output");
923 /* write again after reset */
924 VG_(printf
) ("%s", s
);
929 print_to_initial_valgrind_sink (s
);
933 /* Returns next char from remote GDB. -1 if error. */
934 /* if single, only one character maximum can be read with
935 read system call. Otherwise, when reading an ack character
936 we might pile up the next gdb command in the static buf.
937 The read loop is then blocked in poll till gdb times out. */
939 int readchar (int single
)
941 static unsigned char buf
[PBUFSIZ
];
942 static int bufcnt
= 0;
943 static unsigned char *bufp
;
949 if (remote_desc
== INVALID_DESCRIPTOR
)
952 /* No characters available in buf =>
953 wait for some characters to arrive */
954 remote_desc_pollfdread_activity
.revents
= 0;
955 ret
= VG_(poll_no_eintr
)(&remote_desc_pollfdread_activity
, 1, -1);
956 if (sr_isError(ret
) || sr_Res(ret
) != 1) {
957 if (sr_isError(ret
)) {
958 sr_extended_perror(ret
, "readchar: poll error\n");
960 dlog(0, "readchar: poll got %d, expecting 1\n", (int)sr_Res(ret
));
965 bufcnt
= VG_(read
) (remote_desc
, buf
, 1);
967 bufcnt
= VG_(read
) (remote_desc
, buf
, sizeof (buf
));
971 dlog (1, "readchar: Got EOF\n");
973 warning ("readchar read error\n");
978 shared
->seen_by_valgrind
+= bufcnt
;
980 /* If we have received a character and we do not yet have a
981 connection, we better open our "write" fifo to let vgdb open its
983 if (write_remote_desc
== INVALID_DESCRIPTOR
984 && !ensure_write_remote_desc()) {
985 dlog(1, "reachar: write_remote_desc could not be created");
991 if (poll_cond(remote_desc_pollfdread_activity
.revents
)) {
992 dlog(1, "readchar: POLLcond got %d\n",
993 remote_desc_pollfdread_activity
.revents
);
1001 /* Read a packet from the remote machine, with error checking,
1002 and store it in BUF. Returns length of packet, or negative if error. */
1004 int getpkt (char *buf
)
1007 unsigned char csum
, c1
, c2
;
1017 dlog(3, "[getpkt: discarding char '%c']\n", c
);
1034 c1
= fromhex (readchar (0));
1035 c2
= fromhex (readchar (0));
1037 if (csum
== (c1
<< 4) + c2
)
1040 dlog (0, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1041 (unsigned)(c1
<< 4) + c2
, (unsigned)csum
, buf
);
1042 if (!ensure_write_remote_desc()) {
1043 dlog(1, "getpkt(write nack) no write_remote_desc");
1045 VG_(write
) (write_remote_desc
, "-", 1);
1049 dlog(3, "getpkt (\"%s\"); [no ack] \n", buf
);
1051 dlog(3, "getpkt (\"%s\"); [sending ack] \n", buf
);
1054 if (!ensure_write_remote_desc()) {
1055 dlog(1, "getpkt(write ack) no write_remote_desc");
1057 VG_(write
) (write_remote_desc
, "+", 1);
1058 dlog(3, "[sent ack]\n");
1064 void write_ok (char *buf
)
1071 void write_enn (char *buf
)
1073 /* Some day, we should define the meanings of the error codes... */
1080 void convert_int_to_ascii (const unsigned char *from
, char *to
, int n
)
1086 nib
= ((ch
& 0xf0) >> 4) & 0x0f;
1087 *to
++ = tohex (nib
);
1089 *to
++ = tohex (nib
);
1095 void convert_ascii_to_int (const char *from
, unsigned char *to
, int n
)
1099 nib1
= fromhex (*from
++);
1100 nib2
= fromhex (*from
++);
1101 *to
++ = (((nib1
& 0x0f) << 4) & 0xf0) | (nib2
& 0x0f);
1106 char * outreg (int regno
, char *buf
)
1108 if ((regno
>> 12) != 0)
1109 *buf
++ = tohex ((regno
>> 12) & 0xf);
1110 if ((regno
>> 8) != 0)
1111 *buf
++ = tohex ((regno
>> 8) & 0xf);
1112 *buf
++ = tohex ((regno
>> 4) & 0xf);
1113 *buf
++ = tohex (regno
& 0xf);
1115 collect_register_as_string (regno
, buf
);
1116 buf
+= 2 * register_size (regno
);
1122 void prepare_resume_reply (char *buf
, char status
, unsigned char sig
)
1128 nib
= ((sig
& 0xf0) >> 4);
1129 *buf
++ = tohex (nib
);
1131 *buf
++ = tohex (nib
);
1133 if (status
== 'T') {
1134 const char **regp
= gdbserver_expedite_regs
;
1136 if (valgrind_stopped_by_watchpoint()) {
1140 strncpy (buf
, "watch:", 6);
1143 addr
= valgrind_stopped_data_address ();
1145 /* Convert each byte of the address into two hexadecimal chars.
1146 Note that we take sizeof (void *) instead of sizeof (addr);
1147 this is to avoid sending a 64-bit address to a 32-bit GDB. */
1148 for (i
= sizeof (void *) * 2; i
> 0; i
--) {
1149 *buf
++ = tohex ((addr
>> (i
- 1) * 4) & 0xf);
1154 if (valgrind_stopped_by_syscall () >= 0) {
1155 VG_(sprintf
) (buf
, "%s:%x;",
1156 valgrind_stopped_before_syscall ()
1157 ? "syscall_entry" : "syscall_return",
1158 (UInt
)valgrind_stopped_by_syscall ());
1159 buf
+= strlen (buf
);
1163 buf
= outreg (find_regno (*regp
), buf
);
1168 unsigned int gdb_id_from_wait
;
1170 /* FIXME right place to set this? */
1172 ((struct inferior_list_entry
*)current_inferior
)->id
;
1173 gdb_id_from_wait
= thread_to_gdb_id (current_inferior
);
1175 dlog(1, "Writing resume reply for %lu\n", thread_from_wait
);
1176 /* This if (1) ought to be unnecessary. But remote_wait in GDB
1177 will claim this event belongs to inferior_ptid if we do not
1178 specify a thread, and there's no way for gdbserver to know
1179 what inferior_ptid is. */
1180 if (1 || old_thread_from_wait
!= thread_from_wait
) {
1181 general_thread
= thread_from_wait
;
1182 VG_(sprintf
) (buf
, "thread:%x;", gdb_id_from_wait
);
1183 buf
+= strlen (buf
);
1184 old_thread_from_wait
= thread_from_wait
;
1188 /* For W and X, we're done. */
1192 void decode_m_packet (char *from
, CORE_ADDR
*mem_addr_ptr
, unsigned int *len_ptr
)
1196 *mem_addr_ptr
= *len_ptr
= 0;
1198 while ((ch
= from
[i
++]) != ',') {
1199 *mem_addr_ptr
= *mem_addr_ptr
<< 4;
1200 *mem_addr_ptr
|= fromhex (ch
) & 0x0f;
1203 for (j
= 0; j
< 4; j
++) {
1204 if ((ch
= from
[i
++]) == 0)
1206 *len_ptr
= *len_ptr
<< 4;
1207 *len_ptr
|= fromhex (ch
) & 0x0f;
1211 void decode_M_packet (char *from
, CORE_ADDR
*mem_addr_ptr
, unsigned int *len_ptr
,
1216 *mem_addr_ptr
= *len_ptr
= 0;
1218 while ((ch
= from
[i
++]) != ',') {
1219 *mem_addr_ptr
= *mem_addr_ptr
<< 4;
1220 *mem_addr_ptr
|= fromhex (ch
) & 0x0f;
1223 while ((ch
= from
[i
++]) != ':') {
1224 *len_ptr
= *len_ptr
<< 4;
1225 *len_ptr
|= fromhex (ch
) & 0x0f;
1228 convert_ascii_to_int (&from
[i
++], to
, *len_ptr
);
1231 int decode_X_packet (char *from
, int packet_len
, CORE_ADDR
*mem_addr_ptr
,
1232 unsigned int *len_ptr
, unsigned char *to
)
1236 *mem_addr_ptr
= *len_ptr
= 0;
1238 while ((ch
= from
[i
++]) != ',') {
1239 *mem_addr_ptr
= *mem_addr_ptr
<< 4;
1240 *mem_addr_ptr
|= fromhex (ch
) & 0x0f;
1243 while ((ch
= from
[i
++]) != ':') {
1244 *len_ptr
= *len_ptr
<< 4;
1245 *len_ptr
|= fromhex (ch
) & 0x0f;
1248 if (remote_unescape_input ((const gdb_byte
*) &from
[i
], packet_len
- i
,
1249 to
, *len_ptr
) != *len_ptr
)
1256 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
1257 to communicate with valgrind */
1259 VG_(vgdb_prefix_default
)(void)
1261 static HChar
*prefix
;
1263 if (prefix
== NULL
) {
1264 const HChar
*tmpdir
= VG_(tmpdir
)();
1265 prefix
= malloc(strlen(tmpdir
) + strlen("/vgdb-pipe") + 1);
1266 strcpy(prefix
, tmpdir
);
1267 strcat(prefix
, "/vgdb-pipe");