hexdump.c revision 1.3
1/*-
2 * Copyright (c) 2017 The NetBSD Foundation, Inc.
3 * All rights reserved.
4 *
5 * This code is derived from software contributed to The NetBSD Foundation
6 * by Christos Zoulas.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 */
29#include <sys/cdefs.h>
30__KERNEL_RCSID(0, "$NetBSD: hexdump.c,v 1.3 2017/12/08 23:57:57 christos Exp $");
31
32#ifdef DEBUG_HEXDUMP
33#include <stdio.h>
34#include <ctype.h>
35#include <string.h>
36#include <stdlib.h>
37static const char hexdigits[] = "0123456789abcdef";
38#else
39#include <lib/libkern/libkern.h>
40#include <sys/systm.h>
41#endif
42
43#define MID (3 * 8)
44#define BAR ((3 * 16) + 1)
45#define ASC (BAR + 2)
46#define NL (BAR + 18)
47
48void
49hexdump(const char *msg, const void *ptr, size_t len)
50{
51	size_t i, p, q;
52	const unsigned char *u = ptr;
53	char buf[NL + 2];
54
55	if (msg)
56		printf("%s: %zu bytes @ %p\n", msg, len, ptr);
57
58	buf[BAR] = '|';
59	buf[BAR + 1] = ' ';
60	buf[NL] = '\n';
61	buf[NL + 1] = '\0';
62	memset(buf, ' ', BAR);
63        for (q = p = i = 0; i < len; i++) {
64		unsigned char c = u[i];
65		buf[p++] = hexdigits[(c >> 4) & 0xf];
66		buf[p++] = hexdigits[(c >> 0) & 0xf];
67		buf[p++] = ' ';
68                if (q == 7)
69		       buf[p++] = ' ';
70
71		buf[ASC + q++] = isprint(c) ? c : '.';
72
73		if (q == 16) {
74			q = p = 0;
75			printf("%s", buf);
76			memset(buf, ' ', BAR);
77		}
78        }
79	if (q) {
80		buf[ASC + q++] = '\n';
81		buf[ASC + q] = '\0';
82		printf("%s", buf);
83	}
84}
85
86#ifdef DEBUG_HEXDUMP
87int
88main(int argc, char *argv[])
89{
90	hexdump("foo", main, atoi(argv[1]));
91	return 0;
92}
93#endif
94