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.
5
6 This file is part of GDB.
7 It has been modified to integrate it in valgrind
8
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.
13
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.
18
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. */
23
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
30 #include "server.h"
31
32 # if defined(VGO_linux)
33 #include <sys/prctl.h>
34 # endif
35
36 Bool noack_mode;
37
38 static int readchar (int single);
39
40 void remote_utils_output_status(void);
41
42 static int remote_desc;
43
44 static VgdbShared *shared;
45 static int last_looked_cntr = -1;
46 static struct vki_pollfd remote_desc_pollfdread_activity;
47 #define INVALID_DESCRIPTOR -1
48
49 /* for a gdbserver embedded in valgrind, we read from a FIFO and write
50 to another FIFO So, we need two descriptors */
51 static int write_remote_desc = INVALID_DESCRIPTOR;
52 static int pid_from_to_creator;
53 /* only this pid will remove the FIFOs: if an exec fails, we must avoid
54 that the exiting child believes it has to remove the FIFOs of its parent */
55 static int mknod_done = 0;
56
57 static char *from_gdb = NULL;
58 static char *to_gdb = NULL;
59 static char *shared_mem = NULL;
60
61 static
open_fifo(char * side,char * path,int flags)62 int open_fifo (char *side, char *path, int flags)
63 {
64 SysRes o;
65 int fd;
66 dlog(1, "Opening %s side %s\n", side, path);
67 o = VG_(open) (path, flags, 0);
68 if (sr_isError (o)) {
69 sr_perror(o, "open fifo %s\n", path);
70 fatal ("valgrind: fatal error: vgdb FIFO cannot be opened.\n");
71 } else {
72 fd = sr_Res(o);
73 dlog(1, "result fd %d\n", fd);
74 }
75 fd = VG_(safe_fd)(fd);
76 dlog(1, "result safe_fd %d\n", fd);
77 if (fd == -1)
78 fatal("safe_fd for vgdb FIFO failed\n");
79 return fd;
80 }
81
remote_utils_output_status(void)82 void remote_utils_output_status(void)
83 {
84 if (shared == NULL)
85 VG_(umsg)("remote communication not initialized\n");
86 else
87 VG_(umsg)("shared->written_by_vgdb %d shared->seen_by_valgrind %d\n",
88 shared->written_by_vgdb, shared->seen_by_valgrind);
89 }
90
91 /* Returns 0 if vgdb and connection state looks good,
92 otherwise returns an int value telling which check failed. */
93 static
vgdb_state_looks_bad(char * where)94 int vgdb_state_looks_bad(char* where)
95 {
96 if (VG_(kill)(shared->vgdb_pid, 0) != 0)
97 return 1; // vgdb process does not exist anymore.
98
99 if (remote_desc_activity(where) == 2)
100 return 2; // check for error on remote desc shows a problem
101
102 if (remote_desc == INVALID_DESCRIPTOR)
103 return 3; // after check, remote_desc not ok anymore
104
105 return 0; // all is ok.
106 }
107
108 /* On systems that defines PR_SET_PTRACER, verify if ptrace_scope is
109 is permissive enough for vgdb. Otherwise, call set_ptracer.
110 This is especially aimed at Ubuntu >= 10.10 which has added
111 the ptrace_scope context. */
112 static
set_ptracer(void)113 void set_ptracer(void)
114 {
115 #ifdef PR_SET_PTRACER
116 SysRes o;
117 char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope";
118 int fd;
119 char ptrace_scope;
120 int ret;
121
122 o = VG_(open) (ptrace_scope_setting_file, VKI_O_RDONLY, 0);
123 if (sr_isError(o)) {
124 if (VG_(debugLog_getLevel)() >= 1) {
125 sr_perror(o, "error VG_(open) %s\n", ptrace_scope_setting_file);
126 }
127 /* can't read setting. Assuming ptrace can be called by vgdb. */
128 return;
129 }
130 fd = sr_Res(o);
131 if (VG_(read) (fd, &ptrace_scope, 1) == 1) {
132 dlog(1, "ptrace_scope %c\n", ptrace_scope);
133 if (ptrace_scope != '0') {
134 /* insufficient default ptrace_scope.
135 Indicate to the kernel that we accept to be
136 ptraced by our vgdb. */
137 ret = VG_(prctl) (PR_SET_PTRACER, shared->vgdb_pid, 0, 0, 0);
138 dlog(1, "set_ptracer to vgdb_pid %d result %d\n",
139 shared->vgdb_pid, ret);
140 }
141 } else {
142 dlog(0, "Could not read the ptrace_scope setting from %s\n",
143 ptrace_scope_setting_file);
144 }
145
146 VG_(close) (fd);
147 #endif
148 }
149
150 /* returns 1 if one or more poll "errors" is set.
151 Errors are: VKI_POLLERR or VKI_POLLHUP or VKI_POLLNAL */
152 static
poll_cond(short revents)153 int poll_cond (short revents)
154 {
155 return (revents & (VKI_POLLERR | VKI_POLLHUP | VKI_POLLNVAL));
156 }
157
158 /* Ensures we have a valid write file descriptor.
159 Returns 1 if we have a valid write file descriptor,
160 0 if the write fd could not be opened. */
161 static
ensure_write_remote_desc(void)162 int ensure_write_remote_desc(void)
163 {
164 struct vki_pollfd write_remote_desc_ok;
165 int ret;
166 if (write_remote_desc != INVALID_DESCRIPTOR) {
167 write_remote_desc_ok.fd = write_remote_desc;
168 write_remote_desc_ok.events = VKI_POLLOUT;
169 write_remote_desc_ok.revents = 0;
170 ret = VG_(poll)(&write_remote_desc_ok, 1, 0);
171 if (ret && poll_cond(write_remote_desc_ok.revents)) {
172 dlog(1, "POLLcond %d closing write_remote_desc %d\n",
173 write_remote_desc_ok.revents, write_remote_desc);
174 VG_(close) (write_remote_desc);
175 write_remote_desc = INVALID_DESCRIPTOR;
176 }
177 }
178 if (write_remote_desc == INVALID_DESCRIPTOR) {
179 /* open_fifo write will block if the receiving vgdb
180 process is dead. So, let's check for vgdb state to
181 be reasonably sure someone is reading on the other
182 side of the fifo. */
183 if (!vgdb_state_looks_bad("bad?@ensure_write_remote_desc")) {
184 set_ptracer();
185 write_remote_desc = open_fifo ("write", to_gdb, VKI_O_WRONLY);
186 }
187 }
188
189 return (write_remote_desc != INVALID_DESCRIPTOR);
190 }
191
192 #if defined(VGO_darwin)
193 #define VKI_S_IFIFO 0010000
194 #endif
195 static
safe_mknod(char * nod)196 void safe_mknod (char *nod)
197 {
198 SysRes m;
199 m = VG_(mknod) (nod, VKI_S_IFIFO|0600, 0);
200 if (sr_isError (m)) {
201 if (sr_Err (m) == VKI_EEXIST) {
202 if (VG_(clo_verbosity) > 1) {
203 VG_(umsg)("%s already created\n", nod);
204 }
205 } else {
206 sr_perror(m, "mknod %s\n", nod);
207 VG_(umsg) ("valgrind: fatal error: vgdb FIFOs cannot be created.\n");
208 VG_(exit)(1);
209 }
210 }
211 }
212
213 /* Open a connection to a remote debugger.
214 NAME is the filename used for communication.
215 For Valgrind, name is the prefix for the two read and write FIFOs
216 The two FIFOs names will be build by appending
217 -from-vgdb-to-pid-by-user-on-host and -to-vgdb-from-pid-by-user-on-host
218 with pid being the pidnr of the valgrind process These two FIFOs
219 will be created if not existing yet. They will be removed when
220 the gdbserver connection is closed or the process exits */
221
remote_open(char * name)222 void remote_open (char *name)
223 {
224 const HChar *user, *host;
225 int save_fcntl_flags, len;
226 VgdbShared vgdbinit =
227 {0, 0, (Addr) VG_(invoke_gdbserver),
228 (Addr) VG_(threads), sizeof(ThreadState),
229 offsetof(ThreadState, status),
230 offsetof(ThreadState, os_state) + offsetof(ThreadOSstate, lwpid),
231 0};
232 const int pid = VG_(getpid)();
233 const int name_default = strcmp(name, VG_(vgdb_prefix_default)()) == 0;
234 Addr addr_shared;
235 SysRes o;
236 int shared_mem_fd = INVALID_DESCRIPTOR;
237
238 user = VG_(getenv)("LOGNAME");
239 if (user == NULL) user = VG_(getenv)("USER");
240 if (user == NULL) user = "???";
241
242 host = VG_(getenv)("HOST");
243 if (host == NULL) host = VG_(getenv)("HOSTNAME");
244 if (host == NULL) host = "???";
245
246 len = strlen(name) + strlen(user) + strlen(host) + 40;
247
248 if (from_gdb != NULL)
249 free (from_gdb);
250 from_gdb = malloc (len);
251 if (to_gdb != NULL)
252 free (to_gdb);
253 to_gdb = malloc (len);
254 if (shared_mem != NULL)
255 free (shared_mem);
256 shared_mem = malloc (len);
257 /* below 3 lines must match the equivalent in vgdb.c */
258 VG_(sprintf) (from_gdb, "%s-from-vgdb-to-%d-by-%s-on-%s", name,
259 pid, user, host);
260 VG_(sprintf) (to_gdb, "%s-to-vgdb-from-%d-by-%s-on-%s", name,
261 pid, user, host);
262 VG_(sprintf) (shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", name,
263 pid, user, host);
264 if (VG_(clo_verbosity) > 1) {
265 VG_(umsg)("embedded gdbserver: reading from %s\n", from_gdb);
266 VG_(umsg)("embedded gdbserver: writing to %s\n", to_gdb);
267 VG_(umsg)("embedded gdbserver: shared mem %s\n", shared_mem);
268 VG_(umsg)("\n");
269 VG_(umsg)("TO CONTROL THIS PROCESS USING vgdb (which you probably\n"
270 "don't want to do, unless you know exactly what you're doing,\n"
271 "or are doing some strange experiment):\n"
272 " %s/../../bin/vgdb --pid=%d%s%s ...command...\n",
273 VG_(libdir),
274 pid, (name_default ? "" : " --vgdb-prefix="),
275 (name_default ? "" : name));
276 }
277 if (VG_(clo_verbosity) > 1
278 || VG_(clo_vgdb_error) < 999999999) {
279 VG_(umsg)("\n");
280 VG_(umsg)(
281 "TO DEBUG THIS PROCESS USING GDB: start GDB like this\n"
282 " /path/to/gdb %s\n"
283 "and then give GDB the following command\n"
284 " target remote | %s/../../bin/vgdb --pid=%d%s%s\n",
285 VG_(args_the_exename),
286 VG_(libdir),
287 pid, (name_default ? "" : " --vgdb-prefix="),
288 (name_default ? "" : name)
289 );
290 VG_(umsg)("--pid is optional if only one valgrind process is running\n");
291 VG_(umsg)("\n");
292 }
293
294 if (!mknod_done) {
295 mknod_done++;
296
297 /*
298 * Unlink just in case a previous process with the same PID had been
299 * killed and hence Valgrind hasn't had the chance yet to remove these.
300 */
301 VG_(unlink)(from_gdb);
302 VG_(unlink)(to_gdb);
303 VG_(unlink)(shared_mem);
304
305 safe_mknod(from_gdb);
306 safe_mknod(to_gdb);
307
308 pid_from_to_creator = pid;
309
310 o = VG_(open) (shared_mem, VKI_O_CREAT|VKI_O_RDWR, 0600);
311 if (sr_isError (o)) {
312 sr_perror(o, "cannot create shared_mem file %s\n", shared_mem);
313 fatal("");
314 } else {
315 shared_mem_fd = sr_Res(o);
316 }
317
318 if (VG_(write)(shared_mem_fd, &vgdbinit, sizeof(VgdbShared))
319 != sizeof(VgdbShared)) {
320 fatal("error writing %d bytes to shared mem %s\n",
321 (int) sizeof(VgdbShared), shared_mem);
322 }
323 {
324 SysRes res = VG_(am_shared_mmap_file_float_valgrind)
325 (sizeof(VgdbShared), VKI_PROT_READ|VKI_PROT_WRITE,
326 shared_mem_fd, (Off64T)0);
327 if (sr_isError(res)) {
328 sr_perror(res, "error VG_(am_shared_mmap_file_float_valgrind) %s\n",
329 shared_mem);
330 fatal("");
331 }
332 addr_shared = sr_Res (res);
333 }
334 shared = (VgdbShared*) addr_shared;
335 VG_(close) (shared_mem_fd);
336 }
337
338 /* we open the read side FIFO in non blocking mode
339 We then set the fd in blocking mode.
340 Opening in non-blocking read mode always succeeds while opening
341 in non-blocking write mode succeeds only if the fifo is already
342 opened in read mode. So, we wait till we have read the first
343 character from the read side before opening the write side. */
344 remote_desc = open_fifo ("read", from_gdb, VKI_O_RDONLY|VKI_O_NONBLOCK);
345 save_fcntl_flags = VG_(fcntl) (remote_desc, VKI_F_GETFL, 0);
346 VG_(fcntl) (remote_desc, VKI_F_SETFL, save_fcntl_flags & ~VKI_O_NONBLOCK);
347 remote_desc_pollfdread_activity.fd = remote_desc;
348 remote_desc_pollfdread_activity.events = VKI_POLLIN;
349 remote_desc_pollfdread_activity.revents = 0;
350 }
351
352 /* sync_gdb_connection wait a time long enough to let the connection
353 be properly closed if needed when closing the connection (in case
354 of detach or error), if we reopen it too quickly, it seems there
355 are some events queued in the kernel concerning the "old"
356 connection/remote_desc which are discovered with poll or select on
357 the "new" connection/remote_desc. We bypass this by waiting some
358 time to let a proper cleanup to be donex */
sync_gdb_connection(void)359 void sync_gdb_connection(void)
360 {
361 VG_(poll)(0, 0, 100);
362 }
363
364 static
ppFinishReason(FinishReason reason)365 char * ppFinishReason (FinishReason reason)
366 {
367 switch (reason) {
368 case orderly_finish: return "orderly_finish";
369 case reset_after_error: return "reset_after_error";
370 case reset_after_fork: return "reset_after_fork";
371 default: vg_assert (0);
372 }
373 }
374
remote_finish(FinishReason reason)375 void remote_finish (FinishReason reason)
376 {
377 dlog(1, "remote_finish (reason %s) %d %d\n",
378 ppFinishReason(reason), remote_desc, write_remote_desc);
379 reset_valgrind_sink(ppFinishReason(reason));
380 if (write_remote_desc != INVALID_DESCRIPTOR)
381 VG_(close) (write_remote_desc);
382 write_remote_desc = INVALID_DESCRIPTOR;
383 if (remote_desc != INVALID_DESCRIPTOR) {
384 remote_desc_pollfdread_activity.fd = INVALID_DESCRIPTOR;
385 remote_desc_pollfdread_activity.events = 0;
386 remote_desc_pollfdread_activity.revents = 0;
387 VG_(close) (remote_desc);
388 }
389 remote_desc = INVALID_DESCRIPTOR;
390 noack_mode = False;
391
392 /* ensure the child will create its own FIFOs */
393 if (reason == reset_after_fork)
394 mknod_done = 0;
395
396 if (reason == reset_after_error)
397 sync_gdb_connection();
398 }
399
400 /* orderly close, cleans up everything */
remote_close(void)401 void remote_close (void)
402 {
403 const int pid = VG_(getpid)();
404 remote_finish(orderly_finish);
405 if (pid == pid_from_to_creator) {
406 dlog(1, "unlinking\n %s\n %s\n %s\n",
407 from_gdb, to_gdb, shared_mem);
408 if (VG_(unlink) (from_gdb) == -1)
409 warning ("could not unlink %s\n", from_gdb);
410 if (VG_(unlink) (to_gdb) == -1)
411 warning ("could not unlink %s\n", to_gdb);
412 if (VG_(unlink) (shared_mem) == -1)
413 warning ("could not unlink %s\n", shared_mem);
414 }
415 else {
416 dlog(1, "not creator => not unlinking %s and %s\n", from_gdb, to_gdb);
417 }
418 free (from_gdb);
419 free (to_gdb);
420 }
421
remote_connected(void)422 Bool remote_connected(void)
423 {
424 return write_remote_desc != INVALID_DESCRIPTOR;
425 }
426
427 /* cleanup after an error detected by poll_cond */
428 static
error_poll_cond(void)429 void error_poll_cond(void)
430 {
431 /* if we will close the connection, we assume either that
432 all characters have been seen or that they will be dropped. */
433 shared->seen_by_valgrind = shared->written_by_vgdb;
434 remote_finish(reset_after_error);
435 }
436
437 /* remote_desc_activity might be used at high frequency if the user
438 gives a small value to --vgdb-poll. So, the function avoids
439 doing repetitively system calls by rather looking at the
440 counter values maintained in shared memory by vgdb. */
remote_desc_activity(char * msg)441 int remote_desc_activity(char *msg)
442 {
443 int ret;
444 const int looking_at = shared->written_by_vgdb;
445 if (shared->seen_by_valgrind == looking_at)
446 // if (last_looked_cntr == looking_at)
447 return 0;
448 if (remote_desc == INVALID_DESCRIPTOR)
449 return 0;
450
451 /* poll the remote desc */
452 remote_desc_pollfdread_activity.revents = 0;
453 ret = VG_(poll) (&remote_desc_pollfdread_activity, 1, 0);
454 if (ret && poll_cond(remote_desc_pollfdread_activity.revents)) {
455 dlog(1, "POLLcond %d remote_desc_pollfdread %d\n",
456 remote_desc_pollfdread_activity.revents, remote_desc);
457 error_poll_cond();
458 ret = 2;
459 }
460 dlog(1,
461 "remote_desc_activity %s %d last_looked_cntr %d looking_at %d"
462 " shared->written_by_vgdb %d shared->seen_by_valgrind %d"
463 " ret %d\n",
464 msg, remote_desc, last_looked_cntr, looking_at,
465 shared->written_by_vgdb, shared->seen_by_valgrind,
466 ret);
467 /* if no error from poll, indicate we have "seen" up to looking_at */
468 if (ret != 2)
469 last_looked_cntr = looking_at;
470 return ret;
471 }
472
473 /* Convert hex digit A to a number. */
474
475 static
fromhex(int a)476 int fromhex (int a)
477 {
478 if (a >= '0' && a <= '9')
479 return a - '0';
480 else if (a >= 'a' && a <= 'f')
481 return a - 'a' + 10;
482 else
483 error ("Reply contains invalid hex digit 0x%x\n", a);
484 return 0;
485 }
486
unhexify(char * bin,const char * hex,int count)487 int unhexify (char *bin, const char *hex, int count)
488 {
489 int i;
490
491 for (i = 0; i < count; i++) {
492 if (hex[0] == 0 || hex[1] == 0) {
493 /* Hex string is short, or of uneven length.
494 Return the count that has been converted so far. */
495 return i;
496 }
497 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
498 hex += 2;
499 }
500 return i;
501 }
502
decode_address(CORE_ADDR * addrp,const char * start,int len)503 void decode_address (CORE_ADDR *addrp, const char *start, int len)
504 {
505 CORE_ADDR addr;
506 char ch;
507 int i;
508
509 addr = 0;
510 for (i = 0; i < len; i++) {
511 ch = start[i];
512 addr = addr << 4;
513 addr = addr | (fromhex (ch) & 0x0f);
514 }
515 *addrp = addr;
516 }
517
518 /* Convert number NIB to a hex digit. */
519
520 static
tohex(int nib)521 int tohex (int nib)
522 {
523 if (nib < 10)
524 return '0' + nib;
525 else
526 return 'a' + nib - 10;
527 }
528
hexify(char * hex,const char * bin,int count)529 int hexify (char *hex, const char *bin, int count)
530 {
531 int i;
532
533 /* May use a length, or a nul-terminated string as input. */
534 if (count == 0)
535 count = strlen (bin);
536
537 for (i = 0; i < count; i++) {
538 *hex++ = tohex ((*bin >> 4) & 0xf);
539 *hex++ = tohex (*bin++ & 0xf);
540 }
541 *hex = 0;
542 return i;
543 }
544
545 /* builds an image of bin according to byte order of the architecture
546 Useful for register and int image */
heximage(char * buf,char * bin,int count)547 char* heximage (char *buf, char *bin, int count)
548 {
549 #if defined(VGA_x86) || defined(VGA_amd64)
550 char rev[count];
551 /* note: no need for trailing \0, length is known with count */
552 int i;
553 for (i = 0; i < count; i++)
554 rev[i] = bin[count - i - 1];
555 hexify (buf, rev, count);
556 #else
557 hexify (buf, bin, count);
558 #endif
559 return buf;
560 }
561
C2v(CORE_ADDR addr)562 void* C2v(CORE_ADDR addr)
563 {
564 return (void*) addr;
565 }
566
567
568 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
569 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
570 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
571 (which may be more than *OUT_LEN due to escape characters). The
572 total number of bytes in the output buffer will be at most
573 OUT_MAXLEN. */
574
575 int
remote_escape_output(const gdb_byte * buffer,int len,gdb_byte * out_buf,int * out_len,int out_maxlen)576 remote_escape_output (const gdb_byte *buffer, int len,
577 gdb_byte *out_buf, int *out_len,
578 int out_maxlen)
579 {
580 int input_index, output_index;
581
582 output_index = 0;
583 for (input_index = 0; input_index < len; input_index++) {
584 gdb_byte b = buffer[input_index];
585
586 if (b == '$' || b == '#' || b == '}' || b == '*') {
587 /* These must be escaped. */
588 if (output_index + 2 > out_maxlen)
589 break;
590 out_buf[output_index++] = '}';
591 out_buf[output_index++] = b ^ 0x20;
592 } else {
593 if (output_index + 1 > out_maxlen)
594 break;
595 out_buf[output_index++] = b;
596 }
597 }
598
599 *out_len = input_index;
600 return output_index;
601 }
602
603 /* Convert BUFFER, escaped data LEN bytes long, into binary data
604 in OUT_BUF. Return the number of bytes written to OUT_BUF.
605 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
606
607 This function reverses remote_escape_output. It allows more
608 escaped characters than that function does, in particular because
609 '*' must be escaped to avoid the run-length encoding processing
610 in reading packets. */
611
612 static
remote_unescape_input(const gdb_byte * buffer,int len,gdb_byte * out_buf,int out_maxlen)613 int remote_unescape_input (const gdb_byte *buffer, int len,
614 gdb_byte *out_buf, int out_maxlen)
615 {
616 int input_index, output_index;
617 int escaped;
618
619 output_index = 0;
620 escaped = 0;
621 for (input_index = 0; input_index < len; input_index++) {
622 gdb_byte b = buffer[input_index];
623
624 if (output_index + 1 > out_maxlen)
625 error ("Received too much data (len %d) from the target.\n", len);
626
627 if (escaped) {
628 out_buf[output_index++] = b ^ 0x20;
629 escaped = 0;
630 } else if (b == '}') {
631 escaped = 1;
632 } else {
633 out_buf[output_index++] = b;
634 }
635 }
636
637 if (escaped)
638 error ("Unmatched escape character in target response.\n");
639
640 return output_index;
641 }
642
643 /* Look for a sequence of characters which can be run-length encoded.
644 If there are any, update *CSUM and *P. Otherwise, output the
645 single character. Return the number of characters consumed. */
646
647 static
try_rle(char * buf,int remaining,unsigned char * csum,char ** p)648 int try_rle (char *buf, int remaining, unsigned char *csum, char **p)
649 {
650 int n;
651
652 /* Always output the character. */
653 *csum += buf[0];
654 *(*p)++ = buf[0];
655
656 /* Don't go past '~'. */
657 if (remaining > 97)
658 remaining = 97;
659
660 for (n = 1; n < remaining; n++)
661 if (buf[n] != buf[0])
662 break;
663
664 /* N is the index of the first character not the same as buf[0].
665 buf[0] is counted twice, so by decrementing N, we get the number
666 of characters the RLE sequence will replace. */
667 n--;
668
669 if (n < 3)
670 return 1;
671
672 /* Skip the frame characters. The manual says to skip '+' and '-'
673 also, but there's no reason to. Unfortunately these two unusable
674 characters double the encoded length of a four byte zero
675 value. */
676 while (n + 29 == '$' || n + 29 == '#')
677 n--;
678
679 *csum += '*';
680 *(*p)++ = '*';
681 *csum += n + 29;
682 *(*p)++ = n + 29;
683
684 return n + 1;
685 }
686
687 /* Send a packet to the remote machine, with error checking.
688 The data of the packet is in BUF, and the length of the
689 packet is in CNT. Returns >= 0 on success, -1 otherwise. */
690
putpkt_binary(char * buf,int cnt)691 int putpkt_binary (char *buf, int cnt)
692 {
693 int i;
694 unsigned char csum = 0;
695 char *buf2;
696 char *p;
697 int cc;
698
699 buf2 = malloc (PBUFSIZ);
700
701 /* Copy the packet into buffer BUF2, encapsulating it
702 and giving it a checksum. */
703
704 p = buf2;
705 *p++ = '$';
706
707 for (i = 0; i < cnt;)
708 i += try_rle (buf + i, cnt - i, &csum, &p);
709
710 *p++ = '#';
711 *p++ = tohex ((csum >> 4) & 0xf);
712 *p++ = tohex (csum & 0xf);
713
714 *p = '\0';
715
716 /* we might have to write a pkt when out FIFO not yet/anymore opened */
717 if (!ensure_write_remote_desc()) {
718 warning ("putpkt(write) error: no write_remote_desc\n");
719 return -1;
720 }
721
722 /* Send it once (noack_mode)
723 or send it over and over until we get a positive ack. */
724
725 do {
726 if (VG_(write) (write_remote_desc, buf2, p - buf2) != p - buf2) {
727 warning ("putpkt(write) error\n");
728 return -1;
729 }
730
731 if (noack_mode)
732 dlog(1, "putpkt (\"%s\"); [no ack]\n", buf2);
733 else
734 dlog(1,"putpkt (\"%s\"); [looking for ack]\n", buf2);
735
736 if (noack_mode)
737 break;
738
739 cc = readchar (1);
740 if (cc > 0)
741 dlog(1, "[received '%c' (0x%x)]\n", cc, cc);
742
743 if (cc <= 0) {
744 if (cc == 0)
745 dlog(1, "putpkt(read): Got EOF\n");
746 else
747 warning ("putpkt(read) error\n");
748
749 free (buf2);
750 return -1;
751 }
752
753 /* Check for an input interrupt while we're here. */
754 if (cc == '\003')
755 dlog(1, "Received 0x03 character (SIGINT)\n");
756 }
757 while (cc != '+');
758
759 free (buf2);
760 return 1; /* Success! */
761 }
762
763 /* Send a packet to the remote machine, with error checking. The data
764 of the packet is in BUF, and the packet should be a NUL-terminated
765 string. Returns >= 0 on success, -1 otherwise. */
766
putpkt(char * buf)767 int putpkt (char *buf)
768 {
769 return putpkt_binary (buf, strlen (buf));
770 }
771
monitor_output(char * s)772 void monitor_output (char *s)
773 {
774 const int len = strlen(s);
775 char *buf = malloc(1 + 2*len + 1);
776
777 buf[0] = 'O';
778 hexify(buf+1, s, len);
779 if (putpkt (buf) < 0) {
780 /* We probably have lost the connection with vgdb. */
781 reset_valgrind_sink("Error writing monitor output");
782 /* write again after reset */
783 VG_(printf) ("%s", s);
784 }
785
786 free (buf);
787 }
788
789 /* Returns next char from remote GDB. -1 if error. */
790 /* if single, only one character maximum can be read with
791 read system call. Otherwise, when reading an ack character
792 we might pile up the next gdb command in the static buf.
793 The read loop is then blocked in poll till gdb times out. */
794 static
readchar(int single)795 int readchar (int single)
796 {
797 static unsigned char buf[PBUFSIZ];
798 static int bufcnt = 0;
799 static unsigned char *bufp;
800 int ret;
801
802 if (bufcnt-- > 0)
803 return *bufp++;
804
805 if (remote_desc == INVALID_DESCRIPTOR)
806 return -1;
807
808 /* No characters available in buf =>
809 wait for some characters to arrive */
810 remote_desc_pollfdread_activity.revents = 0;
811 ret = VG_(poll)(&remote_desc_pollfdread_activity, 1, -1);
812 if (ret != 1) {
813 dlog(0, "readchar: poll got %d\n", ret);
814 return -1;
815 }
816 if (single)
817 bufcnt = VG_(read) (remote_desc, buf, 1);
818 else
819 bufcnt = VG_(read) (remote_desc, buf, sizeof (buf));
820
821 if (bufcnt <= 0) {
822 if (bufcnt == 0)
823 dlog (1, "readchar: Got EOF\n");
824 else
825 warning ("readchar read error\n");
826
827 return -1;
828 }
829
830 shared->seen_by_valgrind += bufcnt;
831
832 /* If we have received a character and we do not yet have a
833 connection, we better open our "write" fifo to let vgdb open its
834 read fifo side */
835 if (write_remote_desc == INVALID_DESCRIPTOR
836 && !ensure_write_remote_desc()) {
837 dlog(1, "reachar: write_remote_desc could not be created");
838 }
839
840 bufp = buf;
841 bufcnt--;
842
843 if (poll_cond(remote_desc_pollfdread_activity.revents)) {
844 dlog(1, "readchar: POLLcond got %d\n",
845 remote_desc_pollfdread_activity.revents);
846 error_poll_cond();
847 }
848
849 return *bufp++;
850 }
851
852
853 /* Read a packet from the remote machine, with error checking,
854 and store it in BUF. Returns length of packet, or negative if error. */
855
getpkt(char * buf)856 int getpkt (char *buf)
857 {
858 char *bp;
859 unsigned char csum, c1, c2;
860 int c;
861
862 while (1) {
863 csum = 0;
864
865 while (1) {
866 c = readchar (0);
867 if (c == '$')
868 break;
869 dlog(1, "[getpkt: discarding char '%c']\n", c);
870 if (c < 0)
871 return -1;
872 }
873
874 bp = buf;
875 while (1) {
876 c = readchar (0);
877 if (c < 0)
878 return -1;
879 if (c == '#')
880 break;
881 *bp++ = c;
882 csum += c;
883 }
884 *bp = 0;
885
886 c1 = fromhex (readchar (0));
887 c2 = fromhex (readchar (0));
888
889 if (csum == (c1 << 4) + c2)
890 break;
891
892 dlog (0, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
893 (c1 << 4) + c2, csum, buf);
894 if (!ensure_write_remote_desc()) {
895 dlog(1, "getpkt(write nack) no write_remote_desc");
896 }
897 VG_(write) (write_remote_desc, "-", 1);
898 }
899
900 if (noack_mode)
901 dlog(1, "getpkt (\"%s\"); [no ack] \n", buf);
902 else
903 dlog(1, "getpkt (\"%s\"); [sending ack] \n", buf);
904
905 if (!noack_mode) {
906 if (!ensure_write_remote_desc()) {
907 dlog(1, "getpkt(write ack) no write_remote_desc");
908 }
909 VG_(write) (write_remote_desc, "+", 1);
910 dlog(1, "[sent ack]\n");
911 }
912
913 return bp - buf;
914 }
915
write_ok(char * buf)916 void write_ok (char *buf)
917 {
918 buf[0] = 'O';
919 buf[1] = 'K';
920 buf[2] = '\0';
921 }
922
write_enn(char * buf)923 void write_enn (char *buf)
924 {
925 /* Some day, we should define the meanings of the error codes... */
926 buf[0] = 'E';
927 buf[1] = '0';
928 buf[2] = '1';
929 buf[3] = '\0';
930 }
931
convert_int_to_ascii(unsigned char * from,char * to,int n)932 void convert_int_to_ascii (unsigned char *from, char *to, int n)
933 {
934 int nib;
935 int ch;
936 while (n--) {
937 ch = *from++;
938 nib = ((ch & 0xf0) >> 4) & 0x0f;
939 *to++ = tohex (nib);
940 nib = ch & 0x0f;
941 *to++ = tohex (nib);
942 }
943 *to++ = 0;
944 }
945
946
convert_ascii_to_int(char * from,unsigned char * to,int n)947 void convert_ascii_to_int (char *from, unsigned char *to, int n)
948 {
949 int nib1, nib2;
950 while (n--) {
951 nib1 = fromhex (*from++);
952 nib2 = fromhex (*from++);
953 *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f);
954 }
955 }
956
957 static
outreg(int regno,char * buf)958 char * outreg (int regno, char *buf)
959 {
960 if ((regno >> 12) != 0)
961 *buf++ = tohex ((regno >> 12) & 0xf);
962 if ((regno >> 8) != 0)
963 *buf++ = tohex ((regno >> 8) & 0xf);
964 *buf++ = tohex ((regno >> 4) & 0xf);
965 *buf++ = tohex (regno & 0xf);
966 *buf++ = ':';
967 collect_register_as_string (regno, buf);
968 buf += 2 * register_size (regno);
969 *buf++ = ';';
970
971 return buf;
972 }
973
prepare_resume_reply(char * buf,char status,unsigned char sig)974 void prepare_resume_reply (char *buf, char status, unsigned char sig)
975 {
976 int nib;
977
978 *buf++ = status;
979
980 nib = ((sig & 0xf0) >> 4);
981 *buf++ = tohex (nib);
982 nib = sig & 0x0f;
983 *buf++ = tohex (nib);
984
985 if (status == 'T') {
986 const char **regp = gdbserver_expedite_regs;
987
988 if (valgrind_stopped_by_watchpoint()) {
989 CORE_ADDR addr;
990 int i;
991
992 strncpy (buf, "watch:", 6);
993 buf += 6;
994
995 addr = valgrind_stopped_data_address ();
996
997 /* Convert each byte of the address into two hexadecimal chars.
998 Note that we take sizeof (void *) instead of sizeof (addr);
999 this is to avoid sending a 64-bit address to a 32-bit GDB. */
1000 for (i = sizeof (void *) * 2; i > 0; i--) {
1001 *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf);
1002 }
1003 *buf++ = ';';
1004 }
1005
1006 while (*regp) {
1007 buf = outreg (find_regno (*regp), buf);
1008 regp ++;
1009 }
1010
1011 {
1012 unsigned int gdb_id_from_wait;
1013
1014 /* FIXME right place to set this? */
1015 thread_from_wait =
1016 ((struct inferior_list_entry *)current_inferior)->id;
1017 gdb_id_from_wait = thread_to_gdb_id (current_inferior);
1018
1019 dlog(1, "Writing resume reply for %ld\n", thread_from_wait);
1020 /* This if (1) ought to be unnecessary. But remote_wait in GDB
1021 will claim this event belongs to inferior_ptid if we do not
1022 specify a thread, and there's no way for gdbserver to know
1023 what inferior_ptid is. */
1024 if (1 || old_thread_from_wait != thread_from_wait) {
1025 general_thread = thread_from_wait;
1026 VG_(sprintf) (buf, "thread:%x;", gdb_id_from_wait);
1027 buf += strlen (buf);
1028 old_thread_from_wait = thread_from_wait;
1029 }
1030 }
1031 }
1032 /* For W and X, we're done. */
1033 *buf++ = 0;
1034 }
1035
decode_m_packet(char * from,CORE_ADDR * mem_addr_ptr,unsigned int * len_ptr)1036 void decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
1037 {
1038 int i = 0, j = 0;
1039 char ch;
1040 *mem_addr_ptr = *len_ptr = 0;
1041
1042 while ((ch = from[i++]) != ',') {
1043 *mem_addr_ptr = *mem_addr_ptr << 4;
1044 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1045 }
1046
1047 for (j = 0; j < 4; j++) {
1048 if ((ch = from[i++]) == 0)
1049 break;
1050 *len_ptr = *len_ptr << 4;
1051 *len_ptr |= fromhex (ch) & 0x0f;
1052 }
1053 }
1054
decode_M_packet(char * from,CORE_ADDR * mem_addr_ptr,unsigned int * len_ptr,unsigned char * to)1055 void decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
1056 unsigned char *to)
1057 {
1058 int i = 0;
1059 char ch;
1060 *mem_addr_ptr = *len_ptr = 0;
1061
1062 while ((ch = from[i++]) != ',') {
1063 *mem_addr_ptr = *mem_addr_ptr << 4;
1064 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1065 }
1066
1067 while ((ch = from[i++]) != ':') {
1068 *len_ptr = *len_ptr << 4;
1069 *len_ptr |= fromhex (ch) & 0x0f;
1070 }
1071
1072 convert_ascii_to_int (&from[i++], to, *len_ptr);
1073 }
1074
decode_X_packet(char * from,int packet_len,CORE_ADDR * mem_addr_ptr,unsigned int * len_ptr,unsigned char * to)1075 int decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1076 unsigned int *len_ptr, unsigned char *to)
1077 {
1078 int i = 0;
1079 char ch;
1080 *mem_addr_ptr = *len_ptr = 0;
1081
1082 while ((ch = from[i++]) != ',') {
1083 *mem_addr_ptr = *mem_addr_ptr << 4;
1084 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1085 }
1086
1087 while ((ch = from[i++]) != ':') {
1088 *len_ptr = *len_ptr << 4;
1089 *len_ptr |= fromhex (ch) & 0x0f;
1090 }
1091
1092 if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1093 to, *len_ptr) != *len_ptr)
1094 return -1;
1095
1096 return 0;
1097 }
1098
1099
1100 /* Return the path prefix for the named pipes (FIFOs) used by vgdb/gdb
1101 to communicate with valgrind */
1102 HChar *
VG_(vgdb_prefix_default)1103 VG_(vgdb_prefix_default)(void)
1104 {
1105 static HChar *prefix;
1106
1107 if (prefix == NULL) {
1108 const HChar *tmpdir = VG_(tmpdir)();
1109 prefix = malloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
1110 strcpy(prefix, tmpdir);
1111 strcat(prefix, "/vgdb-pipe");
1112 }
1113 return prefix;
1114 }
1115