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