1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "chre/util/nanoapp/debug.h"
18 
19 #include <cctype>
20 #include <cstdio>
21 
22 #ifdef CHRE_NANOAPP_INTERNAL
23 #include "chre/platform/log.h"
24 #else
25 #define LOG_TAG "[DEBUG]"
26 #include "chre/util/nanoapp/log.h"
27 #endif
28 
29 namespace chre {
30 
logBuffer(const uint8_t * buffer,size_t bufferSize)31 void logBuffer(const uint8_t *buffer, size_t bufferSize) {
32   char line[32];
33   char lineChars[32];
34   size_t offset = 0;
35   size_t offsetChars = 0;
36 
37   if (bufferSize > 128) {
38     LOGD("Dumping first 128 bytes of buffer @ %p, size %zu",
39          buffer, bufferSize);
40     bufferSize = 128;
41   } else {
42     LOGD("Dumping buffer @ %p, size %zu", buffer, bufferSize);
43   }
44 
45   for (size_t i = 1; i <= bufferSize; i++) {
46     // This ignores potential errors returned by snprintf. This is a relatively
47     // simple case and the deliberate decision to ignore them has been made.
48     offset += static_cast<size_t>(
49         snprintf(&line[offset], sizeof(line) - offset, "%02x ", buffer[i - 1]));
50     offsetChars += static_cast<size_t>(
51         snprintf(&lineChars[offsetChars], sizeof(lineChars) - offsetChars,
52                  "%c", (isprint(buffer[i - 1])) ? buffer[i - 1] : '.'));
53     if ((i % 8) == 0) {
54       LOGD("  %s\t%s", line, lineChars);
55       offset = 0;
56       offsetChars = 0;
57     } else if ((i % 4) == 0) {
58       offset += static_cast<size_t>(
59           snprintf(&line[offset], sizeof(line) - offset, " "));
60     }
61   }
62 
63   if (offset > 0) {
64     char tabs[8];
65     char *pos = tabs;
66     while (offset < 28) {
67       *pos++ = '\t';
68       offset += 8;
69     }
70     *pos = '\0';
71     LOGD("  %s%s%s", line, tabs, lineChars);
72   }
73 }
74 
75 }  // namespace chre
76