]> granicus.if.org Git - strace/blob - util.c
util.c: add support for additional escape characters in string_quote
[strace] / util.c
1 /*
2  * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
3  * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
4  * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
5  * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl>
6  * Copyright (c) 1999 IBM Deutschland Entwicklung GmbH, IBM Corporation
7  *                     Linux for s390 port by D.J. Barrow
8  *                    <barrow_dj@mail.yahoo.com,djbarrow@de.ibm.com>
9  * Copyright (c) 1999-2018 The strace developers.
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 #include "defs.h"
36 #include <limits.h>
37 #include <fcntl.h>
38 #include <stdarg.h>
39 #ifdef HAVE_SYS_XATTR_H
40 # include <sys/xattr.h>
41 #endif
42 #include <sys/uio.h>
43 #include "xstring.h"
44
45 int
46 tv_nz(const struct timeval *a)
47 {
48         return a->tv_sec || a->tv_usec;
49 }
50
51 int
52 tv_cmp(const struct timeval *a, const struct timeval *b)
53 {
54         if (a->tv_sec < b->tv_sec
55             || (a->tv_sec == b->tv_sec && a->tv_usec < b->tv_usec))
56                 return -1;
57         if (a->tv_sec > b->tv_sec
58             || (a->tv_sec == b->tv_sec && a->tv_usec > b->tv_usec))
59                 return 1;
60         return 0;
61 }
62
63 double
64 tv_float(const struct timeval *tv)
65 {
66         return tv->tv_sec + tv->tv_usec/1000000.0;
67 }
68
69 void
70 tv_add(struct timeval *tv, const struct timeval *a, const struct timeval *b)
71 {
72         tv->tv_sec = a->tv_sec + b->tv_sec;
73         tv->tv_usec = a->tv_usec + b->tv_usec;
74         if (tv->tv_usec >= 1000000) {
75                 tv->tv_sec++;
76                 tv->tv_usec -= 1000000;
77         }
78 }
79
80 void
81 tv_sub(struct timeval *tv, const struct timeval *a, const struct timeval *b)
82 {
83         tv->tv_sec = a->tv_sec - b->tv_sec;
84         tv->tv_usec = a->tv_usec - b->tv_usec;
85         if (((long) tv->tv_usec) < 0) {
86                 tv->tv_sec--;
87                 tv->tv_usec += 1000000;
88         }
89 }
90
91 void
92 tv_div(struct timeval *tv, const struct timeval *a, int n)
93 {
94         tv->tv_usec = (a->tv_sec % n * 1000000 + a->tv_usec + n / 2) / n;
95         tv->tv_sec = a->tv_sec / n + tv->tv_usec / 1000000;
96         tv->tv_usec %= 1000000;
97 }
98
99 void
100 tv_mul(struct timeval *tv, const struct timeval *a, int n)
101 {
102         tv->tv_usec = a->tv_usec * n;
103         tv->tv_sec = a->tv_sec * n + tv->tv_usec / 1000000;
104         tv->tv_usec %= 1000000;
105 }
106
107 #if !defined HAVE_STPCPY
108 char *
109 stpcpy(char *dst, const char *src)
110 {
111         while ((*dst = *src++) != '\0')
112                 dst++;
113         return dst;
114 }
115 #endif
116
117 /* Find a next bit which is set.
118  * Starts testing at cur_bit.
119  * Returns -1 if no more bits are set.
120  *
121  * We never touch bytes we don't need to.
122  * On big-endian, array is assumed to consist of
123  * current_wordsize wide words: for example, is current_wordsize is 4,
124  * the bytes are walked in 3,2,1,0, 7,6,5,4, 11,10,9,8 ... sequence.
125  * On little-endian machines, word size is immaterial.
126  */
127 int
128 next_set_bit(const void *bit_array, unsigned cur_bit, unsigned size_bits)
129 {
130         const unsigned endian = 1;
131         int little_endian = *(char *) (void *) &endian;
132
133         const uint8_t *array = bit_array;
134         unsigned pos = cur_bit / 8;
135         unsigned pos_xor_mask = little_endian ? 0 : current_wordsize-1;
136
137         for (;;) {
138                 uint8_t bitmask;
139                 uint8_t cur_byte;
140
141                 if (cur_bit >= size_bits)
142                         return -1;
143                 cur_byte = array[pos ^ pos_xor_mask];
144                 if (cur_byte == 0) {
145                         cur_bit = (cur_bit + 8) & (-8);
146                         pos++;
147                         continue;
148                 }
149                 bitmask = 1 << (cur_bit & 7);
150                 for (;;) {
151                         if (cur_byte & bitmask)
152                                 return cur_bit;
153                         cur_bit++;
154                         if (cur_bit >= size_bits)
155                                 return -1;
156                         bitmask <<= 1;
157                         /* This check *can't be* optimized out: */
158                         if (bitmask == 0)
159                                 break;
160                 }
161                 pos++;
162         }
163 }
164
165 /*
166  * Fetch 64bit argument at position arg_no and
167  * return the index of the next argument.
168  */
169 int
170 getllval(struct tcb *tcp, unsigned long long *val, int arg_no)
171 {
172 #if SIZEOF_KERNEL_LONG_T > 4
173 # ifndef current_klongsize
174         if (current_klongsize < SIZEOF_KERNEL_LONG_T) {
175 #  if defined(AARCH64) || defined(POWERPC64)
176                 /* Align arg_no to the next even number. */
177                 arg_no = (arg_no + 1) & 0xe;
178 #  endif /* AARCH64 || POWERPC64 */
179                 *val = ULONG_LONG(tcp->u_arg[arg_no], tcp->u_arg[arg_no + 1]);
180                 arg_no += 2;
181         } else
182 # endif /* !current_klongsize */
183         {
184                 *val = tcp->u_arg[arg_no];
185                 arg_no++;
186         }
187 #else /* SIZEOF_KERNEL_LONG_T == 4 */
188 # if defined __ARM_EABI__       \
189   || defined LINUX_MIPSO32      \
190   || defined POWERPC            \
191   || defined XTENSA
192         /* Align arg_no to the next even number. */
193         arg_no = (arg_no + 1) & 0xe;
194 # elif defined SH
195         /*
196          * The SH4 ABI does allow long longs in odd-numbered registers, but
197          * does not allow them to be split between registers and memory - and
198          * there are only four argument registers for normal functions.  As a
199          * result, pread, for example, takes an extra padding argument before
200          * the offset.  This was changed late in the 2.4 series (around 2.4.20).
201          */
202         if (arg_no == 3)
203                 arg_no++;
204 # endif /* __ARM_EABI__ || LINUX_MIPSO32 || POWERPC || XTENSA || SH */
205         *val = ULONG_LONG(tcp->u_arg[arg_no], tcp->u_arg[arg_no + 1]);
206         arg_no += 2;
207 #endif
208
209         return arg_no;
210 }
211
212 /*
213  * Print 64bit argument at position arg_no and
214  * return the index of the next argument.
215  */
216 int
217 printllval(struct tcb *tcp, const char *format, int arg_no)
218 {
219         unsigned long long val = 0;
220
221         arg_no = getllval(tcp, &val, arg_no);
222         tprintf(format, val);
223         return arg_no;
224 }
225
226 void
227 printaddr(const kernel_ulong_t addr)
228 {
229         if (!addr)
230                 tprints("NULL");
231         else
232                 tprintf("%#" PRI_klx, addr);
233 }
234
235 #define DEF_PRINTNUM(name, type) \
236 bool                                                                    \
237 printnum_ ## name(struct tcb *const tcp, const kernel_ulong_t addr,     \
238                   const char *const fmt)                                \
239 {                                                                       \
240         type num;                                                       \
241         if (umove_or_printaddr(tcp, addr, &num))                        \
242                 return false;                                           \
243         tprints("[");                                                   \
244         tprintf(fmt, num);                                              \
245         tprints("]");                                                   \
246         return true;                                                    \
247 }
248
249 #define DEF_PRINTNUM_ADDR(name, type) \
250 bool                                                                    \
251 printnum_addr_ ## name(struct tcb *tcp, const kernel_ulong_t addr)      \
252 {                                                                       \
253         type num;                                                       \
254         if (umove_or_printaddr(tcp, addr, &num))                        \
255                 return false;                                           \
256         tprints("[");                                                   \
257         printaddr(num);                                                 \
258         tprints("]");                                                   \
259         return true;                                                    \
260 }
261
262 #define DEF_PRINTPAIR(name, type) \
263 bool                                                                    \
264 printpair_ ## name(struct tcb *const tcp, const kernel_ulong_t addr,    \
265                    const char *const fmt)                               \
266 {                                                                       \
267         type pair[2];                                                   \
268         if (umove_or_printaddr(tcp, addr, &pair))                       \
269                 return false;                                           \
270         tprints("[");                                                   \
271         tprintf(fmt, pair[0]);                                          \
272         tprints(", ");                                                  \
273         tprintf(fmt, pair[1]);                                          \
274         tprints("]");                                                   \
275         return true;                                                    \
276 }
277
278 DEF_PRINTNUM(int, int)
279 DEF_PRINTNUM_ADDR(int, unsigned int)
280 DEF_PRINTPAIR(int, int)
281 DEF_PRINTNUM(short, short)
282 DEF_PRINTNUM(int64, uint64_t)
283 DEF_PRINTNUM_ADDR(int64, uint64_t)
284 DEF_PRINTPAIR(int64, uint64_t)
285
286 #ifndef current_wordsize
287 bool
288 printnum_long_int(struct tcb *const tcp, const kernel_ulong_t addr,
289                   const char *const fmt_long, const char *const fmt_int)
290 {
291         if (current_wordsize > sizeof(int)) {
292                 return printnum_int64(tcp, addr, fmt_long);
293         } else {
294                 return printnum_int(tcp, addr, fmt_int);
295         }
296 }
297
298 bool
299 printnum_addr_long_int(struct tcb *tcp, const kernel_ulong_t addr)
300 {
301         if (current_wordsize > sizeof(int)) {
302                 return printnum_addr_int64(tcp, addr);
303         } else {
304                 return printnum_addr_int(tcp, addr);
305         }
306 }
307 #endif /* !current_wordsize */
308
309 #ifndef current_klongsize
310 bool
311 printnum_addr_klong_int(struct tcb *tcp, const kernel_ulong_t addr)
312 {
313         if (current_klongsize > sizeof(int)) {
314                 return printnum_addr_int64(tcp, addr);
315         } else {
316                 return printnum_addr_int(tcp, addr);
317         }
318 }
319 #endif /* !current_klongsize */
320
321 /**
322  * Prints time to a (static internal) buffer and returns pointer to it.
323  *
324  * @param sec           Seconds since epoch.
325  * @param part_sec      Amount of second parts since the start of a second.
326  * @param max_part_sec  Maximum value of a valid part_sec.
327  * @param width         1 + floor(log10(max_part_sec)).
328  */
329 static const char *
330 sprinttime_ex(const long long sec, const unsigned long long part_sec,
331               const unsigned int max_part_sec, const int width)
332 {
333         static char buf[sizeof(int) * 3 * 6 + sizeof(part_sec) * 3
334                         + sizeof("+0000")];
335
336         if ((sec == 0 && part_sec == 0) || part_sec > max_part_sec)
337                 return NULL;
338
339         time_t t = (time_t) sec;
340         struct tm *tmp = (sec == t) ? localtime(&t) : NULL;
341         if (!tmp)
342                 return NULL;
343
344         size_t pos = strftime(buf, sizeof(buf), "%FT%T", tmp);
345         if (!pos)
346                 return NULL;
347
348         if (part_sec > 0)
349                 pos += xsnprintf(buf + pos, sizeof(buf) - pos, ".%0*llu",
350                                  width, part_sec);
351
352         return strftime(buf + pos, sizeof(buf) - pos, "%z", tmp) ? buf : NULL;
353 }
354
355 const char *
356 sprinttime(long long sec)
357 {
358         return sprinttime_ex(sec, 0, 0, 0);
359 }
360
361 const char *
362 sprinttime_usec(long long sec, unsigned long long usec)
363 {
364         return sprinttime_ex(sec, usec, 999999, 6);
365 }
366
367 const char *
368 sprinttime_nsec(long long sec, unsigned long long nsec)
369 {
370         return sprinttime_ex(sec, nsec, 999999999, 9);
371 }
372
373 enum sock_proto
374 getfdproto(struct tcb *tcp, int fd)
375 {
376 #ifdef HAVE_SYS_XATTR_H
377         size_t bufsize = 256;
378         char buf[bufsize];
379         ssize_t r;
380         char path[sizeof("/proc/%u/fd/%u") + 2 * sizeof(int)*3];
381
382         if (fd < 0)
383                 return SOCK_PROTO_UNKNOWN;
384
385         xsprintf(path, "/proc/%u/fd/%u", tcp->pid, fd);
386         r = getxattr(path, "system.sockprotoname", buf, bufsize - 1);
387         if (r <= 0)
388                 return SOCK_PROTO_UNKNOWN;
389         else {
390                 /*
391                  * This is a protection for the case when the kernel
392                  * side does not append a null byte to the buffer.
393                  */
394                 buf[r] = '\0';
395
396                 return get_proto_by_name(buf);
397         }
398 #else
399         return SOCK_PROTO_UNKNOWN;
400 #endif
401 }
402
403 unsigned long
404 getfdinode(struct tcb *tcp, int fd)
405 {
406         char path[PATH_MAX + 1];
407
408         if (getfdpath(tcp, fd, path, sizeof(path)) >= 0) {
409                 const char *str = STR_STRIP_PREFIX(path, "socket:[");
410
411                 if (str != path) {
412                         const size_t str_len = strlen(str);
413                         if (str_len && str[str_len - 1] == ']')
414                                 return strtoul(str, NULL, 10);
415                 }
416         }
417
418         return 0;
419 }
420
421 void
422 printfd(struct tcb *tcp, int fd)
423 {
424         char path[PATH_MAX + 1];
425         if (show_fd_path && getfdpath(tcp, fd, path, sizeof(path)) >= 0) {
426                 const char *str;
427                 size_t len;
428                 unsigned long inode;
429
430                 tprintf("%d<", fd);
431                 if (show_fd_path <= 1
432                     || (str = STR_STRIP_PREFIX(path, "socket:[")) == path
433                     || !(len = strlen(str))
434                     || str[len - 1] != ']'
435                     || !(inode = strtoul(str, NULL, 10))
436                     || !print_sockaddr_by_inode(tcp, fd, inode)) {
437                         print_quoted_string(path, strlen(path),
438                                             QUOTE_OMIT_LEADING_TRAILING_QUOTES);
439                 }
440                 tprints(">");
441         } else
442                 tprintf("%d", fd);
443 }
444
445 /*
446  * Quote string `instr' of length `size'
447  * Write up to (3 + `size' * 4) bytes to `outstr' buffer.
448  *
449  * `escape_chars' specifies characters (in addition to characters with
450  * codes 0..31, 127..255, single and double quotes) that should be escaped.
451  *
452  * If QUOTE_0_TERMINATED `style' flag is set,
453  * treat `instr' as a NUL-terminated string,
454  * checking up to (`size' + 1) bytes of `instr'.
455  *
456  * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set,
457  * do not add leading and trailing quoting symbols.
458  *
459  * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise.
460  * Note that if QUOTE_0_TERMINATED is not set, always returns 1.
461  */
462 int
463 string_quote(const char *instr, char *outstr, const unsigned int size,
464              const unsigned int style, const char *escape_chars)
465 {
466         const unsigned char *ustr = (const unsigned char *) instr;
467         char *s = outstr;
468         unsigned int i;
469         int usehex, c, eol;
470         bool escape;
471
472         if (style & QUOTE_0_TERMINATED)
473                 eol = '\0';
474         else
475                 eol = 0x100; /* this can never match a char */
476
477         usehex = 0;
478         if ((xflag > 1) || (style & QUOTE_FORCE_HEX)) {
479                 usehex = 1;
480         } else if (xflag) {
481                 /* Check for presence of symbol which require
482                    to hex-quote the whole string. */
483                 for (i = 0; i < size; ++i) {
484                         c = ustr[i];
485                         /* Check for NUL-terminated string. */
486                         if (c == eol)
487                                 break;
488
489                         /* Force hex unless c is printable or whitespace */
490                         if (c > 0x7e) {
491                                 usehex = 1;
492                                 break;
493                         }
494                         /* In ASCII isspace is only these chars: "\t\n\v\f\r".
495                          * They happen to have ASCII codes 9,10,11,12,13.
496                          */
497                         if (c < ' ' && (unsigned)(c - 9) >= 5) {
498                                 usehex = 1;
499                                 break;
500                         }
501                 }
502         }
503
504         if (style & QUOTE_EMIT_COMMENT)
505                 s = stpcpy(s, " /* ");
506         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
507                 *s++ = '\"';
508
509         if (usehex) {
510                 /* Hex-quote the whole string. */
511                 for (i = 0; i < size; ++i) {
512                         c = ustr[i];
513                         /* Check for NUL-terminated string. */
514                         if (c == eol)
515                                 goto asciz_ended;
516                         *s++ = '\\';
517                         *s++ = 'x';
518                         *s++ = "0123456789abcdef"[c >> 4];
519                         *s++ = "0123456789abcdef"[c & 0xf];
520                 }
521
522                 goto string_ended;
523         }
524
525         for (i = 0; i < size; ++i) {
526                 c = ustr[i];
527                 /* Check for NUL-terminated string. */
528                 if (c == eol)
529                         goto asciz_ended;
530                 if ((i == (size - 1)) &&
531                     (style & QUOTE_OMIT_TRAILING_0) && (c == '\0'))
532                         goto asciz_ended;
533                 switch (c) {
534                 case '\"': case '\\':
535                         *s++ = '\\';
536                         *s++ = c;
537                         break;
538                 case '\f':
539                         *s++ = '\\';
540                         *s++ = 'f';
541                         break;
542                 case '\n':
543                         *s++ = '\\';
544                         *s++ = 'n';
545                         break;
546                 case '\r':
547                         *s++ = '\\';
548                         *s++ = 'r';
549                         break;
550                 case '\t':
551                         *s++ = '\\';
552                         *s++ = 't';
553                         break;
554                 case '\v':
555                         *s++ = '\\';
556                         *s++ = 'v';
557                         break;
558                 default:
559                         escape = (c < ' ') || (c > 0x7e);
560
561                         if (!escape && escape_chars)
562                                 escape = !!strchr(escape_chars, c);
563
564                         if (!escape) {
565                                 *s++ = c;
566                         } else {
567                                 /* Print \octal */
568                                 *s++ = '\\';
569                                 if (i + 1 < size
570                                     && ustr[i + 1] >= '0'
571                                     && ustr[i + 1] <= '7'
572                                 ) {
573                                         /* Print \ooo */
574                                         *s++ = '0' + (c >> 6);
575                                         *s++ = '0' + ((c >> 3) & 0x7);
576                                 } else {
577                                         /* Print \[[o]o]o */
578                                         if ((c >> 3) != 0) {
579                                                 if ((c >> 6) != 0)
580                                                         *s++ = '0' + (c >> 6);
581                                                 *s++ = '0' + ((c >> 3) & 0x7);
582                                         }
583                                 }
584                                 *s++ = '0' + (c & 0x7);
585                         }
586                 }
587         }
588
589  string_ended:
590         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
591                 *s++ = '\"';
592         if (style & QUOTE_EMIT_COMMENT)
593                 s = stpcpy(s, " */");
594         *s = '\0';
595
596         /* Return zero if we printed entire ASCIZ string (didn't truncate it) */
597         if (style & QUOTE_0_TERMINATED && ustr[i] == '\0') {
598                 /* We didn't see NUL yet (otherwise we'd jump to 'asciz_ended')
599                  * but next char is NUL.
600                  */
601                 return 0;
602         }
603
604         return 1;
605
606  asciz_ended:
607         if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES))
608                 *s++ = '\"';
609         if (style & QUOTE_EMIT_COMMENT)
610                 s = stpcpy(s, " */");
611         *s = '\0';
612         /* Return zero: we printed entire ASCIZ string (didn't truncate it) */
613         return 0;
614 }
615
616 #ifndef ALLOCA_CUTOFF
617 # define ALLOCA_CUTOFF  4032
618 #endif
619 #define use_alloca(n) ((n) <= ALLOCA_CUTOFF)
620
621 /*
622  * Quote string `str' of length `size' and print the result.
623  *
624  * If QUOTE_0_TERMINATED `style' flag is set,
625  * treat `str' as a NUL-terminated string and
626  * quote at most (`size' - 1) bytes.
627  *
628  * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set,
629  * do not add leading and trailing quoting symbols.
630  *
631  * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise.
632  * Note that if QUOTE_0_TERMINATED is not set, always returns 1.
633  */
634 int
635 print_quoted_string_ex(const char *str, unsigned int size,
636                        const unsigned int style, const char *escape_chars)
637 {
638         char *buf;
639         char *outstr;
640         unsigned int alloc_size;
641         int rc;
642
643         if (size && style & QUOTE_0_TERMINATED)
644                 --size;
645
646         alloc_size = 4 * size;
647         if (alloc_size / 4 != size) {
648                 error_msg("Out of memory");
649                 tprints("???");
650                 return -1;
651         }
652         alloc_size += 1 + (style & QUOTE_OMIT_LEADING_TRAILING_QUOTES ? 0 : 2) +
653                 (style & QUOTE_EMIT_COMMENT ? 7 : 0);
654
655         if (use_alloca(alloc_size)) {
656                 outstr = alloca(alloc_size);
657                 buf = NULL;
658         } else {
659                 outstr = buf = malloc(alloc_size);
660                 if (!buf) {
661                         error_msg("Out of memory");
662                         tprints("???");
663                         return -1;
664                 }
665         }
666
667         rc = string_quote(str, outstr, size, style, escape_chars);
668         tprints(outstr);
669
670         free(buf);
671         return rc;
672 }
673
674 inline int
675 print_quoted_string(const char *str, unsigned int size,
676                     const unsigned int style)
677 {
678         return print_quoted_string_ex(str, size, style, NULL);
679 }
680
681 /*
682  * Quote a NUL-terminated string `str' of length up to `size' - 1
683  * and print the result.
684  *
685  * Returns 0 if NUL was seen, 1 otherwise.
686  */
687 int
688 print_quoted_cstring(const char *str, unsigned int size)
689 {
690         int unterminated =
691                 print_quoted_string(str, size, QUOTE_0_TERMINATED);
692
693         if (unterminated)
694                 tprints("...");
695
696         return unterminated;
697 }
698
699 /*
700  * Print path string specified by address `addr' and length `n'.
701  * If path length exceeds `n', append `...' to the output.
702  *
703  * Returns the result of umovenstr.
704  */
705 int
706 printpathn(struct tcb *const tcp, const kernel_ulong_t addr, unsigned int n)
707 {
708         char path[PATH_MAX];
709         int nul_seen;
710
711         if (!addr) {
712                 tprints("NULL");
713                 return -1;
714         }
715
716         /* Cap path length to the path buffer size */
717         if (n > sizeof(path) - 1)
718                 n = sizeof(path) - 1;
719
720         /* Fetch one byte more to find out whether path length > n. */
721         nul_seen = umovestr(tcp, addr, n + 1, path);
722         if (nul_seen < 0)
723                 printaddr(addr);
724         else {
725                 path[n++] = !nul_seen;
726                 print_quoted_cstring(path, n);
727         }
728
729         return nul_seen;
730 }
731
732 int
733 printpath(struct tcb *const tcp, const kernel_ulong_t addr)
734 {
735         /* Size must correspond to char path[] size in printpathn */
736         return printpathn(tcp, addr, PATH_MAX - 1);
737 }
738
739 /*
740  * Print string specified by address `addr' and length `len'.
741  * If `user_style' has QUOTE_0_TERMINATED bit set, treat the string
742  * as a NUL-terminated string.
743  * Pass `user_style' on to `string_quote'.
744  * Append `...' to the output if either the string length exceeds `max_strlen',
745  * or QUOTE_0_TERMINATED bit is set and the string length exceeds `len'.
746  *
747  * Returns the result of umovenstr if style has QUOTE_0_TERMINATED,
748  * or the result of umoven otherwise.
749  */
750 int
751 printstr_ex(struct tcb *const tcp, const kernel_ulong_t addr,
752             const kernel_ulong_t len, const unsigned int user_style)
753 {
754         static char *str;
755         static char *outstr;
756
757         unsigned int size;
758         unsigned int style = user_style;
759         int rc;
760         int ellipsis;
761
762         if (!addr) {
763                 tprints("NULL");
764                 return -1;
765         }
766         /* Allocate static buffers if they are not allocated yet. */
767         if (!str) {
768                 const unsigned int outstr_size =
769                         4 * max_strlen + /* for quotes and NUL */ 3;
770                 /*
771                  * We can assume that outstr_size / 4 == max_strlen
772                  * since we have a guarantee that max_strlen <= -1U / 4.
773                  */
774
775                 str = xmalloc(max_strlen + 1);
776                 outstr = xmalloc(outstr_size);
777         }
778
779         /* Fetch one byte more because string_quote may look one byte ahead. */
780         size = max_strlen + 1;
781
782         if (size > len)
783                 size = len;
784         if (style & QUOTE_0_TERMINATED)
785                 rc = umovestr(tcp, addr, size, str);
786         else
787                 rc = umoven(tcp, addr, size, str);
788
789         if (rc < 0) {
790                 printaddr(addr);
791                 return rc;
792         }
793
794         if (size > max_strlen)
795                 size = max_strlen;
796         else
797                 str[size] = '\xff';
798
799         /* If string_quote didn't see NUL and (it was supposed to be ASCIZ str
800          * or we were requested to print more than -s NUM chars)...
801          */
802         ellipsis = string_quote(str, outstr, size, style, NULL)
803                    && len
804                    && ((style & QUOTE_0_TERMINATED)
805                        || len > max_strlen);
806
807         tprints(outstr);
808         if (ellipsis)
809                 tprints("...");
810
811         return rc;
812 }
813
814 void
815 dumpiov_upto(struct tcb *const tcp, const int len, const kernel_ulong_t addr,
816              kernel_ulong_t data_size)
817 {
818 #if ANY_WORDSIZE_LESS_THAN_KERNEL_LONG
819         union {
820                 struct { uint32_t base; uint32_t len; } *iov32;
821                 struct { uint64_t base; uint64_t len; } *iov64;
822         } iovu;
823 #define iov iovu.iov64
824 #define sizeof_iov \
825         (current_wordsize == 4 ? sizeof(*iovu.iov32) : sizeof(*iovu.iov64))
826 #define iov_iov_base(i) \
827         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].base : iovu.iov64[i].base)
828 #define iov_iov_len(i) \
829         (current_wordsize == 4 ? (uint64_t) iovu.iov32[i].len : iovu.iov64[i].len)
830 #else
831         struct iovec *iov;
832 #define sizeof_iov sizeof(*iov)
833 #define iov_iov_base(i) ptr_to_kulong(iov[i].iov_base)
834 #define iov_iov_len(i) iov[i].iov_len
835 #endif
836         int i;
837         unsigned size;
838
839         size = sizeof_iov * len;
840         /* Assuming no sane program has millions of iovs */
841         if ((unsigned)len > 1024*1024 /* insane or negative size? */
842             || (iov = malloc(size)) == NULL) {
843                 error_msg("Out of memory");
844                 return;
845         }
846         if (umoven(tcp, addr, size, iov) >= 0) {
847                 for (i = 0; i < len; i++) {
848                         kernel_ulong_t iov_len = iov_iov_len(i);
849                         if (iov_len > data_size)
850                                 iov_len = data_size;
851                         if (!iov_len)
852                                 break;
853                         data_size -= iov_len;
854                         /* include the buffer number to make it easy to
855                          * match up the trace with the source */
856                         tprintf(" * %" PRI_klu " bytes in buffer %d\n", iov_len, i);
857                         dumpstr(tcp, iov_iov_base(i), iov_len);
858                 }
859         }
860         free(iov);
861 #undef sizeof_iov
862 #undef iov_iov_base
863 #undef iov_iov_len
864 #undef iov
865 }
866
867 void
868 dumpstr(struct tcb *const tcp, const kernel_ulong_t addr, const int len)
869 {
870         static int strsize = -1;
871         static unsigned char *str;
872
873         char outbuf[
874                 (
875                         (sizeof(
876                         "xx xx xx xx xx xx xx xx  xx xx xx xx xx xx xx xx  "
877                         "1234567890123456") + /*in case I'm off by few:*/ 4)
878                 /*align to 8 to make memset easier:*/ + 7) & -8
879         ];
880         const unsigned char *src;
881         int i;
882
883         memset(outbuf, ' ', sizeof(outbuf));
884
885         if (strsize < len + 16) {
886                 free(str);
887                 str = malloc(len + 16);
888                 if (!str) {
889                         strsize = -1;
890                         error_msg("Out of memory");
891                         return;
892                 }
893                 strsize = len + 16;
894         }
895
896         if (umoven(tcp, addr, len, str) < 0)
897                 return;
898
899         /* Space-pad to 16 bytes */
900         i = len;
901         while (i & 0xf)
902                 str[i++] = ' ';
903
904         i = 0;
905         src = str;
906         while (i < len) {
907                 char *dst = outbuf;
908                 /* Hex dump */
909                 do {
910                         if (i < len) {
911                                 *dst++ = "0123456789abcdef"[*src >> 4];
912                                 *dst++ = "0123456789abcdef"[*src & 0xf];
913                         } else {
914                                 *dst++ = ' ';
915                                 *dst++ = ' ';
916                         }
917                         dst++; /* space is there by memset */
918                         i++;
919                         if ((i & 7) == 0)
920                                 dst++; /* space is there by memset */
921                         src++;
922                 } while (i & 0xf);
923                 /* ASCII dump */
924                 i -= 16;
925                 src -= 16;
926                 do {
927                         if (*src >= ' ' && *src < 0x7f)
928                                 *dst++ = *src;
929                         else
930                                 *dst++ = '.';
931                         src++;
932                 } while (++i & 0xf);
933                 *dst = '\0';
934                 tprintf(" | %05x  %s |\n", i - 16, outbuf);
935         }
936 }
937
938 int
939 umoven_or_printaddr(struct tcb *const tcp, const kernel_ulong_t addr,
940                     const unsigned int len, void *const our_addr)
941 {
942         if (!addr || !verbose(tcp) || (exiting(tcp) && syserror(tcp)) ||
943             umoven(tcp, addr, len, our_addr) < 0) {
944                 printaddr(addr);
945                 return -1;
946         }
947         return 0;
948 }
949
950 int
951 umoven_or_printaddr_ignore_syserror(struct tcb *const tcp,
952                                     const kernel_ulong_t addr,
953                                     const unsigned int len,
954                                     void *const our_addr)
955 {
956         if (!addr || !verbose(tcp) || umoven(tcp, addr, len, our_addr) < 0) {
957                 printaddr(addr);
958                 return -1;
959         }
960         return 0;
961 }
962
963 /*
964  * Iteratively fetch and print up to nmemb elements of elem_size size
965  * from the array that starts at tracee's address start_addr.
966  *
967  * Array elements are being fetched to the address specified by elem_buf.
968  *
969  * The fetcher callback function specified by umoven_func should follow
970  * the same semantics as umoven_or_printaddr function.
971  *
972  * The printer callback function specified by print_func is expected
973  * to print something; if it returns false, no more iterations will be made.
974  *
975  * The pointer specified by opaque_data is passed to each invocation
976  * of print_func callback function.
977  *
978  * This function prints:
979  * - "NULL", if start_addr is NULL;
980  * - "[]", if nmemb is 0;
981  * - start_addr, if nmemb * elem_size overflows or wraps around;
982  * - nothing, if the first element cannot be fetched
983  *   (if umoven_func returns non-zero), but it is assumed that
984  *   umoven_func has printed the address it failed to fetch data from;
985  * - elements of the array, delimited by ", ", with the array itself
986  *   enclosed with [] brackets.
987  *
988  * If abbrev(tcp) is true, then
989  * - the maximum number of elements printed equals to max_strlen;
990  * - "..." is printed instead of max_strlen+1 element
991  *   and no more iterations will be made.
992  *
993  * This function returns true only if
994  * - umoven_func has been called at least once AND
995  * - umoven_func has not returned false.
996  */
997 bool
998 print_array(struct tcb *const tcp,
999             const kernel_ulong_t start_addr,
1000             const size_t nmemb,
1001             void *const elem_buf,
1002             const size_t elem_size,
1003             int (*const umoven_func)(struct tcb *,
1004                                      kernel_ulong_t,
1005                                      unsigned int,
1006                                      void *),
1007             bool (*const print_func)(struct tcb *,
1008                                      void *elem_buf,
1009                                      size_t elem_size,
1010                                      void *opaque_data),
1011             void *const opaque_data)
1012 {
1013         if (!start_addr) {
1014                 tprints("NULL");
1015                 return false;
1016         }
1017
1018         if (!nmemb) {
1019                 tprints("[]");
1020                 return false;
1021         }
1022
1023         const size_t size = nmemb * elem_size;
1024         const kernel_ulong_t end_addr = start_addr + size;
1025
1026         if (end_addr <= start_addr || size / elem_size != nmemb) {
1027                 printaddr(start_addr);
1028                 return false;
1029         }
1030
1031         const kernel_ulong_t abbrev_end =
1032                 (abbrev(tcp) && max_strlen < nmemb) ?
1033                         start_addr + elem_size * max_strlen : end_addr;
1034         kernel_ulong_t cur;
1035
1036         for (cur = start_addr; cur < end_addr; cur += elem_size) {
1037                 if (cur != start_addr)
1038                         tprints(", ");
1039
1040                 if (umoven_func(tcp, cur, elem_size, elem_buf))
1041                         break;
1042
1043                 if (cur == start_addr)
1044                         tprints("[");
1045
1046                 if (cur >= abbrev_end) {
1047                         tprints("...");
1048                         cur = end_addr;
1049                         break;
1050                 }
1051
1052                 if (!print_func(tcp, elem_buf, elem_size, opaque_data)) {
1053                         cur = end_addr;
1054                         break;
1055                 }
1056         }
1057         if (cur != start_addr)
1058                 tprints("]");
1059
1060         return cur >= end_addr;
1061 }
1062
1063 int
1064 printargs(struct tcb *tcp)
1065 {
1066         const int n = tcp->s_ent->nargs;
1067         int i;
1068         for (i = 0; i < n; ++i)
1069                 tprintf("%s%#" PRI_klx, i ? ", " : "", tcp->u_arg[i]);
1070         return RVAL_DECODED;
1071 }
1072
1073 int
1074 printargs_u(struct tcb *tcp)
1075 {
1076         const int n = tcp->s_ent->nargs;
1077         int i;
1078         for (i = 0; i < n; ++i)
1079                 tprintf("%s%u", i ? ", " : "",
1080                         (unsigned int) tcp->u_arg[i]);
1081         return RVAL_DECODED;
1082 }
1083
1084 int
1085 printargs_d(struct tcb *tcp)
1086 {
1087         const int n = tcp->s_ent->nargs;
1088         int i;
1089         for (i = 0; i < n; ++i)
1090                 tprintf("%s%d", i ? ", " : "",
1091                         (int) tcp->u_arg[i]);
1092         return RVAL_DECODED;
1093 }
1094
1095 /* Print abnormal high bits of a kernel_ulong_t value. */
1096 void
1097 print_abnormal_hi(const kernel_ulong_t val)
1098 {
1099         if (current_klongsize > 4) {
1100                 const unsigned int hi = (unsigned int) ((uint64_t) val >> 32);
1101                 if (hi)
1102                         tprintf("%#x<<32|", hi);
1103         }
1104 }
1105
1106 #if defined _LARGEFILE64_SOURCE && defined HAVE_OPEN64
1107 # define open_file open64
1108 #else
1109 # define open_file open
1110 #endif
1111
1112 int
1113 read_int_from_file(struct tcb *tcp, const char *const fname, int *const pvalue)
1114 {
1115         const int fd = open_file(fname, O_RDONLY);
1116         if (fd < 0)
1117                 return -1;
1118
1119         long lval;
1120         char buf[sizeof(lval) * 3];
1121         int n = read(fd, buf, sizeof(buf) - 1);
1122         int saved_errno = errno;
1123         close(fd);
1124
1125         if (n < 0) {
1126                 errno = saved_errno;
1127                 return -1;
1128         }
1129
1130         buf[n] = '\0';
1131         char *endptr = 0;
1132         errno = 0;
1133         lval = strtol(buf, &endptr, 10);
1134         if (!endptr || (*endptr && '\n' != *endptr)
1135 #if INT_MAX < LONG_MAX
1136             || lval > INT_MAX || lval < INT_MIN
1137 #endif
1138             || ERANGE == errno) {
1139                 if (!errno)
1140                         errno = EINVAL;
1141                 return -1;
1142         }
1143
1144         *pvalue = (int) lval;
1145         return 0;
1146 }