]> granicus.if.org Git - strace/blob - util.c
Fix printing of time_t values set in the distant future
[strace] / util.c
1 /*
2  * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
3  * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
4  * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
5  * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl>
6  * Copyright (c) 1999 IBM Deutschland Entwicklung GmbH, IBM Corporation
7  *                     Linux for s390 port by D.J. Barrow
8  *                    <barrow_dj@mail.yahoo.com,djbarrow@de.ibm.com>
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include "defs.h"
35 #include <sys/user.h>
36 #include <sys/param.h>
37 #include <fcntl.h>
38 #if HAVE_SYS_XATTR_H
39 # include <sys/xattr.h>
40 #endif
41 #include <sys/uio.h>
42
43 #if defined(IA64)
44 # include <asm/ptrace_offsets.h>
45 # include <asm/rse.h>
46 #endif
47
48 #ifdef HAVE_SYS_REG_H
49 # include <sys/reg.h>
50 #endif
51
52 #ifdef HAVE_LINUX_PTRACE_H
53 # undef PTRACE_SYSCALL
54 # ifdef HAVE_STRUCT_IA64_FPREG
55 #  define ia64_fpreg XXX_ia64_fpreg
56 # endif
57 # ifdef HAVE_STRUCT_PT_ALL_USER_REGS
58 #  define pt_all_user_regs XXX_pt_all_user_regs
59 # endif
60 # ifdef HAVE_STRUCT_PTRACE_PEEKSIGINFO_ARGS
61 #  define ptrace_peeksiginfo_args XXX_ptrace_peeksiginfo_args
62 # endif
63 # include <linux/ptrace.h>
64 # undef ptrace_peeksiginfo_args
65 # undef ia64_fpreg
66 # undef pt_all_user_regs
67 #endif
68
69 int
70 string_to_uint(const char *str)
71 {
72         char *error;
73         long value;
74
75         if (!*str)
76                 return -1;
77         errno = 0;
78         value = strtol(str, &error, 10);
79         if (errno || *error || value < 0 || (long)(int)value != value)
80                 return -1;
81         return (int)value;
82 }
83
84 int
85 tv_nz(const struct timeval *a)
86 {
87         return a->tv_sec || a->tv_usec;
88 }
89
90 int
91 tv_cmp(const struct timeval *a, const struct timeval *b)
92 {
93         if (a->tv_sec < b->tv_sec
94             || (a->tv_sec == b->tv_sec && a->tv_usec < b->tv_usec))
95                 return -1;
96         if (a->tv_sec > b->tv_sec
97             || (a->tv_sec == b->tv_sec && a->tv_usec > b->tv_usec))
98                 return 1;
99         return 0;
100 }
101
102 double
103 tv_float(const struct timeval *tv)
104 {
105         return tv->tv_sec + tv->tv_usec/1000000.0;
106 }
107
108 void
109 tv_add(struct timeval *tv, const struct timeval *a, const struct timeval *b)
110 {
111         tv->tv_sec = a->tv_sec + b->tv_sec;
112         tv->tv_usec = a->tv_usec + b->tv_usec;
113         if (tv->tv_usec >= 1000000) {
114                 tv->tv_sec++;
115                 tv->tv_usec -= 1000000;
116         }
117 }
118
119 void
120 tv_sub(struct timeval *tv, const struct timeval *a, const struct timeval *b)
121 {
122         tv->tv_sec = a->tv_sec - b->tv_sec;
123         tv->tv_usec = a->tv_usec - b->tv_usec;
124         if (((long) tv->tv_usec) < 0) {
125                 tv->tv_sec--;
126                 tv->tv_usec += 1000000;
127         }
128 }
129
130 void
131 tv_div(struct timeval *tv, const struct timeval *a, int n)
132 {
133         tv->tv_usec = (a->tv_sec % n * 1000000 + a->tv_usec + n / 2) / n;
134         tv->tv_sec = a->tv_sec / n + tv->tv_usec / 1000000;
135         tv->tv_usec %= 1000000;
136 }
137
138 void
139 tv_mul(struct timeval *tv, const struct timeval *a, int n)
140 {
141         tv->tv_usec = a->tv_usec * n;
142         tv->tv_sec = a->tv_sec * n + tv->tv_usec / 1000000;
143         tv->tv_usec %= 1000000;
144 }
145
146 const char *
147 xlookup(const struct xlat *xlat, const unsigned int val)
148 {
149         for (; xlat->str != NULL; xlat++)
150                 if (xlat->val == val)
151                         return xlat->str;
152         return NULL;
153 }
154
155 static int
156 xlat_bsearch_compare(const void *a, const void *b)
157 {
158         const unsigned int val1 = (const unsigned long) a;
159         const unsigned int val2 = ((const struct xlat *) b)->val;
160         return (val1 > val2) ? 1 : (val1 < val2) ? -1 : 0;
161 }
162
163 const char *
164 xlat_search(const struct xlat *xlat, const size_t nmemb, const unsigned int val)
165 {
166         const struct xlat *e =
167                 bsearch((const void*) (const unsigned long) val,
168                         xlat, nmemb, sizeof(*xlat), xlat_bsearch_compare);
169
170         return e ? e->str : NULL;
171 }
172
173 #if !defined HAVE_STPCPY
174 char *
175 stpcpy(char *dst, const char *src)
176 {
177         while ((*dst = *src++) != '\0')
178                 dst++;
179         return dst;
180 }
181 #endif
182
183 /* Find a next bit which is set.
184  * Starts testing at cur_bit.
185  * Returns -1 if no more bits are set.
186  *
187  * We never touch bytes we don't need to.
188  * On big-endian, array is assumed to consist of
189  * current_wordsize wide words: for example, is current_wordsize is 4,
190  * the bytes are walked in 3,2,1,0, 7,6,5,4, 11,10,9,8 ... sequence.
191  * On little-endian machines, word size is immaterial.
192  */
193 int
194 next_set_bit(const void *bit_array, unsigned cur_bit, unsigned size_bits)
195 {
196         const unsigned endian = 1;
197         int little_endian = *(char*)&endian;
198
199         const uint8_t *array = bit_array;
200         unsigned pos = cur_bit / 8;
201         unsigned pos_xor_mask = little_endian ? 0 : current_wordsize-1;
202
203         for (;;) {
204                 uint8_t bitmask;
205                 uint8_t cur_byte;
206
207                 if (cur_bit >= size_bits)
208                         return -1;
209                 cur_byte = array[pos ^ pos_xor_mask];
210                 if (cur_byte == 0) {
211                         cur_bit = (cur_bit + 8) & (-8);
212                         pos++;
213                         continue;
214                 }
215                 bitmask = 1 << (cur_bit & 7);
216                 for (;;) {
217                         if (cur_byte & bitmask)
218                                 return cur_bit;
219                         cur_bit++;
220                         if (cur_bit >= size_bits)
221                                 return -1;
222                         bitmask <<= 1;
223                         /* This check *can't be* optimized out: */
224                         if (bitmask == 0)
225                                 break;
226                 }
227                 pos++;
228         }
229 }
230 /*
231  * Print entry in struct xlat table, if there.
232  */
233 void
234 printxval(const struct xlat *xlat, const unsigned int val, const char *dflt)
235 {
236         const char *str = xlookup(xlat, val);
237
238         if (str)
239                 tprints(str);
240         else
241                 tprintf("%#x /* %s */", val, dflt);
242 }
243
244 /*
245  * Print 64bit argument at position arg_no and return the index of the next
246  * argument.
247  */
248 int
249 printllval(struct tcb *tcp, const char *format, int arg_no)
250 {
251 #if SIZEOF_LONG > 4 && SIZEOF_LONG == SIZEOF_LONG_LONG
252 # if SUPPORTED_PERSONALITIES > 1
253         if (current_wordsize > 4) {
254 # endif
255                 tprintf(format, tcp->u_arg[arg_no]);
256                 arg_no++;
257 # if SUPPORTED_PERSONALITIES > 1
258         } else {
259 #  if defined(AARCH64) || defined(POWERPC64)
260                 /* Align arg_no to the next even number. */
261                 arg_no = (arg_no + 1) & 0xe;
262 #  endif
263                 tprintf(format, LONG_LONG(tcp->u_arg[arg_no], tcp->u_arg[arg_no + 1]));
264                 arg_no += 2;
265         }
266 # endif /* SUPPORTED_PERSONALITIES */
267 #elif SIZEOF_LONG > 4
268 #  error Unsupported configuration: SIZEOF_LONG > 4 && SIZEOF_LONG_LONG > SIZEOF_LONG
269 #elif defined LINUX_MIPSN32
270         tprintf(format, tcp->ext_arg[arg_no]);
271         arg_no++;
272 #elif defined X32
273         if (current_personality == 0) {
274                 tprintf(format, tcp->ext_arg[arg_no]);
275                 arg_no++;
276         } else {
277                 tprintf(format, LONG_LONG(tcp->u_arg[arg_no], tcp->u_arg[arg_no + 1]));
278                 arg_no += 2;
279         }
280 #else
281 # if defined __ARM_EABI__ || \
282      defined LINUX_MIPSO32 || \
283      defined POWERPC || \
284      defined XTENSA
285         /* Align arg_no to the next even number. */
286         arg_no = (arg_no + 1) & 0xe;
287 # endif
288         tprintf(format, LONG_LONG(tcp->u_arg[arg_no], tcp->u_arg[arg_no + 1]));
289         arg_no += 2;
290 #endif
291
292         return arg_no;
293 }
294
295 /*
296  * Interpret `xlat' as an array of flags
297  * print the entries whose bits are on in `flags'
298  * return # of flags printed.
299  */
300 void
301 addflags(const struct xlat *xlat, int flags)
302 {
303         for (; xlat->str; xlat++) {
304                 if (xlat->val && (flags & xlat->val) == xlat->val) {
305                         tprintf("|%s", xlat->str);
306                         flags &= ~xlat->val;
307                 }
308         }
309         if (flags) {
310                 tprintf("|%#x", flags);
311         }
312 }
313
314 /*
315  * Interpret `xlat' as an array of flags.
316  * Print to static string the entries whose bits are on in `flags'
317  * Return static string.
318  */
319 const char *
320 sprintflags(const char *prefix, const struct xlat *xlat, int flags)
321 {
322         static char outstr[1024];
323         char *outptr;
324         int found = 0;
325
326         outptr = stpcpy(outstr, prefix);
327
328         for (; xlat->str; xlat++) {
329                 if ((flags & xlat->val) == xlat->val) {
330                         if (found)
331                                 *outptr++ = '|';
332                         outptr = stpcpy(outptr, xlat->str);
333                         found = 1;
334                         flags &= ~xlat->val;
335                         if (!flags)
336                                 break;
337                 }
338         }
339         if (flags) {
340                 if (found)
341                         *outptr++ = '|';
342                 outptr += sprintf(outptr, "%#x", flags);
343         }
344
345         return outstr;
346 }
347
348 int
349 printflags(const struct xlat *xlat, int flags, const char *dflt)
350 {
351         int n;
352         const char *sep;
353
354         if (flags == 0 && xlat->val == 0) {
355                 tprints(xlat->str);
356                 return 1;
357         }
358
359         sep = "";
360         for (n = 0; xlat->str; xlat++) {
361                 if (xlat->val && (flags & xlat->val) == xlat->val) {
362                         tprintf("%s%s", sep, xlat->str);
363                         flags &= ~xlat->val;
364                         sep = "|";
365                         n++;
366                 }
367         }
368
369         if (n) {
370                 if (flags) {
371                         tprintf("%s%#x", sep, flags);
372                         n++;
373                 }
374         } else {
375                 if (flags) {
376                         tprintf("%#x", flags);
377                         if (dflt)
378                                 tprintf(" /* %s */", dflt);
379                 } else {
380                         if (dflt)
381                                 tprints("0");
382                 }
383         }
384
385         return n;
386 }
387
388 void
389 printnum(struct tcb *tcp, long addr, const char *fmt)
390 {
391         long num;
392
393         if (!addr) {
394                 tprints("NULL");
395                 return;
396         }
397         if (umove(tcp, addr, &num) < 0) {
398                 tprintf("%#lx", addr);
399                 return;
400         }
401         tprints("[");
402         tprintf(fmt, num);
403         tprints("]");
404 }
405
406 void
407 printnum_int(struct tcb *tcp, long addr, const char *fmt)
408 {
409         int num;
410
411         if (!addr) {
412                 tprints("NULL");
413                 return;
414         }
415         if (umove(tcp, addr, &num) < 0) {
416                 tprintf("%#lx", addr);
417                 return;
418         }
419         tprints("[");
420         tprintf(fmt, num);
421         tprints("]");
422 }
423
424 const char *
425 sprinttime(time_t t)
426 {
427         struct tm *tmp;
428         static char buf[sizeof(int) * 3 * 6];
429
430         if (t == 0) {
431                 strcpy(buf, "0");
432                 return buf;
433         }
434         tmp = localtime(&t);
435         if (tmp)
436                 snprintf(buf, sizeof buf, "%02d/%02d/%02d-%02d:%02d:%02d",
437                         tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday,
438                         tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
439         else
440                 snprintf(buf, sizeof buf, "%lu", (unsigned long) t);
441
442         return buf;
443 }
444
445 static char *
446 getfdproto(struct tcb *tcp, int fd, char *buf, unsigned bufsize)
447 {
448 #if HAVE_SYS_XATTR_H
449         ssize_t r;
450         char path[sizeof("/proc/%u/fd/%u") + 2 * sizeof(int)*3];
451
452         if (fd < 0)
453                 return NULL;
454
455         sprintf(path, "/proc/%u/fd/%u", tcp->pid, fd);
456         r = getxattr(path, "system.sockprotoname", buf, bufsize - 1);
457         if (r <= 0)
458                 return NULL;
459         else {
460                 /*
461                  * This is a protection for the case when the kernel
462                  * side does not append a null byte to the buffer.
463                  */
464                 buf[r] = '\0';
465                 return buf;
466         }
467 #else
468         return NULL;
469 #endif
470 }
471
472 void
473 printfd(struct tcb *tcp, int fd)
474 {
475         char path[PATH_MAX + 1];
476         if (show_fd_path && getfdpath(tcp, fd, path, sizeof(path)) >= 0) {
477                 static const char socket_prefix[] = "socket:[";
478                 const size_t socket_prefix_len = sizeof(socket_prefix) - 1;
479                 size_t path_len;
480
481                 if (show_fd_path > 1 &&
482                     strncmp(path, socket_prefix, socket_prefix_len) == 0 &&
483                     path[(path_len = strlen(path)) - 1] == ']') {
484                         unsigned long inodenr;
485 #define PROTO_NAME_LEN 32
486                         char proto_buf[PROTO_NAME_LEN];
487                         const char *proto =
488                                 getfdproto(tcp, fd, proto_buf, PROTO_NAME_LEN);
489                         inodenr = strtoul(path + socket_prefix_len, NULL, 10);
490                         tprintf("%d<", fd);
491                         if (!print_sockaddr_by_inode(inodenr, proto)) {
492                                 if (proto)
493                                         tprintf("%s:[%lu]", proto, inodenr);
494                                 else
495                                         tprints(path);
496                         }
497                         tprints(">");
498                 } else {
499                         tprintf("%d<%s>", fd, path);
500                 }
501         } else
502                 tprintf("%d", fd);
503 }
504
505 /*
506  * Quote string `instr' of length `size'
507  * Write up to (3 + `size' * 4) bytes to `outstr' buffer.
508  * If `len' is -1, treat `instr' as a NUL-terminated string
509  * and quote at most (`size' - 1) bytes.
510  *
511  * Returns 0 if len == -1 and NUL was seen, 1 otherwise.
512  * Note that if len >= 0, always returns 1.
513  */
514 int
515 string_quote(const char *instr, char *outstr, long len, int size)
516 {
517         const unsigned char *ustr = (const unsigned char *) instr;
518         char *s = outstr;
519         int usehex, c, i, eol;
520
521         eol = 0x100; /* this can never match a char */
522         if (len == -1) {
523                 size--;
524                 eol = '\0';
525         }
526
527         usehex = 0;
528         if (xflag > 1)
529                 usehex = 1;
530         else if (xflag) {
531                 /* Check for presence of symbol which require
532                    to hex-quote the whole string. */
533                 for (i = 0; i < size; ++i) {
534                         c = ustr[i];
535                         /* Check for NUL-terminated string. */
536                         if (c == eol)
537                                 break;
538
539                         /* Force hex unless c is printable or whitespace */
540                         if (c > 0x7e) {
541                                 usehex = 1;
542                                 break;
543                         }
544                         /* In ASCII isspace is only these chars: "\t\n\v\f\r".
545                          * They happen to have ASCII codes 9,10,11,12,13.
546                          */
547                         if (c < ' ' && (unsigned)(c - 9) >= 5) {
548                                 usehex = 1;
549                                 break;
550                         }
551                 }
552         }
553
554         *s++ = '\"';
555
556         if (usehex) {
557                 /* Hex-quote the whole string. */
558                 for (i = 0; i < size; ++i) {
559                         c = ustr[i];
560                         /* Check for NUL-terminated string. */
561                         if (c == eol)
562                                 goto asciz_ended;
563                         *s++ = '\\';
564                         *s++ = 'x';
565                         *s++ = "0123456789abcdef"[c >> 4];
566                         *s++ = "0123456789abcdef"[c & 0xf];
567                 }
568         } else {
569                 for (i = 0; i < size; ++i) {
570                         c = ustr[i];
571                         /* Check for NUL-terminated string. */
572                         if (c == eol)
573                                 goto asciz_ended;
574                         switch (c) {
575                                 case '\"': case '\\':
576                                         *s++ = '\\';
577                                         *s++ = c;
578                                         break;
579                                 case '\f':
580                                         *s++ = '\\';
581                                         *s++ = 'f';
582                                         break;
583                                 case '\n':
584                                         *s++ = '\\';
585                                         *s++ = 'n';
586                                         break;
587                                 case '\r':
588                                         *s++ = '\\';
589                                         *s++ = 'r';
590                                         break;
591                                 case '\t':
592                                         *s++ = '\\';
593                                         *s++ = 't';
594                                         break;
595                                 case '\v':
596                                         *s++ = '\\';
597                                         *s++ = 'v';
598                                         break;
599                                 default:
600                                         if (c >= ' ' && c <= 0x7e)
601                                                 *s++ = c;
602                                         else {
603                                                 /* Print \octal */
604                                                 *s++ = '\\';
605                                                 if (i + 1 < size
606                                                     && ustr[i + 1] >= '0'
607                                                     && ustr[i + 1] <= '9'
608                                                 ) {
609                                                         /* Print \ooo */
610                                                         *s++ = '0' + (c >> 6);
611                                                         *s++ = '0' + ((c >> 3) & 0x7);
612                                                 } else {
613                                                         /* Print \[[o]o]o */
614                                                         if ((c >> 3) != 0) {
615                                                                 if ((c >> 6) != 0)
616                                                                         *s++ = '0' + (c >> 6);
617                                                                 *s++ = '0' + ((c >> 3) & 0x7);
618                                                         }
619                                                 }
620                                                 *s++ = '0' + (c & 0x7);
621                                         }
622                                         break;
623                         }
624                 }
625         }
626
627         *s++ = '\"';
628         *s = '\0';
629
630         /* Return zero if we printed entire ASCIZ string (didn't truncate it) */
631         if (len == -1 && ustr[i] == '\0') {
632                 /* We didn't see NUL yet (otherwise we'd jump to 'asciz_ended')
633                  * but next char is NUL.
634                  */
635                 return 0;
636         }
637
638         return 1;
639
640  asciz_ended:
641         *s++ = '\"';
642         *s = '\0';
643         /* Return zero: we printed entire ASCIZ string (didn't truncate it) */
644         return 0;
645 }
646
647 /*
648  * Print path string specified by address `addr' and length `n'.
649  * If path length exceeds `n', append `...' to the output.
650  */
651 void
652 printpathn(struct tcb *tcp, long addr, unsigned int n)
653 {
654         char path[PATH_MAX + 1];
655         int nul_seen;
656
657         if (!addr) {
658                 tprints("NULL");
659                 return;
660         }
661
662         /* Cap path length to the path buffer size */
663         if (n > sizeof path - 1)
664                 n = sizeof path - 1;
665
666         /* Fetch one byte more to find out whether path length > n. */
667         nul_seen = umovestr(tcp, addr, n + 1, path);
668         if (nul_seen < 0)
669                 tprintf("%#lx", addr);
670         else {
671                 char *outstr;
672
673                 path[n] = '\0';
674                 n++;
675                 outstr = alloca(4 * n); /* 4*(n-1) + 3 for quotes and NUL */
676                 string_quote(path, outstr, -1, n);
677                 tprints(outstr);
678                 if (!nul_seen)
679                         tprints("...");
680         }
681 }
682
683 void
684 printpath(struct tcb *tcp, long addr)
685 {
686         /* Size must correspond to char path[] size in printpathn */
687         printpathn(tcp, addr, PATH_MAX);
688 }
689
690 /*
691  * Print string specified by address `addr' and length `len'.
692  * If `len' < 0, treat the string as a NUL-terminated string.
693  * If string length exceeds `max_strlen', append `...' to the output.
694  */
695 void
696 printstr(struct tcb *tcp, long addr, long len)
697 {
698         static char *str = NULL;
699         static char *outstr;
700         unsigned int size;
701         int ellipsis;
702
703         if (!addr) {
704                 tprints("NULL");
705                 return;
706         }
707         /* Allocate static buffers if they are not allocated yet. */
708         if (!str) {
709                 unsigned int outstr_size = 4 * max_strlen + /*for quotes and NUL:*/ 3;
710
711                 if (outstr_size / 4 != max_strlen)
712                         die_out_of_memory();
713                 str = malloc(max_strlen + 1);
714                 if (!str)
715                         die_out_of_memory();
716                 outstr = malloc(outstr_size);
717                 if (!outstr)
718                         die_out_of_memory();
719         }
720
721         if (len == -1) {
722                 /*
723                  * Treat as a NUL-terminated string: fetch one byte more
724                  * because string_quote() quotes one byte less.
725                  */
726                 size = max_strlen + 1;
727                 if (umovestr(tcp, addr, size, str) < 0) {
728                         tprintf("%#lx", addr);
729                         return;
730                 }
731         }
732         else {
733                 size = max_strlen;
734                 if (size > (unsigned long)len)
735                         size = (unsigned long)len;
736                 if (umoven(tcp, addr, size, str) < 0) {
737                         tprintf("%#lx", addr);
738                         return;
739                 }
740         }
741
742         /* If string_quote didn't see NUL and (it was supposed to be ASCIZ str
743          * or we were requested to print more than -s NUM chars)...
744          */
745         ellipsis = (string_quote(str, outstr, len, size) &&
746                         (len < 0 || (unsigned long) len > max_strlen));
747
748         tprints(outstr);
749         if (ellipsis)
750                 tprints("...");
751 }
752
753 void
754 dumpiov(struct tcb *tcp, int len, long addr)
755 {
756 #if SUPPORTED_PERSONALITIES > 1
757         union {
758                 struct { u_int32_t base; u_int32_t len; } *iov32;
759                 struct { u_int64_t base; u_int64_t len; } *iov64;
760         } iovu;
761 #define iov iovu.iov64
762 #define sizeof_iov \
763         (current_wordsize == 4 ? sizeof(*iovu.iov32) : sizeof(*iovu.iov64))
764 #define iov_iov_base(i) \
765         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].base : iovu.iov64[i].base)
766 #define iov_iov_len(i) \
767         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].len : iovu.iov64[i].len)
768 #else
769         struct iovec *iov;
770 #define sizeof_iov sizeof(*iov)
771 #define iov_iov_base(i) iov[i].iov_base
772 #define iov_iov_len(i) iov[i].iov_len
773 #endif
774         int i;
775         unsigned size;
776
777         size = sizeof_iov * len;
778         /* Assuming no sane program has millions of iovs */
779         if ((unsigned)len > 1024*1024 /* insane or negative size? */
780             || (iov = malloc(size)) == NULL) {
781                 fprintf(stderr, "Out of memory\n");
782                 return;
783         }
784         if (umoven(tcp, addr, size, (char *) iov) >= 0) {
785                 for (i = 0; i < len; i++) {
786                         /* include the buffer number to make it easy to
787                          * match up the trace with the source */
788                         tprintf(" * %lu bytes in buffer %d\n",
789                                 (unsigned long)iov_iov_len(i), i);
790                         dumpstr(tcp, (long) iov_iov_base(i),
791                                 iov_iov_len(i));
792                 }
793         }
794         free(iov);
795 #undef sizeof_iov
796 #undef iov_iov_base
797 #undef iov_iov_len
798 #undef iov
799 }
800
801 void
802 dumpstr(struct tcb *tcp, long addr, int len)
803 {
804         static int strsize = -1;
805         static unsigned char *str;
806
807         char outbuf[
808                 (
809                         (sizeof(
810                         "xx xx xx xx xx xx xx xx  xx xx xx xx xx xx xx xx  "
811                         "1234567890123456") + /*in case I'm off by few:*/ 4)
812                 /*align to 8 to make memset easier:*/ + 7) & -8
813         ];
814         const unsigned char *src;
815         int i;
816
817         memset(outbuf, ' ', sizeof(outbuf));
818
819         if (strsize < len + 16) {
820                 free(str);
821                 str = malloc(len + 16);
822                 if (!str) {
823                         strsize = -1;
824                         fprintf(stderr, "Out of memory\n");
825                         return;
826                 }
827                 strsize = len + 16;
828         }
829
830         if (umoven(tcp, addr, len, (char *) str) < 0)
831                 return;
832
833         /* Space-pad to 16 bytes */
834         i = len;
835         while (i & 0xf)
836                 str[i++] = ' ';
837
838         i = 0;
839         src = str;
840         while (i < len) {
841                 char *dst = outbuf;
842                 /* Hex dump */
843                 do {
844                         if (i < len) {
845                                 *dst++ = "0123456789abcdef"[*src >> 4];
846                                 *dst++ = "0123456789abcdef"[*src & 0xf];
847                         }
848                         else {
849                                 *dst++ = ' ';
850                                 *dst++ = ' ';
851                         }
852                         dst++; /* space is there by memset */
853                         i++;
854                         if ((i & 7) == 0)
855                                 dst++; /* space is there by memset */
856                         src++;
857                 } while (i & 0xf);
858                 /* ASCII dump */
859                 i -= 16;
860                 src -= 16;
861                 do {
862                         if (*src >= ' ' && *src < 0x7f)
863                                 *dst++ = *src;
864                         else
865                                 *dst++ = '.';
866                         src++;
867                 } while (++i & 0xf);
868                 *dst = '\0';
869                 tprintf(" | %05x  %s |\n", i - 16, outbuf);
870         }
871 }
872
873 #ifdef HAVE_PROCESS_VM_READV
874 /* C library supports this, but the kernel might not. */
875 static bool process_vm_readv_not_supported = 0;
876 #else
877
878 /* Need to do this since process_vm_readv() is not yet available in libc.
879  * When libc is be updated, only "static bool process_vm_readv_not_supported"
880  * line should remain.
881  */
882 #if !defined(__NR_process_vm_readv)
883 # if defined(I386)
884 #  define __NR_process_vm_readv  347
885 # elif defined(X86_64)
886 #  define __NR_process_vm_readv  310
887 # elif defined(POWERPC)
888 #  define __NR_process_vm_readv  351
889 # endif
890 #endif
891
892 #if defined(__NR_process_vm_readv)
893 static bool process_vm_readv_not_supported = 0;
894 /* Have to avoid duplicating with the C library headers. */
895 static ssize_t strace_process_vm_readv(pid_t pid,
896                  const struct iovec *lvec,
897                  unsigned long liovcnt,
898                  const struct iovec *rvec,
899                  unsigned long riovcnt,
900                  unsigned long flags)
901 {
902         return syscall(__NR_process_vm_readv, (long)pid, lvec, liovcnt, rvec, riovcnt, flags);
903 }
904 #define process_vm_readv strace_process_vm_readv
905 #else
906 static bool process_vm_readv_not_supported = 1;
907 # define process_vm_readv(...) (errno = ENOSYS, -1)
908 #endif
909
910 #endif /* end of hack */
911
912 #define PAGMASK (~(PAGSIZ - 1))
913 /*
914  * move `len' bytes of data from process `pid'
915  * at address `addr' to our space at `laddr'
916  */
917 int
918 umoven(struct tcb *tcp, long addr, int len, char *laddr)
919 {
920         int pid = tcp->pid;
921         int n, m, nread;
922         union {
923                 long val;
924                 char x[sizeof(long)];
925         } u;
926
927 #if SUPPORTED_PERSONALITIES > 1 && SIZEOF_LONG > 4
928         if (current_wordsize < sizeof(addr))
929                 addr &= (1ul << 8 * current_wordsize) - 1;
930 #endif
931
932         if (!process_vm_readv_not_supported) {
933                 struct iovec local[1], remote[1];
934                 int r;
935
936                 local[0].iov_base = laddr;
937                 remote[0].iov_base = (void*)addr;
938                 local[0].iov_len = remote[0].iov_len = len;
939                 r = process_vm_readv(pid, local, 1, remote, 1, 0);
940                 if (r == len)
941                         return 0;
942                 if (r >= 0) {
943                         error_msg("umoven: short read (%d < %d) @0x%lx",
944                                   r, len, addr);
945                         return -1;
946                 }
947                 switch (errno) {
948                         case ENOSYS:
949                                 process_vm_readv_not_supported = 1;
950                                 break;
951                         case ESRCH:
952                                 /* the process is gone */
953                                 return -1;
954                         case EFAULT: case EIO: case EPERM:
955                                 /* address space is inaccessible */
956                                 return -1;
957                         default:
958                                 /* all the rest is strange and should be reported */
959                                 perror_msg("process_vm_readv");
960                                 return -1;
961                 }
962         }
963
964         nread = 0;
965         if (addr & (sizeof(long) - 1)) {
966                 /* addr not a multiple of sizeof(long) */
967                 n = addr - (addr & -sizeof(long)); /* residue */
968                 addr &= -sizeof(long); /* residue */
969                 errno = 0;
970                 u.val = ptrace(PTRACE_PEEKDATA, pid, (char *) addr, 0);
971                 switch (errno) {
972                         case 0:
973                                 break;
974                         case ESRCH: case EINVAL:
975                                 /* these could be seen if the process is gone */
976                                 return -1;
977                         case EFAULT: case EIO: case EPERM:
978                                 /* address space is inaccessible */
979                                 return -1;
980                         default:
981                                 /* all the rest is strange and should be reported */
982                                 perror_msg("umoven: PTRACE_PEEKDATA pid:%d @0x%lx",
983                                             pid, addr);
984                                 return -1;
985                 }
986                 m = MIN(sizeof(long) - n, len);
987                 memcpy(laddr, &u.x[n], m);
988                 addr += sizeof(long);
989                 laddr += m;
990                 nread += m;
991                 len -= m;
992         }
993         while (len) {
994                 errno = 0;
995                 u.val = ptrace(PTRACE_PEEKDATA, pid, (char *) addr, 0);
996                 switch (errno) {
997                         case 0:
998                                 break;
999                         case ESRCH: case EINVAL:
1000                                 /* these could be seen if the process is gone */
1001                                 return -1;
1002                         case EFAULT: case EIO: case EPERM:
1003                                 /* address space is inaccessible */
1004                                 if (nread) {
1005                                         perror_msg("umoven: short read (%d < %d) @0x%lx",
1006                                                    nread, nread + len, addr - nread);
1007                                 }
1008                                 return -1;
1009                         default:
1010                                 /* all the rest is strange and should be reported */
1011                                 perror_msg("umoven: PTRACE_PEEKDATA pid:%d @0x%lx",
1012                                             pid, addr);
1013                                 return -1;
1014                 }
1015                 m = MIN(sizeof(long), len);
1016                 memcpy(laddr, u.x, m);
1017                 addr += sizeof(long);
1018                 laddr += m;
1019                 nread += m;
1020                 len -= m;
1021         }
1022
1023         return 0;
1024 }
1025
1026 /*
1027  * Like `umove' but make the additional effort of looking
1028  * for a terminating zero byte.
1029  *
1030  * Returns < 0 on error, > 0 if NUL was seen,
1031  * (TODO if useful: return count of bytes including NUL),
1032  * else 0 if len bytes were read but no NUL byte seen.
1033  *
1034  * Note: there is no guarantee we won't overwrite some bytes
1035  * in laddr[] _after_ terminating NUL (but, of course,
1036  * we never write past laddr[len-1]).
1037  */
1038 int
1039 umovestr(struct tcb *tcp, long addr, int len, char *laddr)
1040 {
1041 #if SIZEOF_LONG == 4
1042         const unsigned long x01010101 = 0x01010101ul;
1043         const unsigned long x80808080 = 0x80808080ul;
1044 #elif SIZEOF_LONG == 8
1045         const unsigned long x01010101 = 0x0101010101010101ul;
1046         const unsigned long x80808080 = 0x8080808080808080ul;
1047 #else
1048 # error SIZEOF_LONG > 8
1049 #endif
1050
1051         int pid = tcp->pid;
1052         int n, m, nread;
1053         union {
1054                 unsigned long val;
1055                 char x[sizeof(long)];
1056         } u;
1057
1058 #if SUPPORTED_PERSONALITIES > 1 && SIZEOF_LONG > 4
1059         if (current_wordsize < sizeof(addr))
1060                 addr &= (1ul << 8 * current_wordsize) - 1;
1061 #endif
1062
1063         nread = 0;
1064         if (!process_vm_readv_not_supported) {
1065                 struct iovec local[1], remote[1];
1066
1067                 local[0].iov_base = laddr;
1068                 remote[0].iov_base = (void*)addr;
1069
1070                 while (len > 0) {
1071                         int end_in_page;
1072                         int r;
1073                         int chunk_len;
1074
1075                         /* Don't read kilobytes: most strings are short */
1076                         chunk_len = len;
1077                         if (chunk_len > 256)
1078                                 chunk_len = 256;
1079                         /* Don't cross pages. I guess otherwise we can get EFAULT
1080                          * and fail to notice that terminating NUL lies
1081                          * in the existing (first) page.
1082                          * (I hope there aren't arches with pages < 4K)
1083                          */
1084                         end_in_page = ((addr + chunk_len) & 4095);
1085                         r = chunk_len - end_in_page;
1086                         if (r > 0) /* if chunk_len > end_in_page */
1087                                 chunk_len = r; /* chunk_len -= end_in_page */
1088
1089                         local[0].iov_len = remote[0].iov_len = chunk_len;
1090                         r = process_vm_readv(pid, local, 1, remote, 1, 0);
1091                         if (r > 0) {
1092                                 if (memchr(local[0].iov_base, '\0', r))
1093                                         return 1;
1094                                 local[0].iov_base += r;
1095                                 remote[0].iov_base += r;
1096                                 len -= r;
1097                                 nread += r;
1098                                 continue;
1099                         }
1100                         switch (errno) {
1101                                 case ENOSYS:
1102                                         process_vm_readv_not_supported = 1;
1103                                         goto vm_readv_didnt_work;
1104                                 case ESRCH:
1105                                         /* the process is gone */
1106                                         return -1;
1107                                 case EFAULT: case EIO: case EPERM:
1108                                         /* address space is inaccessible */
1109                                         if (nread) {
1110                                                 perror_msg("umovestr: short read (%d < %d) @0x%lx",
1111                                                            nread, nread + len, addr);
1112                                         }
1113                                         return -1;
1114                                 default:
1115                                         /* all the rest is strange and should be reported */
1116                                         perror_msg("process_vm_readv");
1117                                         return -1;
1118                         }
1119                 }
1120                 return 0;
1121         }
1122  vm_readv_didnt_work:
1123
1124         if (addr & (sizeof(long) - 1)) {
1125                 /* addr not a multiple of sizeof(long) */
1126                 n = addr - (addr & -sizeof(long)); /* residue */
1127                 addr &= -sizeof(long); /* residue */
1128                 errno = 0;
1129                 u.val = ptrace(PTRACE_PEEKDATA, pid, (char *)addr, 0);
1130                 switch (errno) {
1131                         case 0:
1132                                 break;
1133                         case ESRCH: case EINVAL:
1134                                 /* these could be seen if the process is gone */
1135                                 return -1;
1136                         case EFAULT: case EIO: case EPERM:
1137                                 /* address space is inaccessible */
1138                                 return -1;
1139                         default:
1140                                 /* all the rest is strange and should be reported */
1141                                 perror_msg("umovestr: PTRACE_PEEKDATA pid:%d @0x%lx",
1142                                             pid, addr);
1143                                 return -1;
1144                 }
1145                 m = MIN(sizeof(long) - n, len);
1146                 memcpy(laddr, &u.x[n], m);
1147                 while (n & (sizeof(long) - 1))
1148                         if (u.x[n++] == '\0')
1149                                 return 1;
1150                 addr += sizeof(long);
1151                 laddr += m;
1152                 nread += m;
1153                 len -= m;
1154         }
1155
1156         while (len) {
1157                 errno = 0;
1158                 u.val = ptrace(PTRACE_PEEKDATA, pid, (char *)addr, 0);
1159                 switch (errno) {
1160                         case 0:
1161                                 break;
1162                         case ESRCH: case EINVAL:
1163                                 /* these could be seen if the process is gone */
1164                                 return -1;
1165                         case EFAULT: case EIO: case EPERM:
1166                                 /* address space is inaccessible */
1167                                 if (nread) {
1168                                         perror_msg("umovestr: short read (%d < %d) @0x%lx",
1169                                                    nread, nread + len, addr - nread);
1170                                 }
1171                                 return -1;
1172                         default:
1173                                 /* all the rest is strange and should be reported */
1174                                 perror_msg("umovestr: PTRACE_PEEKDATA pid:%d @0x%lx",
1175                                            pid, addr);
1176                                 return -1;
1177                 }
1178                 m = MIN(sizeof(long), len);
1179                 memcpy(laddr, u.x, m);
1180                 /* "If a NUL char exists in this word" */
1181                 if ((u.val - x01010101) & ~u.val & x80808080)
1182                         return 1;
1183                 addr += sizeof(long);
1184                 laddr += m;
1185                 nread += m;
1186                 len -= m;
1187         }
1188         return 0;
1189 }
1190
1191 int
1192 upeek(int pid, long off, long *res)
1193 {
1194         long val;
1195
1196         errno = 0;
1197         val = ptrace(PTRACE_PEEKUSER, (pid_t)pid, (char *) off, 0);
1198         if (val == -1 && errno) {
1199                 if (errno != ESRCH) {
1200                         perror_msg("upeek: PTRACE_PEEKUSER pid:%d @0x%lx)", pid, off);
1201                 }
1202                 return -1;
1203         }
1204         *res = val;
1205         return 0;
1206 }
1207
1208 /* Note! On new kernels (about 2.5.46+), we use PTRACE_O_TRACECLONE
1209  * and PTRACE_O_TRACE[V]FORK for tracing children.
1210  * If you are adding a new arch which is only supported by newer kernels,
1211  * you most likely don't need to add any code below
1212  * beside a dummy "return 0" block in change_syscall().
1213  */
1214
1215 /*
1216  * These #if's are huge, please indent them correctly.
1217  * It's easy to get confused otherwise.
1218  */
1219
1220 #include "syscall.h"
1221
1222 #ifndef CLONE_PTRACE
1223 # define CLONE_PTRACE    0x00002000
1224 #endif
1225 #ifndef CLONE_VFORK
1226 # define CLONE_VFORK     0x00004000
1227 #endif
1228 #ifndef CLONE_VM
1229 # define CLONE_VM        0x00000100
1230 #endif
1231
1232 #ifdef IA64
1233
1234 typedef unsigned long *arg_setup_state;
1235
1236 static int
1237 arg_setup(struct tcb *tcp, arg_setup_state *state)
1238 {
1239         unsigned long cfm, sof, sol;
1240         long bsp;
1241
1242         if (ia64_ia32mode) {
1243                 /* Satisfy a false GCC warning.  */
1244                 *state = NULL;
1245                 return 0;
1246         }
1247
1248         if (upeek(tcp->pid, PT_AR_BSP, &bsp) < 0)
1249                 return -1;
1250         if (upeek(tcp->pid, PT_CFM, (long *) &cfm) < 0)
1251                 return -1;
1252
1253         sof = (cfm >> 0) & 0x7f;
1254         sol = (cfm >> 7) & 0x7f;
1255         bsp = (long) ia64_rse_skip_regs((unsigned long *) bsp, -sof + sol);
1256
1257         *state = (unsigned long *) bsp;
1258         return 0;
1259 }
1260
1261 # define arg_finish_change(tcp, state)  0
1262
1263 static int
1264 get_arg0(struct tcb *tcp, arg_setup_state *state, long *valp)
1265 {
1266         int ret;
1267
1268         if (ia64_ia32mode)
1269                 ret = upeek(tcp->pid, PT_R11, valp);
1270         else
1271                 ret = umoven(tcp,
1272                               (unsigned long) ia64_rse_skip_regs(*state, 0),
1273                               sizeof(long), (void *) valp);
1274         return ret;
1275 }
1276
1277 static int
1278 get_arg1(struct tcb *tcp, arg_setup_state *state, long *valp)
1279 {
1280         int ret;
1281
1282         if (ia64_ia32mode)
1283                 ret = upeek(tcp->pid, PT_R9, valp);
1284         else
1285                 ret = umoven(tcp,
1286                               (unsigned long) ia64_rse_skip_regs(*state, 1),
1287                               sizeof(long), (void *) valp);
1288         return ret;
1289 }
1290
1291 static int
1292 set_arg0(struct tcb *tcp, arg_setup_state *state, long val)
1293 {
1294         int req = PTRACE_POKEDATA;
1295         void *ap;
1296
1297         if (ia64_ia32mode) {
1298                 ap = (void *) (intptr_t) PT_R11;         /* r11 == EBX */
1299                 req = PTRACE_POKEUSER;
1300         } else
1301                 ap = ia64_rse_skip_regs(*state, 0);
1302         errno = 0;
1303         ptrace(req, tcp->pid, ap, val);
1304         return errno ? -1 : 0;
1305 }
1306
1307 static int
1308 set_arg1(struct tcb *tcp, arg_setup_state *state, long val)
1309 {
1310         int req = PTRACE_POKEDATA;
1311         void *ap;
1312
1313         if (ia64_ia32mode) {
1314                 ap = (void *) (intptr_t) PT_R9;         /* r9 == ECX */
1315                 req = PTRACE_POKEUSER;
1316         } else
1317                 ap = ia64_rse_skip_regs(*state, 1);
1318         errno = 0;
1319         ptrace(req, tcp->pid, ap, val);
1320         return errno ? -1 : 0;
1321 }
1322
1323 /* ia64 does not return the input arguments from functions (and syscalls)
1324    according to ia64 RSE (Register Stack Engine) behavior.  */
1325
1326 # define restore_arg0(tcp, state, val) ((void) (state), 0)
1327 # define restore_arg1(tcp, state, val) ((void) (state), 0)
1328
1329 #elif defined(SPARC) || defined(SPARC64)
1330
1331 # if defined(SPARC64)
1332 #  undef PTRACE_GETREGS
1333 #  define PTRACE_GETREGS PTRACE_GETREGS64
1334 #  undef PTRACE_SETREGS
1335 #  define PTRACE_SETREGS PTRACE_SETREGS64
1336 # endif
1337
1338 typedef struct pt_regs arg_setup_state;
1339
1340 # define arg_setup(tcp, state) \
1341     (ptrace(PTRACE_GETREGS, (tcp)->pid, (char *) (state), 0))
1342 # define arg_finish_change(tcp, state) \
1343     (ptrace(PTRACE_SETREGS, (tcp)->pid, (char *) (state), 0))
1344
1345 # define get_arg0(tcp, state, valp) (*(valp) = (state)->u_regs[U_REG_O0], 0)
1346 # define get_arg1(tcp, state, valp) (*(valp) = (state)->u_regs[U_REG_O1], 0)
1347 # define set_arg0(tcp, state, val)  ((state)->u_regs[U_REG_O0] = (val), 0)
1348 # define set_arg1(tcp, state, val)  ((state)->u_regs[U_REG_O1] = (val), 0)
1349 # define restore_arg0(tcp, state, val) 0
1350
1351 #else /* other architectures */
1352
1353 # if defined S390 || defined S390X
1354 /* Note: this is only true for the `clone' system call, which handles
1355    arguments specially.  We could as well say that its first two arguments
1356    are swapped relative to other architectures, but that would just be
1357    another #ifdef in the calls.  */
1358 #  define arg0_offset   PT_GPR3
1359 #  define arg1_offset   PT_ORIGGPR2
1360 #  define restore_arg0(tcp, state, val) ((void) (state), 0)
1361 #  define restore_arg1(tcp, state, val) ((void) (state), 0)
1362 #  define arg0_index    1
1363 #  define arg1_index    0
1364 # elif defined(ALPHA) || defined(MIPS)
1365 #  define arg0_offset   REG_A0
1366 #  define arg1_offset   (REG_A0+1)
1367 # elif defined(POWERPC)
1368 #  define arg0_offset   (sizeof(unsigned long)*PT_R3)
1369 #  define arg1_offset   (sizeof(unsigned long)*PT_R4)
1370 #  define restore_arg0(tcp, state, val) ((void) (state), 0)
1371 # elif defined(HPPA)
1372 #  define arg0_offset   PT_GR26
1373 #  define arg1_offset   (PT_GR26-4)
1374 # elif defined(X86_64) || defined(X32)
1375 #  define arg0_offset   ((long)(8*(current_personality ? RBX : RDI)))
1376 #  define arg1_offset   ((long)(8*(current_personality ? RCX : RSI)))
1377 # elif defined(SH)
1378 #  define arg0_offset   (4*(REG_REG0+4))
1379 #  define arg1_offset   (4*(REG_REG0+5))
1380 # elif defined(SH64)
1381    /* ABI defines arg0 & 1 in r2 & r3 */
1382 #  define arg0_offset   (REG_OFFSET+16)
1383 #  define arg1_offset   (REG_OFFSET+24)
1384 #  define restore_arg0(tcp, state, val) 0
1385 # elif defined CRISV10 || defined CRISV32
1386 #  define arg0_offset   (4*PT_R11)
1387 #  define arg1_offset   (4*PT_ORIG_R10)
1388 #  define restore_arg0(tcp, state, val) 0
1389 #  define restore_arg1(tcp, state, val) 0
1390 #  define arg0_index    1
1391 #  define arg1_index    0
1392 # else
1393 #  define arg0_offset   0
1394 #  define arg1_offset   4
1395 #  if defined ARM
1396 #   define restore_arg0(tcp, state, val) 0
1397 #  endif
1398 # endif
1399
1400 typedef int arg_setup_state;
1401
1402 # define arg_setup(tcp, state)         (0)
1403 # define arg_finish_change(tcp, state) 0
1404 # define get_arg0(tcp, cookie, valp)   (upeek((tcp)->pid, arg0_offset, (valp)))
1405 # define get_arg1(tcp, cookie, valp)   (upeek((tcp)->pid, arg1_offset, (valp)))
1406
1407 static int
1408 set_arg0(struct tcb *tcp, void *cookie, long val)
1409 {
1410         return ptrace(PTRACE_POKEUSER, tcp->pid, (char*)arg0_offset, val);
1411 }
1412
1413 static int
1414 set_arg1(struct tcb *tcp, void *cookie, long val)
1415 {
1416         return ptrace(PTRACE_POKEUSER, tcp->pid, (char*)arg1_offset, val);
1417 }
1418
1419 #endif /* architectures */
1420
1421 #ifndef restore_arg0
1422 # define restore_arg0(tcp, state, val) set_arg0((tcp), (state), (val))
1423 #endif
1424 #ifndef restore_arg1
1425 # define restore_arg1(tcp, state, val) set_arg1((tcp), (state), (val))
1426 #endif
1427
1428 #ifndef arg0_index
1429 # define arg0_index 0
1430 # define arg1_index 1
1431 #endif
1432
1433 static int
1434 change_syscall(struct tcb *tcp, arg_setup_state *state, int new)
1435 {
1436 #if defined(I386)
1437         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(ORIG_EAX * 4), new) < 0)
1438                 return -1;
1439         return 0;
1440 #elif defined(X86_64)
1441         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(ORIG_RAX * 8), new) < 0)
1442                 return -1;
1443         return 0;
1444 #elif defined(X32)
1445         /* setbpt/clearbpt never used: */
1446         /* X32 is only supported since about linux-3.0.30 */
1447 #elif defined(POWERPC)
1448         if (ptrace(PTRACE_POKEUSER, tcp->pid,
1449                    (char*)(sizeof(unsigned long)*PT_R0), new) < 0)
1450                 return -1;
1451         return 0;
1452 #elif defined(S390) || defined(S390X)
1453         /* s390 linux after 2.4.7 has a hook in entry.S to allow this */
1454         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(PT_GPR2), new) < 0)
1455                 return -1;
1456         return 0;
1457 #elif defined(M68K)
1458         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(4*PT_ORIG_D0), new) < 0)
1459                 return -1;
1460         return 0;
1461 #elif defined(SPARC) || defined(SPARC64)
1462         state->u_regs[U_REG_G1] = new;
1463         return 0;
1464 #elif defined(MIPS)
1465         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(REG_V0), new) < 0)
1466                 return -1;
1467         return 0;
1468 #elif defined(ALPHA)
1469         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(REG_A3), new) < 0)
1470                 return -1;
1471         return 0;
1472 #elif defined(AVR32)
1473         /* setbpt/clearbpt never used: */
1474         /* AVR32 is only supported since about linux-2.6.19 */
1475 #elif defined(BFIN)
1476         /* setbpt/clearbpt never used: */
1477         /* Blackfin is only supported since about linux-2.6.23 */
1478 #elif defined(IA64)
1479         if (ia64_ia32mode) {
1480                 switch (new) {
1481                 case 2:
1482                         break;  /* x86 SYS_fork */
1483                 case SYS_clone:
1484                         new = 120;
1485                         break;
1486                 default:
1487                         fprintf(stderr, "%s: unexpected syscall %d\n",
1488                                 __FUNCTION__, new);
1489                         return -1;
1490                 }
1491                 if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(PT_R1), new) < 0)
1492                         return -1;
1493         } else if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(PT_R15), new) < 0)
1494                 return -1;
1495         return 0;
1496 #elif defined(HPPA)
1497         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(PT_GR20), new) < 0)
1498                 return -1;
1499         return 0;
1500 #elif defined(SH)
1501         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(4*(REG_REG0+3)), new) < 0)
1502                 return -1;
1503         return 0;
1504 #elif defined(SH64)
1505         /* Top half of reg encodes the no. of args n as 0x1n.
1506            Assume 0 args as kernel never actually checks... */
1507         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(REG_SYSCALL),
1508                                 0x100000 | new) < 0)
1509                 return -1;
1510         return 0;
1511 #elif defined(CRISV10) || defined(CRISV32)
1512         if (ptrace(PTRACE_POKEUSER, tcp->pid, (char*)(4*PT_R9), new) < 0)
1513                 return -1;
1514         return 0;
1515 #elif defined(ARM)
1516         /* Some kernels support this, some (pre-2.6.16 or so) don't.  */
1517 # ifndef PTRACE_SET_SYSCALL
1518 #  define PTRACE_SET_SYSCALL 23
1519 # endif
1520         if (ptrace(PTRACE_SET_SYSCALL, tcp->pid, 0, new & 0xffff) != 0)
1521                 return -1;
1522         return 0;
1523 #elif defined(AARCH64)
1524         /* setbpt/clearbpt never used: */
1525         /* AARCH64 is only supported since about linux-3.0.31 */
1526 #elif defined(TILE)
1527         /* setbpt/clearbpt never used: */
1528         /* Tilera CPUs are only supported since about linux-2.6.34 */
1529 #elif defined(MICROBLAZE)
1530         /* setbpt/clearbpt never used: */
1531         /* microblaze is only supported since about linux-2.6.30 */
1532 #elif defined(OR1K)
1533         /* never reached; OR1K is only supported by kernels since 3.1.0. */
1534 #elif defined(METAG)
1535         /* setbpt/clearbpt never used: */
1536         /* Meta is only supported since linux-3.7 */
1537 #elif defined(XTENSA)
1538         /* setbpt/clearbpt never used: */
1539         /* Xtensa is only supported since linux 2.6.13 */
1540 #elif defined(ARC)
1541         /* setbpt/clearbpt never used: */
1542         /* ARC only supported since 3.9 */
1543 #else
1544 #warning Do not know how to handle change_syscall for this architecture
1545 #endif /* architecture */
1546         return -1;
1547 }
1548
1549 int
1550 setbpt(struct tcb *tcp)
1551 {
1552         static int clone_scno[SUPPORTED_PERSONALITIES] = { SYS_clone };
1553         arg_setup_state state;
1554
1555         if (tcp->flags & TCB_BPTSET) {
1556                 fprintf(stderr, "PANIC: TCB already set in pid %u\n", tcp->pid);
1557                 return -1;
1558         }
1559
1560         /*
1561          * It's a silly kludge to initialize this with a search at runtime.
1562          * But it's better than maintaining another magic thing in the
1563          * godforsaken tables.
1564          */
1565         if (clone_scno[current_personality] == 0) {
1566                 unsigned int i;
1567                 for (i = 0; i < nsyscalls; ++i)
1568                         if (sysent[i].sys_func == sys_clone) {
1569                                 clone_scno[current_personality] = i;
1570                                 break;
1571                         }
1572         }
1573
1574         if (tcp->s_ent->sys_func == sys_fork) {
1575                 if (arg_setup(tcp, &state) < 0
1576                     || get_arg0(tcp, &state, &tcp->inst[0]) < 0
1577                     || get_arg1(tcp, &state, &tcp->inst[1]) < 0
1578                     || change_syscall(tcp, &state,
1579                                       clone_scno[current_personality]) < 0
1580                     || set_arg0(tcp, &state, CLONE_PTRACE|SIGCHLD) < 0
1581                     || set_arg1(tcp, &state, 0) < 0
1582                     || arg_finish_change(tcp, &state) < 0)
1583                         return -1;
1584                 tcp->u_arg[arg0_index] = CLONE_PTRACE|SIGCHLD;
1585                 tcp->u_arg[arg1_index] = 0;
1586                 tcp->flags |= TCB_BPTSET;
1587                 return 0;
1588         }
1589
1590         if (tcp->s_ent->sys_func == sys_clone) {
1591                 /* ia64 calls directly `clone (CLONE_VFORK | CLONE_VM)'
1592                    contrary to x86 vfork above.  Even on x86 we turn the
1593                    vfork semantics into plain fork - each application must not
1594                    depend on the vfork specifics according to POSIX.  We would
1595                    hang waiting for the parent resume otherwise.  We need to
1596                    clear also CLONE_VM but only in the CLONE_VFORK case as
1597                    otherwise we would break pthread_create.  */
1598
1599                 long new_arg0 = (tcp->u_arg[arg0_index] | CLONE_PTRACE);
1600                 if (new_arg0 & CLONE_VFORK)
1601                         new_arg0 &= ~(unsigned long)(CLONE_VFORK | CLONE_VM);
1602                 if (arg_setup(tcp, &state) < 0
1603                  || set_arg0(tcp, &state, new_arg0) < 0
1604                  || arg_finish_change(tcp, &state) < 0)
1605                         return -1;
1606                 tcp->inst[0] = tcp->u_arg[arg0_index];
1607                 tcp->inst[1] = tcp->u_arg[arg1_index];
1608                 tcp->flags |= TCB_BPTSET;
1609                 return 0;
1610         }
1611
1612         fprintf(stderr, "PANIC: setbpt for syscall %ld on %u???\n",
1613                 tcp->scno, tcp->pid);
1614         return -1;
1615 }
1616
1617 int
1618 clearbpt(struct tcb *tcp)
1619 {
1620         arg_setup_state state;
1621         if (arg_setup(tcp, &state) < 0
1622             || change_syscall(tcp, &state, tcp->scno) < 0
1623             || restore_arg0(tcp, &state, tcp->inst[0]) < 0
1624             || restore_arg1(tcp, &state, tcp->inst[1]) < 0
1625             || arg_finish_change(tcp, &state))
1626                 if (errno != ESRCH)
1627                         return -1;
1628         tcp->flags &= ~TCB_BPTSET;
1629         return 0;
1630 }