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