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