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 <signal.h>
18 #include <cstdlib>
19 #include <fstream>
20
21 #include "chre_host/config_util.h"
22 #include "chre_host/daemon_base.h"
23 #include "chre_host/file_stream.h"
24 #include "chre_host/log.h"
25 #include "chre_host/napp_header.h"
26
27 #ifdef CHRE_DAEMON_METRIC_ENABLED
28 #include <chre_atoms_log.h>
29 #include <system/chre/core/chre_metrics.pb.h>
30
31 using ::aidl::android::frameworks::stats::IStats;
32 using ::aidl::android::frameworks::stats::VendorAtom;
33 using ::aidl::android::frameworks::stats::VendorAtomValue;
34 #endif // CHRE_DAEMON_METRIC_ENABLED
35
36 // Aliased for consistency with the way these symbols are referenced in
37 // CHRE-side code
38 namespace fbs = ::chre::fbs;
39
40 namespace android {
41 namespace chre {
42
43 namespace {
44
signalHandler(void * ctx)45 void signalHandler(void *ctx) {
46 auto *daemon = static_cast<ChreDaemonBase *>(ctx);
47 int rc = -1;
48 sigset_t signalMask;
49 sigfillset(&signalMask);
50 sigdelset(&signalMask, SIGINT);
51 sigdelset(&signalMask, SIGTERM);
52 if (sigprocmask(SIG_SETMASK, &signalMask, NULL) != 0) {
53 LOG_ERROR("Couldn't mask all signals except INT/TERM", errno);
54 }
55
56 while (true) {
57 int signum = 0;
58 if ((rc = sigwait(&signalMask, &signum)) != 0) {
59 LOGE("Sigwait failed: %d", rc);
60 }
61 LOGI("Received signal %d", signum);
62 if (signum == SIGINT || signum == SIGTERM) {
63 daemon->onShutdown();
64 break;
65 }
66 }
67 }
68
69 } // anonymous namespace
70
ChreDaemonBase()71 ChreDaemonBase::ChreDaemonBase() : mChreShutdownRequested(false) {
72 mLogger.init();
73 // TODO(b/297388964): Replace thread with handler installed via std::signal()
74 mSignalHandlerThread = std::thread(signalHandler, this);
75 }
76
loadPreloadedNanoapps()77 void ChreDaemonBase::loadPreloadedNanoapps() {
78 const std::string kPreloadedNanoappsConfigPath =
79 "/vendor/etc/chre/preloaded_nanoapps.json";
80 std::string directory;
81 std::vector<std::string> nanoapps;
82 bool success = getPreloadedNanoappsFromConfigFile(
83 kPreloadedNanoappsConfigPath, directory, nanoapps);
84 if (!success) {
85 LOGE("Failed to parse preloaded nanoapps config file");
86 return;
87 }
88
89 for (uint32_t i = 0; i < nanoapps.size(); ++i) {
90 loadPreloadedNanoapp(directory, nanoapps[i], i);
91 }
92 }
93
loadPreloadedNanoapp(const std::string & directory,const std::string & name,uint32_t transactionId)94 void ChreDaemonBase::loadPreloadedNanoapp(const std::string &directory,
95 const std::string &name,
96 uint32_t transactionId) {
97 std::vector<uint8_t> headerBuffer;
98
99 std::string headerFile = directory + "/" + name + ".napp_header";
100
101 // Only create the nanoapp filename as the CHRE framework will load from
102 // within the directory its own binary resides in.
103 std::string nanoappFilename = name + ".so";
104
105 if (!readFileContents(headerFile.c_str(), headerBuffer) ||
106 !loadNanoapp(headerBuffer, nanoappFilename, transactionId)) {
107 LOGE("Failed to load nanoapp: '%s'", name.c_str());
108 }
109 }
110
loadNanoapp(const std::vector<uint8_t> & header,const std::string & nanoappName,uint32_t transactionId)111 bool ChreDaemonBase::loadNanoapp(const std::vector<uint8_t> &header,
112 const std::string &nanoappName,
113 uint32_t transactionId) {
114 bool success = false;
115 if (header.size() != sizeof(NanoAppBinaryHeader)) {
116 LOGE("Header size mismatch");
117 } else {
118 // The header blob contains the struct above.
119 const auto *appHeader =
120 reinterpret_cast<const NanoAppBinaryHeader *>(header.data());
121
122 // Build the target API version from major and minor.
123 uint32_t targetApiVersion = (appHeader->targetChreApiMajorVersion << 24) |
124 (appHeader->targetChreApiMinorVersion << 16);
125
126 success = sendNanoappLoad(appHeader->appId, appHeader->appVersion,
127 targetApiVersion, nanoappName, transactionId);
128 }
129
130 return success;
131 }
132
sendTimeSyncWithRetry(size_t numRetries,useconds_t retryDelayUs,bool logOnError)133 bool ChreDaemonBase::sendTimeSyncWithRetry(size_t numRetries,
134 useconds_t retryDelayUs,
135 bool logOnError) {
136 bool success = false;
137 while (!success && (numRetries-- != 0)) {
138 success = sendTimeSync(logOnError);
139 if (!success) {
140 usleep(retryDelayUs);
141 }
142 }
143 return success;
144 }
145
handleNanConfigurationRequest(const::chre::fbs::NanConfigurationRequestT *)146 void ChreDaemonBase::handleNanConfigurationRequest(
147 const ::chre::fbs::NanConfigurationRequestT * /*request*/) {
148 LOGE("NAN is unsupported on this platform");
149 }
150
151 #ifdef CHRE_DAEMON_METRIC_ENABLED
handleMetricLog(const::chre::fbs::MetricLogT * metricMsg)152 void ChreDaemonBase::handleMetricLog(const ::chre::fbs::MetricLogT *metricMsg) {
153 const std::vector<int8_t> &encodedMetric = metricMsg->encoded_metric;
154
155 switch (metricMsg->id) {
156 case Atoms::CHRE_PAL_OPEN_FAILED: {
157 metrics::ChrePalOpenFailed metric;
158 if (!metric.ParseFromArray(encodedMetric.data(), encodedMetric.size())) {
159 LOGE("Failed to parse metric data");
160 } else {
161 std::vector<VendorAtomValue> values(2);
162 values[0].set<VendorAtomValue::intValue>(metric.pal());
163 values[1].set<VendorAtomValue::intValue>(metric.type());
164 const VendorAtom atom{
165 .atomId = Atoms::CHRE_PAL_OPEN_FAILED,
166 .values{std::move(values)},
167 };
168 reportMetric(atom);
169 }
170 break;
171 }
172 case Atoms::CHRE_EVENT_QUEUE_SNAPSHOT_REPORTED: {
173 metrics::ChreEventQueueSnapshotReported metric;
174 if (!metric.ParseFromArray(encodedMetric.data(), encodedMetric.size())) {
175 LOGE("Failed to parse metric data");
176 } else {
177 std::vector<VendorAtomValue> values(6);
178 values[0].set<VendorAtomValue::intValue>(
179 metric.snapshot_chre_get_time_ms());
180 values[1].set<VendorAtomValue::intValue>(metric.max_event_queue_size());
181 values[2].set<VendorAtomValue::intValue>(
182 metric.mean_event_queue_size());
183 values[3].set<VendorAtomValue::intValue>(metric.num_dropped_events());
184 // Last two values are not currently populated and will be implemented
185 // later. To avoid confusion of the interpretation, we use UINT32_MAX
186 // as a placeholder value.
187 values[4].set<VendorAtomValue::intValue>(
188 UINT32_MAX); // max_queue_delay_us
189 values[5].set<VendorAtomValue::intValue>(
190 UINT32_MAX); // mean_queue_delay_us
191 const VendorAtom atom{
192 .atomId = Atoms::CHRE_EVENT_QUEUE_SNAPSHOT_REPORTED,
193 .values{std::move(values)},
194 };
195 reportMetric(atom);
196 }
197 break;
198 }
199 default: {
200 #ifdef CHRE_LOG_ATOM_EXTENSION_ENABLED
201 handleVendorMetricLog(metricMsg);
202 #else
203 LOGW("Unknown metric ID %" PRIu32, metricMsg->id);
204 #endif // CHRE_LOG_ATOM_EXTENSION_ENABLED
205 }
206 }
207 }
208
reportMetric(const VendorAtom & atom)209 void ChreDaemonBase::reportMetric(const VendorAtom &atom) {
210 const std::string statsServiceName =
211 std::string(IStats::descriptor).append("/default");
212 if (!AServiceManager_isDeclared(statsServiceName.c_str())) {
213 LOGE("Stats service is not declared.");
214 return;
215 }
216
217 std::shared_ptr<IStats> stats_client = IStats::fromBinder(ndk::SpAIBinder(
218 AServiceManager_waitForService(statsServiceName.c_str())));
219 if (stats_client == nullptr) {
220 LOGE("Failed to get IStats service");
221 return;
222 }
223
224 const ndk::ScopedAStatus ret = stats_client->reportVendorAtom(atom);
225 if (!ret.isOk()) {
226 LOGE("Failed to report vendor atom");
227 }
228 }
229 #endif // CHRE_DAEMON_METRIC_ENABLED
230
231 } // namespace chre
232 } // namespace android
233