6af818beb3cb6caa987f9e39550dbca1e9c2279e
[dpdk.git] / lib / librte_eal / common / eal_common_hexdump.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation
3  */
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <errno.h>
7 #include <stdint.h>
8 #include <rte_hexdump.h>
9 #include <rte_string_fns.h>
10
11 #define LINE_LEN 128
12
13 void
14 rte_hexdump(FILE *f, const char *title, const void *buf, unsigned int len)
15 {
16         unsigned int i, out, ofs;
17         const unsigned char *data = buf;
18         char line[LINE_LEN];    /* space needed 8+16*3+3+16 == 75 */
19
20         fprintf(f, "%s at [%p], len=%u\n",
21                 title ? : "  Dump data", data, len);
22         ofs = 0;
23         while (ofs < len) {
24                 /* format the line in the buffer */
25                 out = snprintf(line, LINE_LEN, "%08X:", ofs);
26                 for (i = 0; i < 16 && ofs + i < len; i++)
27                         out += snprintf(line + out, LINE_LEN - out,
28                                          " %02X", (data[ofs + i] & 0xff));
29                 for (; i <= 16; i++)
30                         out += snprintf(line + out, LINE_LEN - out, " | ");
31
32                 for (i = 0; ofs < len && i < 16; i++, ofs++) {
33                         unsigned char c = data[ofs];
34
35                         if (c < ' ' || c > '~')
36                                 c = '.';
37                         out += snprintf(line + out, LINE_LEN - out, "%c", c);
38                 }
39                 fprintf(f, "%s\n", line);
40         }
41         fflush(f);
42 }
43
44 void
45 rte_memdump(FILE *f, const char *title, const void *buf, unsigned int len)
46 {
47         unsigned int i, out;
48         const unsigned char *data = buf;
49         char line[LINE_LEN];
50
51         if (title)
52                 fprintf(f, "%s: ", title);
53
54         line[0] = '\0';
55         for (i = 0, out = 0; i < len; i++) {
56                 /* Make sure we do not overrun the line buffer length. */
57                 if (out >= LINE_LEN - 4) {
58                         fprintf(f, "%s", line);
59                         out = 0;
60                         line[out] = '\0';
61                 }
62                 out += snprintf(line + out, LINE_LEN - out, "%02x%s",
63                                 (data[i] & 0xff), ((i + 1) < len) ? ":" : "");
64         }
65         if (out > 0)
66                 fprintf(f, "%s", line);
67         fprintf(f, "\n");
68
69         fflush(f);
70 }