]> granicus.if.org Git - strace/blob - syscall.c
Rewrite qual_desc using bit sets
[strace] / syscall.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 "native_defs.h"
36 #include <sys/param.h>
37 #include <signal.h>
38
39 /* for struct iovec */
40 #include <sys/uio.h>
41
42 #include "regs.h"
43 #include "ptrace.h"
44
45 #if defined(SPARC64)
46 # undef PTRACE_GETREGS
47 # define PTRACE_GETREGS PTRACE_GETREGS64
48 # undef PTRACE_SETREGS
49 # define PTRACE_SETREGS PTRACE_SETREGS64
50 #endif
51
52 #if defined SPARC64
53 # include <asm/psrcompat.h>
54 #elif defined SPARC
55 # include <asm/psr.h>
56 #endif
57
58 #ifdef IA64
59 # include <asm/rse.h>
60 #endif
61
62 #ifndef NT_PRSTATUS
63 # define NT_PRSTATUS 1
64 #endif
65
66 #ifndef NSIG
67 # warning: NSIG is not defined, using 32
68 # define NSIG 32
69 #endif
70
71 #include "syscall.h"
72
73 /* Define these shorthand notations to simplify the syscallent files. */
74 #define TD TRACE_DESC
75 #define TF TRACE_FILE
76 #define TI TRACE_IPC
77 #define TN TRACE_NETWORK
78 #define TP TRACE_PROCESS
79 #define TS TRACE_SIGNAL
80 #define TM TRACE_MEMORY
81 #define NF SYSCALL_NEVER_FAILS
82 #define MA MAX_ARGS
83 #define SI STACKTRACE_INVALIDATE_CACHE
84 #define SE STACKTRACE_CAPTURE_ON_ENTER
85
86 #define SEN(syscall_name) SEN_ ## syscall_name, SYS_FUNC_NAME(sys_ ## syscall_name)
87
88 const struct_sysent sysent0[] = {
89 #include "syscallent.h"
90 };
91
92 #if SUPPORTED_PERSONALITIES > 1
93 # include PERSONALITY1_INCLUDE_FUNCS
94 static const struct_sysent sysent1[] = {
95 # include "syscallent1.h"
96 };
97 #endif
98
99 #if SUPPORTED_PERSONALITIES > 2
100 # include PERSONALITY2_INCLUDE_FUNCS
101 static const struct_sysent sysent2[] = {
102 # include "syscallent2.h"
103 };
104 #endif
105
106 /* Now undef them since short defines cause wicked namespace pollution. */
107 #undef SEN
108 #undef TD
109 #undef TF
110 #undef TI
111 #undef TN
112 #undef TP
113 #undef TS
114 #undef TM
115 #undef NF
116 #undef MA
117 #undef SI
118 #undef SE
119
120 /*
121  * `ioctlent[012].h' files are automatically generated by the auxiliary
122  * program `ioctlsort', such that the list is sorted by the `code' field.
123  * This has the side-effect of resolving the _IO.. macros into
124  * plain integers, eliminating the need to include here everything
125  * in "/usr/include".
126  */
127
128 const char *const errnoent0[] = {
129 #include "errnoent.h"
130 };
131 const char *const signalent0[] = {
132 #include "signalent.h"
133 };
134 const struct_ioctlent ioctlent0[] = {
135 #include "ioctlent0.h"
136 };
137
138 #if SUPPORTED_PERSONALITIES > 1
139 static const char *const errnoent1[] = {
140 # include "errnoent1.h"
141 };
142 static const char *const signalent1[] = {
143 # include "signalent1.h"
144 };
145 static const struct_ioctlent ioctlent1[] = {
146 # include "ioctlent1.h"
147 };
148 # include PERSONALITY0_INCLUDE_PRINTERS_DECLS
149 static const struct_printers printers0 = {
150 # include PERSONALITY0_INCLUDE_PRINTERS_DEFS
151 };
152 # include PERSONALITY1_INCLUDE_PRINTERS_DECLS
153 static const struct_printers printers1 = {
154 # include PERSONALITY1_INCLUDE_PRINTERS_DEFS
155 };
156 #endif
157
158 #if SUPPORTED_PERSONALITIES > 2
159 static const char *const errnoent2[] = {
160 # include "errnoent2.h"
161 };
162 static const char *const signalent2[] = {
163 # include "signalent2.h"
164 };
165 static const struct_ioctlent ioctlent2[] = {
166 # include "ioctlent2.h"
167 };
168 # include PERSONALITY2_INCLUDE_PRINTERS_DECLS
169 static const struct_printers printers2 = {
170 # include PERSONALITY2_INCLUDE_PRINTERS_DEFS
171 };
172 #endif
173
174 enum {
175         nsyscalls0 = ARRAY_SIZE(sysent0)
176 #if SUPPORTED_PERSONALITIES > 1
177         , nsyscalls1 = ARRAY_SIZE(sysent1)
178 # if SUPPORTED_PERSONALITIES > 2
179         , nsyscalls2 = ARRAY_SIZE(sysent2)
180 # endif
181 #endif
182 };
183
184 enum {
185         nerrnos0 = ARRAY_SIZE(errnoent0)
186 #if SUPPORTED_PERSONALITIES > 1
187         , nerrnos1 = ARRAY_SIZE(errnoent1)
188 # if SUPPORTED_PERSONALITIES > 2
189         , nerrnos2 = ARRAY_SIZE(errnoent2)
190 # endif
191 #endif
192 };
193
194 enum {
195         nsignals0 = ARRAY_SIZE(signalent0)
196 #if SUPPORTED_PERSONALITIES > 1
197         , nsignals1 = ARRAY_SIZE(signalent1)
198 # if SUPPORTED_PERSONALITIES > 2
199         , nsignals2 = ARRAY_SIZE(signalent2)
200 # endif
201 #endif
202 };
203
204 enum {
205         nioctlents0 = ARRAY_SIZE(ioctlent0)
206 #if SUPPORTED_PERSONALITIES > 1
207         , nioctlents1 = ARRAY_SIZE(ioctlent1)
208 # if SUPPORTED_PERSONALITIES > 2
209         , nioctlents2 = ARRAY_SIZE(ioctlent2)
210 # endif
211 #endif
212 };
213
214 #if SUPPORTED_PERSONALITIES > 1
215 const struct_sysent *sysent = sysent0;
216 const char *const *errnoent = errnoent0;
217 const char *const *signalent = signalent0;
218 const struct_ioctlent *ioctlent = ioctlent0;
219 const struct_printers *printers = &printers0;
220 #endif
221
222 unsigned nsyscalls = nsyscalls0;
223 unsigned nerrnos = nerrnos0;
224 unsigned nsignals = nsignals0;
225 unsigned nioctlents = nioctlents0;
226
227 unsigned num_quals;
228 qualbits_t *qual_vec[SUPPORTED_PERSONALITIES];
229
230 static const unsigned nsyscall_vec[SUPPORTED_PERSONALITIES] = {
231         nsyscalls0,
232 #if SUPPORTED_PERSONALITIES > 1
233         nsyscalls1,
234 #endif
235 #if SUPPORTED_PERSONALITIES > 2
236         nsyscalls2,
237 #endif
238 };
239 static const struct_sysent *const sysent_vec[SUPPORTED_PERSONALITIES] = {
240         sysent0,
241 #if SUPPORTED_PERSONALITIES > 1
242         sysent1,
243 #endif
244 #if SUPPORTED_PERSONALITIES > 2
245         sysent2,
246 #endif
247 };
248
249 enum {
250         MAX_NSYSCALLS1 = (nsyscalls0
251 #if SUPPORTED_PERSONALITIES > 1
252                         > nsyscalls1 ? nsyscalls0 : nsyscalls1
253 #endif
254                         ),
255         MAX_NSYSCALLS2 = (MAX_NSYSCALLS1
256 #if SUPPORTED_PERSONALITIES > 2
257                         > nsyscalls2 ? MAX_NSYSCALLS1 : nsyscalls2
258 #endif
259                         ),
260         MAX_NSYSCALLS = MAX_NSYSCALLS2,
261         /* We are ready for arches with up to 255 signals,
262          * even though the largest known signo is on MIPS and it is 128.
263          * The number of existing syscalls on all arches is
264          * larger that 255 anyway, so it is just a pedantic matter.
265          */
266         MIN_QUALS = MAX_NSYSCALLS > 255 ? MAX_NSYSCALLS : 255
267 };
268
269 #if SUPPORTED_PERSONALITIES > 1
270 unsigned current_personality;
271
272 # ifndef current_wordsize
273 unsigned current_wordsize;
274 static const int personality_wordsize[SUPPORTED_PERSONALITIES] = {
275         PERSONALITY0_WORDSIZE,
276         PERSONALITY1_WORDSIZE,
277 # if SUPPORTED_PERSONALITIES > 2
278         PERSONALITY2_WORDSIZE,
279 # endif
280 };
281 # endif
282
283 void
284 set_personality(int personality)
285 {
286         nsyscalls = nsyscall_vec[personality];
287         sysent = sysent_vec[personality];
288
289         switch (personality) {
290         case 0:
291                 errnoent = errnoent0;
292                 nerrnos = nerrnos0;
293                 ioctlent = ioctlent0;
294                 nioctlents = nioctlents0;
295                 signalent = signalent0;
296                 nsignals = nsignals0;
297                 printers = &printers0;
298                 break;
299
300         case 1:
301                 errnoent = errnoent1;
302                 nerrnos = nerrnos1;
303                 ioctlent = ioctlent1;
304                 nioctlents = nioctlents1;
305                 signalent = signalent1;
306                 nsignals = nsignals1;
307                 printers = &printers1;
308                 break;
309
310 # if SUPPORTED_PERSONALITIES > 2
311         case 2:
312                 errnoent = errnoent2;
313                 nerrnos = nerrnos2;
314                 ioctlent = ioctlent2;
315                 nioctlents = nioctlents2;
316                 signalent = signalent2;
317                 nsignals = nsignals2;
318                 printers = &printers2;
319                 break;
320 # endif
321         }
322
323         current_personality = personality;
324 # ifndef current_wordsize
325         current_wordsize = personality_wordsize[personality];
326 # endif
327 }
328
329 static void
330 update_personality(struct tcb *tcp, unsigned int personality)
331 {
332         if (personality == current_personality)
333                 return;
334         set_personality(personality);
335
336         if (personality == tcp->currpers)
337                 return;
338         tcp->currpers = personality;
339
340 # undef PERSONALITY_NAMES
341 # if defined POWERPC64
342 #  define PERSONALITY_NAMES {"64 bit", "32 bit"}
343 # elif defined X86_64
344 #  define PERSONALITY_NAMES {"64 bit", "32 bit", "x32"}
345 # elif defined X32
346 #  define PERSONALITY_NAMES {"x32", "32 bit"}
347 # elif defined AARCH64
348 #  define PERSONALITY_NAMES {"64 bit", "32 bit"}
349 # elif defined TILE
350 #  define PERSONALITY_NAMES {"64-bit", "32-bit"}
351 # endif
352 # ifdef PERSONALITY_NAMES
353         if (!qflag) {
354                 static const char *const names[] = PERSONALITY_NAMES;
355                 error_msg("[ Process PID=%d runs in %s mode. ]",
356                           tcp->pid, names[personality]);
357         }
358 # endif
359 }
360 #endif
361
362 static int qual_fault(const char *, unsigned int, int);
363 static int qual_signal(const char *, unsigned int, int);
364 static int qual_syscall(const char *, unsigned int, int);
365
366 static const struct qual_options {
367         unsigned int bitflag;
368         const char *option_name;
369         int (*qualify)(const char *, unsigned int, int);
370         const char *argument_name;
371 } qual_options[] = {
372         { QUAL_TRACE,   "trace",        qual_syscall,   "system call"   },
373         { QUAL_TRACE,   "t",            qual_syscall,   "system call"   },
374         { QUAL_ABBREV,  "abbrev",       qual_syscall,   "system call"   },
375         { QUAL_ABBREV,  "a",            qual_syscall,   "system call"   },
376         { QUAL_VERBOSE, "verbose",      qual_syscall,   "system call"   },
377         { QUAL_VERBOSE, "v",            qual_syscall,   "system call"   },
378         { QUAL_RAW,     "raw",          qual_syscall,   "system call"   },
379         { QUAL_RAW,     "x",            qual_syscall,   "system call"   },
380         { QUAL_SIGNAL,  "signal",       qual_signal,    "signal"        },
381         { QUAL_SIGNAL,  "signals",      qual_signal,    "signal"        },
382         { QUAL_SIGNAL,  "s",            qual_signal,    "signal"        },
383         { QUAL_READ,    "read",         NULL,           "descriptor"    },
384         { QUAL_READ,    "reads",        NULL,           "descriptor"    },
385         { QUAL_READ,    "r",            NULL,           "descriptor"    },
386         { QUAL_WRITE,   "write",        NULL,           "descriptor"    },
387         { QUAL_WRITE,   "writes",       NULL,           "descriptor"    },
388         { QUAL_WRITE,   "w",            NULL,           "descriptor"    },
389         { QUAL_FAULT,   "fault",        qual_fault,     "fault argument"},
390         { 0,            NULL,           NULL,           NULL            },
391 };
392
393 static void
394 reallocate_vec(void **vec, unsigned int old_nmemb,
395                size_t size, unsigned int new_nmemb)
396 {
397         unsigned int p;
398
399         for (p = 0; p < SUPPORTED_PERSONALITIES; ++p) {
400                 vec[p] = xreallocarray(vec[p], new_nmemb, size);
401                 memset(vec[p] + size * old_nmemb, 0,
402                        (new_nmemb - old_nmemb) * size);
403         }
404 }
405
406 static void
407 reallocate_qual(const unsigned int n)
408 {
409         reallocate_vec((void **) qual_vec, num_quals, sizeof(qualbits_t), n);
410         num_quals = n;
411 }
412
413 struct fault_opts {
414         uint16_t first;
415         uint16_t step;
416         uint16_t err;
417 };
418
419 static unsigned int num_faults;
420 static struct fault_opts *fault_vec[SUPPORTED_PERSONALITIES];
421
422 static inline void
423 reallocate_fault(const unsigned int n)
424 {
425         reallocate_vec((void **) fault_vec, num_faults,
426                        sizeof(struct fault_opts), n);
427         num_faults = n;
428 }
429
430 static void
431 qualify_one(const unsigned int n, unsigned int bitflag, const int not,
432             const int pers, const struct fault_opts *fopts)
433 {
434         int p;
435
436         if (num_quals <= n) {
437                 reallocate_qual(n + 1);
438                 reallocate_fault(n + 1);
439         }
440
441         for (p = 0; p < SUPPORTED_PERSONALITIES; p++) {
442                 if (pers == p || pers < 0) {
443                         if (not)
444                                 qual_vec[p][n] &= ~bitflag;
445                         else {
446                                 qual_vec[p][n] |= bitflag;
447                                 if (fopts)
448                                         memcpy(&fault_vec[p][n], fopts,
449                                                sizeof(*fopts));
450                         }
451                 }
452         }
453 }
454
455 static bool
456 qualify_scno(const char *const s, const unsigned int bitflag,
457              const int not, const struct fault_opts *const fopts)
458 {
459         int n = string_to_uint_upto(s, MAX_NSYSCALLS - 1);
460         if (n < 0)
461                 return false;
462
463         if (not && fopts) {
464                 /* set bitflag for all syscall numbers except n */
465                 unsigned int p;
466                 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p) {
467                         unsigned int i;
468
469                         for (i = 0; i < nsyscall_vec[p]; ++i) {
470                                 if (i != (unsigned int) n
471                                     && sysent_vec[p][i].sys_name) {
472                                         qualify_one(i, bitflag, 0, p, fopts);
473                                 }
474                         }
475                 }
476         } else {
477                 qualify_one(n, bitflag, not, -1, fopts);
478         }
479
480         return true;
481 }
482
483 static int
484 lookup_class(const char *s)
485 {
486         if (strcmp(s, "all") == 0)
487                 return 0;
488         if (strcmp(s, "file") == 0)
489                 return TRACE_FILE;
490         if (strcmp(s, "ipc") == 0)
491                 return TRACE_IPC;
492         if (strcmp(s, "network") == 0)
493                 return TRACE_NETWORK;
494         if (strcmp(s, "process") == 0)
495                 return TRACE_PROCESS;
496         if (strcmp(s, "signal") == 0)
497                 return TRACE_SIGNAL;
498         if (strcmp(s, "desc") == 0)
499                 return TRACE_DESC;
500         if (strcmp(s, "memory") == 0)
501                 return TRACE_MEMORY;
502         return -1;
503 }
504
505 static bool
506 qualify_syscall_class(const char *const s, const unsigned int bitflag,
507                       const int not, const struct fault_opts *const fopts)
508 {
509         unsigned int p;
510         const int n = lookup_class(s);
511
512         if (n < 0)
513                 return false;
514
515         for (p = 0; p < SUPPORTED_PERSONALITIES; ++p) {
516                 unsigned int i;
517
518                 for (i = 0; i < nsyscall_vec[p]; ++i) {
519                         if (!sysent_vec[p][i].sys_name)
520                                 continue;
521                         const bool match = (sysent_vec[p][i].sys_flags & n) == n;
522                         if (match ^ (not && fopts)) {
523                                 qualify_one(i, bitflag, not && !fopts, p, fopts);
524                         }
525                 }
526         }
527
528         return true;
529 }
530
531 static bool
532 qualify_syscall_name(const char *const s, const unsigned int bitflag,
533                      const int not, const struct fault_opts *const fopts)
534 {
535         bool found = false;
536         unsigned int p;
537
538         for (p = 0; p < SUPPORTED_PERSONALITIES; ++p) {
539                 unsigned int i;
540
541                 for (i = 0; i < nsyscall_vec[p]; ++i) {
542                         if (!sysent_vec[p][i].sys_name)
543                                 continue;
544                         const bool match = !strcmp(s, sysent_vec[p][i].sys_name);
545                         found = found || match;
546                         if (match ^ (not && fopts)) {
547                                 qualify_one(i, bitflag, not && !fopts, p, fopts);
548                         }
549                 }
550         }
551
552         return found;
553 }
554
555 static int
556 qual_syscall_ex(const char *const s, const unsigned int bitflag,
557                 const int not, const struct fault_opts *const fopts)
558 {
559         if (qualify_scno(s, bitflag, not, fopts)
560             || qualify_syscall_class(s, bitflag, not, fopts)
561             || qualify_syscall_name(s, bitflag, not, fopts)) {
562                 return 0;
563         }
564
565         return -1;
566 }
567
568 static int
569 qual_syscall(const char *const s, const unsigned int bitflag, const int not)
570 {
571         return qual_syscall_ex(s, bitflag, not, NULL);
572 }
573
574 /*
575  * Returns NULL if STR does not start with PREFIX,
576  * or a pointer to the first char in STR after PREFIX.
577  */
578 static const char *
579 strip_prefix(const char *prefix, const char *str)
580 {
581         size_t len = strlen(prefix);
582
583         return strncmp(prefix, str, len) ? NULL : str + len;
584 }
585
586 static int
587 find_errno_by_name(const char *name)
588 {
589         unsigned int i;
590
591         for (i = 1; i < nerrnos; ++i) {
592                 if (errnoent[i] && (strcmp(name, errnoent[i]) == 0))
593                         return i;
594         }
595
596         return -1;
597 }
598
599 static bool
600 parse_fault_token(const char *const token, struct fault_opts *const fopts)
601 {
602         const char *val;
603         int intval;
604
605         if ((val = strip_prefix("when=", token))) {
606                 /*
607                  *      == 1+1
608                  * F    == F+0
609                  * F+   == F+1
610                  * F+S
611                  */
612                 char *end;
613                 intval = string_to_uint_ex(val, &end, 0xffff, "+");
614                 if (intval < 1)
615                         return false;
616
617                 fopts->first = intval;
618
619                 if (*end) {
620                         val = end + 1;
621                         if (*val) {
622                                 /* F+S */
623                                 intval = string_to_uint_upto(val, 0xffff);
624                                 if (intval < 1)
625                                         return false;
626                                 fopts->step = intval;
627                         } else {
628                                 /* F+ == F+1 */
629                                 fopts->step = 1;
630                         }
631                 } else {
632                         /* F == F+0 */
633                         fopts->step = 0;
634                 }
635         } else if ((val = strip_prefix("error=", token))) {
636                 intval = string_to_uint_upto(val, 4095);
637                 if (intval < 0)
638                         intval = find_errno_by_name(val);
639                 if (intval < 1)
640                         return false;
641                 fopts->err = intval;
642         } else {
643                 return false;
644         }
645
646         return true;
647 }
648
649 static char *
650 parse_fault_expression(const char *const s, char **buf,
651                        struct fault_opts *const fopts)
652 {
653         char *saveptr = NULL;
654         char *name = NULL;
655         char *token;
656
657         *buf = xstrdup(s);
658         for (token = strtok_r(*buf, ":", &saveptr); token;
659              token = strtok_r(NULL, ":", &saveptr)) {
660                 if (!name)
661                         name = token;
662                 else if (!parse_fault_token(token, fopts))
663                         goto parse_error;
664         }
665
666         if (name)
667                 return name;
668
669 parse_error:
670         free(*buf);
671         return *buf = NULL;
672 }
673
674 static int
675 qual_fault(const char *const s, const unsigned int bitflag, const int not)
676 {
677         struct fault_opts opts = {
678                 .first = 1,
679                 .step = 1,
680                 .err = 0
681         };
682
683         char *buf = NULL;
684         char *name = parse_fault_expression(s, &buf, &opts);
685         char *saveptr = NULL;
686         const char *token;
687         int rc = -1;
688
689         if (!name)
690                 return -1;
691
692         for (token = strtok_r(name, ",", &saveptr); token;
693              token = strtok_r(NULL, ",", &saveptr)) {
694                 rc = qual_syscall_ex(token, bitflag, not, &opts);
695                 if (rc)
696                         break;
697         }
698
699         free(buf);
700         return rc;
701 }
702
703 static int
704 qual_signal(const char *s, const unsigned int bitflag, const int not)
705 {
706         int i;
707
708         if (*s >= '0' && *s <= '9') {
709                 i = string_to_uint_upto(s, 255);
710                 if (i < 0)
711                         return -1;
712                 qualify_one(i, bitflag, not, -1, NULL);
713                 return 0;
714         }
715         if (strncasecmp(s, "SIG", 3) == 0)
716                 s += 3;
717         for (i = 0; i <= NSIG; ++i) {
718                 const char *name = signame(i);
719                 if (strncasecmp(name, "SIG", 3) != 0)
720                         continue;
721                 name += 3;
722
723                 if (strcasecmp(name, s) != 0)
724                         continue;
725                 qualify_one(i, bitflag, not, -1, NULL);
726                 return 0;
727         }
728         return -1;
729 }
730
731 void
732 qualify(const char *s)
733 {
734         const struct qual_options *opt;
735         char *copy;
736         const char *p;
737         int not;
738         unsigned int i;
739
740         if (num_quals == 0) {
741                 reallocate_qual(MIN_QUALS);
742                 reallocate_fault(MIN_QUALS);
743         }
744
745         opt = &qual_options[0];
746         for (i = 0; (p = qual_options[i].option_name); i++) {
747                 unsigned int len = strlen(p);
748                 if (strncmp(s, p, len) == 0 && s[len] == '=') {
749                         opt = &qual_options[i];
750                         s += len + 1;
751                         break;
752                 }
753         }
754
755         switch (opt->bitflag) {
756                 case QUAL_READ:
757                         qualify_read(s);
758                         return;
759                 case QUAL_WRITE:
760                         qualify_write(s);
761                         return;
762         }
763
764         not = 0;
765         if (*s == '!') {
766                 not = 1;
767                 s++;
768         }
769         if (strcmp(s, "none") == 0) {
770                 not = 1 - not;
771                 s = "all";
772         }
773         if (opt->bitflag == QUAL_FAULT) {
774                 if (opt->qualify(s, opt->bitflag, not)) {
775                         error_msg_and_die("invalid %s '%s'",
776                                 opt->argument_name, s);
777                 }
778                 return;
779         }
780         if (strcmp(s, "all") == 0) {
781                 for (i = 0; i < num_quals; ++i) {
782                         qualify_one(i, opt->bitflag, not, -1, NULL);
783                 }
784                 return;
785         }
786         for (i = 0; i < num_quals; ++i) {
787                 qualify_one(i, opt->bitflag, !not, -1, NULL);
788         }
789         copy = xstrdup(s);
790         for (p = strtok(copy, ","); p; p = strtok(NULL, ",")) {
791                 if (opt->qualify(p, opt->bitflag, not)) {
792                         error_msg_and_die("invalid %s '%s'",
793                                 opt->argument_name, p);
794                 }
795         }
796         free(copy);
797         return;
798 }
799
800 #ifdef SYS_socket_subcall
801 static void
802 decode_socket_subcall(struct tcb *tcp)
803 {
804         const int call = tcp->u_arg[0];
805
806         if (call < 1 || call >= SYS_socket_nsubcalls)
807                 return;
808
809         const unsigned long scno = SYS_socket_subcall + call;
810         const unsigned int nargs = sysent[scno].nargs;
811         uint64_t buf[nargs];
812
813         if (umoven(tcp, tcp->u_arg[1], nargs * current_wordsize, buf) < 0)
814                 return;
815
816         tcp->scno = scno;
817         tcp->qual_flg = qual_flags[scno];
818         tcp->s_ent = &sysent[scno];
819
820         unsigned int i;
821         for (i = 0; i < nargs; ++i)
822                 tcp->u_arg[i] = (sizeof(uint32_t) == current_wordsize)
823                                 ? ((uint32_t *) (void *) buf)[i] : buf[i];
824 }
825 #endif
826
827 #ifdef SYS_ipc_subcall
828 static void
829 decode_ipc_subcall(struct tcb *tcp)
830 {
831         unsigned int call = tcp->u_arg[0];
832         const unsigned int version = call >> 16;
833
834         if (version) {
835 # if defined S390 || defined S390X
836                 return;
837 # else
838 #  ifdef SPARC64
839                 if (current_wordsize == 8)
840                         return;
841 #  endif
842                 set_tcb_priv_ulong(tcp, version);
843                 call &= 0xffff;
844 # endif
845         }
846
847         switch (call) {
848                 case  1: case  2: case  3: case  4:
849                 case 11: case 12: case 13: case 14:
850                 case 21: case 22: case 23: case 24:
851                         break;
852                 default:
853                         return;
854         }
855
856         tcp->scno = SYS_ipc_subcall + call;
857         tcp->qual_flg = qual_flags[tcp->scno];
858         tcp->s_ent = &sysent[tcp->scno];
859
860         const unsigned int n = tcp->s_ent->nargs;
861         unsigned int i;
862         for (i = 0; i < n; i++)
863                 tcp->u_arg[i] = tcp->u_arg[i + 1];
864 }
865 #endif
866
867 #ifdef LINUX_MIPSO32
868 static void
869 decode_mips_subcall(struct tcb *tcp)
870 {
871         if (!SCNO_IS_VALID(tcp->u_arg[0]))
872                 return;
873         tcp->scno = tcp->u_arg[0];
874         tcp->qual_flg = qual_flags[tcp->scno];
875         tcp->s_ent = &sysent[tcp->scno];
876         memmove(&tcp->u_arg[0], &tcp->u_arg[1],
877                 sizeof(tcp->u_arg) - sizeof(tcp->u_arg[0]));
878         /*
879          * Fetching the last arg of 7-arg syscalls (fadvise64_64
880          * and sync_file_range) requires additional code,
881          * see linux/mips/get_syscall_args.c
882          */
883         if (tcp->s_ent->nargs == MAX_ARGS) {
884                 if (umoven(tcp,
885                            mips_REG_SP + MAX_ARGS * sizeof(tcp->u_arg[0]),
886                            sizeof(tcp->u_arg[0]),
887                            &tcp->u_arg[MAX_ARGS - 1]) < 0)
888                 tcp->u_arg[MAX_ARGS - 1] = 0;
889         }
890 }
891 #endif /* LINUX_MIPSO32 */
892
893 static void
894 dumpio(struct tcb *tcp)
895 {
896         if (syserror(tcp))
897                 return;
898
899         int fd = tcp->u_arg[0];
900         if (fd < 0)
901                 return;
902
903         if (is_number_in_set(fd, &read_set)) {
904                 switch (tcp->s_ent->sen) {
905                 case SEN_read:
906                 case SEN_pread:
907                 case SEN_recv:
908                 case SEN_recvfrom:
909                 case SEN_mq_timedreceive:
910                         dumpstr(tcp, tcp->u_arg[1], tcp->u_rval);
911                         return;
912                 case SEN_readv:
913                 case SEN_preadv:
914                 case SEN_preadv2:
915                         dumpiov_upto(tcp, tcp->u_arg[2], tcp->u_arg[1],
916                                      tcp->u_rval);
917                         return;
918                 case SEN_recvmsg:
919                         dumpiov_in_msghdr(tcp, tcp->u_arg[1], tcp->u_rval);
920                         return;
921                 case SEN_recvmmsg:
922                         dumpiov_in_mmsghdr(tcp, tcp->u_arg[1]);
923                         return;
924                 }
925         }
926         if (is_number_in_set(fd, &write_set)) {
927                 switch (tcp->s_ent->sen) {
928                 case SEN_write:
929                 case SEN_pwrite:
930                 case SEN_send:
931                 case SEN_sendto:
932                 case SEN_mq_timedsend:
933                         dumpstr(tcp, tcp->u_arg[1], tcp->u_arg[2]);
934                         break;
935                 case SEN_writev:
936                 case SEN_pwritev:
937                 case SEN_pwritev2:
938                 case SEN_vmsplice:
939                         dumpiov(tcp, tcp->u_arg[2], tcp->u_arg[1]);
940                         break;
941                 case SEN_sendmsg:
942                         dumpiov_in_msghdr(tcp, tcp->u_arg[1],
943                                           (unsigned long) -1L);
944                         break;
945                 case SEN_sendmmsg:
946                         dumpiov_in_mmsghdr(tcp, tcp->u_arg[1]);
947                         break;
948                 }
949         }
950 }
951
952 /*
953  * Shuffle syscall numbers so that we don't have huge gaps in syscall table.
954  * The shuffling should be an involution: shuffle_scno(shuffle_scno(n)) == n.
955  */
956 #if defined(ARM) || defined(AARCH64) /* So far only 32-bit ARM needs this */
957 static long
958 shuffle_scno(unsigned long scno)
959 {
960         if (scno < ARM_FIRST_SHUFFLED_SYSCALL)
961                 return scno;
962
963         /* __ARM_NR_cmpxchg? Swap with LAST_ORDINARY+1 */
964         if (scno == ARM_FIRST_SHUFFLED_SYSCALL)
965                 return 0x000ffff0;
966         if (scno == 0x000ffff0)
967                 return ARM_FIRST_SHUFFLED_SYSCALL;
968
969 #define ARM_SECOND_SHUFFLED_SYSCALL (ARM_FIRST_SHUFFLED_SYSCALL + 1)
970         /*
971          * Is it ARM specific syscall?
972          * Swap [0x000f0000, 0x000f0000 + LAST_SPECIAL] range
973          * with [SECOND_SHUFFLED, SECOND_SHUFFLED + LAST_SPECIAL] range.
974          */
975         if (scno >= 0x000f0000 &&
976             scno <= 0x000f0000 + ARM_LAST_SPECIAL_SYSCALL) {
977                 return scno - 0x000f0000 + ARM_SECOND_SHUFFLED_SYSCALL;
978         }
979         if (scno <= ARM_SECOND_SHUFFLED_SYSCALL + ARM_LAST_SPECIAL_SYSCALL) {
980                 return scno + 0x000f0000 - ARM_SECOND_SHUFFLED_SYSCALL;
981         }
982
983         return scno;
984 }
985 #else
986 # define shuffle_scno(scno) ((long)(scno))
987 #endif
988
989 const char *
990 err_name(unsigned long err)
991 {
992         if ((err < nerrnos) && errnoent[err])
993                 return errnoent[err];
994
995         return NULL;
996 }
997
998 static long get_regs_error;
999
1000 void
1001 clear_regs(void)
1002 {
1003         get_regs_error = -1;
1004 }
1005
1006 static int get_syscall_args(struct tcb *);
1007 static int get_syscall_result(struct tcb *);
1008 static int arch_get_scno(struct tcb *tcp);
1009 static int arch_set_scno(struct tcb *, long);
1010 static void get_error(struct tcb *, const bool);
1011 static int arch_set_error(struct tcb *);
1012
1013 static struct fault_opts *
1014 tcb_fault_opts(struct tcb *tcp)
1015 {
1016         return (SCNO_IN_RANGE(tcp->scno) && tcp->fault_vec[current_personality])
1017                ? &tcp->fault_vec[current_personality][tcp->scno] : NULL;
1018 }
1019
1020
1021 static long
1022 inject_syscall_fault_entering(struct tcb *tcp)
1023 {
1024         if (!tcp->fault_vec[current_personality]) {
1025                 tcp->fault_vec[current_personality] =
1026                         xreallocarray(NULL, num_faults,
1027                                       sizeof(struct fault_opts));
1028                 memcpy(tcp->fault_vec[current_personality],
1029                        fault_vec[current_personality],
1030                        num_faults * sizeof(struct fault_opts));
1031         }
1032
1033         struct fault_opts *opts = tcb_fault_opts(tcp);
1034
1035         if (opts->first == 0)
1036                 return 0;
1037
1038         --opts->first;
1039
1040         if (opts->first != 0)
1041                 return 0;
1042
1043         opts->first = opts->step;
1044
1045         if (!arch_set_scno(tcp, -1))
1046                 tcp->flags |= TCB_FAULT_INJ;
1047
1048         return 0;
1049 }
1050
1051 static long
1052 update_syscall_fault_exiting(struct tcb *tcp)
1053 {
1054         struct fault_opts *opts = tcb_fault_opts(tcp);
1055
1056         if (opts && opts->err && tcp->u_error != opts->err) {
1057                 unsigned long u_error = tcp->u_error;
1058                 tcp->u_error = opts->err;
1059                 if (arch_set_error(tcp))
1060                         tcp->u_error = u_error;
1061         }
1062
1063         return 0;
1064 }
1065
1066 static int
1067 trace_syscall_entering(struct tcb *tcp)
1068 {
1069         int res, scno_good;
1070
1071         scno_good = res = get_scno(tcp);
1072         if (res == 0)
1073                 return res;
1074         if (res == 1)
1075                 res = get_syscall_args(tcp);
1076
1077         if (res != 1) {
1078                 printleader(tcp);
1079                 tprintf("%s(", scno_good == 1 ? tcp->s_ent->sys_name : "????");
1080                 /*
1081                  * " <unavailable>" will be added later by the code which
1082                  * detects ptrace errors.
1083                  */
1084                 goto ret;
1085         }
1086
1087 #ifdef LINUX_MIPSO32
1088         if (SEN_syscall == tcp->s_ent->sen)
1089                 decode_mips_subcall(tcp);
1090 #endif
1091
1092 #if defined(SYS_socket_subcall) || defined(SYS_ipc_subcall)
1093         switch (tcp->s_ent->sen) {
1094 # ifdef SYS_socket_subcall
1095                 case SEN_socketcall:
1096                         decode_socket_subcall(tcp);
1097                         break;
1098 # endif
1099 # ifdef SYS_ipc_subcall
1100                 case SEN_ipc:
1101                         decode_ipc_subcall(tcp);
1102                         break;
1103 # endif
1104         }
1105 #endif
1106
1107         /* Restrain from fault injection while the trace executes strace code. */
1108         if (hide_log(tcp)) {
1109                 tcp->qual_flg &= ~QUAL_FAULT;
1110         }
1111
1112         switch (tcp->s_ent->sen) {
1113                 case SEN_execve:
1114                 case SEN_execveat:
1115 #if defined SPARC || defined SPARC64
1116                 case SEN_execv:
1117 #endif
1118                         tcp->flags &= ~TCB_HIDE_LOG;
1119                         break;
1120         }
1121
1122         if (!(tcp->qual_flg & QUAL_TRACE)
1123          || (tracing_paths && !pathtrace_match(tcp))
1124         ) {
1125                 tcp->flags |= TCB_INSYSCALL | TCB_FILTERED;
1126                 tcp->sys_func_rval = 0;
1127                 return 0;
1128         }
1129
1130         tcp->flags &= ~TCB_FILTERED;
1131
1132         if (hide_log(tcp)) {
1133                 res = 0;
1134                 goto ret;
1135         }
1136
1137         if (tcp->qual_flg & QUAL_FAULT)
1138                 inject_syscall_fault_entering(tcp);
1139
1140         if (cflag == CFLAG_ONLY_STATS) {
1141                 res = 0;
1142                 goto ret;
1143         }
1144
1145 #ifdef USE_LIBUNWIND
1146         if (stack_trace_enabled) {
1147                 if (tcp->s_ent->sys_flags & STACKTRACE_CAPTURE_ON_ENTER)
1148                         unwind_capture_stacktrace(tcp);
1149         }
1150 #endif
1151
1152         printleader(tcp);
1153         tprintf("%s(", tcp->s_ent->sys_name);
1154         if (tcp->qual_flg & QUAL_RAW)
1155                 res = printargs(tcp);
1156         else
1157                 res = tcp->s_ent->sys_func(tcp);
1158
1159         fflush(tcp->outf);
1160  ret:
1161         tcp->flags |= TCB_INSYSCALL;
1162         tcp->sys_func_rval = res;
1163         /* Measure the entrance time as late as possible to avoid errors. */
1164         if (Tflag || cflag)
1165                 gettimeofday(&tcp->etime, NULL);
1166         return res;
1167 }
1168
1169 static bool
1170 syscall_fault_injected(struct tcb *tcp)
1171 {
1172         return tcp->flags & TCB_FAULT_INJ;
1173 }
1174
1175 static int
1176 trace_syscall_exiting(struct tcb *tcp)
1177 {
1178         int sys_res;
1179         struct timeval tv;
1180         int res;
1181         unsigned long u_error;
1182         const char *u_error_str;
1183
1184         /* Measure the exit time as early as possible to avoid errors. */
1185         if (Tflag || cflag)
1186                 gettimeofday(&tv, NULL);
1187
1188 #ifdef USE_LIBUNWIND
1189         if (stack_trace_enabled) {
1190                 if (tcp->s_ent->sys_flags & STACKTRACE_INVALIDATE_CACHE)
1191                         unwind_cache_invalidate(tcp);
1192         }
1193 #endif
1194
1195 #if SUPPORTED_PERSONALITIES > 1
1196         update_personality(tcp, tcp->currpers);
1197 #endif
1198         res = (get_regs_error ? -1 : get_syscall_result(tcp));
1199         if (filtered(tcp) || hide_log(tcp))
1200                 goto ret;
1201
1202         if (syserror(tcp) && syscall_fault_injected(tcp))
1203                 update_syscall_fault_exiting(tcp);
1204
1205         if (cflag) {
1206                 count_syscall(tcp, &tv);
1207                 if (cflag == CFLAG_ONLY_STATS) {
1208                         goto ret;
1209                 }
1210         }
1211
1212         /* If not in -ff mode, and printing_tcp != tcp,
1213          * then the log currently does not end with output
1214          * of _our syscall entry_, but with something else.
1215          * We need to say which syscall's return is this.
1216          *
1217          * Forced reprinting via TCB_REPRINT is used only by
1218          * "strace -ff -oLOG test/threaded_execve" corner case.
1219          * It's the only case when -ff mode needs reprinting.
1220          */
1221         if ((followfork < 2 && printing_tcp != tcp) || (tcp->flags & TCB_REPRINT)) {
1222                 tcp->flags &= ~TCB_REPRINT;
1223                 printleader(tcp);
1224                 tprintf("<... %s resumed> ", tcp->s_ent->sys_name);
1225         }
1226         printing_tcp = tcp;
1227
1228         tcp->s_prev_ent = NULL;
1229         if (res != 1) {
1230                 /* There was error in one of prior ptrace ops */
1231                 tprints(") ");
1232                 tabto();
1233                 tprints("= ? <unavailable>\n");
1234                 line_ended();
1235                 tcp->flags &= ~(TCB_INSYSCALL | TCB_FAULT_INJ);
1236                 tcp->sys_func_rval = 0;
1237                 free_tcb_priv_data(tcp);
1238                 return res;
1239         }
1240         tcp->s_prev_ent = tcp->s_ent;
1241
1242         sys_res = 0;
1243         if (tcp->qual_flg & QUAL_RAW) {
1244                 /* sys_res = printargs(tcp); - but it's nop on sysexit */
1245         } else {
1246         /* FIXME: not_failing_only (IOW, option -z) is broken:
1247          * failure of syscall is known only after syscall return.
1248          * Thus we end up with something like this on, say, ENOENT:
1249          *     open("doesnt_exist", O_RDONLY <unfinished ...>
1250          *     {next syscall decode}
1251          * whereas the intended result is that open(...) line
1252          * is not shown at all.
1253          */
1254                 if (not_failing_only && tcp->u_error)
1255                         goto ret;       /* ignore failed syscalls */
1256                 if (tcp->sys_func_rval & RVAL_DECODED)
1257                         sys_res = tcp->sys_func_rval;
1258                 else
1259                         sys_res = tcp->s_ent->sys_func(tcp);
1260         }
1261
1262         tprints(") ");
1263         tabto();
1264         u_error = tcp->u_error;
1265
1266         if (tcp->qual_flg & QUAL_RAW) {
1267                 if (u_error) {
1268                         tprintf("= -1 (errno %lu)", u_error);
1269                         if (syscall_fault_injected(tcp))
1270                                 tprints(" (INJECTED)");
1271                 } else {
1272                         tprintf("= %#lx", tcp->u_rval);
1273                 }
1274         }
1275         else if (!(sys_res & RVAL_NONE) && u_error) {
1276                 switch (u_error) {
1277                 /* Blocked signals do not interrupt any syscalls.
1278                  * In this case syscalls don't return ERESTARTfoo codes.
1279                  *
1280                  * Deadly signals set to SIG_DFL interrupt syscalls
1281                  * and kill the process regardless of which of the codes below
1282                  * is returned by the interrupted syscall.
1283                  * In some cases, kernel forces a kernel-generated deadly
1284                  * signal to be unblocked and set to SIG_DFL (and thus cause
1285                  * death) if it is blocked or SIG_IGNed: for example, SIGSEGV
1286                  * or SIGILL. (The alternative is to leave process spinning
1287                  * forever on the faulty instruction - not useful).
1288                  *
1289                  * SIG_IGNed signals and non-deadly signals set to SIG_DFL
1290                  * (for example, SIGCHLD, SIGWINCH) interrupt syscalls,
1291                  * but kernel will always restart them.
1292                  */
1293                 case ERESTARTSYS:
1294                         /* Most common type of signal-interrupted syscall exit code.
1295                          * The system call will be restarted with the same arguments
1296                          * if SA_RESTART is set; otherwise, it will fail with EINTR.
1297                          */
1298                         tprints("= ? ERESTARTSYS (To be restarted if SA_RESTART is set)");
1299                         break;
1300                 case ERESTARTNOINTR:
1301                         /* Rare. For example, fork() returns this if interrupted.
1302                          * SA_RESTART is ignored (assumed set): the restart is unconditional.
1303                          */
1304                         tprints("= ? ERESTARTNOINTR (To be restarted)");
1305                         break;
1306                 case ERESTARTNOHAND:
1307                         /* pause(), rt_sigsuspend() etc use this code.
1308                          * SA_RESTART is ignored (assumed not set):
1309                          * syscall won't restart (will return EINTR instead)
1310                          * even after signal with SA_RESTART set. However,
1311                          * after SIG_IGN or SIG_DFL signal it will restart
1312                          * (thus the name "restart only if has no handler").
1313                          */
1314                         tprints("= ? ERESTARTNOHAND (To be restarted if no handler)");
1315                         break;
1316                 case ERESTART_RESTARTBLOCK:
1317                         /* Syscalls like nanosleep(), poll() which can't be
1318                          * restarted with their original arguments use this
1319                          * code. Kernel will execute restart_syscall() instead,
1320                          * which changes arguments before restarting syscall.
1321                          * SA_RESTART is ignored (assumed not set) similarly
1322                          * to ERESTARTNOHAND. (Kernel can't honor SA_RESTART
1323                          * since restart data is saved in "restart block"
1324                          * in task struct, and if signal handler uses a syscall
1325                          * which in turn saves another such restart block,
1326                          * old data is lost and restart becomes impossible)
1327                          */
1328                         tprints("= ? ERESTART_RESTARTBLOCK (Interrupted by signal)");
1329                         break;
1330                 default:
1331                         u_error_str = err_name(u_error);
1332                         if (u_error_str)
1333                                 tprintf("= -1 %s (%s)",
1334                                         u_error_str, strerror(u_error));
1335                         else
1336                                 tprintf("= -1 %lu (%s)",
1337                                         u_error, strerror(u_error));
1338                         break;
1339                 }
1340                 if (syscall_fault_injected(tcp))
1341                         tprintf(" (INJECTED)");
1342                 if ((sys_res & RVAL_STR) && tcp->auxstr)
1343                         tprintf(" (%s)", tcp->auxstr);
1344         }
1345         else {
1346                 if (sys_res & RVAL_NONE)
1347                         tprints("= ?");
1348                 else {
1349                         switch (sys_res & RVAL_MASK) {
1350                         case RVAL_HEX:
1351 #if SUPPORTED_PERSONALITIES > 1
1352                                 if (current_wordsize < sizeof(long))
1353                                         tprintf("= %#x",
1354                                                 (unsigned int) tcp->u_rval);
1355                                 else
1356 #endif
1357                                         tprintf("= %#lx", tcp->u_rval);
1358                                 break;
1359                         case RVAL_OCTAL:
1360                                 tprints("= ");
1361                                 print_numeric_long_umask(tcp->u_rval);
1362                                 break;
1363                         case RVAL_UDECIMAL:
1364 #if SUPPORTED_PERSONALITIES > 1
1365                                 if (current_wordsize < sizeof(long))
1366                                         tprintf("= %u",
1367                                                 (unsigned int) tcp->u_rval);
1368                                 else
1369 #endif
1370                                         tprintf("= %lu", tcp->u_rval);
1371                                 break;
1372                         case RVAL_DECIMAL:
1373                                 tprintf("= %ld", tcp->u_rval);
1374                                 break;
1375                         case RVAL_FD:
1376                                 if (show_fd_path) {
1377                                         tprints("= ");
1378                                         printfd(tcp, tcp->u_rval);
1379                                 }
1380                                 else
1381                                         tprintf("= %ld", tcp->u_rval);
1382                                 break;
1383 #if HAVE_STRUCT_TCB_EXT_ARG
1384                         /*
1385                         case RVAL_LHEX:
1386                                 tprintf("= %#llx", tcp->u_lrval);
1387                                 break;
1388                         case RVAL_LOCTAL:
1389                                 tprintf("= %#llo", tcp->u_lrval);
1390                                 break;
1391                         */
1392                         case RVAL_LUDECIMAL:
1393                                 tprintf("= %llu", tcp->u_lrval);
1394                                 break;
1395                         /*
1396                         case RVAL_LDECIMAL:
1397                                 tprintf("= %lld", tcp->u_lrval);
1398                                 break;
1399                         */
1400 #endif /* HAVE_STRUCT_TCB_EXT_ARG */
1401                         default:
1402                                 error_msg("invalid rval format");
1403                                 break;
1404                         }
1405                 }
1406                 if ((sys_res & RVAL_STR) && tcp->auxstr)
1407                         tprintf(" (%s)", tcp->auxstr);
1408         }
1409         if (Tflag) {
1410                 tv_sub(&tv, &tv, &tcp->etime);
1411                 tprintf(" <%ld.%06ld>",
1412                         (long) tv.tv_sec, (long) tv.tv_usec);
1413         }
1414         tprints("\n");
1415         dumpio(tcp);
1416         line_ended();
1417
1418 #ifdef USE_LIBUNWIND
1419         if (stack_trace_enabled)
1420                 unwind_print_stacktrace(tcp);
1421 #endif
1422
1423  ret:
1424         tcp->flags &= ~(TCB_INSYSCALL | TCB_FAULT_INJ);
1425         tcp->sys_func_rval = 0;
1426         free_tcb_priv_data(tcp);
1427         return 0;
1428 }
1429
1430 int
1431 trace_syscall(struct tcb *tcp)
1432 {
1433         return exiting(tcp) ?
1434                 trace_syscall_exiting(tcp) : trace_syscall_entering(tcp);
1435 }
1436
1437 bool
1438 is_erestart(struct tcb *tcp)
1439 {
1440         switch (tcp->u_error) {
1441                 case ERESTARTSYS:
1442                 case ERESTARTNOINTR:
1443                 case ERESTARTNOHAND:
1444                 case ERESTART_RESTARTBLOCK:
1445                         return true;
1446                 default:
1447                         return false;
1448         }
1449 }
1450
1451 static unsigned long saved_u_error;
1452
1453 void
1454 temporarily_clear_syserror(struct tcb *tcp)
1455 {
1456         saved_u_error = tcp->u_error;
1457         tcp->u_error = 0;
1458 }
1459
1460 void
1461 restore_cleared_syserror(struct tcb *tcp)
1462 {
1463         tcp->u_error = saved_u_error;
1464 }
1465
1466 #include "kernel_types.h"
1467
1468 /*
1469  * Check the syscall return value register value for whether it is
1470  * a negated errno code indicating an error, or a success return value.
1471  */
1472 static inline bool
1473 is_negated_errno(kernel_ulong_t val)
1474 {
1475         /* Linux kernel defines MAX_ERRNO to 4095. */
1476         kernel_ulong_t max = -(kernel_long_t) 4095;
1477
1478 #if defined X86_64 || defined X32
1479         /*
1480          * current_wordsize is 4 for x32 personality
1481          * but truncation _must not_ be done in it, so
1482          * check current_personality instead.
1483          */
1484         if (current_personality == 1) {
1485                 val = (uint32_t) val;
1486                 max = (uint32_t) max;
1487         }
1488 #elif SUPPORTED_PERSONALITIES > 1 && SIZEOF_LONG > 4
1489         if (current_wordsize < sizeof(val)) {
1490                 val = (uint32_t) val;
1491                 max = (uint32_t) max;
1492         }
1493 #endif
1494
1495         return val >= max;
1496 }
1497
1498 #include "arch_regs.c"
1499
1500 #ifdef HAVE_GETRVAL2
1501 # include "arch_getrval2.c"
1502 #endif
1503
1504 void
1505 print_pc(struct tcb *tcp)
1506 {
1507 #if defined ARCH_PC_REG
1508 # define ARCH_GET_PC 0
1509 #elif defined ARCH_PC_PEEK_ADDR
1510         long pc;
1511 # define ARCH_PC_REG pc
1512 # define ARCH_GET_PC upeek(tcp->pid, ARCH_PC_PEEK_ADDR, &pc)
1513 #else
1514 # error Neither ARCH_PC_REG nor ARCH_PC_PEEK_ADDR is defined
1515 #endif
1516         if (get_regs_error || ARCH_GET_PC)
1517                 tprints(current_wordsize == 4 ? "[????????] "
1518                                               : "[????????????????] ");
1519         else
1520                 tprintf(current_wordsize == 4 ? "[%08lx] " : "[%016lx] ",
1521                         (unsigned long) ARCH_PC_REG);
1522 }
1523
1524 #include "getregs_old.h"
1525
1526 #undef ptrace_getregset_or_getregs
1527 #undef ptrace_setregset_or_setregs
1528 #ifdef ARCH_REGS_FOR_GETREGSET
1529
1530 # define ptrace_getregset_or_getregs ptrace_getregset
1531 static long
1532 ptrace_getregset(pid_t pid)
1533 {
1534 # ifdef ARCH_IOVEC_FOR_GETREGSET
1535         /* variable iovec */
1536         ARCH_IOVEC_FOR_GETREGSET.iov_len = sizeof(ARCH_REGS_FOR_GETREGSET);
1537         return ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS,
1538                       &ARCH_IOVEC_FOR_GETREGSET);
1539 # else
1540         /* constant iovec */
1541         static struct iovec io = {
1542                 .iov_base = &ARCH_REGS_FOR_GETREGSET,
1543                 .iov_len = sizeof(ARCH_REGS_FOR_GETREGSET)
1544         };
1545         return ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, &io);
1546
1547 # endif
1548 }
1549
1550 # ifndef HAVE_GETREGS_OLD
1551 #  define ptrace_setregset_or_setregs ptrace_setregset
1552 static int
1553 ptrace_setregset(pid_t pid)
1554 {
1555 #  ifdef ARCH_IOVEC_FOR_GETREGSET
1556         /* variable iovec */
1557         return ptrace(PTRACE_SETREGSET, pid, NT_PRSTATUS,
1558                       &ARCH_IOVEC_FOR_GETREGSET);
1559 #  else
1560         /* constant iovec */
1561         static struct iovec io = {
1562                 .iov_base = &ARCH_REGS_FOR_GETREGSET,
1563                 .iov_len = sizeof(ARCH_REGS_FOR_GETREGSET)
1564         };
1565         return ptrace(PTRACE_SETREGSET, pid, NT_PRSTATUS, &io);
1566 #  endif
1567 }
1568 # endif /* !HAVE_GETREGS_OLD */
1569
1570 #elif defined ARCH_REGS_FOR_GETREGS
1571
1572 # define ptrace_getregset_or_getregs ptrace_getregs
1573 static long
1574 ptrace_getregs(pid_t pid)
1575 {
1576 # if defined SPARC || defined SPARC64
1577         /* SPARC systems have the meaning of data and addr reversed */
1578         return ptrace(PTRACE_GETREGS, pid, (void *) &ARCH_REGS_FOR_GETREGS, 0);
1579 # else
1580         return ptrace(PTRACE_GETREGS, pid, NULL, &ARCH_REGS_FOR_GETREGS);
1581 # endif
1582 }
1583
1584 # ifndef HAVE_GETREGS_OLD
1585 #  define ptrace_setregset_or_setregs ptrace_setregs
1586 static int
1587 ptrace_setregs(pid_t pid)
1588 {
1589 #  if defined SPARC || defined SPARC64
1590         /* SPARC systems have the meaning of data and addr reversed */
1591         return ptrace(PTRACE_SETREGS, pid, (void *) &ARCH_REGS_FOR_GETREGS, 0);
1592 #  else
1593         return ptrace(PTRACE_SETREGS, pid, NULL, &ARCH_REGS_FOR_GETREGS);
1594 #  endif
1595 }
1596 # endif /* !HAVE_GETREGS_OLD */
1597
1598 #endif /* ARCH_REGS_FOR_GETREGSET || ARCH_REGS_FOR_GETREGS */
1599
1600 void
1601 get_regs(pid_t pid)
1602 {
1603 #undef USE_GET_SYSCALL_RESULT_REGS
1604 #ifdef ptrace_getregset_or_getregs
1605
1606 # ifdef HAVE_GETREGS_OLD
1607         /*
1608          * Try PTRACE_GETREGSET/PTRACE_GETREGS first,
1609          * fallback to getregs_old.
1610          */
1611         static int use_getregs_old;
1612         if (use_getregs_old < 0) {
1613                 get_regs_error = ptrace_getregset_or_getregs(pid);
1614                 return;
1615         } else if (use_getregs_old == 0) {
1616                 get_regs_error = ptrace_getregset_or_getregs(pid);
1617                 if (get_regs_error >= 0) {
1618                         use_getregs_old = -1;
1619                         return;
1620                 }
1621                 if (errno == EPERM || errno == ESRCH)
1622                         return;
1623                 use_getregs_old = 1;
1624         }
1625         get_regs_error = getregs_old(pid);
1626 # else /* !HAVE_GETREGS_OLD */
1627         /* Assume that PTRACE_GETREGSET/PTRACE_GETREGS works. */
1628         get_regs_error = ptrace_getregset_or_getregs(pid);
1629 # endif /* !HAVE_GETREGS_OLD */
1630
1631 #else /* !ptrace_getregset_or_getregs */
1632
1633 # define USE_GET_SYSCALL_RESULT_REGS 1
1634 # warning get_regs is not implemented for this architecture yet
1635         get_regs_error = 0;
1636
1637 #endif /* !ptrace_getregset_or_getregs */
1638 }
1639
1640 #ifdef ptrace_setregset_or_setregs
1641 static int
1642 set_regs(pid_t pid)
1643 {
1644         return ptrace_setregset_or_setregs(pid);
1645 }
1646 #endif /* ptrace_setregset_or_setregs */
1647
1648 struct sysent_buf {
1649         struct tcb *tcp;
1650         struct_sysent ent;
1651         char buf[sizeof("syscall_%lu") + sizeof(long) * 3];
1652 };
1653
1654 static void
1655 free_sysent_buf(void *ptr)
1656 {
1657         struct sysent_buf *s = ptr;
1658         s->tcp->s_prev_ent = s->tcp->s_ent = NULL;
1659         free(ptr);
1660 }
1661
1662 /*
1663  * Returns:
1664  * 0: "ignore this ptrace stop", bail out of trace_syscall_entering() silently.
1665  * 1: ok, continue in trace_syscall_entering().
1666  * other: error, trace_syscall_entering() should print error indicator
1667  *    ("????" etc) and bail out.
1668  */
1669 int
1670 get_scno(struct tcb *tcp)
1671 {
1672         if (get_regs_error)
1673                 return -1;
1674
1675         int rc = arch_get_scno(tcp);
1676         if (rc != 1)
1677                 return rc;
1678
1679         if (SCNO_IS_VALID(tcp->scno)) {
1680                 tcp->s_ent = &sysent[tcp->scno];
1681                 tcp->qual_flg = qual_flags[tcp->scno];
1682         } else {
1683                 struct sysent_buf *s = xcalloc(1, sizeof(*s));
1684
1685                 s->tcp = tcp;
1686                 s->ent.nargs = MAX_ARGS;
1687                 s->ent.sen = SEN_printargs;
1688                 s->ent.sys_func = printargs;
1689                 s->ent.sys_name = s->buf;
1690                 sprintf(s->buf, "syscall_%lu", shuffle_scno(tcp->scno));
1691
1692                 tcp->s_ent = &s->ent;
1693                 tcp->qual_flg = QUAL_RAW | DEFAULT_QUAL_FLAGS;
1694
1695                 set_tcb_priv_data(tcp, s, free_sysent_buf);
1696
1697                 if (debug_flag)
1698                         error_msg("pid %d invalid syscall %ld", tcp->pid, tcp->scno);
1699         }
1700         return 1;
1701 }
1702
1703 #ifdef USE_GET_SYSCALL_RESULT_REGS
1704 static int get_syscall_result_regs(struct tcb *);
1705 #endif
1706
1707 /* Returns:
1708  * 1: ok, continue in trace_syscall_exiting().
1709  * -1: error, trace_syscall_exiting() should print error indicator
1710  *    ("????" etc) and bail out.
1711  */
1712 static int
1713 get_syscall_result(struct tcb *tcp)
1714 {
1715 #ifdef USE_GET_SYSCALL_RESULT_REGS
1716         if (get_syscall_result_regs(tcp))
1717                 return -1;
1718 #endif
1719         tcp->u_error = 0;
1720         get_error(tcp, !(tcp->s_ent->sys_flags & SYSCALL_NEVER_FAILS));
1721
1722         return 1;
1723 }
1724
1725 #include "get_scno.c"
1726 #include "set_scno.c"
1727 #include "get_syscall_args.c"
1728 #ifdef USE_GET_SYSCALL_RESULT_REGS
1729 # include "get_syscall_result.c"
1730 #endif
1731 #include "get_error.c"
1732 #include "set_error.c"
1733 #ifdef HAVE_GETREGS_OLD
1734 # include "getregs_old.c"
1735 #endif
1736
1737 const char *
1738 syscall_name(long scno)
1739 {
1740 #if defined X32_PERSONALITY_NUMBER && defined __X32_SYSCALL_BIT
1741         if (current_personality == X32_PERSONALITY_NUMBER)
1742                 scno &= ~__X32_SYSCALL_BIT;
1743 #endif
1744         return SCNO_IS_VALID(scno) ? sysent[scno].sys_name: NULL;
1745 }