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