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) 2005-2018 Dmitry V. Levin <ldv@strace.io>
7 * Copyright (c) 2016-2021 The strace developers.
8 * All rights reserved.
9 *
10 * SPDX-License-Identifier: GPL-2.0-or-later
11 */
12
13 #include "tests.h"
14 #include "xlat.h"
15 #include <stdio.h>
16
17 #if !XLAT_RAW
18 static const char *
19 lookup_xlat(const struct xlat *xlat, unsigned long long val)
20 {
21 const struct xlat_data *xd = xlat->data;
22
23 for (size_t i = 0; i < xlat->size; i++, xd++) {
24 if (!xd->str)
25 continue;
26
27 if (xd->val == val) {
28 return xd->str;
29 }
30 }
31
32 return NULL;
33 }
34 #endif
35
36 int
37 XLAT_NAME(printxval)(const struct xlat *xlat, unsigned long long val,
38 const char *const dflt)
39 {
40 #if XLAT_RAW
41 printf("%#llx", val);
42
43 return 1;
44 #else
45 const char *str = lookup_xlat(xlat, val);
46
47 # if XLAT_VERBOSE
48 printf("%#llx", val);
49 if (str || dflt)
50 printf(" /* %s */", str ?: dflt);
51 # else
52 if (str) {
53 fputs(str, stdout);
54 } else {
55 printf("%#llx", val);
56 if (dflt)
57 printf(" /* %s */", dflt);
58 }
59 # endif /* XLAT_VERBOSE */
60
61 return !!str;
62 #endif /* XLAT_RAW */
63 }
64
65 const char *
66 XLAT_NAME(sprintxlat)(const char *str, unsigned long long val,
67 const char *const dflt)
68 {
69 static char buf[256];
70
71 #if XLAT_RAW
72 snprintf(buf, sizeof(buf), "%#llx", val);
73 #elif XLAT_VERBOSE
74 if (str || dflt)
75 snprintf(buf, sizeof(buf), "%#llx /* %s */", val, str ?: dflt);
76 else
77 snprintf(buf, sizeof(buf), "%#llx", val);
78 #else
79 if (str)
80 return str;
81
82 if (dflt)
83 snprintf(buf, sizeof(buf), "%#llx /* %s */", val, dflt);
84 else
85 snprintf(buf, sizeof(buf), "%#llx", val);
86 #endif
87
88 return buf;
89 }
90
91 const char *
92 XLAT_NAME(sprintxval)(const struct xlat *xlat, unsigned long long val,
93 const char *const dflt)
94 {
95 #if XLAT_RAW
96 return sprintxlat(NULL, val, dflt);
97 #else
98 return sprintxlat(lookup_xlat(xlat, val), val, dflt);
99 #endif
100 }