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