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