]> granicus.if.org Git - strace/blob - util.c
syscall.c: split trace_syscall() into 6 functions
[strace] / util.c
1 /*
2  * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
3  * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
4  * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
5  * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl>
6  * Copyright (c) 1999 IBM Deutschland Entwicklung GmbH, IBM Corporation
7  *                     Linux for s390 port by D.J. Barrow
8  *                    <barrow_dj@mail.yahoo.com,djbarrow@de.ibm.com>
9  * 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 unsigned long
634 getfdinode(struct tcb *tcp, int fd)
635 {
636         char path[PATH_MAX + 1];
637
638         if (getfdpath(tcp, fd, path, sizeof(path)) >= 0) {
639                 const char *str = STR_STRIP_PREFIX(path, "socket:[");
640
641                 if (str != path) {
642                         const size_t str_len = strlen(str);
643                         if (str_len && str[str_len - 1] == ']')
644                                 return strtoul(str, NULL, 10);
645                 }
646         }
647
648         return 0;
649 }
650
651 void
652 printfd(struct tcb *tcp, int fd)
653 {
654         char path[PATH_MAX + 1];
655         if (show_fd_path && getfdpath(tcp, fd, path, sizeof(path)) >= 0) {
656                 const char *str;
657                 size_t len;
658                 unsigned long inode;
659
660                 tprintf("%d<", fd);
661                 if (show_fd_path <= 1
662                     || (str = STR_STRIP_PREFIX(path, "socket:[")) == path
663                     || !(len = strlen(str))
664                     || str[len - 1] != ']'
665                     || !(inode = strtoul(str, NULL, 10))
666                     || !print_sockaddr_by_inode(tcp, fd, inode)) {
667                         print_quoted_string(path, strlen(path),
668                                             QUOTE_OMIT_LEADING_TRAILING_QUOTES);
669                 }
670                 tprints(">");
671         } else
672                 tprintf("%d", fd);
673 }
674
675 /*
676  * Quote string `instr' of length `size'
677  * Write up to (3 + `size' * 4) bytes to `outstr' buffer.
678  *
679  * If QUOTE_0_TERMINATED `style' flag is set,
680  * treat `instr' as a NUL-terminated string,
681  * checking up to (`size' + 1) bytes of `instr'.
682  *
683  * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set,
684  * do not add leading and trailing quoting symbols.
685  *
686  * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise.
687  * Note that if QUOTE_0_TERMINATED is not set, always returns 1.
688  */
689 int
690 string_quote(const char *instr, char *outstr, const unsigned int size,
691              const unsigned int style)
692 {
693         const unsigned char *ustr = (const unsigned char *) instr;
694         char *s = outstr;
695         unsigned int i;
696         int usehex, c, eol;
697
698         if (style & QUOTE_0_TERMINATED)
699                 eol = '\0';
700         else
701                 eol = 0x100; /* this can never match a char */
702
703         usehex = 0;
704         if ((xflag > 1) || (style & QUOTE_FORCE_HEX)) {
705                 usehex = 1;
706         } else if (xflag) {
707                 /* Check for presence of symbol which require
708                    to hex-quote the whole string. */
709                 for (i = 0; i < size; ++i) {
710                         c = ustr[i];
711                         /* Check for NUL-terminated string. */
712                         if (c == eol)
713                                 break;
714
715                         /* Force hex unless c is printable or whitespace */
716                         if (c > 0x7e) {
717                                 usehex = 1;
718                                 break;
719                         }
720                         /* In ASCII isspace is only these chars: "\t\n\v\f\r".
721                          * They happen to have ASCII codes 9,10,11,12,13.
722                          */
723                         if (c < ' ' && (unsigned)(c - 9) >= 5) {
724                                 usehex = 1;
725                                 break;
726                         }
727                 }
728         }
729
730         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
731                 *s++ = '\"';
732
733         if (usehex) {
734                 /* Hex-quote the whole string. */
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                         *s++ = '\\';
741                         *s++ = 'x';
742                         *s++ = "0123456789abcdef"[c >> 4];
743                         *s++ = "0123456789abcdef"[c & 0xf];
744                 }
745         } else {
746                 for (i = 0; i < size; ++i) {
747                         c = ustr[i];
748                         /* Check for NUL-terminated string. */
749                         if (c == eol)
750                                 goto asciz_ended;
751                         if ((i == (size - 1)) &&
752                             (style & QUOTE_OMIT_TRAILING_0) && (c == '\0'))
753                                 goto asciz_ended;
754                         switch (c) {
755                                 case '\"': case '\\':
756                                         *s++ = '\\';
757                                         *s++ = c;
758                                         break;
759                                 case '\f':
760                                         *s++ = '\\';
761                                         *s++ = 'f';
762                                         break;
763                                 case '\n':
764                                         *s++ = '\\';
765                                         *s++ = 'n';
766                                         break;
767                                 case '\r':
768                                         *s++ = '\\';
769                                         *s++ = 'r';
770                                         break;
771                                 case '\t':
772                                         *s++ = '\\';
773                                         *s++ = 't';
774                                         break;
775                                 case '\v':
776                                         *s++ = '\\';
777                                         *s++ = 'v';
778                                         break;
779                                 default:
780                                         if (c >= ' ' && c <= 0x7e)
781                                                 *s++ = c;
782                                         else {
783                                                 /* Print \octal */
784                                                 *s++ = '\\';
785                                                 if (i + 1 < size
786                                                     && ustr[i + 1] >= '0'
787                                                     && ustr[i + 1] <= '9'
788                                                 ) {
789                                                         /* Print \ooo */
790                                                         *s++ = '0' + (c >> 6);
791                                                         *s++ = '0' + ((c >> 3) & 0x7);
792                                                 } else {
793                                                         /* Print \[[o]o]o */
794                                                         if ((c >> 3) != 0) {
795                                                                 if ((c >> 6) != 0)
796                                                                         *s++ = '0' + (c >> 6);
797                                                                 *s++ = '0' + ((c >> 3) & 0x7);
798                                                         }
799                                                 }
800                                                 *s++ = '0' + (c & 0x7);
801                                         }
802                                         break;
803                         }
804                 }
805         }
806
807         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
808                 *s++ = '\"';
809         *s = '\0';
810
811         /* Return zero if we printed entire ASCIZ string (didn't truncate it) */
812         if (style & QUOTE_0_TERMINATED && ustr[i] == '\0') {
813                 /* We didn't see NUL yet (otherwise we'd jump to 'asciz_ended')
814                  * but next char is NUL.
815                  */
816                 return 0;
817         }
818
819         return 1;
820
821  asciz_ended:
822         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
823                 *s++ = '\"';
824         *s = '\0';
825         /* Return zero: we printed entire ASCIZ string (didn't truncate it) */
826         return 0;
827 }
828
829 #ifndef ALLOCA_CUTOFF
830 # define ALLOCA_CUTOFF  4032
831 #endif
832 #define use_alloca(n) ((n) <= ALLOCA_CUTOFF)
833
834 /*
835  * Quote string `str' of length `size' and print the result.
836  *
837  * If QUOTE_0_TERMINATED `style' flag is set,
838  * treat `str' as a NUL-terminated string and
839  * quote at most (`size' - 1) bytes.
840  *
841  * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set,
842  * do not add leading and trailing quoting symbols.
843  *
844  * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise.
845  * Note that if QUOTE_0_TERMINATED is not set, always returns 1.
846  */
847 int
848 print_quoted_string(const char *str, unsigned int size,
849                     const unsigned int style)
850 {
851         char *buf;
852         char *outstr;
853         unsigned int alloc_size;
854         int rc;
855
856         if (size && style & QUOTE_0_TERMINATED)
857                 --size;
858
859         alloc_size = 4 * size;
860         if (alloc_size / 4 != size) {
861                 error_msg("Out of memory");
862                 tprints("???");
863                 return -1;
864         }
865         alloc_size += 1 + (style & QUOTE_OMIT_LEADING_TRAILING_QUOTES ? 0 : 2);
866
867         if (use_alloca(alloc_size)) {
868                 outstr = alloca(alloc_size);
869                 buf = NULL;
870         } else {
871                 outstr = buf = malloc(alloc_size);
872                 if (!buf) {
873                         error_msg("Out of memory");
874                         tprints("???");
875                         return -1;
876                 }
877         }
878
879         rc = string_quote(str, outstr, size, style);
880         tprints(outstr);
881
882         free(buf);
883         return rc;
884 }
885
886 /*
887  * Print path string specified by address `addr' and length `n'.
888  * If path length exceeds `n', append `...' to the output.
889  */
890 void
891 printpathn(struct tcb *const tcp, const kernel_ulong_t addr, unsigned int n)
892 {
893         char path[PATH_MAX + 1];
894         int nul_seen;
895
896         if (!addr) {
897                 tprints("NULL");
898                 return;
899         }
900
901         /* Cap path length to the path buffer size */
902         if (n > sizeof path - 1)
903                 n = sizeof path - 1;
904
905         /* Fetch one byte more to find out whether path length > n. */
906         nul_seen = umovestr(tcp, addr, n + 1, path);
907         if (nul_seen < 0)
908                 printaddr(addr);
909         else {
910                 path[n++] = '\0';
911                 print_quoted_string(path, n, QUOTE_0_TERMINATED);
912                 if (!nul_seen)
913                         tprints("...");
914         }
915 }
916
917 void
918 printpath(struct tcb *const tcp, const kernel_ulong_t addr)
919 {
920         /* Size must correspond to char path[] size in printpathn */
921         printpathn(tcp, addr, PATH_MAX);
922 }
923
924 /*
925  * Print string specified by address `addr' and length `len'.
926  * If `user_style' has QUOTE_0_TERMINATED bit set, treat the string
927  * as a NUL-terminated string.
928  * Pass `user_style' on to `string_quote'.
929  * Append `...' to the output if either the string length exceeds `max_strlen',
930  * or QUOTE_0_TERMINATED bit is set and the string length exceeds `len'.
931  */
932 void
933 printstr_ex(struct tcb *const tcp, const kernel_ulong_t addr,
934             const kernel_ulong_t len, const unsigned int user_style)
935 {
936         static char *str = NULL;
937         static char *outstr;
938         unsigned int size;
939         unsigned int style = user_style;
940         int rc;
941         int ellipsis;
942
943         if (!addr) {
944                 tprints("NULL");
945                 return;
946         }
947         /* Allocate static buffers if they are not allocated yet. */
948         if (!str) {
949                 unsigned int outstr_size = 4 * max_strlen + /*for quotes and NUL:*/ 3;
950
951                 if (outstr_size / 4 != max_strlen)
952                         die_out_of_memory();
953                 str = xmalloc(max_strlen + 1);
954                 outstr = xmalloc(outstr_size);
955         }
956
957         /* Fetch one byte more because string_quote may look one byte ahead. */
958         size = max_strlen + 1;
959
960         if (size > len)
961                 size = len;
962         if (style & QUOTE_0_TERMINATED)
963                 rc = umovestr(tcp, addr, size, str);
964         else
965                 rc = umoven(tcp, addr, size, str);
966
967         if (rc < 0) {
968                 printaddr(addr);
969                 return;
970         }
971
972         if (size > max_strlen)
973                 size = max_strlen;
974         else
975                 str[size] = '\xff';
976
977         /* If string_quote didn't see NUL and (it was supposed to be ASCIZ str
978          * or we were requested to print more than -s NUM chars)...
979          */
980         ellipsis = string_quote(str, outstr, size, style)
981                    && len
982                    && ((style & QUOTE_0_TERMINATED)
983                        || len > max_strlen);
984
985         tprints(outstr);
986         if (ellipsis)
987                 tprints("...");
988 }
989
990 void
991 dumpiov_upto(struct tcb *const tcp, const int len, const kernel_ulong_t addr,
992              kernel_ulong_t data_size)
993 {
994 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
995         union {
996                 struct { uint32_t base; uint32_t len; } *iov32;
997                 struct { uint64_t base; uint64_t len; } *iov64;
998         } iovu;
999 #define iov iovu.iov64
1000 #define sizeof_iov \
1001         (current_wordsize == 4 ? sizeof(*iovu.iov32) : sizeof(*iovu.iov64))
1002 #define iov_iov_base(i) \
1003         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].base : iovu.iov64[i].base)
1004 #define iov_iov_len(i) \
1005         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].len : iovu.iov64[i].len)
1006 #else
1007         struct iovec *iov;
1008 #define sizeof_iov sizeof(*iov)
1009 #define iov_iov_base(i) ptr_to_kulong(iov[i].iov_base)
1010 #define iov_iov_len(i) iov[i].iov_len
1011 #endif
1012         int i;
1013         unsigned size;
1014
1015         size = sizeof_iov * len;
1016         /* Assuming no sane program has millions of iovs */
1017         if ((unsigned)len > 1024*1024 /* insane or negative size? */
1018             || (iov = malloc(size)) == NULL) {
1019                 error_msg("Out of memory");
1020                 return;
1021         }
1022         if (umoven(tcp, addr, size, iov) >= 0) {
1023                 for (i = 0; i < len; i++) {
1024                         kernel_ulong_t iov_len = iov_iov_len(i);
1025                         if (iov_len > data_size)
1026                                 iov_len = data_size;
1027                         if (!iov_len)
1028                                 break;
1029                         data_size -= iov_len;
1030                         /* include the buffer number to make it easy to
1031                          * match up the trace with the source */
1032                         tprintf(" * %" PRI_klu " bytes in buffer %d\n", iov_len, i);
1033                         dumpstr(tcp, iov_iov_base(i), iov_len);
1034                 }
1035         }
1036         free(iov);
1037 #undef sizeof_iov
1038 #undef iov_iov_base
1039 #undef iov_iov_len
1040 #undef iov
1041 }
1042
1043 void
1044 dumpstr(struct tcb *const tcp, const kernel_ulong_t addr, const int len)
1045 {
1046         static int strsize = -1;
1047         static unsigned char *str;
1048
1049         char outbuf[
1050                 (
1051                         (sizeof(
1052                         "xx xx xx xx xx xx xx xx  xx xx xx xx xx xx xx xx  "
1053                         "1234567890123456") + /*in case I'm off by few:*/ 4)
1054                 /*align to 8 to make memset easier:*/ + 7) & -8
1055         ];
1056         const unsigned char *src;
1057         int i;
1058
1059         memset(outbuf, ' ', sizeof(outbuf));
1060
1061         if (strsize < len + 16) {
1062                 free(str);
1063                 str = malloc(len + 16);
1064                 if (!str) {
1065                         strsize = -1;
1066                         error_msg("Out of memory");
1067                         return;
1068                 }
1069                 strsize = len + 16;
1070         }
1071
1072         if (umoven(tcp, addr, len, str) < 0)
1073                 return;
1074
1075         /* Space-pad to 16 bytes */
1076         i = len;
1077         while (i & 0xf)
1078                 str[i++] = ' ';
1079
1080         i = 0;
1081         src = str;
1082         while (i < len) {
1083                 char *dst = outbuf;
1084                 /* Hex dump */
1085                 do {
1086                         if (i < len) {
1087                                 *dst++ = "0123456789abcdef"[*src >> 4];
1088                                 *dst++ = "0123456789abcdef"[*src & 0xf];
1089                         }
1090                         else {
1091                                 *dst++ = ' ';
1092                                 *dst++ = ' ';
1093                         }
1094                         dst++; /* space is there by memset */
1095                         i++;
1096                         if ((i & 7) == 0)
1097                                 dst++; /* space is there by memset */
1098                         src++;
1099                 } while (i & 0xf);
1100                 /* ASCII dump */
1101                 i -= 16;
1102                 src -= 16;
1103                 do {
1104                         if (*src >= ' ' && *src < 0x7f)
1105                                 *dst++ = *src;
1106                         else
1107                                 *dst++ = '.';
1108                         src++;
1109                 } while (++i & 0xf);
1110                 *dst = '\0';
1111                 tprintf(" | %05x  %s |\n", i - 16, outbuf);
1112         }
1113 }
1114
1115 static bool process_vm_readv_not_supported = 0;
1116 #ifndef HAVE_PROCESS_VM_READV
1117 /*
1118  * Need to do this since process_vm_readv() is not yet available in libc.
1119  * When libc is be updated, only "static bool process_vm_readv_not_supported"
1120  * line should remain.
1121  */
1122 /* Have to avoid duplicating with the C library headers. */
1123 static ssize_t strace_process_vm_readv(pid_t pid,
1124                  const struct iovec *lvec,
1125                  unsigned long liovcnt,
1126                  const struct iovec *rvec,
1127                  unsigned long riovcnt,
1128                  unsigned long flags)
1129 {
1130         return syscall(__NR_process_vm_readv, (long)pid, lvec, liovcnt, rvec, riovcnt, flags);
1131 }
1132 # define process_vm_readv strace_process_vm_readv
1133 #endif /* !HAVE_PROCESS_VM_READV */
1134
1135 static ssize_t
1136 vm_read_mem(const pid_t pid, void *const laddr,
1137             const kernel_ulong_t raddr, const size_t len)
1138 {
1139         const unsigned long truncated_raddr = raddr;
1140
1141         if (raddr != (kernel_ulong_t) truncated_raddr) {
1142                 errno = EIO;
1143                 return -1;
1144         }
1145
1146         const struct iovec local = {
1147                 .iov_base = laddr,
1148                 .iov_len = len
1149         };
1150         const struct iovec remote = {
1151                 .iov_base = (void *) truncated_raddr,
1152                 .iov_len = len
1153         };
1154
1155         return process_vm_readv(pid, &local, 1, &remote, 1, 0);
1156 }
1157
1158 /*
1159  * move `len' bytes of data from process `pid'
1160  * at address `addr' to our space at `our_addr'
1161  */
1162 int
1163 umoven(struct tcb *const tcp, kernel_ulong_t addr, unsigned int len,
1164        void *const our_addr)
1165 {
1166         char *laddr = our_addr;
1167         int pid = tcp->pid;
1168         unsigned int n, m, nread;
1169         union {
1170                 long val;
1171                 char x[sizeof(long)];
1172         } u;
1173
1174 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
1175         if (current_wordsize < sizeof(addr)
1176             && (addr & (~ (kernel_ulong_t) -1U))) {
1177                 return -1;
1178         }
1179 #endif
1180
1181         if (!process_vm_readv_not_supported) {
1182                 int r = vm_read_mem(pid, laddr, addr, len);
1183                 if ((unsigned int) r == len)
1184                         return 0;
1185                 if (r >= 0) {
1186                         error_msg("umoven: short read (%u < %u) @0x%" PRI_klx,
1187                                   (unsigned int) r, len, addr);
1188                         return -1;
1189                 }
1190                 switch (errno) {
1191                         case ENOSYS:
1192                                 process_vm_readv_not_supported = 1;
1193                                 break;
1194                         case EPERM:
1195                                 /* operation not permitted, try PTRACE_PEEKDATA */
1196                                 break;
1197                         case ESRCH:
1198                                 /* the process is gone */
1199                                 return -1;
1200                         case EFAULT: case EIO:
1201                                 /* address space is inaccessible */
1202                                 return -1;
1203                         default:
1204                                 /* all the rest is strange and should be reported */
1205                                 perror_msg("process_vm_readv");
1206                                 return -1;
1207                 }
1208         }
1209
1210         nread = 0;
1211         if (addr & (sizeof(long) - 1)) {
1212                 /* addr not a multiple of sizeof(long) */
1213                 n = addr & (sizeof(long) - 1);  /* residue */
1214                 addr &= -sizeof(long);          /* aligned address */
1215                 errno = 0;
1216                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1217                 switch (errno) {
1218                         case 0:
1219                                 break;
1220                         case ESRCH: case EINVAL:
1221                                 /* these could be seen if the process is gone */
1222                                 return -1;
1223                         case EFAULT: case EIO: case EPERM:
1224                                 /* address space is inaccessible */
1225                                 return -1;
1226                         default:
1227                                 /* all the rest is strange and should be reported */
1228                                 perror_msg("umoven: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1229                                             pid, addr);
1230                                 return -1;
1231                 }
1232                 m = MIN(sizeof(long) - n, len);
1233                 memcpy(laddr, &u.x[n], m);
1234                 addr += sizeof(long);
1235                 laddr += m;
1236                 nread += m;
1237                 len -= m;
1238         }
1239         while (len) {
1240                 errno = 0;
1241                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1242                 switch (errno) {
1243                         case 0:
1244                                 break;
1245                         case ESRCH: case EINVAL:
1246                                 /* these could be seen if the process is gone */
1247                                 return -1;
1248                         case EFAULT: case EIO: case EPERM:
1249                                 /* address space is inaccessible */
1250                                 if (nread) {
1251                                         perror_msg("umoven: short read (%u < %u) @0x%" PRI_klx,
1252                                                    nread, nread + len, addr - nread);
1253                                 }
1254                                 return -1;
1255                         default:
1256                                 /* all the rest is strange and should be reported */
1257                                 perror_msg("umoven: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1258                                             pid, addr);
1259                                 return -1;
1260                 }
1261                 m = MIN(sizeof(long), len);
1262                 memcpy(laddr, u.x, m);
1263                 addr += sizeof(long);
1264                 laddr += m;
1265                 nread += m;
1266                 len -= m;
1267         }
1268
1269         return 0;
1270 }
1271
1272 int
1273 umoven_or_printaddr(struct tcb *const tcp, const kernel_ulong_t addr,
1274                     const unsigned int len, void *const our_addr)
1275 {
1276         if (!addr || !verbose(tcp) || (exiting(tcp) && syserror(tcp)) ||
1277             umoven(tcp, addr, len, our_addr) < 0) {
1278                 printaddr(addr);
1279                 return -1;
1280         }
1281         return 0;
1282 }
1283
1284 int
1285 umoven_or_printaddr_ignore_syserror(struct tcb *const tcp,
1286                                     const kernel_ulong_t addr,
1287                                     const unsigned int len,
1288                                     void *const our_addr)
1289 {
1290         if (!addr || !verbose(tcp) || umoven(tcp, addr, len, our_addr) < 0) {
1291                 printaddr(addr);
1292                 return -1;
1293         }
1294         return 0;
1295 }
1296
1297 /*
1298  * Like `umove' but make the additional effort of looking
1299  * for a terminating zero byte.
1300  *
1301  * Returns < 0 on error, > 0 if NUL was seen,
1302  * (TODO if useful: return count of bytes including NUL),
1303  * else 0 if len bytes were read but no NUL byte seen.
1304  *
1305  * Note: there is no guarantee we won't overwrite some bytes
1306  * in laddr[] _after_ terminating NUL (but, of course,
1307  * we never write past laddr[len-1]).
1308  */
1309 int
1310 umovestr(struct tcb *const tcp, kernel_ulong_t addr, unsigned int len, char *laddr)
1311 {
1312         const unsigned long x01010101 = (unsigned long) 0x0101010101010101ULL;
1313         const unsigned long x80808080 = (unsigned long) 0x8080808080808080ULL;
1314
1315         int pid = tcp->pid;
1316         unsigned int n, m, nread;
1317         union {
1318                 unsigned long val;
1319                 char x[sizeof(long)];
1320         } u;
1321
1322 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
1323         if (current_wordsize < sizeof(addr)
1324             && (addr & (~ (kernel_ulong_t) -1U))) {
1325                 return -1;
1326         }
1327 #endif
1328
1329         nread = 0;
1330         if (!process_vm_readv_not_supported) {
1331                 const size_t page_size = get_pagesize();
1332                 const size_t page_mask = page_size - 1;
1333
1334                 while (len > 0) {
1335                         unsigned int chunk_len;
1336                         unsigned int end_in_page;
1337
1338                         /*
1339                          * Don't cross pages, otherwise we can get EFAULT
1340                          * and fail to notice that terminating NUL lies
1341                          * in the existing (first) page.
1342                          */
1343                         chunk_len = len > page_size ? page_size : len;
1344                         end_in_page = (addr + chunk_len) & page_mask;
1345                         if (chunk_len > end_in_page) /* crosses to the next page */
1346                                 chunk_len -= end_in_page;
1347
1348                         int r = vm_read_mem(pid, laddr, addr, chunk_len);
1349                         if (r > 0) {
1350                                 if (memchr(laddr, '\0', r))
1351                                         return 1;
1352                                 addr += r;
1353                                 laddr += r;
1354                                 nread += r;
1355                                 len -= r;
1356                                 continue;
1357                         }
1358                         switch (errno) {
1359                                 case ENOSYS:
1360                                         process_vm_readv_not_supported = 1;
1361                                         goto vm_readv_didnt_work;
1362                                 case ESRCH:
1363                                         /* the process is gone */
1364                                         return -1;
1365                                 case EPERM:
1366                                         /* operation not permitted, try PTRACE_PEEKDATA */
1367                                         if (!nread)
1368                                                 goto vm_readv_didnt_work;
1369                                         /* fall through */
1370                                 case EFAULT: case EIO:
1371                                         /* address space is inaccessible */
1372                                         if (nread) {
1373                                                 perror_msg("umovestr: short read (%d < %d) @0x%" PRI_klx,
1374                                                            nread, nread + len, addr - nread);
1375                                         }
1376                                         return -1;
1377                                 default:
1378                                         /* all the rest is strange and should be reported */
1379                                         perror_msg("process_vm_readv");
1380                                         return -1;
1381                         }
1382                 }
1383                 return 0;
1384         }
1385  vm_readv_didnt_work:
1386
1387         if (addr & (sizeof(long) - 1)) {
1388                 /* addr not a multiple of sizeof(long) */
1389                 n = addr & (sizeof(long) - 1);  /* residue */
1390                 addr &= -sizeof(long);          /* aligned address */
1391                 errno = 0;
1392                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1393                 switch (errno) {
1394                         case 0:
1395                                 break;
1396                         case ESRCH: case EINVAL:
1397                                 /* these could be seen if the process is gone */
1398                                 return -1;
1399                         case EFAULT: case EIO: case EPERM:
1400                                 /* address space is inaccessible */
1401                                 return -1;
1402                         default:
1403                                 /* all the rest is strange and should be reported */
1404                                 perror_msg("umovestr: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1405                                             pid, addr);
1406                                 return -1;
1407                 }
1408                 m = MIN(sizeof(long) - n, len);
1409                 memcpy(laddr, &u.x[n], m);
1410                 while (n & (sizeof(long) - 1))
1411                         if (u.x[n++] == '\0')
1412                                 return 1;
1413                 addr += sizeof(long);
1414                 laddr += m;
1415                 nread += m;
1416                 len -= m;
1417         }
1418
1419         while (len) {
1420                 errno = 0;
1421                 u.val = ptrace(PTRACE_PEEKDATA, pid, addr, 0);
1422                 switch (errno) {
1423                         case 0:
1424                                 break;
1425                         case ESRCH: case EINVAL:
1426                                 /* these could be seen if the process is gone */
1427                                 return -1;
1428                         case EFAULT: case EIO: case EPERM:
1429                                 /* address space is inaccessible */
1430                                 if (nread) {
1431                                         perror_msg("umovestr: short read (%d < %d) @0x%" PRI_klx,
1432                                                    nread, nread + len, addr - nread);
1433                                 }
1434                                 return -1;
1435                         default:
1436                                 /* all the rest is strange and should be reported */
1437                                 perror_msg("umovestr: PTRACE_PEEKDATA pid:%d @0x%" PRI_klx,
1438                                            pid, addr);
1439                                 return -1;
1440                 }
1441                 m = MIN(sizeof(long), len);
1442                 memcpy(laddr, u.x, m);
1443                 /* "If a NUL char exists in this word" */
1444                 if ((u.val - x01010101) & ~u.val & x80808080)
1445                         return 1;
1446                 addr += sizeof(long);
1447                 laddr += m;
1448                 nread += m;
1449                 len -= m;
1450         }
1451         return 0;
1452 }
1453
1454 /*
1455  * Iteratively fetch and print up to nmemb elements of elem_size size
1456  * from the array that starts at tracee's address start_addr.
1457  *
1458  * Array elements are being fetched to the address specified by elem_buf.
1459  *
1460  * The fetcher callback function specified by umoven_func should follow
1461  * the same semantics as umoven_or_printaddr function.
1462  *
1463  * The printer callback function specified by print_func is expected
1464  * to print something; if it returns false, no more iterations will be made.
1465  *
1466  * The pointer specified by opaque_data is passed to each invocation
1467  * of print_func callback function.
1468  *
1469  * This function prints:
1470  * - "NULL", if start_addr is NULL;
1471  * - "[]", if nmemb is 0;
1472  * - start_addr, if nmemb * elem_size overflows or wraps around;
1473  * - nothing, if the first element cannot be fetched
1474  *   (if umoven_func returns non-zero), but it is assumed that
1475  *   umoven_func has printed the address it failed to fetch data from;
1476  * - elements of the array, delimited by ", ", with the array itself
1477  *   enclosed with [] brackets.
1478  *
1479  * If abbrev(tcp) is true, then
1480  * - the maximum number of elements printed equals to max_strlen;
1481  * - "..." is printed instead of max_strlen+1 element
1482  *   and no more iterations will be made.
1483  *
1484  * This function returns true only if
1485  * - umoven_func has been called at least once AND
1486  * - umoven_func has not returned false.
1487  */
1488 bool
1489 print_array(struct tcb *const tcp,
1490             const kernel_ulong_t start_addr,
1491             const size_t nmemb,
1492             void *const elem_buf,
1493             const size_t elem_size,
1494             int (*const umoven_func)(struct tcb *,
1495                                      kernel_ulong_t,
1496                                      unsigned int,
1497                                      void *),
1498             bool (*const print_func)(struct tcb *,
1499                                      void *elem_buf,
1500                                      size_t elem_size,
1501                                      void *opaque_data),
1502             void *const opaque_data)
1503 {
1504         if (!start_addr) {
1505                 tprints("NULL");
1506                 return false;
1507         }
1508
1509         if (!nmemb) {
1510                 tprints("[]");
1511                 return false;
1512         }
1513
1514         const size_t size = nmemb * elem_size;
1515         const kernel_ulong_t end_addr = start_addr + size;
1516
1517         if (end_addr <= start_addr || size / elem_size != nmemb) {
1518                 printaddr(start_addr);
1519                 return false;
1520         }
1521
1522         const kernel_ulong_t abbrev_end =
1523                 (abbrev(tcp) && max_strlen < nmemb) ?
1524                         start_addr + elem_size * max_strlen : end_addr;
1525         kernel_ulong_t cur;
1526
1527         for (cur = start_addr; cur < end_addr; cur += elem_size) {
1528                 if (cur != start_addr)
1529                         tprints(", ");
1530
1531                 if (umoven_func(tcp, cur, elem_size, elem_buf))
1532                         break;
1533
1534                 if (cur == start_addr)
1535                         tprints("[");
1536
1537                 if (cur >= abbrev_end) {
1538                         tprints("...");
1539                         cur = end_addr;
1540                         break;
1541                 }
1542
1543                 if (!print_func(tcp, elem_buf, elem_size, opaque_data)) {
1544                         cur = end_addr;
1545                         break;
1546                 }
1547         }
1548         if (cur != start_addr)
1549                 tprints("]");
1550
1551         return cur >= end_addr;
1552 }
1553
1554 int
1555 printargs(struct tcb *tcp)
1556 {
1557         const int n = tcp->s_ent->nargs;
1558         int i;
1559         for (i = 0; i < n; ++i)
1560                 tprintf("%s%#" PRI_klx, i ? ", " : "", tcp->u_arg[i]);
1561         return RVAL_DECODED;
1562 }
1563
1564 int
1565 printargs_u(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%u", i ? ", " : "",
1571                         (unsigned int) tcp->u_arg[i]);
1572         return RVAL_DECODED;
1573 }
1574
1575 int
1576 printargs_d(struct tcb *tcp)
1577 {
1578         const int n = tcp->s_ent->nargs;
1579         int i;
1580         for (i = 0; i < n; ++i)
1581                 tprintf("%s%d", i ? ", " : "",
1582                         (int) tcp->u_arg[i]);
1583         return RVAL_DECODED;
1584 }
1585
1586 /* Print abnormal high bits of a kernel_ulong_t value. */
1587 void
1588 print_abnormal_hi(const kernel_ulong_t val)
1589 {
1590         if (current_klongsize > 4) {
1591                 const unsigned int hi = (unsigned int) ((uint64_t) val >> 32);
1592                 if (hi)
1593                         tprintf("%#x<<32|", hi);
1594         }
1595 }
1596
1597 #if defined _LARGEFILE64_SOURCE && defined HAVE_OPEN64
1598 # define open_file open64
1599 #else
1600 # define open_file open
1601 #endif
1602
1603 int
1604 read_int_from_file(const char *const fname, int *const pvalue)
1605 {
1606         const int fd = open_file(fname, O_RDONLY);
1607         if (fd < 0)
1608                 return -1;
1609
1610         long lval;
1611         char buf[sizeof(lval) * 3];
1612         int n = read(fd, buf, sizeof(buf) - 1);
1613         int saved_errno = errno;
1614         close(fd);
1615
1616         if (n < 0) {
1617                 errno = saved_errno;
1618                 return -1;
1619         }
1620
1621         buf[n] = '\0';
1622         char *endptr = 0;
1623         errno = 0;
1624         lval = strtol(buf, &endptr, 10);
1625         if (!endptr || (*endptr && '\n' != *endptr)
1626 #if INT_MAX < LONG_MAX
1627             || lval > INT_MAX || lval < INT_MIN
1628 #endif
1629             || ERANGE == errno) {
1630                 if (!errno)
1631                         errno = EINVAL;
1632                 return -1;
1633         }
1634
1635         *pvalue = (int) lval;
1636         return 0;
1637 }