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