blob: 23e3670634465c6061b19e4b26c628902cfb4a6e [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -03002#include "print_binary.h"
3#include <linux/log2.h>
4#include "sane_ctype.h"
5
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -03006int binary__fprintf(unsigned char *data, size_t len,
7 size_t bytes_per_line, binary__fprintf_t printer,
8 void *extra, FILE *fp)
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -03009{
10 size_t i, j, mask;
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030011 int printed = 0;
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030012
13 if (!printer)
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030014 return 0;
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030015
16 bytes_per_line = roundup_pow_of_two(bytes_per_line);
17 mask = bytes_per_line - 1;
18
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030019 printed += printer(BINARY_PRINT_DATA_BEGIN, 0, extra, fp);
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030020 for (i = 0; i < len; i++) {
21 if ((i & mask) == 0) {
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030022 printed += printer(BINARY_PRINT_LINE_BEGIN, -1, extra, fp);
23 printed += printer(BINARY_PRINT_ADDR, i, extra, fp);
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030024 }
25
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030026 printed += printer(BINARY_PRINT_NUM_DATA, data[i], extra, fp);
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030027
28 if (((i & mask) == mask) || i == len - 1) {
29 for (j = 0; j < mask-(i & mask); j++)
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030030 printed += printer(BINARY_PRINT_NUM_PAD, -1, extra, fp);
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030031
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030032 printer(BINARY_PRINT_SEP, i, extra, fp);
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030033 for (j = i & ~mask; j <= i; j++)
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030034 printed += printer(BINARY_PRINT_CHAR_DATA, data[j], extra, fp);
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030035 for (j = 0; j < mask-(i & mask); j++)
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030036 printed += printer(BINARY_PRINT_CHAR_PAD, i, extra, fp);
37 printed += printer(BINARY_PRINT_LINE_END, -1, extra, fp);
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030038 }
39 }
Arnaldo Carvalho de Melo923d0c92017-10-17 10:35:00 -030040 printed += printer(BINARY_PRINT_DATA_END, -1, extra, fp);
41 return printed;
Arnaldo Carvalho de Melofea01392017-04-17 16:23:22 -030042}
43
44int is_printable_array(char *p, unsigned int len)
45{
46 unsigned int i;
47
48 if (!p || !len || p[len - 1] != 0)
49 return 0;
50
51 len--;
52
53 for (i = 0; i < len; i++) {
54 if (!isprint(p[i]) && !isspace(p[i]))
55 return 0;
56 }
57 return 1;
58}