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 #define LOG_TAG "contexthub_hidl_hal_test"
18
19 #include <VtsHalHidlTargetTestBase.h>
20 #include <android-base/logging.h>
21 #include <android/hardware/contexthub/1.0/IContexthub.h>
22 #include <android/hardware/contexthub/1.0/IContexthubCallback.h>
23 #include <android/hardware/contexthub/1.0/types.h>
24 #include <android/log.h>
25 #include <log/log.h>
26
27 #include <cinttypes>
28 #include <future>
29 #include <utility>
30
31 using ::android::hardware::Return;
32 using ::android::hardware::Void;
33 using ::android::hardware::hidl_string;
34 using ::android::hardware::hidl_vec;
35 using ::android::hardware::contexthub::V1_0::AsyncEventType;
36 using ::android::hardware::contexthub::V1_0::ContextHub;
37 using ::android::hardware::contexthub::V1_0::ContextHubMsg;
38 using ::android::hardware::contexthub::V1_0::HubAppInfo;
39 using ::android::hardware::contexthub::V1_0::IContexthub;
40 using ::android::hardware::contexthub::V1_0::IContexthubCallback;
41 using ::android::hardware::contexthub::V1_0::NanoAppBinary;
42 using ::android::hardware::contexthub::V1_0::Result;
43 using ::android::hardware::contexthub::V1_0::TransactionResult;
44 using ::android::sp;
45
46 #define ASSERT_OK(result) ASSERT_EQ(result, Result::OK)
47 #define EXPECT_OK(result) EXPECT_EQ(result, Result::OK)
48
49 namespace {
50
51 // App ID with vendor "GoogT" (Google Testing), app identifier 0x555555. This
52 // app ID is reserved and must never appear in the list of loaded apps.
53 constexpr uint64_t kNonExistentAppId = 0x476f6f6754555555;
54
55 // Helper that does explicit conversion of an enum class to its underlying/base
56 // type. Useful for stream output of enum values.
57 template<typename EnumType>
asBaseType(EnumType value)58 constexpr typename std::underlying_type<EnumType>::type asBaseType(
59 EnumType value) {
60 return static_cast<typename std::underlying_type<EnumType>::type>(value);
61 }
62
63 // Synchronously queries IContexthub::getHubs() and returns the result
getHubsSync(sp<IContexthub> hubApi)64 hidl_vec<ContextHub> getHubsSync(sp<IContexthub> hubApi) {
65 hidl_vec<ContextHub> hubList;
66 std::promise<void> barrier;
67
68 hubApi->getHubs([&hubList, &barrier](const hidl_vec<ContextHub>& hubs) {
69 hubList = hubs;
70 barrier.set_value();
71 });
72 barrier.get_future().wait_for(std::chrono::seconds(1));
73
74 return hubList;
75 }
76
77 // Gets a list of valid hub IDs in the system
getHubIds()78 std::vector<uint32_t> getHubIds() {
79 static std::vector<uint32_t> hubIds;
80
81 if (hubIds.size() == 0) {
82 sp<IContexthub> hubApi = ::testing::VtsHalHidlTargetTestBase::getService<IContexthub>();
83
84 if (hubApi != nullptr) {
85 for (ContextHub hub : getHubsSync(hubApi)) {
86 hubIds.push_back(hub.hubId);
87 }
88 }
89 }
90
91 ALOGD("Running tests against all %zu reported hubs", hubIds.size());
92 return hubIds;
93 }
94
95 // Base test fixture that initializes the HAL and makes the context hub API
96 // handle available
97 class ContexthubHidlTestBase : public ::testing::VtsHalHidlTargetTestBase {
98 public:
SetUp()99 virtual void SetUp() override {
100 hubApi = ::testing::VtsHalHidlTargetTestBase::getService<IContexthub>();
101 ASSERT_NE(hubApi, nullptr);
102
103 // getHubs() must be called at least once for proper initialization of the
104 // HAL implementation
105 getHubsSync(hubApi);
106 }
107
TearDown()108 virtual void TearDown() override {}
109
110 sp<IContexthub> hubApi;
111 };
112
113 // Test fixture parameterized by hub ID
114 class ContexthubHidlTest : public ContexthubHidlTestBase,
115 public ::testing::WithParamInterface<uint32_t> {
116 public:
getHubId()117 uint32_t getHubId() {
118 return GetParam();
119 }
120
registerCallback(sp<IContexthubCallback> cb)121 Result registerCallback(sp<IContexthubCallback> cb) {
122 Result result = hubApi->registerCallback(getHubId(), cb);
123 ALOGD("Registered callback, result %" PRIu32, result);
124 return result;
125 }
126 };
127
128 // Base callback implementation that just logs all callbacks by default
129 class ContexthubCallbackBase : public IContexthubCallback {
130 public:
handleClientMsg(const ContextHubMsg &)131 virtual Return<void> handleClientMsg(const ContextHubMsg& /*msg*/) override {
132 ALOGD("Got client message callback");
133 return Void();
134 }
135
handleTxnResult(uint32_t txnId,TransactionResult result)136 virtual Return<void> handleTxnResult(
137 uint32_t txnId, TransactionResult result) override {
138 ALOGD("Got transaction result callback for txnId %" PRIu32 " with result %"
139 PRId32, txnId, result);
140 return Void();
141 }
142
handleHubEvent(AsyncEventType evt)143 virtual Return<void> handleHubEvent(AsyncEventType evt) override {
144 ALOGD("Got hub event callback for event type %" PRIu32, evt);
145 return Void();
146 }
147
handleAppAbort(uint64_t appId,uint32_t abortCode)148 virtual Return<void> handleAppAbort(uint64_t appId, uint32_t abortCode)
149 override {
150 ALOGD("Got app abort notification for appId 0x%" PRIx64 " with abort code "
151 "0x%" PRIx32, appId, abortCode);
152 return Void();
153 }
154
handleAppsInfo(const hidl_vec<HubAppInfo> &)155 virtual Return<void> handleAppsInfo(const hidl_vec<HubAppInfo>& /*appInfo*/)
156 override {
157 ALOGD("Got app info callback");
158 return Void();
159 }
160 };
161
162 // Wait for a callback to occur (signaled by the given future) up to the
163 // provided timeout. If the future is invalid or the callback does not come
164 // within the given time, returns false.
165 template<class ReturnType>
waitForCallback(std::future<ReturnType> future,ReturnType * result,std::chrono::milliseconds timeout=std::chrono::seconds (5))166 bool waitForCallback(
167 std::future<ReturnType> future,
168 ReturnType *result,
169 std::chrono::milliseconds timeout = std::chrono::seconds(5)) {
170 auto expiration = std::chrono::system_clock::now() + timeout;
171
172 EXPECT_NE(result, nullptr);
173 EXPECT_TRUE(future.valid());
174 if (result != nullptr && future.valid()) {
175 std::future_status status = future.wait_until(expiration);
176 EXPECT_NE(status, std::future_status::timeout)
177 << "Timed out waiting for callback";
178
179 if (status == std::future_status::ready) {
180 *result = future.get();
181 return true;
182 }
183 }
184
185 return false;
186 }
187
188 // Ensures that the metadata reported in getHubs() is sane
TEST_F(ContexthubHidlTestBase,TestGetHubs)189 TEST_F(ContexthubHidlTestBase, TestGetHubs) {
190 hidl_vec<ContextHub> hubs = getHubsSync(hubApi);
191 ALOGD("System reports %zu hubs", hubs.size());
192
193 for (ContextHub hub : hubs) {
194 ALOGD("Checking hub ID %" PRIu32, hub.hubId);
195
196 EXPECT_FALSE(hub.name.empty());
197 EXPECT_FALSE(hub.vendor.empty());
198 EXPECT_FALSE(hub.toolchain.empty());
199 EXPECT_GT(hub.peakMips, 0);
200 EXPECT_GE(hub.stoppedPowerDrawMw, 0);
201 EXPECT_GE(hub.sleepPowerDrawMw, 0);
202 EXPECT_GT(hub.peakPowerDrawMw, 0);
203
204 // Minimum 128 byte MTU as required by CHRE API v1.0
205 EXPECT_GE(hub.maxSupportedMsgLen, UINT32_C(128));
206 }
207 }
208
TEST_P(ContexthubHidlTest,TestRegisterCallback)209 TEST_P(ContexthubHidlTest, TestRegisterCallback) {
210 ALOGD("TestRegisterCallback called, hubId %" PRIu32, getHubId());
211 ASSERT_OK(registerCallback(new ContexthubCallbackBase()));
212 }
213
TEST_P(ContexthubHidlTest,TestRegisterNullCallback)214 TEST_P(ContexthubHidlTest, TestRegisterNullCallback) {
215 ALOGD("TestRegisterNullCallback called, hubId %" PRIu32, getHubId());
216 ASSERT_OK(registerCallback(nullptr));
217 }
218
219 // Helper callback that puts the async appInfo callback data into a promise
220 class QueryAppsCallback : public ContexthubCallbackBase {
221 public:
handleAppsInfo(const hidl_vec<HubAppInfo> & appInfo)222 virtual Return<void> handleAppsInfo(const hidl_vec<HubAppInfo>& appInfo)
223 override {
224 ALOGD("Got app info callback with %zu apps", appInfo.size());
225 promise.set_value(appInfo);
226 return Void();
227 }
228
229 std::promise<hidl_vec<HubAppInfo>> promise;
230 };
231
232 // Calls queryApps() and checks the returned metadata
TEST_P(ContexthubHidlTest,TestQueryApps)233 TEST_P(ContexthubHidlTest, TestQueryApps) {
234 ALOGD("TestQueryApps called, hubId %u", getHubId());
235 sp<QueryAppsCallback> cb = new QueryAppsCallback();
236 ASSERT_OK(registerCallback(cb));
237
238 Result result = hubApi->queryApps(getHubId());
239 ASSERT_OK(result);
240
241 ALOGD("Waiting for app info callback");
242 hidl_vec<HubAppInfo> appList;
243 ASSERT_TRUE(waitForCallback(cb->promise.get_future(), &appList));
244 for (const HubAppInfo &appInfo : appList) {
245 EXPECT_NE(appInfo.appId, UINT64_C(0));
246 EXPECT_NE(appInfo.appId, kNonExistentAppId);
247 }
248 }
249
250 // Helper callback that puts the TransactionResult for the expectedTxnId into a
251 // promise
252 class TxnResultCallback : public ContexthubCallbackBase {
253 public:
handleTxnResult(uint32_t txnId,TransactionResult result)254 virtual Return<void> handleTxnResult(
255 uint32_t txnId, TransactionResult result) override {
256 ALOGD("Got transaction result callback for txnId %" PRIu32 " (expecting %"
257 PRIu32 ") with result %" PRId32, txnId, expectedTxnId, result);
258 if (txnId == expectedTxnId) {
259 promise.set_value(result);
260 }
261 return Void();
262 }
263
264 uint32_t expectedTxnId = 0;
265 std::promise<TransactionResult> promise;
266 };
267
268 // Parameterized fixture that sets the callback to TxnResultCallback
269 class ContexthubTxnTest : public ContexthubHidlTest {
270 public:
SetUp()271 virtual void SetUp() override {
272 ContexthubHidlTest::SetUp();
273 ASSERT_OK(registerCallback(cb));
274 }
275
276 sp<TxnResultCallback> cb = new TxnResultCallback();
277 };
278
279
280 // Checks cases where the hub implementation is expected to return an error, but
281 // that error can be returned either synchronously or in the asynchronous
282 // transaction callback. Returns an AssertionResult that can be used in
283 // ASSERT/EXPECT_TRUE. Allows checking the sync result against 1 additional
284 // allowed error code apart from OK and TRANSACTION_FAILED, which are always
285 // allowed.
checkFailureSyncOrAsync(Result result,Result allowedSyncResult,std::future<TransactionResult> && future)286 ::testing::AssertionResult checkFailureSyncOrAsync(
287 Result result, Result allowedSyncResult,
288 std::future<TransactionResult>&& future) {
289 if (result == Result::OK) {
290 // No error reported synchronously - this is OK, but then we should get an
291 // async callback with a failure status
292 TransactionResult asyncResult;
293 if (!waitForCallback(std::forward<std::future<TransactionResult>>(future),
294 &asyncResult)) {
295 return ::testing::AssertionFailure()
296 << "Got successful sync result, then failed to receive async cb";
297 } else if (asyncResult == TransactionResult::SUCCESS) {
298 return ::testing::AssertionFailure()
299 << "Got successful sync result, then unexpected successful async "
300 "result";
301 }
302 } else if (result != allowedSyncResult &&
303 result != Result::TRANSACTION_FAILED) {
304 return ::testing::AssertionFailure() << "Got sync result "
305 << asBaseType(result) << ", expected TRANSACTION_FAILED or "
306 << asBaseType(allowedSyncResult);
307 }
308
309 return ::testing::AssertionSuccess();
310 }
311
TEST_P(ContexthubTxnTest,TestSendMessageToNonExistentNanoApp)312 TEST_P(ContexthubTxnTest, TestSendMessageToNonExistentNanoApp) {
313 ContextHubMsg msg;
314 msg.appName = kNonExistentAppId;
315 msg.msgType = 1;
316 msg.msg.resize(4);
317 std::fill(msg.msg.begin(), msg.msg.end(), 0);
318
319 ALOGD("Sending message to non-existent nanoapp");
320 Result result = hubApi->sendMessageToHub(getHubId(), msg);
321 if (result != Result::OK &&
322 result != Result::BAD_PARAMS &&
323 result != Result::TRANSACTION_FAILED) {
324 FAIL() << "Got result " << asBaseType(result) << ", expected OK, BAD_PARAMS"
325 << ", or TRANSACTION_FAILED";
326 }
327 }
328
TEST_P(ContexthubTxnTest,TestLoadEmptyNanoApp)329 TEST_P(ContexthubTxnTest, TestLoadEmptyNanoApp) {
330 cb->expectedTxnId = 0123;
331 NanoAppBinary emptyApp;
332
333 emptyApp.appId = kNonExistentAppId;
334 emptyApp.appVersion = 1;
335 emptyApp.flags = 0;
336 emptyApp.targetChreApiMajorVersion = 1;
337 emptyApp.targetChreApiMinorVersion = 0;
338
339 ALOGD("Loading empty nanoapp");
340 Result result = hubApi->loadNanoApp(getHubId(), emptyApp, cb->expectedTxnId);
341 EXPECT_TRUE(checkFailureSyncOrAsync(result, Result::BAD_PARAMS,
342 cb->promise.get_future()));
343 }
344
TEST_P(ContexthubTxnTest,TestUnloadNonexistentNanoApp)345 TEST_P(ContexthubTxnTest, TestUnloadNonexistentNanoApp) {
346 cb->expectedTxnId = 1234;
347
348 ALOGD("Unloading nonexistent nanoapp");
349 Result result = hubApi->unloadNanoApp(getHubId(), kNonExistentAppId,
350 cb->expectedTxnId);
351 EXPECT_TRUE(checkFailureSyncOrAsync(result, Result::BAD_PARAMS,
352 cb->promise.get_future()));
353 }
354
TEST_P(ContexthubTxnTest,TestEnableNonexistentNanoApp)355 TEST_P(ContexthubTxnTest, TestEnableNonexistentNanoApp) {
356 cb->expectedTxnId = 2345;
357
358 ALOGD("Enabling nonexistent nanoapp");
359 Result result = hubApi->enableNanoApp(getHubId(), kNonExistentAppId,
360 cb->expectedTxnId);
361 EXPECT_TRUE(checkFailureSyncOrAsync(result, Result::BAD_PARAMS,
362 cb->promise.get_future()));
363 }
364
TEST_P(ContexthubTxnTest,TestDisableNonexistentNanoApp)365 TEST_P(ContexthubTxnTest, TestDisableNonexistentNanoApp) {
366 cb->expectedTxnId = 3456;
367
368 ALOGD("Disabling nonexistent nanoapp");
369 Result result = hubApi->disableNanoApp(getHubId(), kNonExistentAppId,
370 cb->expectedTxnId);
371 EXPECT_TRUE(checkFailureSyncOrAsync(result, Result::BAD_PARAMS,
372 cb->promise.get_future()));
373 }
374
375 // Parameterize all SingleContexthubTest tests against each valid hub ID
376 INSTANTIATE_TEST_CASE_P(HubIdSpecificTests, ContexthubHidlTest,
377 ::testing::ValuesIn(getHubIds()));
378 INSTANTIATE_TEST_CASE_P(HubIdSpecificTests, ContexthubTxnTest,
379 ::testing::ValuesIn(getHubIds()));
380
381 } // anonymous namespace
382
main(int argc,char ** argv)383 int main(int argc, char **argv) {
384 ::testing::InitGoogleTest(&argc, argv);
385 return RUN_ALL_TESTS();
386 }
387
388