blob: c0a08ddcf94e2ee42eaf94c50727a8024464ceed [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * lib/hexdump.c
4 */
5
6#include <linux/types.h>
7#include <linux/ctype.h>
8#include <linux/errno.h>
9#include <linux/kernel.h>
10#include <linux/export.h>
11#include <asm/unaligned.h>
12
13const char hex_asc[] = "0123456789abcdef";
14EXPORT_SYMBOL(hex_asc);
15const char hex_asc_upper[] = "0123456789ABCDEF";
16EXPORT_SYMBOL(hex_asc_upper);
17
18/**
19 * hex_to_bin - convert a hex digit to its real value
20 * @ch: ascii character represents hex digit
21 *
22 * hex_to_bin() converts one hex digit to its actual value or -1 in case of bad
23 * input.
24 *
25 * This function is used to load cryptographic keys, so it is coded in such a
26 * way that there are no conditions or memory accesses that depend on data.
27 *
28 * Explanation of the logic:
29 * (ch - '9' - 1) is negative if ch <= '9'
30 * ('0' - 1 - ch) is negative if ch >= '0'
31 * we "and" these two values, so the result is negative if ch is in the range
32 * '0' ... '9'
33 * we are only interested in the sign, so we do a shift ">> 8"; note that right
34 * shift of a negative value is implementation-defined, so we cast the
35 * value to (unsigned) before the shift --- we have 0xffffff if ch is in
36 * the range '0' ... '9', 0 otherwise
37 * we "and" this value with (ch - '0' + 1) --- we have a value 1 ... 10 if ch is
38 * in the range '0' ... '9', 0 otherwise
39 * we add this value to -1 --- we have a value 0 ... 9 if ch is in the range '0'
40 * ... '9', -1 otherwise
41 * the next line is similar to the previous one, but we need to decode both
42 * uppercase and lowercase letters, so we use (ch & 0xdf), which converts
43 * lowercase to uppercase
44 */
45int hex_to_bin(unsigned char ch)
46{
47 unsigned char cu = ch & 0xdf;
48 return -1 +
49 ((ch - '0' + 1) & (unsigned)((ch - '9' - 1) & ('0' - 1 - ch)) >> 8) +
50 ((cu - 'A' + 11) & (unsigned)((cu - 'F' - 1) & ('A' - 1 - cu)) >> 8);
51}
52EXPORT_SYMBOL(hex_to_bin);
53
54/**
55 * hex2bin - convert an ascii hexadecimal string to its binary representation
56 * @dst: binary result
57 * @src: ascii hexadecimal string
58 * @count: result length
59 *
60 * Return 0 on success, -EINVAL in case of bad input.
61 */
62int hex2bin(u8 *dst, const char *src, size_t count)
63{
64 while (count--) {
65 int hi, lo;
66
67 hi = hex_to_bin(*src++);
68 if (unlikely(hi < 0))
69 return -EINVAL;
70 lo = hex_to_bin(*src++);
71 if (unlikely(lo < 0))
72 return -EINVAL;
73
74 *dst++ = (hi << 4) | lo;
75 }
76 return 0;
77}
78EXPORT_SYMBOL(hex2bin);
79
80/**
81 * bin2hex - convert binary data to an ascii hexadecimal string
82 * @dst: ascii hexadecimal result
83 * @src: binary data
84 * @count: binary data length
85 */
86char *bin2hex(char *dst, const void *src, size_t count)
87{
88 const unsigned char *_src = src;
89
90 while (count--)
91 dst = hex_byte_pack(dst, *_src++);
92 return dst;
93}
94EXPORT_SYMBOL(bin2hex);
95
96/**
97 * hex_dump_to_buffer - convert a blob of data to "hex ASCII" in memory
98 * @buf: data blob to dump
99 * @len: number of bytes in the @buf
100 * @rowsize: number of bytes to print per line; must be 16 or 32
101 * @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1)
102 * @linebuf: where to put the converted data
103 * @linebuflen: total size of @linebuf, including space for terminating NUL
104 * @ascii: include ASCII after the hex output
105 *
106 * hex_dump_to_buffer() works on one "line" of output at a time, i.e.,
107 * 16 or 32 bytes of input data converted to hex + ASCII output.
108 *
109 * Given a buffer of u8 data, hex_dump_to_buffer() converts the input data
110 * to a hex + ASCII dump at the supplied memory location.
111 * The converted output is always NUL-terminated.
112 *
113 * E.g.:
114 * hex_dump_to_buffer(frame->data, frame->len, 16, 1,
115 * linebuf, sizeof(linebuf), true);
116 *
117 * example output buffer:
118 * 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO
119 *
120 * Return:
121 * The amount of bytes placed in the buffer without terminating NUL. If the
122 * output was truncated, then the return value is the number of bytes
123 * (excluding the terminating NUL) which would have been written to the final
124 * string if enough space had been available.
125 */
126int hex_dump_to_buffer(const void *buf, size_t len, int rowsize, int groupsize,
127 char *linebuf, size_t linebuflen, bool ascii)
128{
129 const u8 *ptr = buf;
130 int ngroups;
131 u8 ch;
132 int j, lx = 0;
133 int ascii_column;
134 int ret;
135
136 if (rowsize != 16 && rowsize != 32)
137 rowsize = 16;
138
139 if (len > rowsize) /* limit to one line at a time */
140 len = rowsize;
141 if (!is_power_of_2(groupsize) || groupsize > 8)
142 groupsize = 1;
143 if ((len % groupsize) != 0) /* no mixed size output */
144 groupsize = 1;
145
146 ngroups = len / groupsize;
147 ascii_column = rowsize * 2 + rowsize / groupsize + 1;
148
149 if (!linebuflen)
150 goto overflow1;
151
152 if (!len)
153 goto nil;
154
155 if (groupsize == 8) {
156 const u64 *ptr8 = buf;
157
158 for (j = 0; j < ngroups; j++) {
159 ret = snprintf(linebuf + lx, linebuflen - lx,
160 "%s%16.16llx", j ? " " : "",
161 get_unaligned(ptr8 + j));
162 if (ret >= linebuflen - lx)
163 goto overflow1;
164 lx += ret;
165 }
166 } else if (groupsize == 4) {
167 const u32 *ptr4 = buf;
168
169 for (j = 0; j < ngroups; j++) {
170 ret = snprintf(linebuf + lx, linebuflen - lx,
171 "%s%8.8x", j ? " " : "",
172 get_unaligned(ptr4 + j));
173 if (ret >= linebuflen - lx)
174 goto overflow1;
175 lx += ret;
176 }
177 } else if (groupsize == 2) {
178 const u16 *ptr2 = buf;
179
180 for (j = 0; j < ngroups; j++) {
181 ret = snprintf(linebuf + lx, linebuflen - lx,
182 "%s%4.4x", j ? " " : "",
183 get_unaligned(ptr2 + j));
184 if (ret >= linebuflen - lx)
185 goto overflow1;
186 lx += ret;
187 }
188 } else {
189 for (j = 0; j < len; j++) {
190 if (linebuflen < lx + 2)
191 goto overflow2;
192 ch = ptr[j];
193 linebuf[lx++] = hex_asc_hi(ch);
194 if (linebuflen < lx + 2)
195 goto overflow2;
196 linebuf[lx++] = hex_asc_lo(ch);
197 if (linebuflen < lx + 2)
198 goto overflow2;
199 linebuf[lx++] = ' ';
200 }
201 if (j)
202 lx--;
203 }
204 if (!ascii)
205 goto nil;
206
207 while (lx < ascii_column) {
208 if (linebuflen < lx + 2)
209 goto overflow2;
210 linebuf[lx++] = ' ';
211 }
212 for (j = 0; j < len; j++) {
213 if (linebuflen < lx + 2)
214 goto overflow2;
215 ch = ptr[j];
216 linebuf[lx++] = (isascii(ch) && isprint(ch)) ? ch : '.';
217 }
218nil:
219 linebuf[lx] = '\0';
220 return lx;
221overflow2:
222 linebuf[lx++] = '\0';
223overflow1:
224 return ascii ? ascii_column + len : (groupsize * 2 + 1) * ngroups - 1;
225}
226EXPORT_SYMBOL(hex_dump_to_buffer);
227
228#ifdef CONFIG_PRINTK
229/**
230 * print_hex_dump - print a text hex dump to syslog for a binary blob of data
231 * @level: kernel log level (e.g. KERN_DEBUG)
232 * @prefix_str: string to prefix each line with;
233 * caller supplies trailing spaces for alignment if desired
234 * @prefix_type: controls whether prefix of an offset, address, or none
235 * is printed (%DUMP_PREFIX_OFFSET, %DUMP_PREFIX_ADDRESS, %DUMP_PREFIX_NONE)
236 * @rowsize: number of bytes to print per line; must be 16 or 32
237 * @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1)
238 * @buf: data blob to dump
239 * @len: number of bytes in the @buf
240 * @ascii: include ASCII after the hex output
241 *
242 * Given a buffer of u8 data, print_hex_dump() prints a hex + ASCII dump
243 * to the kernel log at the specified kernel log level, with an optional
244 * leading prefix.
245 *
246 * print_hex_dump() works on one "line" of output at a time, i.e.,
247 * 16 or 32 bytes of input data converted to hex + ASCII output.
248 * print_hex_dump() iterates over the entire input @buf, breaking it into
249 * "line size" chunks to format and print.
250 *
251 * E.g.:
252 * print_hex_dump(KERN_DEBUG, "raw data: ", DUMP_PREFIX_ADDRESS,
253 * 16, 1, frame->data, frame->len, true);
254 *
255 * Example output using %DUMP_PREFIX_OFFSET and 1-byte mode:
256 * 0009ab42: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO
257 * Example output using %DUMP_PREFIX_ADDRESS and 4-byte mode:
258 * ffffffff88089af0: 73727170 77767574 7b7a7978 7f7e7d7c pqrstuvwxyz{|}~.
259 */
260void print_hex_dump(const char *level, const char *prefix_str, int prefix_type,
261 int rowsize, int groupsize,
262 const void *buf, size_t len, bool ascii)
263{
264 const u8 *ptr = buf;
265 int i, linelen, remaining = len;
266 unsigned char linebuf[32 * 3 + 2 + 32 + 1];
267
268 if (rowsize != 16 && rowsize != 32)
269 rowsize = 16;
270
271 for (i = 0; i < len; i += rowsize) {
272 linelen = min(remaining, rowsize);
273 remaining -= rowsize;
274
275 hex_dump_to_buffer(ptr + i, linelen, rowsize, groupsize,
276 linebuf, sizeof(linebuf), ascii);
277
278 switch (prefix_type) {
279 case DUMP_PREFIX_ADDRESS:
280 printk("%s%s%p: %s\n",
281 level, prefix_str, ptr + i, linebuf);
282 break;
283 case DUMP_PREFIX_OFFSET:
284 printk("%s%s%.8x: %s\n", level, prefix_str, i, linebuf);
285 break;
286 default:
287 printk("%s%s%s\n", level, prefix_str, linebuf);
288 break;
289 }
290 }
291}
292EXPORT_SYMBOL(print_hex_dump);
293
294#endif /* defined(CONFIG_PRINTK) */