blob: df9c650050d751eaff4ca1d2854d8c2b131f9b67 [file] [log] [blame]
Aatir186ce8c2019-10-20 15:13:39 -05001#include "hexdump.hpp"
2
3#include <stdio.h>
4
5#include <cstring>
6#include <sstream>
7#include <string>
8
9namespace openpower
10{
11namespace pels
12{
13
14std::string escapeJSON(const std::string& input)
15{
16 std::string output;
17 output.reserve(input.length());
18
19 for (const auto c : input)
20 {
21 switch (c)
22 {
23 case '"':
24 output += "\\\"";
25 break;
26 case '/':
27 output += "\\/";
28 break;
29 case '\b':
30 output += "\\b";
31 break;
32 case '\f':
33 output += "\\f";
34 break;
35 case '\n':
36 output += "\\n";
37 break;
38 case '\r':
39 output += "\\r";
40 break;
41 case '\t':
42 output += "\\t";
43 break;
44 case '\\':
45 output += "\\\\";
46 break;
47 default:
48 output += c;
49 break;
50 }
51 }
52
53 return output;
54}
55char* dumpHex(const void* data, size_t size)
56{
57 const int symbolSize = 100;
58 char* buffer = (char*)calloc(10 * size, sizeof(char));
59 char* symbol = (char*)calloc(symbolSize, sizeof(char));
60 char ascii[17];
61 size_t i, j;
62 ascii[16] = '\0';
63 for (i = 0; i < size; ++i)
64 {
65 if (i % 16 == 0)
66 {
67 strcat(buffer, "\"");
68 }
69 snprintf(symbol, symbolSize, "%02X ", ((unsigned char*)data)[i]);
70 strcat(buffer, symbol);
71 memset(symbol, 0, strlen(symbol));
72 if (((unsigned char*)data)[i] >= ' ' &&
73 ((unsigned char*)data)[i] <= '~')
74 {
75 ascii[i % 16] = ((unsigned char*)data)[i];
76 }
77 else
78 {
79 ascii[i % 16] = '.';
80 }
81 if ((i + 1) % 8 == 0 || i + 1 == size)
82 {
83 std::string asciiString(ascii);
84 asciiString = escapeJSON(asciiString);
85 const char* asciiToPrint = asciiString.c_str();
86 strcat(buffer, " ");
87 if ((i + 1) % 16 == 0)
88 {
89 if (i + 1 != size)
90 {
91 snprintf(symbol, symbolSize, "| %s\", \n ", asciiToPrint);
92 }
93 else
94 {
95 snprintf(symbol, symbolSize, "| %s\" \n ", asciiToPrint);
96 }
97 strcat(buffer, symbol);
98 memset(symbol, 0, strlen(symbol));
99 }
100 else if (i + 1 == size)
101 {
102 ascii[(i + 1) % 16] = '\0';
103 if ((i + 1) % 16 <= 8)
104 {
105 strcat(buffer, " ");
106 }
107 for (j = (i + 1) % 16; j < 16; ++j)
108 {
109 strcat(buffer, " ");
110 }
111 snprintf(symbol, symbolSize, "| %s\" \n ", asciiToPrint);
112 strcat(buffer, symbol);
113 memset(symbol, 0, strlen(symbol));
114 }
115 }
116 }
117 free(symbol);
118 return buffer;
119}
120} // namespace pels
121} // namespace openpower