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