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