1 /*
2  * Copyright (C) 2020 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 #ifndef CHRE_LOG_MESSAGE_PARSER_H_
18 #define CHRE_LOG_MESSAGE_PARSER_H_
19 
20 #include <endian.h>
21 #include <cinttypes>
22 #include <memory>
23 #include <optional>
24 #include "chre/util/time.h"
25 #include "chre_host/bt_snoop_log_parser.h"
26 #include "chre_host/generated/host_messages_generated.h"
27 #include "chre_host/nanoapp_load_listener.h"
28 
29 #include <android/log.h>
30 
31 #include "pw_tokenizer/detokenize.h"
32 
33 using chre::fbs::LogType;
34 using pw::tokenizer::DetokenizedString;
35 using pw::tokenizer::Detokenizer;
36 
37 namespace android {
38 namespace chre {
39 
40 class LogMessageParser : public INanoappLoadListener {
41  public:
42   LogMessageParser();
43 
44   /**
45    * Allow the user to enable verbose logging during instantiation.
46    */
LogMessageParser(bool enableVerboseLogging)47   LogMessageParser(bool enableVerboseLogging)
48       : mVerboseLoggingEnabled(enableVerboseLogging) {}
49 
50   /**
51    * Initializes the log message parser by reading the log token database,
52    * and instantiates a detokenizer to handle encoded log messages.
53    *
54    * @param nanoappImageHeaderSize Offset in bytes between the address of the
55    * nanoapp binary and the real start of the ELF header.
56    */
57   void init(size_t nanoappImageHeaderSize = 0);
58 
59   //! Logs from a log buffer containing one or more log messages (version 1)
60   void log(const uint8_t *logBuffer, size_t logBufferSize);
61 
62   //! Logs from a log buffer containing one or more log messages (version 2)
63   void logV2(const uint8_t *logBuffer, size_t logBufferSize,
64              uint32_t numLogsDropped);
65 
66   /**
67    * With verbose logging enabled (either during instantiation via a
68    * constructor argument, or during compilation via N_DEBUG being defined
69    * and set), dump a binary log buffer to a human-readable string.
70    *
71    * @param logBuffer buffer to be output as a string
72    * @param logBufferSize size of the buffer being output
73    */
74   void dump(const uint8_t *logBuffer, size_t logBufferSize);
75 
76   /**
77    * Stores a pigweed detokenizer for decoding logs from a given nanoapp.
78    *
79    * @param appId The app ID associated with the nanoapp.
80    * @param instanceId The instance ID assigned to this nanoapp by the CHRE
81    * event loop.
82    * @param databaseOffset The size offset of the token database from the start
83    * of the address of the ELF binary in bytes.
84    * @param databaseSize The size of the token database section in the ELF
85    * binary in bytes.
86    */
87   void addNanoappDetokenizer(uint64_t appId, uint16_t instanceId,
88                              uint64_t databaseOffset, size_t databaseSize);
89 
90   /**
91    * Remove an existing detokenizer associated with a nanoapp if it exists.
92    *
93    * @param appId The app ID associated with the nanoapp.
94    * @param removeBinary Remove the nanoapp binary associated with the app ID if
95    * true.
96    */
97   void removeNanoappDetokenizerAndBinary(uint64_t appId);
98 
99   /**
100    * Reset all nanoapp log detokenizers.
101    */
102   void resetNanoappDetokenizerState();
103 
104   // Functions from INanoappLoadListener.
105   void onNanoappLoadStarted(
106       uint64_t appId,
107       std::shared_ptr<const std::vector<uint8_t>> nanoappBinary) override;
108 
109   void onNanoappLoadFailed(uint64_t appId) override;
110 
111   void onNanoappUnloaded(uint64_t appId) override;
112 
113  private:
114   static constexpr char kHubLogFormatStr[] = "@ %3" PRIu32 ".%03" PRIu32 ": %s";
115 
116   // Constants used to extract the log type from log metadata.
117   static constexpr uint8_t kLogTypeMask = 0xF0;
118   static constexpr uint8_t kLogTypeBitOffset = 4;
119 
120   enum LogLevel : uint8_t {
121     ERROR = 1,
122     WARNING = 2,
123     INFO = 3,
124     DEBUG = 4,
125     VERBOSE = 5,
126   };
127 
128   //! See host_messages.fbs for the definition of this struct.
129   struct LogMessage {
130     enum LogLevel logLevel;
131     uint64_t timestampNanos;
132     char logMessage[];
133   } __attribute__((packed));
134 
135   //! See host_messages.fbs for the definition of this struct.
136   struct LogMessageV2 {
137     uint8_t metadata;
138     uint32_t timestampMillis;
139     char logMessage[];
140   } __attribute__((packed));
141 
142   /**
143    * Helper struct for readable decoding of a tokenized log message payload,
144    * essentially encapsulates the 'logMessage' field in LogMessageV2 for an
145    * encoded log.
146    */
147   struct EncodedLog {
148     uint8_t size;
149     char data[];
150   };
151 
152   /**
153    * Helper struct for readable decoding of a tokenized log message from a
154    * nanoapp.
155    */
156   struct NanoappTokenizedLog {
157     uint16_t instanceId;
158     uint8_t size;
159     char data[];
160   } __attribute__((packed));
161 
162   bool mVerboseLoggingEnabled;
163 
164   //! The number of logs dropped since CHRE start.
165   uint32_t mNumLogsDropped = 0;
166 
167   //! Log detokenizer used for CHRE system logs.
168   std::unique_ptr<Detokenizer> mSystemDetokenizer;
169 
170   /**
171    * Helper struct for keep track of nanoapp's log detokenizer with appIDs.
172    */
173   struct NanoappDetokenizer {
174     std::unique_ptr<Detokenizer> detokenizer;
175     uint64_t appId;
176   };
177 
178   //! Maps nanoapp instance IDs to the corresponding app ID and pigweed
179   //! detokenizer.
180   std::unordered_map<uint16_t /*instanceId*/, NanoappDetokenizer>
181       mNanoappDetokenizers;
182 
183   //! This is used to find the binary associated with a nanoapp with its app ID.
184   std::unordered_map<uint64_t /*appId*/,
185                      std::shared_ptr<const std::vector<uint8_t>>>
186       mNanoappAppIdToBinary;
187 
188   static android_LogPriority chreLogLevelToAndroidLogPriority(uint8_t level);
189 
190   BtSnoopLogParser mBtLogParser;
191 
192   //! Offset in bytes between the address of the nanoapp binary and the real
193   //! start of the ELF header.
194   size_t mNanoappImageHeaderSize = 0;
195 
196   void updateAndPrintDroppedLogs(uint32_t numLogsDropped);
197 
198   //! Method for parsing unencoded (string) log messages.
199   std::optional<size_t> parseAndEmitStringLogMessageAndGetSize(
200       const LogMessageV2 *message, size_t maxLogMessageLen);
201 
202   /**
203    * Parses and emits an encoded log message while also returning the size of
204    * the parsed message for buffer index bookkeeping.
205    *
206    * @param message Buffer containing the log metadata and log payload.
207    * @param maxLogMessageLen The max size allowed for the log payload.
208    * @return Size of the encoded log message payload, std::nullopt if the
209    * message format is invalid. Note that the size includes the 1 byte header
210    * that we use for encoded log messages to track message size.
211    */
212   std::optional<size_t> parseAndEmitTokenizedLogMessageAndGetSize(
213       const LogMessageV2 *message, size_t maxLogMessageLen);
214 
215   /**
216    * Similar to parseAndEmitTokenizedLogMessageAndGetSize, but used for encoded
217    * log message from nanoapps.
218    *
219    * @param message Buffer containing the log metadata and log payload.
220    * @param maxLogMessageLen The max size allowed for the log payload.
221    * @return Size of the encoded log message payload, std::nullopt if the
222    * message format is invalid. Note that the size includes the 1 byte header
223    * that we use for encoded log messages to track message size, and the 2 byte
224    * instance ID that the host uses to find the correct detokenizer.
225    */
226   std::optional<size_t> parseAndEmitNanoappTokenizedLogMessageAndGetSize(
227       const LogMessageV2 *message, size_t maxLogMessageLen);
228 
229   void emitLogMessage(uint8_t level, uint32_t timestampMillis,
230                       const char *logMessage);
231 
232   /**
233    * Initialize the Log Detokenizer
234    *
235    * The log detokenizer reads a binary database file that contains key value
236    * pairs of hash-keys <--> Decoded log messages, and creates an instance
237    * of the Detokenizer.
238    *
239    * @return an instance of the Detokenizer
240    */
241   std::unique_ptr<Detokenizer> logDetokenizerInit();
242 
243   /**
244    * Helper function to get the logging level from the log message metadata.
245    *
246    * @param metadata A byte from the log message payload containing the
247    *        log level and encoding information.
248    *
249    * @return The log level of the current log message.
250    */
251   uint8_t getLogLevelFromMetadata(uint8_t metadata);
252 
253   /**
254    * Helper function to check the metadata whether the log message was encoded.
255    *
256    * @param metadata A byte from the log message payload containing the
257    *        log level and encoding information.
258    *
259    * @return true if an encoding was used on the log message payload.
260    */
261   bool isLogMessageEncoded(uint8_t metadata);
262 
263   /**
264    * Helper function to check the metadata whether the log message is a BT snoop
265    * log.
266    *
267    * @param metadata A byte from the log message payload containing the
268    *        log level and log type information.
269    *
270    * @return true if the log message type is BT Snoop log.
271    */
272   bool isBtSnoopLogMessage(uint8_t metadata);
273 
274   /**
275    * Helper function to check the metadata whether the log message is tokenized
276    * and sent from a nanoapp
277    *
278    * @param metadata A byte from the log message payload containing the
279    *        log level and log type information.
280    *
281    * @return true if the log message is tokenzied and sent from a nanoapp.
282    */
283   bool isNanoappTokenizedLogMessage(uint8_t metadata);
284 
285   /**
286    * Helper function to check nanoapp log token database for memory overflow and
287    * wraparound.
288    *
289    * @param databaseOffset The size offset of the token database from the start
290    * of the address of the ELF binary in bytes.
291    * @param databaseSize The size of the token database section in the ELF
292    * binary in bytes.
293    * @param binarySize. The size of the nanoapp binary in bytes.
294    *
295    * @return True if the token database passes memory bounds checks.
296    */
297   bool checkTokenDatabaseOverflow(uint32_t databaseOffset, size_t databaseSize,
298                                   size_t binarySize);
299 
300   /*
301    * Helper function that returns the log type of a log message.
302    */
extractLogType(const LogMessageV2 * message)303   LogType extractLogType(const LogMessageV2 *message) {
304     return static_cast<LogType>((message->metadata & kLogTypeMask) >>
305                                 kLogTypeBitOffset);
306   }
307 };
308 
309 }  // namespace chre
310 }  // namespace android
311 
312 #endif  // CHRE_LOG_MESSAGE_PARSER_H_
313