]> granicus.if.org Git - strace/blob - util.c
util: add support for forcing printing string as hex-escaped
[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         if (dflt)
255                 tprintf(" /* %s */", 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         if (dflt)
289                 tprintf(" /* %s */", dflt);
290
291         return 0;
292 }
293
294 /*
295  * Fetch 64bit argument at position arg_no and
296  * return the index of the next argument.
297  */
298 int
299 getllval(struct tcb *tcp, unsigned long long *val, int arg_no)
300 {
301 #if SIZEOF_KERNEL_LONG_T > 4
302 # ifndef current_klongsize
303         if (current_klongsize < SIZEOF_KERNEL_LONG_T) {
304 #  if defined(AARCH64) || defined(POWERPC64)
305                 /* Align arg_no to the next even number. */
306                 arg_no = (arg_no + 1) & 0xe;
307 #  endif /* AARCH64 || POWERPC64 */
308                 *val = ULONG_LONG(tcp->u_arg[arg_no], tcp->u_arg[arg_no + 1]);
309                 arg_no += 2;
310         } else
311 # endif /* !current_klongsize */
312         {
313                 *val = tcp->u_arg[arg_no];
314                 arg_no++;
315         }
316 #else /* SIZEOF_KERNEL_LONG_T == 4 */
317 # if defined __ARM_EABI__ || \
318      defined LINUX_MIPSO32 || \
319      defined POWERPC || \
320      defined XTENSA
321         /* Align arg_no to the next even number. */
322         arg_no = (arg_no + 1) & 0xe;
323 # elif defined SH
324         /*
325          * The SH4 ABI does allow long longs in odd-numbered registers, but
326          * does not allow them to be split between registers and memory - and
327          * there are only four argument registers for normal functions.  As a
328          * result, pread, for example, takes an extra padding argument before
329          * the offset.  This was changed late in the 2.4 series (around 2.4.20).
330          */
331         if (arg_no == 3)
332                 arg_no++;
333 # endif /* __ARM_EABI__ || LINUX_MIPSO32 || POWERPC || XTENSA || SH */
334         *val = ULONG_LONG(tcp->u_arg[arg_no], tcp->u_arg[arg_no + 1]);
335         arg_no += 2;
336 #endif
337
338         return arg_no;
339 }
340
341 /*
342  * Print 64bit argument at position arg_no and
343  * return the index of the next argument.
344  */
345 int
346 printllval(struct tcb *tcp, const char *format, int arg_no)
347 {
348         unsigned long long val = 0;
349
350         arg_no = getllval(tcp, &val, arg_no);
351         tprintf(format, val);
352         return arg_no;
353 }
354
355 /*
356  * Interpret `xlat' as an array of flags
357  * print the entries whose bits are on in `flags'
358  * return # of flags printed.
359  */
360 void
361 addflags(const struct xlat *xlat, uint64_t flags)
362 {
363         for (; xlat->str; xlat++) {
364                 if (xlat->val && (flags & xlat->val) == xlat->val) {
365                         tprintf("|%s", xlat->str);
366                         flags &= ~xlat->val;
367                 }
368         }
369         if (flags) {
370                 tprintf("|%#" PRIx64, flags);
371         }
372 }
373
374 /*
375  * Interpret `xlat' as an array of flags.
376  * Print to static string the entries whose bits are on in `flags'
377  * Return static string.
378  */
379 const char *
380 sprintflags(const char *prefix, const struct xlat *xlat, uint64_t flags)
381 {
382         static char outstr[1024];
383         char *outptr;
384         int found = 0;
385
386         outptr = stpcpy(outstr, prefix);
387
388         if (flags == 0 && xlat->val == 0 && xlat->str) {
389                 strcpy(outptr, xlat->str);
390                 return outstr;
391         }
392
393         for (; xlat->str; xlat++) {
394                 if (xlat->val && (flags & xlat->val) == xlat->val) {
395                         if (found)
396                                 *outptr++ = '|';
397                         outptr = stpcpy(outptr, xlat->str);
398                         found = 1;
399                         flags &= ~xlat->val;
400                         if (!flags)
401                                 break;
402                 }
403         }
404         if (flags) {
405                 if (found)
406                         *outptr++ = '|';
407                 outptr += sprintf(outptr, "%#" PRIx64, flags);
408         }
409
410         return outstr;
411 }
412
413 int
414 printflags64(const struct xlat *xlat, uint64_t flags, const char *dflt)
415 {
416         int n;
417         const char *sep;
418
419         if (flags == 0 && xlat->val == 0 && xlat->str) {
420                 tprints(xlat->str);
421                 return 1;
422         }
423
424         sep = "";
425         for (n = 0; xlat->str; xlat++) {
426                 if (xlat->val && (flags & xlat->val) == xlat->val) {
427                         tprintf("%s%s", sep, xlat->str);
428                         flags &= ~xlat->val;
429                         sep = "|";
430                         n++;
431                 }
432         }
433
434         if (n) {
435                 if (flags) {
436                         tprintf("%s%#" PRIx64, sep, flags);
437                         n++;
438                 }
439         } else {
440                 if (flags) {
441                         tprintf("%#" PRIx64, flags);
442                         if (dflt)
443                                 tprintf(" /* %s */", dflt);
444                 } else {
445                         if (dflt)
446                                 tprints("0");
447                 }
448         }
449
450         return n;
451 }
452
453 void
454 printaddr(const kernel_ulong_t addr)
455 {
456         if (!addr)
457                 tprints("NULL");
458         else
459                 tprintf("%#" PRI_klx, addr);
460 }
461
462 #define DEF_PRINTNUM(name, type) \
463 bool                                                                    \
464 printnum_ ## name(struct tcb *const tcp, const kernel_ulong_t addr,     \
465                   const char *const fmt)                                \
466 {                                                                       \
467         type num;                                                       \
468         if (umove_or_printaddr(tcp, addr, &num))                        \
469                 return false;                                           \
470         tprints("[");                                                   \
471         tprintf(fmt, num);                                              \
472         tprints("]");                                                   \
473         return true;                                                    \
474 }
475
476 #define DEF_PRINTNUM_ADDR(name, type) \
477 bool                                                                    \
478 printnum_addr_ ## name(struct tcb *tcp, const kernel_ulong_t addr)      \
479 {                                                                       \
480         type num;                                                       \
481         if (umove_or_printaddr(tcp, addr, &num))                        \
482                 return false;                                           \
483         tprints("[");                                                   \
484         printaddr(num);                                                 \
485         tprints("]");                                                   \
486         return true;                                                    \
487 }
488
489 #define DEF_PRINTPAIR(name, type) \
490 bool                                                                    \
491 printpair_ ## name(struct tcb *const tcp, const kernel_ulong_t addr,    \
492                    const char *const fmt)                               \
493 {                                                                       \
494         type pair[2];                                                   \
495         if (umove_or_printaddr(tcp, addr, &pair))                       \
496                 return false;                                           \
497         tprints("[");                                                   \
498         tprintf(fmt, pair[0]);                                          \
499         tprints(", ");                                                  \
500         tprintf(fmt, pair[1]);                                          \
501         tprints("]");                                                   \
502         return true;                                                    \
503 }
504
505 DEF_PRINTNUM(int, int)
506 DEF_PRINTNUM_ADDR(int, unsigned int)
507 DEF_PRINTPAIR(int, int)
508 DEF_PRINTNUM(short, short)
509 DEF_PRINTNUM(int64, uint64_t)
510 DEF_PRINTNUM_ADDR(int64, uint64_t)
511 DEF_PRINTPAIR(int64, uint64_t)
512
513 #ifndef current_wordsize
514 bool
515 printnum_long_int(struct tcb *const tcp, const kernel_ulong_t addr,
516                   const char *const fmt_long, const char *const fmt_int)
517 {
518         if (current_wordsize > sizeof(int)) {
519                 return printnum_int64(tcp, addr, fmt_long);
520         } else {
521                 return printnum_int(tcp, addr, fmt_int);
522         }
523 }
524
525 bool
526 printnum_addr_long_int(struct tcb *tcp, const kernel_ulong_t addr)
527 {
528         if (current_wordsize > sizeof(int)) {
529                 return printnum_addr_int64(tcp, addr);
530         } else {
531                 return printnum_addr_int(tcp, addr);
532         }
533 }
534 #endif /* !current_wordsize */
535
536 #ifndef current_klongsize
537 bool
538 printnum_addr_klong_int(struct tcb *tcp, const kernel_ulong_t addr)
539 {
540         if (current_klongsize > sizeof(int)) {
541                 return printnum_addr_int64(tcp, addr);
542         } else {
543                 return printnum_addr_int(tcp, addr);
544         }
545 }
546 #endif /* !current_klongsize */
547
548 const char *
549 sprinttime(time_t t)
550 {
551         struct tm *tmp;
552         static char buf[sizeof(int) * 3 * 6 + sizeof("+0000")];
553
554         if (t == 0) {
555                 strcpy(buf, "0");
556                 return buf;
557         }
558         tmp = localtime(&t);
559         if (tmp)
560                 strftime(buf, sizeof(buf), "%FT%T%z", tmp);
561         else
562                 snprintf(buf, sizeof(buf), "%lu", (unsigned long) t);
563
564         return buf;
565 }
566
567 enum sock_proto
568 getfdproto(struct tcb *tcp, int fd)
569 {
570 #ifdef HAVE_SYS_XATTR_H
571         size_t bufsize = 256;
572         char buf[bufsize];
573         ssize_t r;
574         char path[sizeof("/proc/%u/fd/%u") + 2 * sizeof(int)*3];
575
576         if (fd < 0)
577                 return SOCK_PROTO_UNKNOWN;
578
579         sprintf(path, "/proc/%u/fd/%u", tcp->pid, fd);
580         r = getxattr(path, "system.sockprotoname", buf, bufsize - 1);
581         if (r <= 0)
582                 return SOCK_PROTO_UNKNOWN;
583         else {
584                 /*
585                  * This is a protection for the case when the kernel
586                  * side does not append a null byte to the buffer.
587                  */
588                 buf[r] = '\0';
589
590                 return get_proto_by_name(buf);
591         }
592 #else
593         return SOCK_PROTO_UNKNOWN;
594 #endif
595 }
596
597 void
598 printfd(struct tcb *tcp, int fd)
599 {
600         char path[PATH_MAX + 1];
601         if (show_fd_path && getfdpath(tcp, fd, path, sizeof(path)) >= 0) {
602                 static const char socket_prefix[] = "socket:[";
603                 const size_t socket_prefix_len = sizeof(socket_prefix) - 1;
604                 const size_t path_len = strlen(path);
605
606                 tprintf("%d<", fd);
607                 if (show_fd_path > 1 &&
608                     strncmp(path, socket_prefix, socket_prefix_len) == 0 &&
609                     path[path_len - 1] == ']') {
610                         unsigned long inode =
611                                 strtoul(path + socket_prefix_len, NULL, 10);
612
613                         if (!print_sockaddr_by_inode_cached(inode)) {
614                                 const enum sock_proto proto =
615                                         getfdproto(tcp, fd);
616                                 if (!print_sockaddr_by_inode(inode, proto))
617                                         tprints(path);
618                         }
619                 } else {
620                         print_quoted_string(path, path_len,
621                                             QUOTE_OMIT_LEADING_TRAILING_QUOTES);
622                 }
623                 tprints(">");
624         } else
625                 tprintf("%d", fd);
626 }
627
628 /*
629  * Quote string `instr' of length `size'
630  * Write up to (3 + `size' * 4) bytes to `outstr' buffer.
631  *
632  * If QUOTE_0_TERMINATED `style' flag is set,
633  * treat `instr' as a NUL-terminated string,
634  * checking up to (`size' + 1) bytes of `instr'.
635  *
636  * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set,
637  * do not add leading and trailing quoting symbols.
638  *
639  * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise.
640  * Note that if QUOTE_0_TERMINATED is not set, always returns 1.
641  */
642 int
643 string_quote(const char *instr, char *outstr, const unsigned int size,
644              const unsigned int style)
645 {
646         const unsigned char *ustr = (const unsigned char *) instr;
647         char *s = outstr;
648         unsigned int i;
649         int usehex, c, eol;
650
651         if (style & QUOTE_0_TERMINATED)
652                 eol = '\0';
653         else
654                 eol = 0x100; /* this can never match a char */
655
656         usehex = 0;
657         if ((xflag > 1) || (style & QUOTE_FORCE_HEX)) {
658                 usehex = 1;
659         } else if (xflag) {
660                 /* Check for presence of symbol which require
661                    to hex-quote the whole string. */
662                 for (i = 0; i < size; ++i) {
663                         c = ustr[i];
664                         /* Check for NUL-terminated string. */
665                         if (c == eol)
666                                 break;
667
668                         /* Force hex unless c is printable or whitespace */
669                         if (c > 0x7e) {
670                                 usehex = 1;
671                                 break;
672                         }
673                         /* In ASCII isspace is only these chars: "\t\n\v\f\r".
674                          * They happen to have ASCII codes 9,10,11,12,13.
675                          */
676                         if (c < ' ' && (unsigned)(c - 9) >= 5) {
677                                 usehex = 1;
678                                 break;
679                         }
680                 }
681         }
682
683         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
684                 *s++ = '\"';
685
686         if (usehex) {
687                 /* Hex-quote the whole string. */
688                 for (i = 0; i < size; ++i) {
689                         c = ustr[i];
690                         /* Check for NUL-terminated string. */
691                         if (c == eol)
692                                 goto asciz_ended;
693                         *s++ = '\\';
694                         *s++ = 'x';
695                         *s++ = "0123456789abcdef"[c >> 4];
696                         *s++ = "0123456789abcdef"[c & 0xf];
697                 }
698         } else {
699                 for (i = 0; i < size; ++i) {
700                         c = ustr[i];
701                         /* Check for NUL-terminated string. */
702                         if (c == eol)
703                                 goto asciz_ended;
704                         if ((i == (size - 1)) &&
705                             (style & QUOTE_OMIT_TRAILING_0) && (c == '\0'))
706                                 goto asciz_ended;
707                         switch (c) {
708                                 case '\"': case '\\':
709                                         *s++ = '\\';
710                                         *s++ = c;
711                                         break;
712                                 case '\f':
713                                         *s++ = '\\';
714                                         *s++ = 'f';
715                                         break;
716                                 case '\n':
717                                         *s++ = '\\';
718                                         *s++ = 'n';
719                                         break;
720                                 case '\r':
721                                         *s++ = '\\';
722                                         *s++ = 'r';
723                                         break;
724                                 case '\t':
725                                         *s++ = '\\';
726                                         *s++ = 't';
727                                         break;
728                                 case '\v':
729                                         *s++ = '\\';
730                                         *s++ = 'v';
731                                         break;
732                                 default:
733                                         if (c >= ' ' && c <= 0x7e)
734                                                 *s++ = c;
735                                         else {
736                                                 /* Print \octal */
737                                                 *s++ = '\\';
738                                                 if (i + 1 < size
739                                                     && ustr[i + 1] >= '0'
740                                                     && ustr[i + 1] <= '9'
741                                                 ) {
742                                                         /* Print \ooo */
743                                                         *s++ = '0' + (c >> 6);
744                                                         *s++ = '0' + ((c >> 3) & 0x7);
745                                                 } else {
746                                                         /* Print \[[o]o]o */
747                                                         if ((c >> 3) != 0) {
748                                                                 if ((c >> 6) != 0)
749                                                                         *s++ = '0' + (c >> 6);
750                                                                 *s++ = '0' + ((c >> 3) & 0x7);
751                                                         }
752                                                 }
753                                                 *s++ = '0' + (c & 0x7);
754                                         }
755                                         break;
756                         }
757                 }
758         }
759
760         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
761                 *s++ = '\"';
762         *s = '\0';
763
764         /* Return zero if we printed entire ASCIZ string (didn't truncate it) */
765         if (style & QUOTE_0_TERMINATED && ustr[i] == '\0') {
766                 /* We didn't see NUL yet (otherwise we'd jump to 'asciz_ended')
767                  * but next char is NUL.
768                  */
769                 return 0;
770         }
771
772         return 1;
773
774  asciz_ended:
775         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
776                 *s++ = '\"';
777         *s = '\0';
778         /* Return zero: we printed entire ASCIZ string (didn't truncate it) */
779         return 0;
780 }
781
782 #ifndef ALLOCA_CUTOFF
783 # define ALLOCA_CUTOFF  4032
784 #endif
785 #define use_alloca(n) ((n) <= ALLOCA_CUTOFF)
786
787 /*
788  * Quote string `str' of length `size' and print the result.
789  *
790  * If QUOTE_0_TERMINATED `style' flag is set,
791  * treat `str' as a NUL-terminated string and
792  * quote at most (`size' - 1) bytes.
793  *
794  * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set,
795  * do not add leading and trailing quoting symbols.
796  *
797  * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise.
798  * Note that if QUOTE_0_TERMINATED is not set, always returns 1.
799  */
800 int
801 print_quoted_string(const char *str, unsigned int size,
802                     const unsigned int style)
803 {
804         char *buf;
805         char *outstr;
806         unsigned int alloc_size;
807         int rc;
808
809         if (size && style & QUOTE_0_TERMINATED)
810                 --size;
811
812         alloc_size = 4 * size;
813         if (alloc_size / 4 != size) {
814                 error_msg("Out of memory");
815                 tprints("???");
816                 return -1;
817         }
818         alloc_size += 1 + (style & QUOTE_OMIT_LEADING_TRAILING_QUOTES ? 0 : 2);
819
820         if (use_alloca(alloc_size)) {
821                 outstr = alloca(alloc_size);
822                 buf = NULL;
823         } else {
824                 outstr = buf = malloc(alloc_size);
825                 if (!buf) {
826                         error_msg("Out of memory");
827                         tprints("???");
828                         return -1;
829                 }
830         }
831
832         rc = string_quote(str, outstr, size, style);
833         tprints(outstr);
834
835         free(buf);
836         return rc;
837 }
838
839 /*
840  * Print path string specified by address `addr' and length `n'.
841  * If path length exceeds `n', append `...' to the output.
842  */
843 void
844 printpathn(struct tcb *const tcp, const kernel_ulong_t addr, unsigned int n)
845 {
846         char path[PATH_MAX + 1];
847         int nul_seen;
848
849         if (!addr) {
850                 tprints("NULL");
851                 return;
852         }
853
854         /* Cap path length to the path buffer size */
855         if (n > sizeof path - 1)
856                 n = sizeof path - 1;
857
858         /* Fetch one byte more to find out whether path length > n. */
859         nul_seen = umovestr(tcp, addr, n + 1, path);
860         if (nul_seen < 0)
861                 printaddr(addr);
862         else {
863                 path[n++] = '\0';
864                 print_quoted_string(path, n, QUOTE_0_TERMINATED);
865                 if (!nul_seen)
866                         tprints("...");
867         }
868 }
869
870 void
871 printpath(struct tcb *const tcp, const kernel_ulong_t addr)
872 {
873         /* Size must correspond to char path[] size in printpathn */
874         printpathn(tcp, addr, PATH_MAX);
875 }
876
877 /*
878  * Print string specified by address `addr' and length `len'.
879  * If `user_style' has QUOTE_0_TERMINATED bit set, treat the string
880  * as a NUL-terminated string.
881  * Pass `user_style' on to `string_quote'.
882  * Append `...' to the output if either the string length exceeds `max_strlen',
883  * or QUOTE_0_TERMINATED bit is set and the string length exceeds `len'.
884  */
885 void
886 printstr_ex(struct tcb *const tcp, const kernel_ulong_t addr,
887             const kernel_ulong_t len, const unsigned int user_style)
888 {
889         static char *str = NULL;
890         static char *outstr;
891         unsigned int size;
892         unsigned int style = user_style;
893         int rc;
894         int ellipsis;
895
896         if (!addr) {
897                 tprints("NULL");
898                 return;
899         }
900         /* Allocate static buffers if they are not allocated yet. */
901         if (!str) {
902                 unsigned int outstr_size = 4 * max_strlen + /*for quotes and NUL:*/ 3;
903
904                 if (outstr_size / 4 != max_strlen)
905                         die_out_of_memory();
906                 str = xmalloc(max_strlen + 1);
907                 outstr = xmalloc(outstr_size);
908         }
909
910         /* Fetch one byte more because string_quote may look one byte ahead. */
911         size = max_strlen + 1;
912
913         if (size > len)
914                 size = len;
915         if (style & QUOTE_0_TERMINATED)
916                 rc = umovestr(tcp, addr, size, str);
917         else
918                 rc = umoven(tcp, addr, size, str);
919
920         if (rc < 0) {
921                 printaddr(addr);
922                 return;
923         }
924
925         if (size > max_strlen)
926                 size = max_strlen;
927         else
928                 str[size] = '\xff';
929
930         /* If string_quote didn't see NUL and (it was supposed to be ASCIZ str
931          * or we were requested to print more than -s NUM chars)...
932          */
933         ellipsis = string_quote(str, outstr, size, style)
934                    && len
935                    && ((style & QUOTE_0_TERMINATED)
936                        || len > max_strlen);
937
938         tprints(outstr);
939         if (ellipsis)
940                 tprints("...");
941 }
942
943 void
944 dumpiov_upto(struct tcb *const tcp, const int len, const kernel_ulong_t addr,
945              kernel_ulong_t data_size)
946 {
947 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
948         union {
949                 struct { uint32_t base; uint32_t len; } *iov32;
950                 struct { uint64_t base; uint64_t len; } *iov64;
951         } iovu;
952 #define iov iovu.iov64
953 #define sizeof_iov \
954         (current_wordsize == 4 ? sizeof(*iovu.iov32) : sizeof(*iovu.iov64))
955 #define iov_iov_base(i) \
956         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].base : iovu.iov64[i].base)
957 #define iov_iov_len(i) \
958         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].len : iovu.iov64[i].len)
959 #else
960         struct iovec *iov;
961 #define sizeof_iov sizeof(*iov)
962 #define iov_iov_base(i) ptr_to_kulong(iov[i].iov_base)
963 #define iov_iov_len(i) iov[i].iov_len
964 #endif
965         int i;
966         unsigned size;
967
968         size = sizeof_iov * len;
969         /* Assuming no sane program has millions of iovs */
970         if ((unsigned)len > 1024*1024 /* insane or negative size? */
971             || (iov = malloc(size)) == NULL) {
972                 error_msg("Out of memory");
973                 return;
974         }
975         if (umoven(tcp, addr, size, iov) >= 0) {
976                 for (i = 0; i < len; i++) {
977                         kernel_ulong_t iov_len = iov_iov_len(i);
978                         if (iov_len > data_size)
979                                 iov_len = data_size;
980                         if (!iov_len)
981                                 break;
982                         data_size -= iov_len;
983                         /* include the buffer number to make it easy to
984                          * match up the trace with the source */
985                         tprintf(" * %" PRI_klu " bytes in buffer %d\n", iov_len, i);
986                         dumpstr(tcp, iov_iov_base(i), iov_len);
987                 }
988         }
989         free(iov);
990 #undef sizeof_iov
991 #undef iov_iov_base
992 #undef iov_iov_len
993 #undef iov
994 }
995
996 void
997 dumpstr(struct tcb *const tcp, const kernel_ulong_t addr, const int len)
998 {
999         static int strsize = -1;
1000         static unsigned char *str;
1001
1002         char outbuf[
1003                 (
1004                         (sizeof(
1005                         "xx xx xx xx xx xx xx xx  xx xx xx xx xx xx xx xx  "
1006                         "1234567890123456") + /*in case I'm off by few:*/ 4)
1007                 /*align to 8 to make memset easier:*/ + 7) & -8
1008         ];
1009         const unsigned char *src;
1010         int i;
1011
1012         memset(outbuf, ' ', sizeof(outbuf));
1013
1014         if (strsize < len + 16) {
1015                 free(str);
1016                 str = malloc(len + 16);
1017                 if (!str) {
1018                         strsize = -1;
1019                         error_msg("Out of memory");
1020                         return;
1021                 }
1022                 strsize = len + 16;
1023         }
1024
1025         if (umoven(tcp, addr, len, str) < 0)
1026                 return;
1027
1028         /* Space-pad to 16 bytes */
1029         i = len;
1030         while (i & 0xf)
1031                 str[i++] = ' ';
1032
1033         i = 0;
1034         src = str;
1035         while (i < len) {
1036                 char *dst = outbuf;
1037                 /* Hex dump */
1038                 do {
1039                         if (i < len) {
1040                                 *dst++ = "0123456789abcdef"[*src >> 4];
1041                                 *dst++ = "0123456789abcdef"[*src & 0xf];
1042                         }
1043                         else {
1044                                 *dst++ = ' ';
1045                                 *dst++ = ' ';
1046                         }
1047                         dst++; /* space is there by memset */
1048                         i++;
1049                         if ((i & 7) == 0)
1050                                 dst++; /* space is there by memset */
1051                         src++;
1052                 } while (i & 0xf);
1053                 /* ASCII dump */
1054                 i -= 16;
1055                 src -= 16;
1056                 do {
1057                         if (*src >= ' ' && *src < 0x7f)
1058                                 *dst++ = *src;
1059                         else
1060                                 *dst++ = '.';
1061                         src++;
1062                 } while (++i & 0xf);
1063                 *dst = '\0';
1064                 tprintf(" | %05x  %s |\n", i - 16, outbuf);
1065         }
1066 }
1067
1068 static bool process_vm_readv_not_supported = 0;
1069 #ifndef HAVE_PROCESS_VM_READV
1070 /*
1071  * Need to do this since process_vm_readv() is not yet available in libc.
1072  * When libc is be updated, only "static bool process_vm_readv_not_supported"
1073  * line should remain.
1074  */
1075 /* Have to avoid duplicating with the C library headers. */
1076 static ssize_t strace_process_vm_readv(pid_t pid,
1077                  const struct iovec *lvec,
1078                  unsigned long liovcnt,
1079                  const struct iovec *rvec,
1080                  unsigned long riovcnt,
1081                  unsigned long flags)
1082 {
1083         return syscall(__NR_process_vm_readv, (long)pid, lvec, liovcnt, rvec, riovcnt, flags);
1084 }
1085 # define process_vm_readv strace_process_vm_readv
1086 #endif /* !HAVE_PROCESS_VM_READV */
1087
1088 static ssize_t
1089 vm_read_mem(const pid_t pid, void *const laddr,
1090             const kernel_ulong_t raddr, const size_t len)
1091 {
1092         const unsigned long truncated_raddr = raddr;
1093
1094         if (raddr != (kernel_ulong_t) truncated_raddr) {
1095                 errno = EIO;
1096                 return -1;
1097         }
1098
1099         const struct iovec local = {
1100                 .iov_base = laddr,
1101                 .iov_len = len
1102         };
1103         const struct iovec remote = {
1104                 .iov_base = (void *) truncated_raddr,
1105                 .iov_len = len
1106         };
1107
1108         return process_vm_readv(pid, &local, 1, &remote, 1, 0);
1109 }
1110
1111 /*
1112  * move `len' bytes of data from process `pid'
1113  * at address `addr' to our space at `our_addr'
1114  */
1115 int
1116 umoven(struct tcb *const tcp, kernel_ulong_t addr, unsigned int len,
1117        void *const our_addr)
1118 {
1119         char *laddr = our_addr;
1120         int pid = tcp->pid;
1121         unsigned int n, m, nread;
1122         union {
1123                 long val;
1124                 char x[sizeof(long)];
1125         } u;
1126
1127 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
1128         if (current_wordsize < sizeof(addr)
1129             && (addr & (~ (kernel_ulong_t) -1U))) {
1130                 return -1;
1131         }
1132 #endif
1133
1134         if (!process_vm_readv_not_supported) {
1135                 int r = vm_read_mem(pid, laddr, addr, len);
1136                 if ((unsigned int) r == len)
1137                         return 0;
1138                 if (r >= 0) {
1139                         error_msg("umoven: short read (%u < %u) @0x%" PRI_klx,
1140                                   (unsigned int) r, len, addr);
1141                         return -1;
1142                 }
1143                 switch (errno) {
1144                         case ENOSYS:
1145                                 process_vm_readv_not_supported = 1;
1146                                 break;
1147                         case EPERM:
1148                                 /* operation not permitted, try PTRACE_PEEKDATA */
1149                                 break;
1150                         case ESRCH:
1151                                 /* the process is gone */
1152                                 return -1;
1153                         case EFAULT: case EIO:
1154                                 /* address space is inaccessible */
1155                                 return -1;
1156                         default:
1157                                 /* all the rest is strange and should be reported */
1158                                 perror_msg("process_vm_readv");
1159                                 return -1;
1160                 }
1161         }
1162
1163         nread = 0;
1164         if (addr & (sizeof(long) - 1)) {
1165                 /* addr not a multiple of sizeof(long) */
1166                 n = addr & (sizeof(long) - 1);  /* residue */
1167                 addr &= -sizeof(long);          /* aligned address */
1168                 errno = 0;
1169                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1170                 switch (errno) {
1171                         case 0:
1172                                 break;
1173                         case ESRCH: case EINVAL:
1174                                 /* these could be seen if the process is gone */
1175                                 return -1;
1176                         case EFAULT: case EIO: case EPERM:
1177                                 /* address space is inaccessible */
1178                                 return -1;
1179                         default:
1180                                 /* all the rest is strange and should be reported */
1181                                 perror_msg("umoven: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1182                                             pid, addr);
1183                                 return -1;
1184                 }
1185                 m = MIN(sizeof(long) - n, len);
1186                 memcpy(laddr, &u.x[n], m);
1187                 addr += sizeof(long);
1188                 laddr += m;
1189                 nread += m;
1190                 len -= m;
1191         }
1192         while (len) {
1193                 errno = 0;
1194                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1195                 switch (errno) {
1196                         case 0:
1197                                 break;
1198                         case ESRCH: case EINVAL:
1199                                 /* these could be seen if the process is gone */
1200                                 return -1;
1201                         case EFAULT: case EIO: case EPERM:
1202                                 /* address space is inaccessible */
1203                                 if (nread) {
1204                                         perror_msg("umoven: short read (%u < %u) @0x%" PRI_klx,
1205                                                    nread, nread + len, addr - nread);
1206                                 }
1207                                 return -1;
1208                         default:
1209                                 /* all the rest is strange and should be reported */
1210                                 perror_msg("umoven: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1211                                             pid, addr);
1212                                 return -1;
1213                 }
1214                 m = MIN(sizeof(long), len);
1215                 memcpy(laddr, u.x, m);
1216                 addr += sizeof(long);
1217                 laddr += m;
1218                 nread += m;
1219                 len -= m;
1220         }
1221
1222         return 0;
1223 }
1224
1225 int
1226 umoven_or_printaddr(struct tcb *const tcp, const kernel_ulong_t addr,
1227                     const unsigned int len, void *const our_addr)
1228 {
1229         if (!addr || !verbose(tcp) || (exiting(tcp) && syserror(tcp)) ||
1230             umoven(tcp, addr, len, our_addr) < 0) {
1231                 printaddr(addr);
1232                 return -1;
1233         }
1234         return 0;
1235 }
1236
1237 int
1238 umoven_or_printaddr_ignore_syserror(struct tcb *const tcp,
1239                                     const kernel_ulong_t addr,
1240                                     const unsigned int len,
1241                                     void *const our_addr)
1242 {
1243         if (!addr || !verbose(tcp) || umoven(tcp, addr, len, our_addr) < 0) {
1244                 printaddr(addr);
1245                 return -1;
1246         }
1247         return 0;
1248 }
1249
1250 /*
1251  * Like `umove' but make the additional effort of looking
1252  * for a terminating zero byte.
1253  *
1254  * Returns < 0 on error, > 0 if NUL was seen,
1255  * (TODO if useful: return count of bytes including NUL),
1256  * else 0 if len bytes were read but no NUL byte seen.
1257  *
1258  * Note: there is no guarantee we won't overwrite some bytes
1259  * in laddr[] _after_ terminating NUL (but, of course,
1260  * we never write past laddr[len-1]).
1261  */
1262 int
1263 umovestr(struct tcb *const tcp, kernel_ulong_t addr, unsigned int len, char *laddr)
1264 {
1265         const unsigned long x01010101 = (unsigned long) 0x0101010101010101ULL;
1266         const unsigned long x80808080 = (unsigned long) 0x8080808080808080ULL;
1267
1268         int pid = tcp->pid;
1269         unsigned int n, m, nread;
1270         union {
1271                 unsigned long val;
1272                 char x[sizeof(long)];
1273         } u;
1274
1275 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
1276         if (current_wordsize < sizeof(addr)
1277             && (addr & (~ (kernel_ulong_t) -1U))) {
1278                 return -1;
1279         }
1280 #endif
1281
1282         nread = 0;
1283         if (!process_vm_readv_not_supported) {
1284                 const size_t page_size = get_pagesize();
1285                 const size_t page_mask = page_size - 1;
1286
1287                 while (len > 0) {
1288                         unsigned int chunk_len;
1289                         unsigned int end_in_page;
1290
1291                         /*
1292                          * Don't cross pages, otherwise we can get EFAULT
1293                          * and fail to notice that terminating NUL lies
1294                          * in the existing (first) page.
1295                          */
1296                         chunk_len = len > page_size ? page_size : len;
1297                         end_in_page = (addr + chunk_len) & page_mask;
1298                         if (chunk_len > end_in_page) /* crosses to the next page */
1299                                 chunk_len -= end_in_page;
1300
1301                         int r = vm_read_mem(pid, laddr, addr, chunk_len);
1302                         if (r > 0) {
1303                                 if (memchr(laddr, '\0', r))
1304                                         return 1;
1305                                 addr += r;
1306                                 laddr += r;
1307                                 nread += r;
1308                                 len -= r;
1309                                 continue;
1310                         }
1311                         switch (errno) {
1312                                 case ENOSYS:
1313                                         process_vm_readv_not_supported = 1;
1314                                         goto vm_readv_didnt_work;
1315                                 case ESRCH:
1316                                         /* the process is gone */
1317                                         return -1;
1318                                 case EPERM:
1319                                         /* operation not permitted, try PTRACE_PEEKDATA */
1320                                         if (!nread)
1321                                                 goto vm_readv_didnt_work;
1322                                         /* fall through */
1323                                 case EFAULT: case EIO:
1324                                         /* address space is inaccessible */
1325                                         if (nread) {
1326                                                 perror_msg("umovestr: short read (%d < %d) @0x%" PRI_klx,
1327                                                            nread, nread + len, addr - nread);
1328                                         }
1329                                         return -1;
1330                                 default:
1331                                         /* all the rest is strange and should be reported */
1332                                         perror_msg("process_vm_readv");
1333                                         return -1;
1334                         }
1335                 }
1336                 return 0;
1337         }
1338  vm_readv_didnt_work:
1339
1340         if (addr & (sizeof(long) - 1)) {
1341                 /* addr not a multiple of sizeof(long) */
1342                 n = addr & (sizeof(long) - 1);  /* residue */
1343                 addr &= -sizeof(long);          /* aligned address */
1344                 errno = 0;
1345                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1346                 switch (errno) {
1347                         case 0:
1348                                 break;
1349                         case ESRCH: case EINVAL:
1350                                 /* these could be seen if the process is gone */
1351                                 return -1;
1352                         case EFAULT: case EIO: case EPERM:
1353                                 /* address space is inaccessible */
1354                                 return -1;
1355                         default:
1356                                 /* all the rest is strange and should be reported */
1357                                 perror_msg("umovestr: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1358                                             pid, addr);
1359                                 return -1;
1360                 }
1361                 m = MIN(sizeof(long) - n, len);
1362                 memcpy(laddr, &u.x[n], m);
1363                 while (n & (sizeof(long) - 1))
1364                         if (u.x[n++] == '\0')
1365                                 return 1;
1366                 addr += sizeof(long);
1367                 laddr += m;
1368                 nread += m;
1369                 len -= m;
1370         }
1371
1372         while (len) {
1373                 errno = 0;
1374                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1375                 switch (errno) {
1376                         case 0:
1377                                 break;
1378                         case ESRCH: case EINVAL:
1379                                 /* these could be seen if the process is gone */
1380                                 return -1;
1381                         case EFAULT: case EIO: case EPERM:
1382                                 /* address space is inaccessible */
1383                                 if (nread) {
1384                                         perror_msg("umovestr: short read (%d < %d) @0x%" PRI_klx,
1385                                                    nread, nread + len, addr - nread);
1386                                 }
1387                                 return -1;
1388                         default:
1389                                 /* all the rest is strange and should be reported */
1390                                 perror_msg("umovestr: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1391                                            pid, addr);
1392                                 return -1;
1393                 }
1394                 m = MIN(sizeof(long), len);
1395                 memcpy(laddr, u.x, m);
1396                 /* "If a NUL char exists in this word" */
1397                 if ((u.val - x01010101) & ~u.val & x80808080)
1398                         return 1;
1399                 addr += sizeof(long);
1400                 laddr += m;
1401                 nread += m;
1402                 len -= m;
1403         }
1404         return 0;
1405 }
1406
1407 /*
1408  * Iteratively fetch and print up to nmemb elements of elem_size size
1409  * from the array that starts at tracee's address start_addr.
1410  *
1411  * Array elements are being fetched to the address specified by elem_buf.
1412  *
1413  * The fetcher callback function specified by umoven_func should follow
1414  * the same semantics as umoven_or_printaddr function.
1415  *
1416  * The printer callback function specified by print_func is expected
1417  * to print something; if it returns false, no more iterations will be made.
1418  *
1419  * The pointer specified by opaque_data is passed to each invocation
1420  * of print_func callback function.
1421  *
1422  * This function prints:
1423  * - "NULL", if start_addr is NULL;
1424  * - "[]", if nmemb is 0;
1425  * - start_addr, if nmemb * elem_size overflows or wraps around;
1426  * - nothing, if the first element cannot be fetched
1427  *   (if umoven_func returns non-zero), but it is assumed that
1428  *   umoven_func has printed the address it failed to fetch data from;
1429  * - elements of the array, delimited by ", ", with the array itself
1430  *   enclosed with [] brackets.
1431  *
1432  * If abbrev(tcp) is true, then
1433  * - the maximum number of elements printed equals to max_strlen;
1434  * - "..." is printed instead of max_strlen+1 element
1435  *   and no more iterations will be made.
1436  *
1437  * This function returns true only if
1438  * - umoven_func has been called at least once AND
1439  * - umoven_func has not returned false.
1440  */
1441 bool
1442 print_array(struct tcb *const tcp,
1443             const kernel_ulong_t start_addr,
1444             const size_t nmemb,
1445             void *const elem_buf,
1446             const size_t elem_size,
1447             int (*const umoven_func)(struct tcb *,
1448                                      kernel_ulong_t,
1449                                      unsigned int,
1450                                      void *),
1451             bool (*const print_func)(struct tcb *,
1452                                      void *elem_buf,
1453                                      size_t elem_size,
1454                                      void *opaque_data),
1455             void *const opaque_data)
1456 {
1457         if (!start_addr) {
1458                 tprints("NULL");
1459                 return false;
1460         }
1461
1462         if (!nmemb) {
1463                 tprints("[]");
1464                 return false;
1465         }
1466
1467         const size_t size = nmemb * elem_size;
1468         const kernel_ulong_t end_addr = start_addr + size;
1469
1470         if (end_addr <= start_addr || size / elem_size != nmemb) {
1471                 printaddr(start_addr);
1472                 return false;
1473         }
1474
1475         const kernel_ulong_t abbrev_end =
1476                 (abbrev(tcp) && max_strlen < nmemb) ?
1477                         start_addr + elem_size * max_strlen : end_addr;
1478         kernel_ulong_t cur;
1479
1480         for (cur = start_addr; cur < end_addr; cur += elem_size) {
1481                 if (cur != start_addr)
1482                         tprints(", ");
1483
1484                 if (umoven_func(tcp, cur, elem_size, elem_buf))
1485                         break;
1486
1487                 if (cur == start_addr)
1488                         tprints("[");
1489
1490                 if (cur >= abbrev_end) {
1491                         tprints("...");
1492                         cur = end_addr;
1493                         break;
1494                 }
1495
1496                 if (!print_func(tcp, elem_buf, elem_size, opaque_data)) {
1497                         cur = end_addr;
1498                         break;
1499                 }
1500         }
1501         if (cur != start_addr)
1502                 tprints("]");
1503
1504         return cur >= end_addr;
1505 }
1506
1507 int
1508 printargs(struct tcb *tcp)
1509 {
1510         const int n = tcp->s_ent->nargs;
1511         int i;
1512         for (i = 0; i < n; ++i)
1513                 tprintf("%s%#" PRI_klx, i ? ", " : "", tcp->u_arg[i]);
1514         return RVAL_DECODED;
1515 }
1516
1517 int
1518 printargs_u(struct tcb *tcp)
1519 {
1520         const int n = tcp->s_ent->nargs;
1521         int i;
1522         for (i = 0; i < n; ++i)
1523                 tprintf("%s%u", i ? ", " : "",
1524                         (unsigned int) tcp->u_arg[i]);
1525         return RVAL_DECODED;
1526 }
1527
1528 int
1529 printargs_d(struct tcb *tcp)
1530 {
1531         const int n = tcp->s_ent->nargs;
1532         int i;
1533         for (i = 0; i < n; ++i)
1534                 tprintf("%s%d", i ? ", " : "",
1535                         (int) tcp->u_arg[i]);
1536         return RVAL_DECODED;
1537 }
1538
1539 #if defined _LARGEFILE64_SOURCE && defined HAVE_OPEN64
1540 # define open_file open64
1541 #else
1542 # define open_file open
1543 #endif
1544
1545 int
1546 read_int_from_file(const char *const fname, int *const pvalue)
1547 {
1548         const int fd = open_file(fname, O_RDONLY);
1549         if (fd < 0)
1550                 return -1;
1551
1552         long lval;
1553         char buf[sizeof(lval) * 3];
1554         int n = read(fd, buf, sizeof(buf) - 1);
1555         int saved_errno = errno;
1556         close(fd);
1557
1558         if (n < 0) {
1559                 errno = saved_errno;
1560                 return -1;
1561         }
1562
1563         buf[n] = '\0';
1564         char *endptr = 0;
1565         errno = 0;
1566         lval = strtol(buf, &endptr, 10);
1567         if (!endptr || (*endptr && '\n' != *endptr)
1568 #if INT_MAX < LONG_MAX
1569             || lval > INT_MAX || lval < INT_MIN
1570 #endif
1571             || ERANGE == errno) {
1572                 if (!errno)
1573                         errno = EINVAL;
1574                 return -1;
1575         }
1576
1577         *pvalue = (int) lval;
1578         return 0;
1579 }