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