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"
33 # if defined(VGO_linux)
34 #include <sys/prctl.h>
37 /* Calls sr_perror with msg.
38 Outputs more information about Valgrind state if verbosity > 0
39 or debuglog_getlevel > 0. */
41 void sr_extended_perror (SysRes sr
, const HChar
*msg
)
43 sr_perror (sr
, "%s", msg
);
44 if (VG_(clo_verbosity
) > 0 || VG_(debugLog_getLevel
)() >= 1) {
46 vki_sigset_t cursigset
;
47 VG_(show_sched_status
) (True
, // host_stacktrace
49 True
); // exited_threads
50 VG_(sigprocmask
) (0, // dummy how.
51 NULL
, // do not change the sigmask
53 VG_(dmsg
)("current sigmask value { ");
54 for (i
= 1; i
<= _VKI_NSIG
; i
++) {
55 if (VG_(sigismember
)(&cursigset
, i
))
62 /* Calls VG_(poll) with given arguments. If VG_(poll) fails due to EINTR,
64 Normally, VG_(poll) gdbsrv syscalls are not supposed to be interrupted :
65 either gdbsrv has been called by the scheduler (so all async signals
67 or gdbsrv has been forced invoked by vgdb+ptrace, and vgdb is queuing
70 However, on old kernels (such as on RHEL5.5 2.6.18), when vgdb+ptrace
71 intercepts and queues an async signal, the poll syscall is not properly
72 restarted. Instead, it returns EINTR even if no signal was effectively
73 received by the ptraced process.
74 See red-hat "Bug 679129 - Change in behaviour between RH5.5 and RH6
75 with ptrace and syscalls bugzilla"
76 e.g. "Why rhel5 differs? Because unlike in rhel6, sys_poll() returns
77 -EINTR if interrupted, that is all. This old implementation does
78 not support the restart-if-eintr-is-spurious."
80 So in case VG_(poll) fails with EINTR, we retry. */
81 static SysRes
VG_(poll_no_eintr
) (struct vki_pollfd
*fds
, Int nfds
, Int timeout
)
83 const HChar
* msg
= "VG_(poll) failed (old kernel ?) retrying ... \n";
86 sr
= VG_(poll
) (fds
, nfds
, timeout
);
87 if (!sr_isError(sr
) || sr_Err(sr
) != VKI_EINTR
)
89 sr_perror (sr
, "%s", msg
);
90 if (VG_(debugLog_getLevel
)() >= 1) {
91 sr_extended_perror (sr
, msg
);
99 static int readchar (int single
);
101 void remote_utils_output_status(void);
103 #define INVALID_DESCRIPTOR -1
104 static int remote_desc
= INVALID_DESCRIPTOR
;
106 static VgdbShared
*shared
;
107 static int last_looked_cntr
= -1;
108 static struct vki_pollfd remote_desc_pollfdread_activity
;
110 /* for a gdbserver embedded in valgrind, we read from a FIFO and write
111 to another FIFO So, we need two descriptors */
112 static int write_remote_desc
= INVALID_DESCRIPTOR
;
113 static int pid_from_to_creator
;
114 /* only this pid will remove the FIFOs: if an exec fails, we must avoid
115 that the exiting child believes it has to remove the FIFOs of its parent */
116 static int mknod_done
= 0;
118 static char *from_gdb
= NULL
;
119 static char *to_gdb
= NULL
;
120 static char *shared_mem
= NULL
;
123 int open_fifo (const char *side
, const char *path
, int flags
)
127 dlog(1, "Opening %s side %s\n", side
, path
);
128 o
= VG_(open
) (path
, flags
, 0);
129 if (sr_isError (o
)) {
130 sr_perror(o
, "open fifo %s\n", path
);
131 fatal ("valgrind: fatal error: vgdb FIFO cannot be opened.\n");
134 dlog(1, "result fd %d\n", fd
);
136 fd
= VG_(safe_fd
)(fd
);
137 dlog(1, "result safe_fd %d\n", fd
);
139 fatal("safe_fd for vgdb FIFO failed\n");
143 void remote_utils_output_status(void)
146 VG_(umsg
)("remote communication not initialized\n");
148 VG_(umsg
)("shared->written_by_vgdb %d shared->seen_by_valgrind %d\n",
149 shared
->written_by_vgdb
, shared
->seen_by_valgrind
);
152 /* Returns 0 if vgdb and connection state looks good,
153 otherwise returns an int value telling which check failed. */
155 int vgdb_state_looks_bad(const char* where
)
157 if (VG_(kill
)(shared
->vgdb_pid
, 0) != 0)
158 return 1; // vgdb process does not exist anymore.
160 if (remote_desc_activity(where
) == 2)
161 return 2; // check for error on remote desc shows a problem
163 if (remote_desc
== INVALID_DESCRIPTOR
)
164 return 3; // after check, remote_desc not ok anymore
166 return 0; // all is ok.
169 void VG_(set_ptracer
)(void)
171 #ifdef PR_SET_PTRACER
173 const char *ptrace_scope_setting_file
= "/proc/sys/kernel/yama/ptrace_scope";
178 o
= VG_(open
) (ptrace_scope_setting_file
, VKI_O_RDONLY
, 0);
180 if (VG_(debugLog_getLevel
)() >= 1) {
181 sr_perror(o
, "error VG_(open) %s\n", ptrace_scope_setting_file
);
183 /* can't read setting. Assuming ptrace can be called by vgdb. */
187 if (VG_(read
) (fd
, &ptrace_scope
, 1) == 1) {
188 dlog(1, "ptrace_scope %c\n", ptrace_scope
);
189 if (ptrace_scope
!= '0') {
190 /* insufficient default ptrace_scope.
191 Indicate to the kernel that we accept to be ptraced. */
192 #ifdef PR_SET_PTRACER_ANY
193 ret
= VG_(prctl
) (PR_SET_PTRACER
, PR_SET_PTRACER_ANY
, 0, 0, 0);
194 dlog(1, "set_ptracer to PR_SET_PTRACER_ANY result %d\n", ret
);
196 ret
= VG_(prctl
) (PR_SET_PTRACER
, 1, 0, 0, 0);
197 dlog(1, "set_ptracer to 1 result %d\n", ret
);
200 VG_(umsg
)("error calling PR_SET_PTRACER, vgdb might block\n");
203 dlog(0, "Could not read the ptrace_scope setting from %s\n",
204 ptrace_scope_setting_file
);
211 /* returns 1 if one or more poll "errors" is set.
212 Errors are: VKI_POLLERR or VKI_POLLHUP or VKI_POLLNAL */
214 int poll_cond (short revents
)
216 return (revents
& (VKI_POLLERR
| VKI_POLLHUP
| VKI_POLLNVAL
));
219 /* Ensures we have a valid write file descriptor.
220 Returns 1 if we have a valid write file descriptor,
221 0 if the write fd is not valid/cannot be opened. */
223 int ensure_write_remote_desc(void)
225 struct vki_pollfd write_remote_desc_ok
;
227 if (write_remote_desc
!= INVALID_DESCRIPTOR
) {
228 write_remote_desc_ok
.fd
= write_remote_desc
;
229 write_remote_desc_ok
.events
= VKI_POLLOUT
;
230 write_remote_desc_ok
.revents
= 0;
231 ret
= VG_(poll_no_eintr
)(&write_remote_desc_ok
, 1, 0);
233 || (sr_Res(ret
) > 0 && poll_cond(write_remote_desc_ok
.revents
))) {
234 if (sr_isError(ret
)) {
235 sr_extended_perror(ret
, "ensure_write_remote_desc: poll error\n");
237 dlog(0, "POLLcond %d closing write_remote_desc %d\n",
238 write_remote_desc_ok
.revents
, write_remote_desc
);
240 VG_(close
) (write_remote_desc
);
241 write_remote_desc
= INVALID_DESCRIPTOR
;
244 if (write_remote_desc
== INVALID_DESCRIPTOR
) {
245 /* open_fifo write will block if the receiving vgdb
246 process is dead. So, let's check for vgdb state to
247 be reasonably sure someone is reading on the other
249 if (!vgdb_state_looks_bad("bad?@ensure_write_remote_desc")) {
250 write_remote_desc
= open_fifo ("write", to_gdb
, VKI_O_WRONLY
);
254 return (write_remote_desc
!= INVALID_DESCRIPTOR
);
257 #if defined(VGO_darwin)
258 #define VKI_S_IFIFO 0010000
261 void safe_mknod (char *nod
)
264 m
= VG_(mknod
) (nod
, VKI_S_IFIFO
|0600, 0);
265 if (sr_isError (m
)) {
266 if (sr_Err (m
) == VKI_EEXIST
) {
267 if (VG_(clo_verbosity
) > 1) {
268 VG_(umsg
)("%s already created\n", nod
);
271 sr_perror(m
, "mknod %s\n", nod
);
272 VG_(umsg
) ("valgrind: fatal error: vgdb FIFOs cannot be created.\n");
278 /* If remote_desc is not opened, open it.
279 Setup remote_desc_pollfdread_activity. */
280 static void setup_remote_desc_for_reading (void)
282 int save_fcntl_flags
;
284 if (remote_desc
== INVALID_DESCRIPTOR
) {
285 /* we open the read side FIFO in non blocking mode
286 We then set the fd in blocking mode.
287 Opening in non-blocking read mode always succeeds while opening
288 in non-blocking write mode succeeds only if the fifo is already
289 opened in read mode. So, we wait till we have read the first
290 character from the read side before opening the write side. */
291 remote_desc
= open_fifo ("read", from_gdb
, VKI_O_RDONLY
|VKI_O_NONBLOCK
);
292 save_fcntl_flags
= VG_(fcntl
) (remote_desc
, VKI_F_GETFL
, 0);
293 VG_(fcntl
) (remote_desc
, VKI_F_SETFL
, save_fcntl_flags
& ~VKI_O_NONBLOCK
);
295 remote_desc_pollfdread_activity
.fd
= remote_desc
;
296 remote_desc_pollfdread_activity
.events
= VKI_POLLIN
;
297 remote_desc_pollfdread_activity
.revents
= 0;
300 /* Open a connection to a remote debugger.
301 NAME is the filename used for communication.
302 For Valgrind, name is the prefix for the two read and write FIFOs
303 The two FIFOs names will be build by appending
304 -from-vgdb-to-pid-by-user-on-host and -to-vgdb-from-pid-by-user-on-host
305 with pid being the pidnr of the valgrind process These two FIFOs
306 will be created if not existing yet. They will be removed when
307 the gdbserver connection is closed or the process exits */
309 void remote_open (const HChar
*name
)
311 const HChar
*user
, *host
;
314 const int pid
= VG_(getpid
)();
317 int shared_mem_fd
= INVALID_DESCRIPTOR
;
319 VG_(memset
) (&vgdbinit
, 0, sizeof (VgdbShared
));
320 vgdbinit
= (VgdbShared
)
321 {0, 0, (Addr
) VG_(invoke_gdbserver
),
322 (Addr
) VG_(threads
), VG_N_THREADS
, sizeof(ThreadState
),
323 offsetof(ThreadState
, status
),
324 offsetof(ThreadState
, os_state
) + offsetof(ThreadOSstate
, lwpid
),
327 user
= VG_(getenv
)("LOGNAME");
328 if (user
== NULL
) user
= VG_(getenv
)("USER");
329 if (user
== NULL
) user
= "???";
330 if (VG_(strchr
)(user
, '/')) user
= "???";
332 host
= VG_(getenv
)("HOST");
333 if (host
== NULL
) host
= VG_(getenv
)("HOSTNAME");
334 if (host
== NULL
) host
= "???";
335 if (VG_(strchr
)(host
, '/')) host
= "???";
337 len
= strlen(name
) + strlen(user
) + strlen(host
) + 40;
339 if (from_gdb
!= NULL
)
341 from_gdb
= malloc (len
);
344 to_gdb
= malloc (len
);
345 if (shared_mem
!= NULL
)
347 shared_mem
= malloc (len
);
348 /* below 3 lines must match the equivalent in vgdb.c */
349 VG_(sprintf
) (from_gdb
, "%s-from-vgdb-to-%d-by-%s-on-%s", name
,
351 VG_(sprintf
) (to_gdb
, "%s-to-vgdb-from-%d-by-%s-on-%s", name
,
353 VG_(sprintf
) (shared_mem
, "%s-shared-mem-vgdb-%d-by-%s-on-%s", name
,
355 if (VG_(clo_verbosity
) > 1) {
356 VG_(umsg
)("embedded gdbserver: reading from %s\n", from_gdb
);
357 VG_(umsg
)("embedded gdbserver: writing to %s\n", to_gdb
);
358 VG_(umsg
)("embedded gdbserver: shared mem %s\n", shared_mem
);
360 VG_(umsg
)("TO CONTROL THIS PROCESS USING vgdb (which you probably\n"
361 "don't want to do, unless you know exactly what you're doing,\n"
362 "or are doing some strange experiment):\n"
363 " %s/../../bin/vgdb%s%s --pid=%d ...command...\n",
365 (VG_(arg_vgdb_prefix
) ? " " : ""),
366 (VG_(arg_vgdb_prefix
) ? VG_(arg_vgdb_prefix
) : ""),
369 if (VG_(clo_verbosity
) > 1
370 || VG_(clo_vgdb_error
) < 999999999
371 || VG_(clo_vgdb_stop_at
) != 0) {
374 "TO DEBUG THIS PROCESS USING GDB: start GDB like this\n"
376 "and then give GDB the following command\n"
377 " target remote | %s/../../bin/vgdb%s%s --pid=%d\n",
378 VG_(args_the_exename
),
380 (VG_(arg_vgdb_prefix
) ? " " : ""),
381 (VG_(arg_vgdb_prefix
) ? VG_(arg_vgdb_prefix
) : ""),
384 VG_(umsg
)("--pid is optional if only one valgrind process is running\n");
392 * Unlink just in case a previous process with the same PID had been
393 * killed and hence Valgrind hasn't had the chance yet to remove these.
395 VG_(unlink
)(from_gdb
);
397 VG_(unlink
)(shared_mem
);
399 o
= VG_(open
) (shared_mem
, VKI_O_CREAT
|VKI_O_RDWR
, 0600);
400 if (sr_isError (o
)) {
401 sr_perror(o
, "cannot create shared_mem file %s\n", shared_mem
);
402 fatal("Cannot recover from previous error. Good-bye.");
404 shared_mem_fd
= sr_Res(o
);
407 if (VG_(write
)(shared_mem_fd
, &vgdbinit
, sizeof(VgdbShared
))
408 != sizeof(VgdbShared
)) {
409 fatal("error writing %d bytes to shared mem %s\n",
410 (int) sizeof(VgdbShared
), shared_mem
);
413 SysRes res
= VG_(am_shared_mmap_file_float_valgrind
)
414 (sizeof(VgdbShared
), VKI_PROT_READ
|VKI_PROT_WRITE
,
415 shared_mem_fd
, (Off64T
)0);
416 if (sr_isError(res
)) {
417 sr_perror(res
, "error VG_(am_shared_mmap_file_float_valgrind) %s\n",
419 fatal("Cannot recover from previous error. Good-bye.");
421 addr_shared
= sr_Res (res
);
423 shared
= (VgdbShared
*) addr_shared
;
424 VG_(close
) (shared_mem_fd
);
427 safe_mknod(from_gdb
);
428 /* from_gdb is the last resource created: vgdb searches such FIFOs
429 to detect the presence of a valgrind process.
430 So, we better create this resource when all the rest needed by
431 vgdb is ready : the other FIFO and the shared memory. */
433 pid_from_to_creator
= pid
;
436 setup_remote_desc_for_reading ();
439 /* sync_gdb_connection wait a time long enough to let the connection
440 be properly closed if needed when closing the connection (in case
441 of detach or error), if we reopen it too quickly, it seems there
442 are some events queued in the kernel concerning the "old"
443 connection/remote_desc which are discovered with poll or select on
444 the "new" connection/remote_desc. We bypass this by waiting some
445 time to let a proper cleanup to be donex */
446 void sync_gdb_connection(void)
449 ret
= VG_(poll_no_eintr
)(0, 0, 100);
451 sr_extended_perror(ret
, "sync_gdb_connection: poll error\n");
455 const char * ppFinishReason (FinishReason reason
)
458 case orderly_finish
: return "orderly_finish";
459 case reset_after_error
: return "reset_after_error";
460 case reset_after_fork
: return "reset_after_fork";
461 default: vg_assert (0);
465 void remote_finish (FinishReason reason
)
467 dlog(1, "remote_finish (reason %s) %d %d\n",
468 ppFinishReason(reason
), remote_desc
, write_remote_desc
);
469 reset_valgrind_sink(ppFinishReason(reason
));
470 if (write_remote_desc
!= INVALID_DESCRIPTOR
)
471 VG_(close
) (write_remote_desc
);
472 write_remote_desc
= INVALID_DESCRIPTOR
;
474 if (remote_desc
!= INVALID_DESCRIPTOR
) {
475 /* Fully close the connection, either due to orderly_finish or
476 to reset_after_fork or reset_after_error. For
477 reset_after_error, the FIFO will be re-opened soon. This
478 leaves a small window during which a race condition can
479 happen between vgdb and a forking process: Just after fork,
480 both the parent and the child have the FIFO open. The child
481 will close it asap (as part of the 'after fork cleanup'). If
482 2 vgdbs are launched very quickly just after the fork, the
483 parent will close its FIFO when the 1st vgdb exits. Then if
484 the 2nd vgdb is started before the parent has the time to
485 re-open the FIFO, the 2nd vgdb will be able to open the FIFO
486 (as it is still opened by the child). The 2nd vgdb can then
487 have a 'write' error when the child closes the FIFO. After
488 the 1st vgdb closes its FIFO write side, the parent gets EOF
489 on its reading FIFO till it is closed and re-opened. Opening
490 a 2nd time the FIFO before closing the 'previous fd' solves
491 this race condition, but causes other (not understood)
492 problems due to too early re-invocation of gdbsrv. Rather
493 than to handle this race condition in gdbsrv side, we put a
494 'retry' loop in vgdb for the initial write on the write
496 remote_desc_pollfdread_activity
.fd
= INVALID_DESCRIPTOR
;
497 remote_desc_pollfdread_activity
.events
= 0;
498 remote_desc_pollfdread_activity
.revents
= 0;
499 VG_(close
) (remote_desc
);
500 remote_desc
= INVALID_DESCRIPTOR
;
504 /* ensure the child will create its own FIFOs */
505 if (reason
== reset_after_fork
)
508 if (reason
== reset_after_error
)
509 sync_gdb_connection();
512 /* orderly close, cleans up everything */
513 void remote_close (void)
515 const int pid
= VG_(getpid
)();
516 remote_finish(orderly_finish
);
517 dlog(1, "%d (creator %d) maybe unlinking \n %s\n %s\n %s\n",
518 pid
, pid_from_to_creator
,
519 from_gdb
? from_gdb
: "NULL",
520 to_gdb
? to_gdb
: "NULL",
521 shared_mem
? shared_mem
: "NULL");
522 if (pid
== pid_from_to_creator
&& from_gdb
&& VG_(unlink
) (from_gdb
) == -1)
523 warning ("could not unlink %s\n", from_gdb
);
524 if (pid
== pid_from_to_creator
&& to_gdb
&& VG_(unlink
) (to_gdb
) == -1)
525 warning ("could not unlink %s\n", to_gdb
);
526 if (pid
== pid_from_to_creator
&& shared_mem
&& VG_(unlink
) (shared_mem
) == -1)
527 warning ("could not unlink %s\n", shared_mem
);
536 Bool
remote_connected(void)
538 return write_remote_desc
!= INVALID_DESCRIPTOR
;
541 /* cleanup after an error detected by poll_cond */
543 void error_poll_cond(void)
545 /* if we will close the connection, we assume either that
546 all characters have been seen or that they will be dropped. */
547 shared
->seen_by_valgrind
= shared
->written_by_vgdb
;
548 remote_finish(reset_after_error
);
551 /* remote_desc_activity might be used at high frequency if the user
552 gives a small value to --vgdb-poll. So, the function avoids
553 doing repetitively system calls by rather looking at the
554 counter values maintained in shared memory by vgdb. */
555 int remote_desc_activity(const char *msg
)
559 const int looking_at
= shared
->written_by_vgdb
;
560 if (shared
->seen_by_valgrind
== looking_at
)
562 if (remote_desc
== INVALID_DESCRIPTOR
)
565 /* poll the remote desc */
566 remote_desc_pollfdread_activity
.revents
= 0;
567 ret
= VG_(poll_no_eintr
) (&remote_desc_pollfdread_activity
, 1, 0);
569 || (sr_Res(ret
) && poll_cond(remote_desc_pollfdread_activity
.revents
))) {
570 if (sr_isError(ret
)) {
571 sr_extended_perror(ret
, "remote_desc_activity: poll error\n");
573 dlog(0, "POLLcond %d remote_desc_pollfdread %d\n",
574 remote_desc_pollfdread_activity
.revents
, remote_desc
);
579 retval
= sr_Res(ret
);
582 "remote_desc_activity %s %d last_looked_cntr %d looking_at %d"
583 " shared->written_by_vgdb %d shared->seen_by_valgrind %d"
585 msg
, remote_desc
, last_looked_cntr
, looking_at
,
586 shared
->written_by_vgdb
, shared
->seen_by_valgrind
,
588 /* if no error from poll, indicate we have "seen" up to looking_at */
590 last_looked_cntr
= looking_at
;
594 /* Convert hex digit A to a number. */
599 if (a
>= '0' && a
<= '9')
601 else if (a
>= 'a' && a
<= 'f')
604 error ("Reply contains invalid hex digit 0x%x\n", (unsigned)a
);
608 int unhexify (char *bin
, const char *hex
, int count
)
612 for (i
= 0; i
< count
; i
++) {
613 if (hex
[0] == 0 || hex
[1] == 0) {
614 /* Hex string is short, or of uneven length.
615 Return the count that has been converted so far. */
618 *bin
++ = fromhex (hex
[0]) * 16 + fromhex (hex
[1]);
624 void decode_address (CORE_ADDR
*addrp
, const char *start
, int len
)
631 for (i
= 0; i
< len
; i
++) {
634 addr
= addr
| (fromhex (ch
) & 0x0f);
639 /* Convert number NIB to a hex digit. */
647 return 'a' + nib
- 10;
650 int hexify (char *hex
, const char *bin
, int count
)
654 /* May use a length, or a nul-terminated string as input. */
656 count
= strlen (bin
);
658 for (i
= 0; i
< count
; i
++) {
659 *hex
++ = tohex ((*bin
>> 4) & 0xf);
660 *hex
++ = tohex (*bin
++ & 0xf);
666 /* builds an image of bin according to byte order of the architecture
667 Useful for register and int image */
668 char* heximage (char *buf
, char *bin
, int count
)
670 #if (VKI_LITTLE_ENDIAN)
672 /* note: no need for trailing \0, length is known with count */
674 for (i
= 0; i
< count
; i
++)
675 rev
[i
] = bin
[count
- i
- 1];
676 hexify (buf
, rev
, count
);
678 hexify (buf
, bin
, count
);
683 void* C2v(CORE_ADDR addr
)
689 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
690 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
691 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
692 (which may be more than *OUT_LEN due to escape characters). The
693 total number of bytes in the output buffer will be at most
697 remote_escape_output (const gdb_byte
*buffer
, int len
,
698 gdb_byte
*out_buf
, int *out_len
,
701 int input_index
, output_index
;
704 for (input_index
= 0; input_index
< len
; input_index
++) {
705 gdb_byte b
= buffer
[input_index
];
707 if (b
== '$' || b
== '#' || b
== '}' || b
== '*') {
708 /* These must be escaped. */
709 if (output_index
+ 2 > out_maxlen
)
711 out_buf
[output_index
++] = '}';
712 out_buf
[output_index
++] = b
^ 0x20;
714 if (output_index
+ 1 > out_maxlen
)
716 out_buf
[output_index
++] = b
;
720 *out_len
= input_index
;
724 /* Convert BUFFER, escaped data LEN bytes long, into binary data
725 in OUT_BUF. Return the number of bytes written to OUT_BUF.
726 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
728 This function reverses remote_escape_output. It allows more
729 escaped characters than that function does, in particular because
730 '*' must be escaped to avoid the run-length encoding processing
731 in reading packets. */
734 int remote_unescape_input (const gdb_byte
*buffer
, int len
,
735 gdb_byte
*out_buf
, int out_maxlen
)
737 int input_index
, output_index
;
742 for (input_index
= 0; input_index
< len
; input_index
++) {
743 gdb_byte b
= buffer
[input_index
];
745 if (output_index
+ 1 > out_maxlen
)
746 error ("Received too much data (len %d) from the target.\n", len
);
749 out_buf
[output_index
++] = b
^ 0x20;
751 } else if (b
== '}') {
754 out_buf
[output_index
++] = b
;
759 error ("Unmatched escape character in target response.\n");
764 /* Look for a sequence of characters which can be run-length encoded.
765 If there are any, update *CSUM and *P. Otherwise, output the
766 single character. Return the number of characters consumed. */
769 int try_rle (char *buf
, int remaining
, unsigned char *csum
, char **p
)
773 /* Always output the character. */
777 /* Don't go past '~'. */
781 for (n
= 1; n
< remaining
; n
++)
782 if (buf
[n
] != buf
[0])
785 /* N is the index of the first character not the same as buf[0].
786 buf[0] is counted twice, so by decrementing N, we get the number
787 of characters the RLE sequence will replace. */
793 /* Skip the frame characters. The manual says to skip '+' and '-'
794 also, but there's no reason to. Unfortunately these two unusable
795 characters double the encoded length of a four byte zero
797 while (n
+ 29 == '$' || n
+ 29 == '#')
808 /* Send a packet to the remote machine, with error checking.
809 The data of the packet is in BUF, and the length of the
810 packet is in CNT. Returns >= 0 on success, -1 otherwise. */
812 int putpkt_binary (char *buf
, int cnt
)
815 unsigned char csum
= 0;
820 buf2
= malloc (PBUFSIZ
+POVERHSIZ
);
821 // should malloc PBUFSIZ, but bypass GDB bug (see gdbserver_init in server.c)
822 vg_assert (5 == POVERHSIZ
);
823 vg_assert (cnt
<= PBUFSIZ
); // be tolerant for GDB bug.
825 /* Copy the packet into buffer BUF2, encapsulating it
826 and giving it a checksum. */
831 for (i
= 0; i
< cnt
;)
832 i
+= try_rle (buf
+ i
, cnt
- i
, &csum
, &p
);
835 *p
++ = tohex ((csum
>> 4) & 0xf);
836 *p
++ = tohex (csum
& 0xf);
840 /* we might have to write a pkt when out FIFO not yet/anymore opened */
841 if (!ensure_write_remote_desc()) {
842 warning ("putpkt(write) error: no write_remote_desc\n");
847 /* Send it once (noack_mode)
848 or send it over and over until we get a positive ack. */
851 if (VG_(write
) (write_remote_desc
, buf2
, p
- buf2
) != p
- buf2
) {
852 warning ("putpkt(write) error\n");
857 if (VG_(debugLog_getLevel
)() >= 3) {
858 char *tracebuf
= malloc(4 * (p
- buf2
) + 1); // worst case
861 for (UInt npr
= 0; npr
< p
- buf2
; npr
++) {
862 UChar uc
= (unsigned char)buf2
[npr
];
863 if (uc
> 31 && uc
< 127) {
867 VG_(sprintf
)(tr
, "%03o", uc
);
872 dlog(3, "putpkt (\"%s\"); (%slen %d) %s\n", tracebuf
,
873 strlen(tracebuf
) == p
- buf2
? "binary " : "",
875 noack_mode
? "[no ack]" : "[looking for ack]");
884 dlog(3, "[received '%c' (0x%x)]\n", cc
, (unsigned)cc
);
888 dlog(1, "putpkt(read): Got EOF\n");
890 warning ("putpkt(read) error\n");
896 /* Check for an input interrupt while we're here. */
898 dlog(1, "Received 0x03 character (SIGINT)\n");
903 return 1; /* Success! */
906 /* Send a packet to the remote machine, with error checking. The data
907 of the packet is in BUF, and the packet should be a NUL-terminated
908 string. Returns >= 0 on success, -1 otherwise. */
910 int putpkt (char *buf
)
912 return putpkt_binary (buf
, strlen (buf
));
915 void monitor_output (char *s
)
917 if (remote_connected()) {
918 const int len
= strlen(s
);
919 char *buf
= malloc(1 + 2*len
+ 1);
922 hexify(buf
+1, s
, len
);
923 if (putpkt (buf
) < 0) {
924 /* We probably have lost the connection with vgdb. */
925 reset_valgrind_sink("Error writing monitor output");
926 /* write again after reset */
927 VG_(printf
) ("%s", s
);
932 print_to_initial_valgrind_sink (s
);
936 /* Returns next char from remote GDB. -1 if error. */
937 /* if single, only one character maximum can be read with
938 read system call. Otherwise, when reading an ack character
939 we might pile up the next gdb command in the static buf.
940 The read loop is then blocked in poll till gdb times out. */
942 int readchar (int single
)
944 static unsigned char buf
[PBUFSIZ
];
945 static int bufcnt
= 0;
946 static unsigned char *bufp
;
952 if (remote_desc
== INVALID_DESCRIPTOR
)
955 /* No characters available in buf =>
956 wait for some characters to arrive */
957 remote_desc_pollfdread_activity
.revents
= 0;
958 ret
= VG_(poll_no_eintr
)(&remote_desc_pollfdread_activity
, 1, -1);
959 if (sr_isError(ret
) || sr_Res(ret
) != 1) {
960 if (sr_isError(ret
)) {
961 sr_extended_perror(ret
, "readchar: poll error\n");
963 dlog(0, "readchar: poll got %d, expecting 1\n", (int)sr_Res(ret
));
968 bufcnt
= VG_(read
) (remote_desc
, buf
, 1);
970 bufcnt
= VG_(read
) (remote_desc
, buf
, sizeof (buf
));
974 dlog (1, "readchar: Got EOF\n");
976 warning ("readchar read error\n");
981 shared
->seen_by_valgrind
+= bufcnt
;
983 /* If we have received a character and we do not yet have a
984 connection, we better open our "write" fifo to let vgdb open its
986 if (write_remote_desc
== INVALID_DESCRIPTOR
987 && !ensure_write_remote_desc()) {
988 dlog(1, "reachar: write_remote_desc could not be created");
994 if (poll_cond(remote_desc_pollfdread_activity
.revents
)) {
995 dlog(1, "readchar: POLLcond got %d\n",
996 remote_desc_pollfdread_activity
.revents
);
1004 /* Read a packet from the remote machine, with error checking,
1005 and store it in BUF. Returns length of packet, or negative if error. */
1007 int getpkt (char *buf
)
1010 unsigned char csum
, c1
, c2
;
1020 dlog(3, "[getpkt: discarding char '%c']\n", c
);
1037 c1
= fromhex (readchar (0));
1038 c2
= fromhex (readchar (0));
1040 if (csum
== (c1
<< 4) + c2
)
1043 dlog (0, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1044 (unsigned)(c1
<< 4) + c2
, (unsigned)csum
, buf
);
1045 if (!ensure_write_remote_desc()) {
1046 dlog(1, "getpkt(write nack) no write_remote_desc");
1048 VG_(write
) (write_remote_desc
, "-", 1);
1052 dlog(3, "getpkt (\"%s\"); [no ack] \n", buf
);
1054 dlog(3, "getpkt (\"%s\"); [sending ack] \n", buf
);
1057 if (!ensure_write_remote_desc()) {
1058 dlog(1, "getpkt(write ack) no write_remote_desc");
1060 VG_(write
) (write_remote_desc
, "+", 1);
1061 dlog(3, "[sent ack]\n");
1067 void write_ok (char *buf
)
1074 void write_enn (char *buf
)
1076 /* Some day, we should define the meanings of the error codes... */
1083 void convert_int_to_ascii (const unsigned char *from
, char *to
, int n
)
1089 nib
= ((ch
& 0xf0) >> 4) & 0x0f;
1090 *to
++ = tohex (nib
);
1092 *to
++ = tohex (nib
);
1098 void convert_ascii_to_int (const char *from
, unsigned char *to
, int n
)
1102 nib1
= fromhex (*from
++);
1103 nib2
= fromhex (*from
++);
1104 *to
++ = (((nib1
& 0x0f) << 4) & 0xf0) | (nib2
& 0x0f);
1109 char * outreg (int regno
, char *buf
)
1111 if ((regno
>> 12) != 0)
1112 *buf
++ = tohex ((regno
>> 12) & 0xf);
1113 if ((regno
>> 8) != 0)
1114 *buf
++ = tohex ((regno
>> 8) & 0xf);
1115 *buf
++ = tohex ((regno
>> 4) & 0xf);
1116 *buf
++ = tohex (regno
& 0xf);
1118 collect_register_as_string (regno
, buf
);
1119 buf
+= 2 * register_size (regno
);
1125 void prepare_resume_reply (char *buf
, char status
, unsigned char sig
)
1131 nib
= ((sig
& 0xf0) >> 4);
1132 *buf
++ = tohex (nib
);
1134 *buf
++ = tohex (nib
);
1136 if (status
== 'T') {
1137 const char **regp
= gdbserver_expedite_regs
;
1139 if (valgrind_stopped_by_watchpoint()) {
1143 strncpy (buf
, "watch:", 6);
1146 addr
= valgrind_stopped_data_address ();
1148 /* Convert each byte of the address into two hexadecimal chars.
1149 Note that we take sizeof (void *) instead of sizeof (addr);
1150 this is to avoid sending a 64-bit address to a 32-bit GDB. */
1151 for (i
= sizeof (void *) * 2; i
> 0; i
--) {
1152 *buf
++ = tohex ((addr
>> (i
- 1) * 4) & 0xf);
1157 if (valgrind_stopped_by_syscall () >= 0) {
1158 VG_(sprintf
) (buf
, "%s:%x;",
1159 valgrind_stopped_before_syscall ()
1160 ? "syscall_entry" : "syscall_return",
1161 valgrind_stopped_by_syscall ());
1162 buf
+= strlen (buf
);
1166 buf
= outreg (find_regno (*regp
), buf
);
1171 unsigned int gdb_id_from_wait
;
1173 /* FIXME right place to set this? */
1175 ((struct inferior_list_entry
*)current_inferior
)->id
;
1176 gdb_id_from_wait
= thread_to_gdb_id (current_inferior
);
1178 dlog(1, "Writing resume reply for %lu\n", thread_from_wait
);
1179 /* This if (1) ought to be unnecessary. But remote_wait in GDB
1180 will claim this event belongs to inferior_ptid if we do not
1181 specify a thread, and there's no way for gdbserver to know
1182 what inferior_ptid is. */
1183 if (1 || old_thread_from_wait
!= thread_from_wait
) {
1184 general_thread
= thread_from_wait
;
1185 VG_(sprintf
) (buf
, "thread:%x;", gdb_id_from_wait
);
1186 buf
+= strlen (buf
);
1187 old_thread_from_wait
= thread_from_wait
;
1191 /* For W and X, we're done. */
1195 void decode_m_packet (char *from
, CORE_ADDR
*mem_addr_ptr
, unsigned int *len_ptr
)
1199 *mem_addr_ptr
= *len_ptr
= 0;
1201 while ((ch
= from
[i
++]) != ',') {
1202 *mem_addr_ptr
= *mem_addr_ptr
<< 4;
1203 *mem_addr_ptr
|= fromhex (ch
) & 0x0f;
1206 for (j
= 0; j
< 4; j
++) {
1207 if ((ch
= from
[i
++]) == 0)
1209 *len_ptr
= *len_ptr
<< 4;
1210 *len_ptr
|= fromhex (ch
) & 0x0f;
1214 void decode_M_packet (char *from
, CORE_ADDR
*mem_addr_ptr
, unsigned int *len_ptr
,
1219 *mem_addr_ptr
= *len_ptr
= 0;
1221 while ((ch
= from
[i
++]) != ',') {
1222 *mem_addr_ptr
= *mem_addr_ptr
<< 4;
1223 *mem_addr_ptr
|= fromhex (ch
) & 0x0f;
1226 while ((ch
= from
[i
++]) != ':') {
1227 *len_ptr
= *len_ptr
<< 4;
1228 *len_ptr
|= fromhex (ch
) & 0x0f;
1231 convert_ascii_to_int (&from
[i
++], to
, *len_ptr
);
1234 int decode_X_packet (char *from
, int packet_len
, CORE_ADDR
*mem_addr_ptr
,
1235 unsigned int *len_ptr
, unsigned char *to
)
1239 *mem_addr_ptr
= *len_ptr
= 0;
1241 while ((ch
= from
[i
++]) != ',') {
1242 *mem_addr_ptr
= *mem_addr_ptr
<< 4;
1243 *mem_addr_ptr
|= fromhex (ch
) & 0x0f;
1246 while ((ch
= from
[i
++]) != ':') {
1247 *len_ptr
= *len_ptr
<< 4;
1248 *len_ptr
|= fromhex (ch
) & 0x0f;
1251 if (remote_unescape_input ((const gdb_byte
*) &from
[i
], packet_len
- i
,
1252 to
, *len_ptr
) != *len_ptr
)
1259 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
1260 to communicate with valgrind */
1262 VG_(vgdb_prefix_default
)(void)
1264 static HChar
*prefix
;
1266 if (prefix
== NULL
) {
1267 const HChar
*tmpdir
= VG_(tmpdir
)();
1268 prefix
= malloc(strlen(tmpdir
) + strlen("/vgdb-pipe") + 1);
1269 strcpy(prefix
, tmpdir
);
1270 strcat(prefix
, "/vgdb-pipe");