]> granicus.if.org Git - strace/blob - util.c
socketeutils: extend receive_responses further
[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  * Copyright (c) 1999-2017 The strace developers.
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 #include "defs.h"
36 #include <sys/param.h>
37 #include <fcntl.h>
38 #include <stdarg.h>
39 #ifdef HAVE_SYS_XATTR_H
40 # include <sys/xattr.h>
41 #endif
42 #include <sys/uio.h>
43 #include <asm/unistd.h>
44
45 #include "scno.h"
46 #include "regs.h"
47 #include "ptrace.h"
48
49 int
50 string_to_uint_ex(const char *const str, char **const endptr,
51                   const unsigned int max_val, const char *const accepted_ending)
52 {
53         char *end;
54         long val;
55
56         if (!*str)
57                 return -1;
58
59         errno = 0;
60         val = strtol(str, &end, 10);
61
62         if (str == end || val < 0 || (unsigned long) val > max_val
63             || (val == LONG_MAX && errno == ERANGE))
64                 return -1;
65
66         if (*end && (!accepted_ending || !strchr(accepted_ending, *end)))
67                 return -1;
68
69         if (endptr)
70                 *endptr = end;
71
72         return (int) val;
73 }
74
75 int
76 string_to_uint(const char *const str)
77 {
78         return string_to_uint_upto(str, INT_MAX);
79 }
80
81 int
82 tv_nz(const struct timeval *a)
83 {
84         return a->tv_sec || a->tv_usec;
85 }
86
87 int
88 tv_cmp(const struct timeval *a, const struct timeval *b)
89 {
90         if (a->tv_sec < b->tv_sec
91             || (a->tv_sec == b->tv_sec && a->tv_usec < b->tv_usec))
92                 return -1;
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         return 0;
97 }
98
99 double
100 tv_float(const struct timeval *tv)
101 {
102         return tv->tv_sec + tv->tv_usec/1000000.0;
103 }
104
105 void
106 tv_add(struct timeval *tv, const struct timeval *a, const struct timeval *b)
107 {
108         tv->tv_sec = a->tv_sec + b->tv_sec;
109         tv->tv_usec = a->tv_usec + b->tv_usec;
110         if (tv->tv_usec >= 1000000) {
111                 tv->tv_sec++;
112                 tv->tv_usec -= 1000000;
113         }
114 }
115
116 void
117 tv_sub(struct timeval *tv, const struct timeval *a, const struct timeval *b)
118 {
119         tv->tv_sec = a->tv_sec - b->tv_sec;
120         tv->tv_usec = a->tv_usec - b->tv_usec;
121         if (((long) tv->tv_usec) < 0) {
122                 tv->tv_sec--;
123                 tv->tv_usec += 1000000;
124         }
125 }
126
127 void
128 tv_div(struct timeval *tv, const struct timeval *a, int n)
129 {
130         tv->tv_usec = (a->tv_sec % n * 1000000 + a->tv_usec + n / 2) / n;
131         tv->tv_sec = a->tv_sec / n + tv->tv_usec / 1000000;
132         tv->tv_usec %= 1000000;
133 }
134
135 void
136 tv_mul(struct timeval *tv, const struct timeval *a, int n)
137 {
138         tv->tv_usec = a->tv_usec * n;
139         tv->tv_sec = a->tv_sec * n + tv->tv_usec / 1000000;
140         tv->tv_usec %= 1000000;
141 }
142
143 const char *
144 xlookup(const struct xlat *xlat, const uint64_t val)
145 {
146         for (; xlat->str != NULL; xlat++)
147                 if (xlat->val == val)
148                         return xlat->str;
149         return NULL;
150 }
151
152 static int
153 xlat_bsearch_compare(const void *a, const void *b)
154 {
155         const uint64_t val1 = *(const uint64_t *) a;
156         const uint64_t val2 = ((const struct xlat *) b)->val;
157         return (val1 > val2) ? 1 : (val1 < val2) ? -1 : 0;
158 }
159
160 const char *
161 xlat_search(const struct xlat *xlat, const size_t nmemb, const uint64_t val)
162 {
163         const struct xlat *e =
164                 bsearch((const void*) &val,
165                         xlat, nmemb, sizeof(*xlat), xlat_bsearch_compare);
166
167         return e ? e->str : NULL;
168 }
169
170 #if !defined HAVE_STPCPY
171 char *
172 stpcpy(char *dst, const char *src)
173 {
174         while ((*dst = *src++) != '\0')
175                 dst++;
176         return dst;
177 }
178 #endif
179
180 /* Find a next bit which is set.
181  * Starts testing at cur_bit.
182  * Returns -1 if no more bits are set.
183  *
184  * We never touch bytes we don't need to.
185  * On big-endian, array is assumed to consist of
186  * current_wordsize wide words: for example, is current_wordsize is 4,
187  * the bytes are walked in 3,2,1,0, 7,6,5,4, 11,10,9,8 ... sequence.
188  * On little-endian machines, word size is immaterial.
189  */
190 int
191 next_set_bit(const void *bit_array, unsigned cur_bit, unsigned size_bits)
192 {
193         const unsigned endian = 1;
194         int little_endian = * (char *) (void *) &endian;
195
196         const uint8_t *array = bit_array;
197         unsigned pos = cur_bit / 8;
198         unsigned pos_xor_mask = little_endian ? 0 : current_wordsize-1;
199
200         for (;;) {
201                 uint8_t bitmask;
202                 uint8_t cur_byte;
203
204                 if (cur_bit >= size_bits)
205                         return -1;
206                 cur_byte = array[pos ^ pos_xor_mask];
207                 if (cur_byte == 0) {
208                         cur_bit = (cur_bit + 8) & (-8);
209                         pos++;
210                         continue;
211                 }
212                 bitmask = 1 << (cur_bit & 7);
213                 for (;;) {
214                         if (cur_byte & bitmask)
215                                 return cur_bit;
216                         cur_bit++;
217                         if (cur_bit >= size_bits)
218                                 return -1;
219                         bitmask <<= 1;
220                         /* This check *can't be* optimized out: */
221                         if (bitmask == 0)
222                                 break;
223                 }
224                 pos++;
225         }
226 }
227
228 /**
229  * Print entry in struct xlat table, if there.
230  *
231  * @param val  Value to search a literal representation for.
232  * @param dflt String (abbreviated in comment syntax) which should be emitted
233  *             if no appropriate xlat value has been found.
234  * @param xlat (And the following arguments) Pointers to arrays of xlat values.
235  *             The last argument should be NULL.
236  * @return     1 if appropriate xlat value has been found, 0 otherwise.
237  */
238 int
239 printxvals(const uint64_t val, const char *dflt, const struct xlat *xlat, ...)
240 {
241         va_list args;
242
243         va_start(args, xlat);
244         for (; xlat; xlat = va_arg(args, const struct xlat *)) {
245                 const char *str = xlookup(xlat, val);
246
247                 if (str) {
248                         tprints(str);
249                         va_end(args);
250                         return 1;
251                 }
252         }
253         /* No hits -- print raw # instead. */
254         tprintf("%#" PRIx64, val);
255         tprints_comment(dflt);
256
257         va_end(args);
258
259         return 0;
260 }
261
262 /**
263  * Print entry in sorted struct xlat table, if it is there.
264  *
265  * @param xlat      Pointer to an array of xlat values (not terminated with
266  *                  XLAT_END).
267  * @param xlat_size Number of xlat elements present in array (usually ARRAY_SIZE
268  *                  if array is declared in the unit's scope and not
269  *                  terminated with XLAT_END).
270  * @param val       Value to search literal representation for.
271  * @param dflt      String (abbreviated in comment syntax) which should be
272  *                  emitted if no appropriate xlat value has been found.
273  * @return          1 if appropriate xlat value has been found, 0
274  *                  otherwise.
275  */
276 int
277 printxval_searchn(const struct xlat *xlat, size_t xlat_size, uint64_t val,
278         const char *dflt)
279 {
280         const char *s = xlat_search(xlat, xlat_size, val);
281
282         if (s) {
283                 tprints(s);
284                 return 1;
285         }
286
287         tprintf("%#" PRIx64, val);
288         tprints_comment(dflt);
289
290         return 0;
291 }
292
293 /*
294  * Fetch 64bit argument at position arg_no and
295  * return the index of the next argument.
296  */
297 int
298 getllval(struct tcb *tcp, unsigned long long *val, int arg_no)
299 {
300 #if SIZEOF_KERNEL_LONG_T > 4
301 # ifndef current_klongsize
302         if (current_klongsize < SIZEOF_KERNEL_LONG_T) {
303 #  if defined(AARCH64) || defined(POWERPC64)
304                 /* Align arg_no to the next even number. */
305                 arg_no = (arg_no + 1) & 0xe;
306 #  endif /* AARCH64 || POWERPC64 */
307                 *val = ULONG_LONG(tcp->u_arg[arg_no], tcp->u_arg[arg_no + 1]);
308                 arg_no += 2;
309         } else
310 # endif /* !current_klongsize */
311         {
312                 *val = tcp->u_arg[arg_no];
313                 arg_no++;
314         }
315 #else /* SIZEOF_KERNEL_LONG_T == 4 */
316 # if defined __ARM_EABI__ || \
317      defined LINUX_MIPSO32 || \
318      defined POWERPC || \
319      defined XTENSA
320         /* Align arg_no to the next even number. */
321         arg_no = (arg_no + 1) & 0xe;
322 # elif defined SH
323         /*
324          * The SH4 ABI does allow long longs in odd-numbered registers, but
325          * does not allow them to be split between registers and memory - and
326          * there are only four argument registers for normal functions.  As a
327          * result, pread, for example, takes an extra padding argument before
328          * the offset.  This was changed late in the 2.4 series (around 2.4.20).
329          */
330         if (arg_no == 3)
331                 arg_no++;
332 # endif /* __ARM_EABI__ || LINUX_MIPSO32 || POWERPC || XTENSA || SH */
333         *val = ULONG_LONG(tcp->u_arg[arg_no], tcp->u_arg[arg_no + 1]);
334         arg_no += 2;
335 #endif
336
337         return arg_no;
338 }
339
340 /*
341  * Print 64bit argument at position arg_no and
342  * return the index of the next argument.
343  */
344 int
345 printllval(struct tcb *tcp, const char *format, int arg_no)
346 {
347         unsigned long long val = 0;
348
349         arg_no = getllval(tcp, &val, arg_no);
350         tprintf(format, val);
351         return arg_no;
352 }
353
354 /*
355  * Interpret `xlat' as an array of flags
356  * print the entries whose bits are on in `flags'
357  */
358 void
359 addflags(const struct xlat *xlat, uint64_t flags)
360 {
361         for (; xlat->str; xlat++) {
362                 if (xlat->val && (flags & xlat->val) == xlat->val) {
363                         tprintf("|%s", xlat->str);
364                         flags &= ~xlat->val;
365                 }
366         }
367         if (flags) {
368                 tprintf("|%#" PRIx64, flags);
369         }
370 }
371
372 /*
373  * Interpret `xlat' as an array of flags.
374  * Print to static string the entries whose bits are on in `flags'
375  * Return static string.
376  */
377 const char *
378 sprintflags(const char *prefix, const struct xlat *xlat, uint64_t flags)
379 {
380         static char outstr[1024];
381         char *outptr;
382         int found = 0;
383
384         outptr = stpcpy(outstr, prefix);
385
386         if (flags == 0 && xlat->val == 0 && xlat->str) {
387                 strcpy(outptr, xlat->str);
388                 return outstr;
389         }
390
391         for (; xlat->str; xlat++) {
392                 if (xlat->val && (flags & xlat->val) == xlat->val) {
393                         if (found)
394                                 *outptr++ = '|';
395                         outptr = stpcpy(outptr, xlat->str);
396                         found = 1;
397                         flags &= ~xlat->val;
398                         if (!flags)
399                                 break;
400                 }
401         }
402         if (flags) {
403                 if (found)
404                         *outptr++ = '|';
405                 outptr += sprintf(outptr, "%#" PRIx64, flags);
406         }
407
408         return outstr;
409 }
410
411 int
412 printflags_ex(uint64_t flags, const char *dflt, const struct xlat *xlat, ...)
413 {
414         unsigned int n = 0;
415         va_list args;
416
417         va_start(args, xlat);
418         for (; xlat; xlat = va_arg(args, const struct xlat *)) {
419                 for (; (flags || !n) && xlat->str; ++xlat) {
420                         if ((flags == xlat->val) ||
421                             (xlat->val && (flags & xlat->val) == xlat->val)) {
422                                 tprintf("%s%s", (n++ ? "|" : ""), xlat->str);
423                                 flags &= ~xlat->val;
424                         }
425                         if (!flags)
426                                 break;
427                 }
428         }
429         va_end(args);
430
431         if (n) {
432                 if (flags) {
433                         tprintf("|%#" PRIx64, flags);
434                         n++;
435                 }
436         } else {
437                 if (flags) {
438                         tprintf("%#" PRIx64, flags);
439                         tprints_comment(dflt);
440                 } else {
441                         if (dflt)
442                                 tprints("0");
443                 }
444         }
445
446         return n;
447 }
448
449 void
450 printaddr(const kernel_ulong_t addr)
451 {
452         if (!addr)
453                 tprints("NULL");
454         else
455                 tprintf("%#" PRI_klx, addr);
456 }
457
458 #define DEF_PRINTNUM(name, type) \
459 bool                                                                    \
460 printnum_ ## name(struct tcb *const tcp, const kernel_ulong_t addr,     \
461                   const char *const fmt)                                \
462 {                                                                       \
463         type num;                                                       \
464         if (umove_or_printaddr(tcp, addr, &num))                        \
465                 return false;                                           \
466         tprints("[");                                                   \
467         tprintf(fmt, num);                                              \
468         tprints("]");                                                   \
469         return true;                                                    \
470 }
471
472 #define DEF_PRINTNUM_ADDR(name, type) \
473 bool                                                                    \
474 printnum_addr_ ## name(struct tcb *tcp, const kernel_ulong_t addr)      \
475 {                                                                       \
476         type num;                                                       \
477         if (umove_or_printaddr(tcp, addr, &num))                        \
478                 return false;                                           \
479         tprints("[");                                                   \
480         printaddr(num);                                                 \
481         tprints("]");                                                   \
482         return true;                                                    \
483 }
484
485 #define DEF_PRINTPAIR(name, type) \
486 bool                                                                    \
487 printpair_ ## name(struct tcb *const tcp, const kernel_ulong_t addr,    \
488                    const char *const fmt)                               \
489 {                                                                       \
490         type pair[2];                                                   \
491         if (umove_or_printaddr(tcp, addr, &pair))                       \
492                 return false;                                           \
493         tprints("[");                                                   \
494         tprintf(fmt, pair[0]);                                          \
495         tprints(", ");                                                  \
496         tprintf(fmt, pair[1]);                                          \
497         tprints("]");                                                   \
498         return true;                                                    \
499 }
500
501 DEF_PRINTNUM(int, int)
502 DEF_PRINTNUM_ADDR(int, unsigned int)
503 DEF_PRINTPAIR(int, int)
504 DEF_PRINTNUM(short, short)
505 DEF_PRINTNUM(int64, uint64_t)
506 DEF_PRINTNUM_ADDR(int64, uint64_t)
507 DEF_PRINTPAIR(int64, uint64_t)
508
509 #ifndef current_wordsize
510 bool
511 printnum_long_int(struct tcb *const tcp, const kernel_ulong_t addr,
512                   const char *const fmt_long, const char *const fmt_int)
513 {
514         if (current_wordsize > sizeof(int)) {
515                 return printnum_int64(tcp, addr, fmt_long);
516         } else {
517                 return printnum_int(tcp, addr, fmt_int);
518         }
519 }
520
521 bool
522 printnum_addr_long_int(struct tcb *tcp, const kernel_ulong_t addr)
523 {
524         if (current_wordsize > sizeof(int)) {
525                 return printnum_addr_int64(tcp, addr);
526         } else {
527                 return printnum_addr_int(tcp, addr);
528         }
529 }
530 #endif /* !current_wordsize */
531
532 #ifndef current_klongsize
533 bool
534 printnum_addr_klong_int(struct tcb *tcp, const kernel_ulong_t addr)
535 {
536         if (current_klongsize > sizeof(int)) {
537                 return printnum_addr_int64(tcp, addr);
538         } else {
539                 return printnum_addr_int(tcp, addr);
540         }
541 }
542 #endif /* !current_klongsize */
543
544 /**
545  * Prints time to a (static internal) buffer and returns pointer to it.
546  *
547  * @param sec           Seconds since epoch.
548  * @param part_sec      Amount of second parts since the start of a second.
549  * @param max_part_sec  Maximum value of a valid part_sec.
550  * @param width         1 + floor(log10(max_part_sec)).
551  */
552 static const char *
553 sprinttime_ex(const long long sec, const unsigned long long part_sec,
554               const unsigned int max_part_sec, const int width)
555 {
556         static char buf[sizeof(int) * 3 * 6 + sizeof(part_sec) * 3
557                         + sizeof("+0000")];
558
559         if ((sec == 0 && part_sec == 0) || part_sec > max_part_sec)
560                 return NULL;
561
562         time_t t = (time_t) sec;
563         struct tm *tmp = (sec == t) ? localtime(&t) : NULL;
564         if (!tmp)
565                 return NULL;
566
567         size_t pos = strftime(buf, sizeof(buf), "%FT%T", tmp);
568         if (!pos)
569                 return NULL;
570
571         if (part_sec > 0) {
572                 int ret = snprintf(buf + pos, sizeof(buf) - pos, ".%0*llu",
573                                    width, part_sec);
574
575                 if (ret < 0 || (size_t) ret >= sizeof(buf) - pos)
576                         return NULL;
577
578                 pos += ret;
579         }
580
581         return strftime(buf + pos, sizeof(buf) - pos, "%z", tmp) ? buf : NULL;
582 }
583
584 const char *
585 sprinttime(long long sec)
586 {
587         return sprinttime_ex(sec, 0, 0, 0);
588 }
589
590 const char *
591 sprinttime_usec(long long sec, unsigned long long usec)
592 {
593         return sprinttime_ex(sec, usec, 999999, 6);
594 }
595
596 const char *
597 sprinttime_nsec(long long sec, unsigned long long nsec)
598 {
599         return sprinttime_ex(sec, nsec, 999999999, 9);
600 }
601
602 enum sock_proto
603 getfdproto(struct tcb *tcp, int fd)
604 {
605 #ifdef HAVE_SYS_XATTR_H
606         size_t bufsize = 256;
607         char buf[bufsize];
608         ssize_t r;
609         char path[sizeof("/proc/%u/fd/%u") + 2 * sizeof(int)*3];
610
611         if (fd < 0)
612                 return SOCK_PROTO_UNKNOWN;
613
614         sprintf(path, "/proc/%u/fd/%u", tcp->pid, fd);
615         r = getxattr(path, "system.sockprotoname", buf, bufsize - 1);
616         if (r <= 0)
617                 return SOCK_PROTO_UNKNOWN;
618         else {
619                 /*
620                  * This is a protection for the case when the kernel
621                  * side does not append a null byte to the buffer.
622                  */
623                 buf[r] = '\0';
624
625                 return get_proto_by_name(buf);
626         }
627 #else
628         return SOCK_PROTO_UNKNOWN;
629 #endif
630 }
631
632 unsigned long
633 getfdinode(struct tcb *tcp, int fd)
634 {
635         char path[PATH_MAX + 1];
636
637         if (getfdpath(tcp, fd, path, sizeof(path)) >= 0) {
638                 const char *str = STR_STRIP_PREFIX(path, "socket:[");
639
640                 if (str != path) {
641                         const size_t str_len = strlen(str);
642                         if (str_len && str[str_len - 1] == ']')
643                                 return strtoul(str, NULL, 10);
644                 }
645         }
646
647         return 0;
648 }
649
650 void
651 printfd(struct tcb *tcp, int fd)
652 {
653         char path[PATH_MAX + 1];
654         if (show_fd_path && getfdpath(tcp, fd, path, sizeof(path)) >= 0) {
655                 const char *str;
656                 size_t len;
657                 unsigned long inode;
658
659                 tprintf("%d<", fd);
660                 if (show_fd_path <= 1
661                     || (str = STR_STRIP_PREFIX(path, "socket:[")) == path
662                     || !(len = strlen(str))
663                     || str[len - 1] != ']'
664                     || !(inode = strtoul(str, NULL, 10))
665                     || !print_sockaddr_by_inode(tcp, fd, inode)) {
666                         print_quoted_string(path, strlen(path),
667                                             QUOTE_OMIT_LEADING_TRAILING_QUOTES);
668                 }
669                 tprints(">");
670         } else
671                 tprintf("%d", fd);
672 }
673
674 /*
675  * Quote string `instr' of length `size'
676  * Write up to (3 + `size' * 4) bytes to `outstr' buffer.
677  *
678  * If QUOTE_0_TERMINATED `style' flag is set,
679  * treat `instr' as a NUL-terminated string,
680  * checking up to (`size' + 1) bytes of `instr'.
681  *
682  * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set,
683  * do not add leading and trailing quoting symbols.
684  *
685  * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise.
686  * Note that if QUOTE_0_TERMINATED is not set, always returns 1.
687  */
688 int
689 string_quote(const char *instr, char *outstr, const unsigned int size,
690              const unsigned int style)
691 {
692         const unsigned char *ustr = (const unsigned char *) instr;
693         char *s = outstr;
694         unsigned int i;
695         int usehex, c, eol;
696
697         if (style & QUOTE_0_TERMINATED)
698                 eol = '\0';
699         else
700                 eol = 0x100; /* this can never match a char */
701
702         usehex = 0;
703         if ((xflag > 1) || (style & QUOTE_FORCE_HEX)) {
704                 usehex = 1;
705         } else if (xflag) {
706                 /* Check for presence of symbol which require
707                    to hex-quote the whole string. */
708                 for (i = 0; i < size; ++i) {
709                         c = ustr[i];
710                         /* Check for NUL-terminated string. */
711                         if (c == eol)
712                                 break;
713
714                         /* Force hex unless c is printable or whitespace */
715                         if (c > 0x7e) {
716                                 usehex = 1;
717                                 break;
718                         }
719                         /* In ASCII isspace is only these chars: "\t\n\v\f\r".
720                          * They happen to have ASCII codes 9,10,11,12,13.
721                          */
722                         if (c < ' ' && (unsigned)(c - 9) >= 5) {
723                                 usehex = 1;
724                                 break;
725                         }
726                 }
727         }
728
729         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
730                 *s++ = '\"';
731
732         if (usehex) {
733                 /* Hex-quote the whole string. */
734                 for (i = 0; i < size; ++i) {
735                         c = ustr[i];
736                         /* Check for NUL-terminated string. */
737                         if (c == eol)
738                                 goto asciz_ended;
739                         *s++ = '\\';
740                         *s++ = 'x';
741                         *s++ = "0123456789abcdef"[c >> 4];
742                         *s++ = "0123456789abcdef"[c & 0xf];
743                 }
744         } else {
745                 for (i = 0; i < size; ++i) {
746                         c = ustr[i];
747                         /* Check for NUL-terminated string. */
748                         if (c == eol)
749                                 goto asciz_ended;
750                         if ((i == (size - 1)) &&
751                             (style & QUOTE_OMIT_TRAILING_0) && (c == '\0'))
752                                 goto asciz_ended;
753                         switch (c) {
754                                 case '\"': case '\\':
755                                         *s++ = '\\';
756                                         *s++ = c;
757                                         break;
758                                 case '\f':
759                                         *s++ = '\\';
760                                         *s++ = 'f';
761                                         break;
762                                 case '\n':
763                                         *s++ = '\\';
764                                         *s++ = 'n';
765                                         break;
766                                 case '\r':
767                                         *s++ = '\\';
768                                         *s++ = 'r';
769                                         break;
770                                 case '\t':
771                                         *s++ = '\\';
772                                         *s++ = 't';
773                                         break;
774                                 case '\v':
775                                         *s++ = '\\';
776                                         *s++ = 'v';
777                                         break;
778                                 default:
779                                         if (c >= ' ' && c <= 0x7e)
780                                                 *s++ = c;
781                                         else {
782                                                 /* Print \octal */
783                                                 *s++ = '\\';
784                                                 if (i + 1 < size
785                                                     && ustr[i + 1] >= '0'
786                                                     && ustr[i + 1] <= '9'
787                                                 ) {
788                                                         /* Print \ooo */
789                                                         *s++ = '0' + (c >> 6);
790                                                         *s++ = '0' + ((c >> 3) & 0x7);
791                                                 } else {
792                                                         /* Print \[[o]o]o */
793                                                         if ((c >> 3) != 0) {
794                                                                 if ((c >> 6) != 0)
795                                                                         *s++ = '0' + (c >> 6);
796                                                                 *s++ = '0' + ((c >> 3) & 0x7);
797                                                         }
798                                                 }
799                                                 *s++ = '0' + (c & 0x7);
800                                         }
801                                         break;
802                         }
803                 }
804         }
805
806         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
807                 *s++ = '\"';
808         *s = '\0';
809
810         /* Return zero if we printed entire ASCIZ string (didn't truncate it) */
811         if (style & QUOTE_0_TERMINATED && ustr[i] == '\0') {
812                 /* We didn't see NUL yet (otherwise we'd jump to 'asciz_ended')
813                  * but next char is NUL.
814                  */
815                 return 0;
816         }
817
818         return 1;
819
820  asciz_ended:
821         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
822                 *s++ = '\"';
823         *s = '\0';
824         /* Return zero: we printed entire ASCIZ string (didn't truncate it) */
825         return 0;
826 }
827
828 #ifndef ALLOCA_CUTOFF
829 # define ALLOCA_CUTOFF  4032
830 #endif
831 #define use_alloca(n) ((n) <= ALLOCA_CUTOFF)
832
833 /*
834  * Quote string `str' of length `size' and print the result.
835  *
836  * If QUOTE_0_TERMINATED `style' flag is set,
837  * treat `str' as a NUL-terminated string and
838  * quote at most (`size' - 1) bytes.
839  *
840  * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set,
841  * do not add leading and trailing quoting symbols.
842  *
843  * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise.
844  * Note that if QUOTE_0_TERMINATED is not set, always returns 1.
845  */
846 int
847 print_quoted_string(const char *str, unsigned int size,
848                     const unsigned int style)
849 {
850         char *buf;
851         char *outstr;
852         unsigned int alloc_size;
853         int rc;
854
855         if (size && style & QUOTE_0_TERMINATED)
856                 --size;
857
858         alloc_size = 4 * size;
859         if (alloc_size / 4 != size) {
860                 error_msg("Out of memory");
861                 tprints("???");
862                 return -1;
863         }
864         alloc_size += 1 + (style & QUOTE_OMIT_LEADING_TRAILING_QUOTES ? 0 : 2);
865
866         if (use_alloca(alloc_size)) {
867                 outstr = alloca(alloc_size);
868                 buf = NULL;
869         } else {
870                 outstr = buf = malloc(alloc_size);
871                 if (!buf) {
872                         error_msg("Out of memory");
873                         tprints("???");
874                         return -1;
875                 }
876         }
877
878         rc = string_quote(str, outstr, size, style);
879         tprints(outstr);
880
881         free(buf);
882         return rc;
883 }
884
885 /*
886  * Print path string specified by address `addr' and length `n'.
887  * If path length exceeds `n', append `...' to the output.
888  */
889 void
890 printpathn(struct tcb *const tcp, const kernel_ulong_t addr, unsigned int n)
891 {
892         char path[PATH_MAX + 1];
893         int nul_seen;
894
895         if (!addr) {
896                 tprints("NULL");
897                 return;
898         }
899
900         /* Cap path length to the path buffer size */
901         if (n > sizeof path - 1)
902                 n = sizeof path - 1;
903
904         /* Fetch one byte more to find out whether path length > n. */
905         nul_seen = umovestr(tcp, addr, n + 1, path);
906         if (nul_seen < 0)
907                 printaddr(addr);
908         else {
909                 path[n++] = '\0';
910                 print_quoted_string(path, n, QUOTE_0_TERMINATED);
911                 if (!nul_seen)
912                         tprints("...");
913         }
914 }
915
916 void
917 printpath(struct tcb *const tcp, const kernel_ulong_t addr)
918 {
919         /* Size must correspond to char path[] size in printpathn */
920         printpathn(tcp, addr, PATH_MAX);
921 }
922
923 /*
924  * Print string specified by address `addr' and length `len'.
925  * If `user_style' has QUOTE_0_TERMINATED bit set, treat the string
926  * as a NUL-terminated string.
927  * Pass `user_style' on to `string_quote'.
928  * Append `...' to the output if either the string length exceeds `max_strlen',
929  * or QUOTE_0_TERMINATED bit is set and the string length exceeds `len'.
930  */
931 void
932 printstr_ex(struct tcb *const tcp, const kernel_ulong_t addr,
933             const kernel_ulong_t len, const unsigned int user_style)
934 {
935         static char *str = NULL;
936         static char *outstr;
937         unsigned int size;
938         unsigned int style = user_style;
939         int rc;
940         int ellipsis;
941
942         if (!addr) {
943                 tprints("NULL");
944                 return;
945         }
946         /* Allocate static buffers if they are not allocated yet. */
947         if (!str) {
948                 unsigned int outstr_size = 4 * max_strlen + /*for quotes and NUL:*/ 3;
949
950                 if (outstr_size / 4 != max_strlen)
951                         die_out_of_memory();
952                 str = xmalloc(max_strlen + 1);
953                 outstr = xmalloc(outstr_size);
954         }
955
956         /* Fetch one byte more because string_quote may look one byte ahead. */
957         size = max_strlen + 1;
958
959         if (size > len)
960                 size = len;
961         if (style & QUOTE_0_TERMINATED)
962                 rc = umovestr(tcp, addr, size, str);
963         else
964                 rc = umoven(tcp, addr, size, str);
965
966         if (rc < 0) {
967                 printaddr(addr);
968                 return;
969         }
970
971         if (size > max_strlen)
972                 size = max_strlen;
973         else
974                 str[size] = '\xff';
975
976         /* If string_quote didn't see NUL and (it was supposed to be ASCIZ str
977          * or we were requested to print more than -s NUM chars)...
978          */
979         ellipsis = string_quote(str, outstr, size, style)
980                    && len
981                    && ((style & QUOTE_0_TERMINATED)
982                        || len > max_strlen);
983
984         tprints(outstr);
985         if (ellipsis)
986                 tprints("...");
987 }
988
989 void
990 dumpiov_upto(struct tcb *const tcp, const int len, const kernel_ulong_t addr,
991              kernel_ulong_t data_size)
992 {
993 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
994         union {
995                 struct { uint32_t base; uint32_t len; } *iov32;
996                 struct { uint64_t base; uint64_t len; } *iov64;
997         } iovu;
998 #define iov iovu.iov64
999 #define sizeof_iov \
1000         (current_wordsize == 4 ? sizeof(*iovu.iov32) : sizeof(*iovu.iov64))
1001 #define iov_iov_base(i) \
1002         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].base : iovu.iov64[i].base)
1003 #define iov_iov_len(i) \
1004         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].len : iovu.iov64[i].len)
1005 #else
1006         struct iovec *iov;
1007 #define sizeof_iov sizeof(*iov)
1008 #define iov_iov_base(i) ptr_to_kulong(iov[i].iov_base)
1009 #define iov_iov_len(i) iov[i].iov_len
1010 #endif
1011         int i;
1012         unsigned size;
1013
1014         size = sizeof_iov * len;
1015         /* Assuming no sane program has millions of iovs */
1016         if ((unsigned)len > 1024*1024 /* insane or negative size? */
1017             || (iov = malloc(size)) == NULL) {
1018                 error_msg("Out of memory");
1019                 return;
1020         }
1021         if (umoven(tcp, addr, size, iov) >= 0) {
1022                 for (i = 0; i < len; i++) {
1023                         kernel_ulong_t iov_len = iov_iov_len(i);
1024                         if (iov_len > data_size)
1025                                 iov_len = data_size;
1026                         if (!iov_len)
1027                                 break;
1028                         data_size -= iov_len;
1029                         /* include the buffer number to make it easy to
1030                          * match up the trace with the source */
1031                         tprintf(" * %" PRI_klu " bytes in buffer %d\n", iov_len, i);
1032                         dumpstr(tcp, iov_iov_base(i), iov_len);
1033                 }
1034         }
1035         free(iov);
1036 #undef sizeof_iov
1037 #undef iov_iov_base
1038 #undef iov_iov_len
1039 #undef iov
1040 }
1041
1042 void
1043 dumpstr(struct tcb *const tcp, const kernel_ulong_t addr, const int len)
1044 {
1045         static int strsize = -1;
1046         static unsigned char *str;
1047
1048         char outbuf[
1049                 (
1050                         (sizeof(
1051                         "xx xx xx xx xx xx xx xx  xx xx xx xx xx xx xx xx  "
1052                         "1234567890123456") + /*in case I'm off by few:*/ 4)
1053                 /*align to 8 to make memset easier:*/ + 7) & -8
1054         ];
1055         const unsigned char *src;
1056         int i;
1057
1058         memset(outbuf, ' ', sizeof(outbuf));
1059
1060         if (strsize < len + 16) {
1061                 free(str);
1062                 str = malloc(len + 16);
1063                 if (!str) {
1064                         strsize = -1;
1065                         error_msg("Out of memory");
1066                         return;
1067                 }
1068                 strsize = len + 16;
1069         }
1070
1071         if (umoven(tcp, addr, len, str) < 0)
1072                 return;
1073
1074         /* Space-pad to 16 bytes */
1075         i = len;
1076         while (i & 0xf)
1077                 str[i++] = ' ';
1078
1079         i = 0;
1080         src = str;
1081         while (i < len) {
1082                 char *dst = outbuf;
1083                 /* Hex dump */
1084                 do {
1085                         if (i < len) {
1086                                 *dst++ = "0123456789abcdef"[*src >> 4];
1087                                 *dst++ = "0123456789abcdef"[*src & 0xf];
1088                         }
1089                         else {
1090                                 *dst++ = ' ';
1091                                 *dst++ = ' ';
1092                         }
1093                         dst++; /* space is there by memset */
1094                         i++;
1095                         if ((i & 7) == 0)
1096                                 dst++; /* space is there by memset */
1097                         src++;
1098                 } while (i & 0xf);
1099                 /* ASCII dump */
1100                 i -= 16;
1101                 src -= 16;
1102                 do {
1103                         if (*src >= ' ' && *src < 0x7f)
1104                                 *dst++ = *src;
1105                         else
1106                                 *dst++ = '.';
1107                         src++;
1108                 } while (++i & 0xf);
1109                 *dst = '\0';
1110                 tprintf(" | %05x  %s |\n", i - 16, outbuf);
1111         }
1112 }
1113
1114 static bool process_vm_readv_not_supported = 0;
1115 #ifndef HAVE_PROCESS_VM_READV
1116 /*
1117  * Need to do this since process_vm_readv() is not yet available in libc.
1118  * When libc is be updated, only "static bool process_vm_readv_not_supported"
1119  * line should remain.
1120  */
1121 /* Have to avoid duplicating with the C library headers. */
1122 static ssize_t strace_process_vm_readv(pid_t pid,
1123                  const struct iovec *lvec,
1124                  unsigned long liovcnt,
1125                  const struct iovec *rvec,
1126                  unsigned long riovcnt,
1127                  unsigned long flags)
1128 {
1129         return syscall(__NR_process_vm_readv, (long)pid, lvec, liovcnt, rvec, riovcnt, flags);
1130 }
1131 # define process_vm_readv strace_process_vm_readv
1132 #endif /* !HAVE_PROCESS_VM_READV */
1133
1134 static ssize_t
1135 vm_read_mem(const pid_t pid, void *const laddr,
1136             const kernel_ulong_t raddr, const size_t len)
1137 {
1138         const unsigned long truncated_raddr = raddr;
1139
1140         if (raddr != (kernel_ulong_t) truncated_raddr) {
1141                 errno = EIO;
1142                 return -1;
1143         }
1144
1145         const struct iovec local = {
1146                 .iov_base = laddr,
1147                 .iov_len = len
1148         };
1149         const struct iovec remote = {
1150                 .iov_base = (void *) truncated_raddr,
1151                 .iov_len = len
1152         };
1153
1154         return process_vm_readv(pid, &local, 1, &remote, 1, 0);
1155 }
1156
1157 /*
1158  * move `len' bytes of data from process `pid'
1159  * at address `addr' to our space at `our_addr'
1160  */
1161 int
1162 umoven(struct tcb *const tcp, kernel_ulong_t addr, unsigned int len,
1163        void *const our_addr)
1164 {
1165         char *laddr = our_addr;
1166         int pid = tcp->pid;
1167         unsigned int n, m, nread;
1168         union {
1169                 long val;
1170                 char x[sizeof(long)];
1171         } u;
1172
1173 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
1174         if (current_wordsize < sizeof(addr)
1175             && (addr & (~ (kernel_ulong_t) -1U))) {
1176                 return -1;
1177         }
1178 #endif
1179
1180         if (!process_vm_readv_not_supported) {
1181                 int r = vm_read_mem(pid, laddr, addr, len);
1182                 if ((unsigned int) r == len)
1183                         return 0;
1184                 if (r >= 0) {
1185                         error_msg("umoven: short read (%u < %u) @0x%" PRI_klx,
1186                                   (unsigned int) r, len, addr);
1187                         return -1;
1188                 }
1189                 switch (errno) {
1190                         case ENOSYS:
1191                                 process_vm_readv_not_supported = 1;
1192                                 break;
1193                         case EPERM:
1194                                 /* operation not permitted, try PTRACE_PEEKDATA */
1195                                 break;
1196                         case ESRCH:
1197                                 /* the process is gone */
1198                                 return -1;
1199                         case EFAULT: case EIO:
1200                                 /* address space is inaccessible */
1201                                 return -1;
1202                         default:
1203                                 /* all the rest is strange and should be reported */
1204                                 perror_msg("process_vm_readv");
1205                                 return -1;
1206                 }
1207         }
1208
1209         nread = 0;
1210         if (addr & (sizeof(long) - 1)) {
1211                 /* addr not a multiple of sizeof(long) */
1212                 n = addr & (sizeof(long) - 1);  /* residue */
1213                 addr &= -sizeof(long);          /* aligned address */
1214                 errno = 0;
1215                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1216                 switch (errno) {
1217                         case 0:
1218                                 break;
1219                         case ESRCH: case EINVAL:
1220                                 /* these could be seen if the process is gone */
1221                                 return -1;
1222                         case EFAULT: case EIO: case EPERM:
1223                                 /* address space is inaccessible */
1224                                 return -1;
1225                         default:
1226                                 /* all the rest is strange and should be reported */
1227                                 perror_msg("umoven: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1228                                             pid, addr);
1229                                 return -1;
1230                 }
1231                 m = MIN(sizeof(long) - n, len);
1232                 memcpy(laddr, &u.x[n], m);
1233                 addr += sizeof(long);
1234                 laddr += m;
1235                 nread += m;
1236                 len -= m;
1237         }
1238         while (len) {
1239                 errno = 0;
1240                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1241                 switch (errno) {
1242                         case 0:
1243                                 break;
1244                         case ESRCH: case EINVAL:
1245                                 /* these could be seen if the process is gone */
1246                                 return -1;
1247                         case EFAULT: case EIO: case EPERM:
1248                                 /* address space is inaccessible */
1249                                 if (nread) {
1250                                         perror_msg("umoven: short read (%u < %u) @0x%" PRI_klx,
1251                                                    nread, nread + len, addr - nread);
1252                                 }
1253                                 return -1;
1254                         default:
1255                                 /* all the rest is strange and should be reported */
1256                                 perror_msg("umoven: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1257                                             pid, addr);
1258                                 return -1;
1259                 }
1260                 m = MIN(sizeof(long), len);
1261                 memcpy(laddr, u.x, m);
1262                 addr += sizeof(long);
1263                 laddr += m;
1264                 nread += m;
1265                 len -= m;
1266         }
1267
1268         return 0;
1269 }
1270
1271 int
1272 umoven_or_printaddr(struct tcb *const tcp, const kernel_ulong_t addr,
1273                     const unsigned int len, void *const our_addr)
1274 {
1275         if (!addr || !verbose(tcp) || (exiting(tcp) && syserror(tcp)) ||
1276             umoven(tcp, addr, len, our_addr) < 0) {
1277                 printaddr(addr);
1278                 return -1;
1279         }
1280         return 0;
1281 }
1282
1283 int
1284 umoven_or_printaddr_ignore_syserror(struct tcb *const tcp,
1285                                     const kernel_ulong_t addr,
1286                                     const unsigned int len,
1287                                     void *const our_addr)
1288 {
1289         if (!addr || !verbose(tcp) || umoven(tcp, addr, len, our_addr) < 0) {
1290                 printaddr(addr);
1291                 return -1;
1292         }
1293         return 0;
1294 }
1295
1296 /*
1297  * Like `umove' but make the additional effort of looking
1298  * for a terminating zero byte.
1299  *
1300  * Returns < 0 on error, > 0 if NUL was seen,
1301  * (TODO if useful: return count of bytes including NUL),
1302  * else 0 if len bytes were read but no NUL byte seen.
1303  *
1304  * Note: there is no guarantee we won't overwrite some bytes
1305  * in laddr[] _after_ terminating NUL (but, of course,
1306  * we never write past laddr[len-1]).
1307  */
1308 int
1309 umovestr(struct tcb *const tcp, kernel_ulong_t addr, unsigned int len, char *laddr)
1310 {
1311         const unsigned long x01010101 = (unsigned long) 0x0101010101010101ULL;
1312         const unsigned long x80808080 = (unsigned long) 0x8080808080808080ULL;
1313
1314         int pid = tcp->pid;
1315         unsigned int n, m, nread;
1316         union {
1317                 unsigned long val;
1318                 char x[sizeof(long)];
1319         } u;
1320
1321 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
1322         if (current_wordsize < sizeof(addr)
1323             && (addr & (~ (kernel_ulong_t) -1U))) {
1324                 return -1;
1325         }
1326 #endif
1327
1328         nread = 0;
1329         if (!process_vm_readv_not_supported) {
1330                 const size_t page_size = get_pagesize();
1331                 const size_t page_mask = page_size - 1;
1332
1333                 while (len > 0) {
1334                         unsigned int chunk_len;
1335                         unsigned int end_in_page;
1336
1337                         /*
1338                          * Don't cross pages, otherwise we can get EFAULT
1339                          * and fail to notice that terminating NUL lies
1340                          * in the existing (first) page.
1341                          */
1342                         chunk_len = len > page_size ? page_size : len;
1343                         end_in_page = (addr + chunk_len) & page_mask;
1344                         if (chunk_len > end_in_page) /* crosses to the next page */
1345                                 chunk_len -= end_in_page;
1346
1347                         int r = vm_read_mem(pid, laddr, addr, chunk_len);
1348                         if (r > 0) {
1349                                 if (memchr(laddr, '\0', r))
1350                                         return 1;
1351                                 addr += r;
1352                                 laddr += r;
1353                                 nread += r;
1354                                 len -= r;
1355                                 continue;
1356                         }
1357                         switch (errno) {
1358                                 case ENOSYS:
1359                                         process_vm_readv_not_supported = 1;
1360                                         goto vm_readv_didnt_work;
1361                                 case ESRCH:
1362                                         /* the process is gone */
1363                                         return -1;
1364                                 case EPERM:
1365                                         /* operation not permitted, try PTRACE_PEEKDATA */
1366                                         if (!nread)
1367                                                 goto vm_readv_didnt_work;
1368                                         /* fall through */
1369                                 case EFAULT: case EIO:
1370                                         /* address space is inaccessible */
1371                                         if (nread) {
1372                                                 perror_msg("umovestr: short read (%d < %d) @0x%" PRI_klx,
1373                                                            nread, nread + len, addr - nread);
1374                                         }
1375                                         return -1;
1376                                 default:
1377                                         /* all the rest is strange and should be reported */
1378                                         perror_msg("process_vm_readv");
1379                                         return -1;
1380                         }
1381                 }
1382                 return 0;
1383         }
1384  vm_readv_didnt_work:
1385
1386         if (addr & (sizeof(long) - 1)) {
1387                 /* addr not a multiple of sizeof(long) */
1388                 n = addr & (sizeof(long) - 1);  /* residue */
1389                 addr &= -sizeof(long);          /* aligned address */
1390                 errno = 0;
1391                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1392                 switch (errno) {
1393                         case 0:
1394                                 break;
1395                         case ESRCH: case EINVAL:
1396                                 /* these could be seen if the process is gone */
1397                                 return -1;
1398                         case EFAULT: case EIO: case EPERM:
1399                                 /* address space is inaccessible */
1400                                 return -1;
1401                         default:
1402                                 /* all the rest is strange and should be reported */
1403                                 perror_msg("umovestr: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1404                                             pid, addr);
1405                                 return -1;
1406                 }
1407                 m = MIN(sizeof(long) - n, len);
1408                 memcpy(laddr, &u.x[n], m);
1409                 while (n & (sizeof(long) - 1))
1410                         if (u.x[n++] == '\0')
1411                                 return 1;
1412                 addr += sizeof(long);
1413                 laddr += m;
1414                 nread += m;
1415                 len -= m;
1416         }
1417
1418         while (len) {
1419                 errno = 0;
1420                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1421                 switch (errno) {
1422                         case 0:
1423                                 break;
1424                         case ESRCH: case EINVAL:
1425                                 /* these could be seen if the process is gone */
1426                                 return -1;
1427                         case EFAULT: case EIO: case EPERM:
1428                                 /* address space is inaccessible */
1429                                 if (nread) {
1430                                         perror_msg("umovestr: short read (%d < %d) @0x%" PRI_klx,
1431                                                    nread, nread + len, addr - nread);
1432                                 }
1433                                 return -1;
1434                         default:
1435                                 /* all the rest is strange and should be reported */
1436                                 perror_msg("umovestr: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1437                                            pid, addr);
1438                                 return -1;
1439                 }
1440                 m = MIN(sizeof(long), len);
1441                 memcpy(laddr, u.x, m);
1442                 /* "If a NUL char exists in this word" */
1443                 if ((u.val - x01010101) & ~u.val & x80808080)
1444                         return 1;
1445                 addr += sizeof(long);
1446                 laddr += m;
1447                 nread += m;
1448                 len -= m;
1449         }
1450         return 0;
1451 }
1452
1453 /*
1454  * Iteratively fetch and print up to nmemb elements of elem_size size
1455  * from the array that starts at tracee's address start_addr.
1456  *
1457  * Array elements are being fetched to the address specified by elem_buf.
1458  *
1459  * The fetcher callback function specified by umoven_func should follow
1460  * the same semantics as umoven_or_printaddr function.
1461  *
1462  * The printer callback function specified by print_func is expected
1463  * to print something; if it returns false, no more iterations will be made.
1464  *
1465  * The pointer specified by opaque_data is passed to each invocation
1466  * of print_func callback function.
1467  *
1468  * This function prints:
1469  * - "NULL", if start_addr is NULL;
1470  * - "[]", if nmemb is 0;
1471  * - start_addr, if nmemb * elem_size overflows or wraps around;
1472  * - nothing, if the first element cannot be fetched
1473  *   (if umoven_func returns non-zero), but it is assumed that
1474  *   umoven_func has printed the address it failed to fetch data from;
1475  * - elements of the array, delimited by ", ", with the array itself
1476  *   enclosed with [] brackets.
1477  *
1478  * If abbrev(tcp) is true, then
1479  * - the maximum number of elements printed equals to max_strlen;
1480  * - "..." is printed instead of max_strlen+1 element
1481  *   and no more iterations will be made.
1482  *
1483  * This function returns true only if
1484  * - umoven_func has been called at least once AND
1485  * - umoven_func has not returned false.
1486  */
1487 bool
1488 print_array(struct tcb *const tcp,
1489             const kernel_ulong_t start_addr,
1490             const size_t nmemb,
1491             void *const elem_buf,
1492             const size_t elem_size,
1493             int (*const umoven_func)(struct tcb *,
1494                                      kernel_ulong_t,
1495                                      unsigned int,
1496                                      void *),
1497             bool (*const print_func)(struct tcb *,
1498                                      void *elem_buf,
1499                                      size_t elem_size,
1500                                      void *opaque_data),
1501             void *const opaque_data)
1502 {
1503         if (!start_addr) {
1504                 tprints("NULL");
1505                 return false;
1506         }
1507
1508         if (!nmemb) {
1509                 tprints("[]");
1510                 return false;
1511         }
1512
1513         const size_t size = nmemb * elem_size;
1514         const kernel_ulong_t end_addr = start_addr + size;
1515
1516         if (end_addr <= start_addr || size / elem_size != nmemb) {
1517                 printaddr(start_addr);
1518                 return false;
1519         }
1520
1521         const kernel_ulong_t abbrev_end =
1522                 (abbrev(tcp) && max_strlen < nmemb) ?
1523                         start_addr + elem_size * max_strlen : end_addr;
1524         kernel_ulong_t cur;
1525
1526         for (cur = start_addr; cur < end_addr; cur += elem_size) {
1527                 if (cur != start_addr)
1528                         tprints(", ");
1529
1530                 if (umoven_func(tcp, cur, elem_size, elem_buf))
1531                         break;
1532
1533                 if (cur == start_addr)
1534                         tprints("[");
1535
1536                 if (cur >= abbrev_end) {
1537                         tprints("...");
1538                         cur = end_addr;
1539                         break;
1540                 }
1541
1542                 if (!print_func(tcp, elem_buf, elem_size, opaque_data)) {
1543                         cur = end_addr;
1544                         break;
1545                 }
1546         }
1547         if (cur != start_addr)
1548                 tprints("]");
1549
1550         return cur >= end_addr;
1551 }
1552
1553 int
1554 printargs(struct tcb *tcp)
1555 {
1556         const int n = tcp->s_ent->nargs;
1557         int i;
1558         for (i = 0; i < n; ++i)
1559                 tprintf("%s%#" PRI_klx, i ? ", " : "", tcp->u_arg[i]);
1560         return RVAL_DECODED;
1561 }
1562
1563 int
1564 printargs_u(struct tcb *tcp)
1565 {
1566         const int n = tcp->s_ent->nargs;
1567         int i;
1568         for (i = 0; i < n; ++i)
1569                 tprintf("%s%u", i ? ", " : "",
1570                         (unsigned int) tcp->u_arg[i]);
1571         return RVAL_DECODED;
1572 }
1573
1574 int
1575 printargs_d(struct tcb *tcp)
1576 {
1577         const int n = tcp->s_ent->nargs;
1578         int i;
1579         for (i = 0; i < n; ++i)
1580                 tprintf("%s%d", i ? ", " : "",
1581                         (int) tcp->u_arg[i]);
1582         return RVAL_DECODED;
1583 }
1584
1585 /* Print abnormal high bits of a kernel_ulong_t value. */
1586 void
1587 print_abnormal_hi(const kernel_ulong_t val)
1588 {
1589         if (current_klongsize > 4) {
1590                 const unsigned int hi = (unsigned int) ((uint64_t) val >> 32);
1591                 if (hi)
1592                         tprintf("%#x<<32|", hi);
1593         }
1594 }
1595
1596 #if defined _LARGEFILE64_SOURCE && defined HAVE_OPEN64
1597 # define open_file open64
1598 #else
1599 # define open_file open
1600 #endif
1601
1602 int
1603 read_int_from_file(const char *const fname, int *const pvalue)
1604 {
1605         const int fd = open_file(fname, O_RDONLY);
1606         if (fd < 0)
1607                 return -1;
1608
1609         long lval;
1610         char buf[sizeof(lval) * 3];
1611         int n = read(fd, buf, sizeof(buf) - 1);
1612         int saved_errno = errno;
1613         close(fd);
1614
1615         if (n < 0) {
1616                 errno = saved_errno;
1617                 return -1;
1618         }
1619
1620         buf[n] = '\0';
1621         char *endptr = 0;
1622         errno = 0;
1623         lval = strtol(buf, &endptr, 10);
1624         if (!endptr || (*endptr && '\n' != *endptr)
1625 #if INT_MAX < LONG_MAX
1626             || lval > INT_MAX || lval < INT_MIN
1627 #endif
1628             || ERANGE == errno) {
1629                 if (!errno)
1630                         errno = EINVAL;
1631                 return -1;
1632         }
1633
1634         *pvalue = (int) lval;
1635         return 0;
1636 }