xref: /aosp_15_r20/system/chre/host/common/fbs_daemon_base.cc (revision 84e339476a462649f82315436d70fd732297a399)
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 #include <cstdlib>
18 #include <fstream>
19 
20 #include "chre_host/fbs_daemon_base.h"
21 #include "chre_host/log.h"
22 #include "chre_host/napp_header.h"
23 
24 #include <json/json.h>
25 
26 #ifdef CHRE_DAEMON_METRIC_ENABLED
27 #include <aidl/android/frameworks/stats/IStats.h>
28 #include <android/binder_manager.h>
29 #include <android_chre_flags.h>
30 #include <chre_atoms_log.h>
31 #endif  // CHRE_DAEMON_METRIC_ENABLED
32 
33 // Aliased for consistency with the way these symbols are referenced in
34 // CHRE-side code
35 namespace fbs = ::chre::fbs;
36 
37 namespace android {
38 namespace chre {
39 
40 #ifdef CHRE_DAEMON_METRIC_ENABLED
41 using ::aidl::android::frameworks::stats::IStats;
42 using ::aidl::android::frameworks::stats::VendorAtom;
43 using ::aidl::android::frameworks::stats::VendorAtomValue;
44 using ::android::chre::Atoms::ChreHalNanoappLoadFailed;
45 #endif  // CHRE_DAEMON_METRIC_ENABLED
46 
sendNanoappLoad(uint64_t appId,uint32_t appVersion,uint32_t appTargetApiVersion,const std::string & appBinaryName,uint32_t transactionId)47 bool FbsDaemonBase::sendNanoappLoad(uint64_t appId, uint32_t appVersion,
48                                     uint32_t appTargetApiVersion,
49                                     const std::string &appBinaryName,
50                                     uint32_t transactionId) {
51   flatbuffers::FlatBufferBuilder builder;
52   HostProtocolHost::encodeLoadNanoappRequestForFile(
53       builder, transactionId, appId, appVersion, appTargetApiVersion,
54       appBinaryName.c_str());
55 
56   bool success = sendMessageToChre(
57       kHostClientIdDaemon, builder.GetBufferPointer(), builder.GetSize());
58 
59   if (!success) {
60     LOGE("Failed to send nanoapp filename.");
61   } else {
62     Transaction transaction = {
63         .transactionId = transactionId,
64         .nanoappId = appId,
65     };
66     mPreloadedNanoappPendingTransactions.push(transaction);
67   }
68 
69   return success;
70 }
71 
sendTimeSync(bool logOnError)72 bool FbsDaemonBase::sendTimeSync(bool logOnError) {
73   bool success = false;
74   int64_t timeOffset = getTimeOffset(&success);
75 
76   if (success) {
77     flatbuffers::FlatBufferBuilder builder(64);
78     HostProtocolHost::encodeTimeSyncMessage(builder, timeOffset);
79     success = sendMessageToChre(kHostClientIdDaemon, builder.GetBufferPointer(),
80                                 builder.GetSize());
81 
82     if (!success && logOnError) {
83       LOGE("Failed to deliver time sync message from host to CHRE");
84     }
85   }
86 
87   return success;
88 }
89 
sendMessageToChre(uint16_t clientId,void * data,size_t length)90 bool FbsDaemonBase::sendMessageToChre(uint16_t clientId, void *data,
91                                       size_t length) {
92   bool success = false;
93   if (!HostProtocolHost::mutateHostClientId(data, length, clientId)) {
94     LOGE("Couldn't set host client ID in message container!");
95   } else {
96     LOGV("Delivering message from host (size %zu)", length);
97     getLogger().dump(static_cast<const uint8_t *>(data), length);
98     success = doSendMessage(data, length);
99   }
100 
101   return success;
102 }
103 
onMessageReceived(const unsigned char * messageBuffer,size_t messageLen)104 void FbsDaemonBase::onMessageReceived(const unsigned char *messageBuffer,
105                                       size_t messageLen) {
106   getLogger().dump(messageBuffer, messageLen);
107 
108   uint16_t hostClientId;
109   fbs::ChreMessage messageType;
110   if (!HostProtocolHost::extractHostClientIdAndType(
111           messageBuffer, messageLen, &hostClientId, &messageType)) {
112     LOGW("Failed to extract host client ID from message - sending broadcast");
113     hostClientId = ::chre::kHostClientIdUnspecified;
114   }
115 
116   std::unique_ptr<fbs::MessageContainerT> container =
117       fbs::UnPackMessageContainer(messageBuffer);
118 
119   if (messageType == fbs::ChreMessage::LogMessage) {
120     const auto *logMessage = container->message.AsLogMessage();
121     const std::vector<int8_t> &logData = logMessage->buffer;
122 
123     getLogger().log(reinterpret_cast<const uint8_t *>(logData.data()),
124                     logData.size());
125   } else if (messageType == fbs::ChreMessage::LogMessageV2) {
126     const auto *logMessage = container->message.AsLogMessageV2();
127     const std::vector<int8_t> &logDataBuffer = logMessage->buffer;
128     const auto *logData =
129         reinterpret_cast<const uint8_t *>(logDataBuffer.data());
130     uint32_t numLogsDropped = logMessage->num_logs_dropped;
131     getLogger().logV2(logData, logDataBuffer.size(), numLogsDropped);
132   } else if (messageType == fbs::ChreMessage::TimeSyncRequest) {
133     sendTimeSync(true /* logOnError */);
134   } else if (messageType == fbs::ChreMessage::LowPowerMicAccessRequest) {
135     configureLpma(true /* enabled */);
136   } else if (messageType == fbs::ChreMessage::LowPowerMicAccessRelease) {
137     configureLpma(false /* enabled */);
138   } else if (messageType == fbs::ChreMessage::MetricLog) {
139 #ifdef CHRE_DAEMON_METRIC_ENABLED
140     const auto *metricMsg = container->message.AsMetricLog();
141     handleMetricLog(metricMsg);
142 #endif  // CHRE_DAEMON_METRIC_ENABLED
143   } else if (messageType == fbs::ChreMessage::NanConfigurationRequest) {
144     handleNanConfigurationRequest(
145         container->message.AsNanConfigurationRequest());
146   } else if (messageType == fbs::ChreMessage::NanoappTokenDatabaseInfo) {
147     // TODO(b/242760291): Use this info to map nanoapp log detokenizers with
148     // instance ID in log message parser.
149   } else if (hostClientId == kHostClientIdDaemon) {
150     handleDaemonMessage(messageBuffer);
151   } else if (hostClientId == ::chre::kHostClientIdUnspecified) {
152     mServer.sendToAllClients(messageBuffer, static_cast<size_t>(messageLen));
153   } else {
154     mServer.sendToClientById(messageBuffer, static_cast<size_t>(messageLen),
155                              hostClientId);
156   }
157 }
158 
handleDaemonMessage(const uint8_t * message)159 void FbsDaemonBase::handleDaemonMessage(const uint8_t *message) {
160   std::unique_ptr<fbs::MessageContainerT> container =
161       fbs::UnPackMessageContainer(message);
162   if (container->message.type != fbs::ChreMessage::LoadNanoappResponse) {
163     LOGE("Invalid message from CHRE directed to daemon");
164   } else {
165     const auto *response = container->message.AsLoadNanoappResponse();
166     if (mPreloadedNanoappPendingTransactions.empty()) {
167       LOGE("Received nanoapp load response with no pending load");
168     } else if (mPreloadedNanoappPendingTransactions.front().transactionId !=
169                response->transaction_id) {
170       LOGE("Received nanoapp load response with ID %" PRIu32
171            " expected transaction id %" PRIu32,
172            response->transaction_id,
173            mPreloadedNanoappPendingTransactions.front().transactionId);
174     } else {
175       if (!response->success) {
176         LOGE("Received unsuccessful nanoapp load response with ID %" PRIu32,
177              mPreloadedNanoappPendingTransactions.front().transactionId);
178 
179 #ifdef CHRE_DAEMON_METRIC_ENABLED
180         if (!mMetricsReporter.logNanoappLoadFailed(
181                 mPreloadedNanoappPendingTransactions.front().nanoappId,
182                 ChreHalNanoappLoadFailed::TYPE_PRELOADED,
183                 ChreHalNanoappLoadFailed::REASON_ERROR_GENERIC)) {
184           LOGE("Could not log the nanoapp load failed metric");
185         }
186 #endif  // CHRE_DAEMON_METRIC_ENABLED
187       }
188       mPreloadedNanoappPendingTransactions.pop();
189     }
190   }
191 }
192 
193 }  // namespace chre
194 }  // namespace android
195