1 /*
2  * Copyright (C) 2022 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 "sensor_manager_aidl_hal_test"
18 #include <aidl/Gtest.h>
19 #include <aidl/Vintf.h>
20 #include <aidl/android/frameworks/sensorservice/ISensorManager.h>
21 #include <aidl/sensors/convert.h>
22 #include <android-base/logging.h>
23 #include <android-base/result.h>
24 #include <android/binder_manager.h>
25 #include <android/sensor.h>
26 #include <binder/IServiceManager.h>
27 #include <cutils/ashmem.h>
28 #include <gmock/gmock.h>
29 #include <gtest/gtest.h>
30 #include <sys/mman.h>
31 
32 #include <chrono>
33 #include <thread>
34 
35 using aidl::android::frameworks::sensorservice::IDirectReportChannel;
36 using aidl::android::frameworks::sensorservice::ISensorManager;
37 using aidl::android::hardware::common::Ashmem;
38 using aidl::android::hardware::sensors::Event;
39 using aidl::android::hardware::sensors::ISensors;
40 using aidl::android::hardware::sensors::SensorInfo;
41 using aidl::android::hardware::sensors::SensorType;
42 using ::android::sp;
43 using ndk::ScopedAStatus;
44 using ndk::ScopedFileDescriptor;
45 using ::testing::Contains;
46 
isOk(const ScopedAStatus & status)47 static inline ::testing::AssertionResult isOk(const ScopedAStatus& status) {
48     return status.isOk() ? ::testing::AssertionSuccess()
49                          : ::testing::AssertionFailure() << status.getDescription();
50 }
51 
52 template <typename I, typename F>
isIncreasing(I begin,I end,F getField)53 static ::testing::AssertionResult isIncreasing(I begin, I end, F getField) {
54     typename std::iterator_traits<I>::pointer lastValue = nullptr;
55     I iter;
56     size_t pos;
57     for (iter = begin, pos = 0; iter != end; ++iter, ++pos) {
58         if (iter == begin) {
59             lastValue = &(*iter);
60             continue;
61         }
62         if (getField(*iter) < getField(*lastValue)) {
63             return ::testing::AssertionFailure()
64                    << "Not an increasing sequence, pos = " << pos << ", " << getField(*iter)
65                    << " < " << getField(*lastValue);
66         }
67     }
68     return ::testing::AssertionSuccess();
69 }
70 
71 #define EXPECT_OK(__ret__) EXPECT_TRUE(isOk(__ret__))
72 #define ASSERT_OK(__ret__) ASSERT_TRUE(isOk(__ret__))
73 
74 class SensorManagerTest : public ::testing::TestWithParam<std::string> {
75    public:
SetUp()76     virtual void SetUp() override {
77         manager_ = ISensorManager::fromBinder(
78             ndk::SpAIBinder(AServiceManager_waitForService(GetParam().c_str())));
79         ASSERT_NE(manager_, nullptr);
80     }
81 
82     // Call getSensorList. Filter result based on |pred| if it is provided.
GetSensorList(std::vector<SensorInfo> * out_info,const std::function<bool (SensorInfo)> & pred=nullptr)83     ndk::ScopedAStatus GetSensorList(std::vector<SensorInfo>* out_info,
84                                      const std::function<bool(SensorInfo)>& pred = nullptr) {
85         ndk::ScopedAStatus ret = manager_->getSensorList(out_info);
86         if (ret.isOk() && pred) {
87             out_info->erase(std::remove_if(out_info->begin(), out_info->end(),
88                                            [pred](const auto& el) { return !pred(el); }),
89                             out_info->end());
90         }
91         return ret;
92     }
93 
94     std::shared_ptr<ISensorManager> manager_;
95 };
96 
97 using map_region = std::unique_ptr<void, std::function<void(void*)>>;
98 
map(const Ashmem & mem)99 map_region map(const Ashmem& mem) {
100     if (mem.fd.get() == -1) {
101         return nullptr;
102     }
103     size_t size = mem.size;
104     void* buf = mmap(nullptr, size, PROT_READ, MAP_SHARED, mem.fd.get(), 0);
105     return map_region{buf, [size](void* localBuf) { munmap(localBuf, size); }};
106 }
107 
TEST_P(SensorManagerTest,List)108 TEST_P(SensorManagerTest, List) {
109     std::vector<SensorInfo> sensorList;
110     auto res = GetSensorList(&sensorList);
111     ASSERT_OK(res) << res.getDescription();
112 }
113 
TEST_P(SensorManagerTest,Ashmem)114 TEST_P(SensorManagerTest, Ashmem) {
115     std::vector<SensorInfo> sensorList;
116     auto res = GetSensorList(&sensorList, [](const auto& info) {
117         return info.flags & SensorInfo::SENSOR_FLAG_BITS_DIRECT_CHANNEL_ASHMEM;
118     });
119     ASSERT_OK(res);
120     if (sensorList.empty()) {
121         GTEST_SKIP() << "DIRECT_CHANNEL_ASHMEM not supported by HAL, skipping";
122     }
123     auto testOne = [this](int64_t memSize, int64_t intendedSize,
124                           void (*callback)(const std::shared_ptr<IDirectReportChannel>&,
125                                            const ScopedAStatus&)) {
126         auto fd = ashmem_create_region("sensorservice_vts", memSize);
127         ASSERT_TRUE(fd != -1);
128         Ashmem ashmem = {ScopedFileDescriptor(fd), memSize};
129         std::shared_ptr<IDirectReportChannel> chan;
130         ScopedAStatus res = manager_->createAshmemDirectChannel(ashmem, intendedSize, &chan);
131         callback(chan, res);
132     };
133 
134     testOne(16, 16, [](const auto& chan, const ScopedAStatus& result) {
135         EXPECT_EQ(result.getServiceSpecificError(), ISensorManager::RESULT_BAD_VALUE)
136             << "unexpected result when memory size is too small";
137         EXPECT_EQ(chan, nullptr);
138     });
139 
140     testOne(1024, 1024, [](const auto& chan, const ScopedAStatus& result) {
141         EXPECT_OK(result);
142         EXPECT_NE(chan, nullptr);
143     });
144 
145     testOne(1024, 2048, [](const auto& chan, const ScopedAStatus& result) {
146         EXPECT_EQ(result.getServiceSpecificError(), ISensorManager::RESULT_BAD_VALUE)
147             << "unexpected result when intended size is too big";
148         EXPECT_EQ(chan, nullptr);
149     });
150 
151     testOne(1024, 16, [](const auto& chan, const ScopedAStatus& result) {
152         EXPECT_EQ(result.getServiceSpecificError(), ISensorManager::RESULT_BAD_VALUE)
153             << "unexpected result when intended size is too small";
154         EXPECT_EQ(chan, nullptr);
155     });
156 }
157 
parseEvents(uint8_t * buf,size_t memSize)158 static std::vector<Event> parseEvents(uint8_t* buf, size_t memSize) {
159     using android::hardware::sensors::implementation::convertFromSensorEvent;
160     size_t offset = 0;
161     int64_t lastCounter = -1;
162     std::vector<Event> events;
163     Event event;
164 
165     while (offset + (size_t)ISensors::DIRECT_REPORT_SENSOR_EVENT_TOTAL_LENGTH <= memSize) {
166         uint8_t* start = buf + offset;
167         int64_t atomicCounter = *reinterpret_cast<uint32_t*>(
168             start + (size_t)ISensors::DIRECT_REPORT_SENSOR_EVENT_OFFSET_SIZE_ATOMIC_COUNTER);
169         if (atomicCounter <= lastCounter) {
170             break;
171         }
172         int32_t size = *reinterpret_cast<int32_t*>(
173             start + (size_t)ISensors::DIRECT_REPORT_SENSOR_EVENT_OFFSET_SIZE_FIELD);
174         if (size != (size_t)ISensors::DIRECT_REPORT_SENSOR_EVENT_TOTAL_LENGTH) {
175             // unknown error, events parsed may be wrong, remove all
176             events.clear();
177             break;
178         }
179 
180         convertFromSensorEvent(*reinterpret_cast<const sensors_event_t*>(start), &event);
181         events.push_back(event);
182         lastCounter = atomicCounter;
183         offset += (size_t)ISensors::DIRECT_REPORT_SENSOR_EVENT_TOTAL_LENGTH;
184     }
185     return events;
186 }
187 
TEST_P(SensorManagerTest,GetDefaultAccelerometer)188 TEST_P(SensorManagerTest, GetDefaultAccelerometer) {
189     std::vector<SensorInfo> sensorList;
190     auto res = GetSensorList(
191         &sensorList, [](const auto& info) { return info.type == SensorType::ACCELEROMETER; });
192     ASSERT_OK(res);
193 
194     SensorInfo info;
195     res = manager_->getDefaultSensor(SensorType::ACCELEROMETER, &info);
196     if (sensorList.empty()) {
197         ASSERT_EQ(ISensorManager::RESULT_NOT_EXIST, res.getServiceSpecificError());
198     } else {
199         ASSERT_OK(res);
200         ASSERT_THAT(sensorList, Contains(info));
201     }
202 }
203 
TEST_P(SensorManagerTest,Accelerometer)204 TEST_P(SensorManagerTest, Accelerometer) {
205     using std::literals::chrono_literals::operator""ms;
206 
207     std::vector<SensorInfo> sensorList;
208     auto res = GetSensorList(&sensorList, [](const auto& info) {
209         if (info.type != SensorType::ACCELEROMETER) return false;
210         if (!(info.flags & SensorInfo::SENSOR_FLAG_BITS_DIRECT_CHANNEL_ASHMEM)) return false;
211         int maxLevel = (info.flags & SensorInfo::SENSOR_FLAG_BITS_MASK_DIRECT_REPORT) >>
212                        SensorInfo::SENSOR_FLAG_SHIFT_DIRECT_REPORT;
213         return maxLevel >= static_cast<int>(ISensors::RateLevel::FAST);
214     });
215     ASSERT_OK(res);
216 
217     if (sensorList.empty()) {
218         GTEST_SKIP()
219             << "No accelerometer sensor that supports DIRECT_CHANNEL_ASHMEM and fast report "
220             << "rate, skipping";
221     }
222 
223     for (const auto& info : sensorList) {
224         int32_t handle = info.sensorHandle;
225         const size_t memSize = (size_t)ISensors::DIRECT_REPORT_SENSOR_EVENT_TOTAL_LENGTH * 300;
226         auto fd = ashmem_create_region("sensorservice_vts", memSize);
227         ASSERT_TRUE(fd != -1);
228         Ashmem mem = {ScopedFileDescriptor(fd), memSize};
229         map_region buf = map(mem);
230         ASSERT_NE(buf, nullptr);
231         std::shared_ptr<IDirectReportChannel> chan;
232         auto res = manager_->createAshmemDirectChannel(mem, memSize, &chan);
233         ASSERT_OK(res);
234         ASSERT_NE(chan, nullptr);
235 
236         int32_t token = 0;
237         ASSERT_OK(chan->configure(handle, ISensors::RateLevel::FAST, &token));
238         ASSERT_GT(token, 0);
239         std::this_thread::sleep_for(500ms);
240         int32_t zeroToken = 0;
241         ASSERT_OK(chan->configure(handle, ISensors::RateLevel::STOP, &zeroToken));
242         ASSERT_OK(res);
243         ASSERT_EQ(zeroToken, 0);
244 
245         auto events = parseEvents(static_cast<uint8_t*>(buf.get()), memSize);
246 
247         EXPECT_TRUE(isIncreasing(events.begin(), events.end(), [](const auto& event) {
248             return event.timestamp;
249         })) << "timestamp is not monotonically increasing";
250         for (const auto& event : events) {
251             EXPECT_EQ(token, event.sensorHandle)
252                 << "configure token and sensor handle don't match.";
253         }
254     }
255 }
256 
257 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SensorManagerTest);
258 INSTANTIATE_TEST_SUITE_P(
259     PerInstance, SensorManagerTest,
260     testing::ValuesIn(android::getAidlHalInstanceNames(ISensorManager::descriptor)),
261     android::PrintInstanceNameToString);
262