1 /*
2  * Copyright (C) 2019, 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 <ctime>
19 #include <iostream>
20 #include <numeric>
21 #include <string>
22 #include <thread>
23 
24 #include <unistd.h>
25 
26 #include <ILazyTestService.h>
27 #include <binder/IPCThreadState.h>
28 #include <binder/IServiceManager.h>
29 #include <gtest/gtest.h>
30 #include <utils/String8.h>
31 
32 using ::ILazyTestService;
33 using ::android::IBinder;
34 using ::android::IPCThreadState;
35 using ::android::IServiceManager;
36 using ::android::sp;
37 using ::android::String16;
38 
39 std::vector<String16> gServiceNames;
40 static constexpr size_t SHUTDOWN_WAIT_TIME = 10;
41 
waitForService(const String16 & name)42 sp<IBinder> waitForService(const String16& name) {
43   sp<IServiceManager> manager;
44   manager = android::defaultServiceManager();
45   EXPECT_NE(manager, nullptr);
46 
47   return manager->waitForService(name);
48 }
49 
isServiceRunning(const String16 & name)50 bool isServiceRunning(const String16& name) {
51   sp<IServiceManager> manager;
52   manager = android::defaultServiceManager();
53   EXPECT_NE(manager, nullptr);
54 
55   return manager->checkService(name) != nullptr;
56 }
57 
58 class AidlLazyTest : public ::testing::Test {
59  protected:
60   sp<IServiceManager> manager;
61 
SetUp()62   void SetUp() override {
63     manager = android::defaultServiceManager();
64     ASSERT_NE(manager, nullptr);
65 
66     for (size_t i = 0; i < gServiceNames.size(); i++) {
67       ASSERT_FALSE(isServiceRunning(gServiceNames.at(i)))
68           << "Service '" << android::String8(gServiceNames.at(i)) << "' is already running. "
69           << "Please ensure this is implemented as a lazy service, then kill all "
70           << "clients of this service and try again.";
71     }
72   }
73 
TearDown()74   void TearDown() override {
75     std::cout << "Waiting " << SHUTDOWN_WAIT_TIME << " seconds before checking that the "
76               << "service has shut down." << std::endl;
77     IPCThreadState::self()->flushCommands();
78     sleep(SHUTDOWN_WAIT_TIME);
79     for (size_t i = 0; i < gServiceNames.size(); i++) {
80       ASSERT_FALSE(isServiceRunning(gServiceNames.at(i))) << "Service failed to shut down.";
81     }
82   }
83 };
84 
85 static constexpr size_t NUM_IMMEDIATE_GETS = 100;
TEST_F(AidlLazyTest,GetRelease)86 TEST_F(AidlLazyTest, GetRelease) {
87   size_t nServices = gServiceNames.size();
88 
89   for (size_t i = 0; i < nServices * NUM_IMMEDIATE_GETS; i++) {
90     IPCThreadState::self()->flushCommands();
91     sp<IBinder> service = waitForService(gServiceNames.at(i % nServices));
92     ASSERT_NE(service.get(), nullptr);
93     ASSERT_EQ(service->pingBinder(), android::NO_ERROR);
94   }
95 }
96 
waitTimes(size_t numTimes,size_t maxWait)97 static std::vector<size_t> waitTimes(size_t numTimes, size_t maxWait) {
98   std::vector<size_t> times(numTimes);
99   for (size_t i = 0; i < numTimes; i++) {
100     times.at(i) = (size_t)(rand() % (maxWait + 1));
101   }
102   return times;
103 }
104 
testWithTimes(const std::vector<size_t> & waitTimes,bool beforeGet)105 static void testWithTimes(const std::vector<size_t>& waitTimes, bool beforeGet) {
106   size_t nServices = gServiceNames.size();
107   for (size_t i = 0; i < waitTimes.size(); i++) {
108     IPCThreadState::self()->flushCommands();
109     if (beforeGet) {
110       std::cout << "Thread waiting " << waitTimes.at(i) << " while not holding service."
111                 << std::endl;
112       sleep(waitTimes.at(i));
113     }
114 
115     sp<IBinder> service = waitForService(gServiceNames.at(i % nServices));
116 
117     if (!beforeGet) {
118       std::cout << "Thread waiting " << waitTimes.at(i) << " while holding service." << std::endl;
119       sleep(waitTimes.at(i));
120     }
121 
122     ASSERT_NE(service.get(), nullptr);
123     ASSERT_EQ(service->pingBinder(), android::NO_ERROR);
124   }
125 }
126 
127 static constexpr size_t NUM_TIMES_GET_RELEASE = 5;
128 static constexpr size_t MAX_WAITING_DURATION = 10;
129 static constexpr size_t NUM_CONCURRENT_THREADS = 3;
testConcurrentThreadsWithDelays(bool delayBeforeGet)130 static void testConcurrentThreadsWithDelays(bool delayBeforeGet) {
131   size_t nServices = gServiceNames.size();
132   std::vector<std::vector<size_t>> threadWaitTimes(NUM_CONCURRENT_THREADS);
133   int maxWait = 0;
134   for (size_t i = 0; i < threadWaitTimes.size(); i++) {
135     threadWaitTimes.at(i) = waitTimes(NUM_TIMES_GET_RELEASE * nServices, MAX_WAITING_DURATION);
136     int totalWait = std::accumulate(threadWaitTimes.at(i).begin(), threadWaitTimes.at(i).end(), 0);
137     maxWait = std::max(maxWait, totalWait);
138   }
139   std::cout << "Additional runtime expected from sleeps: " << maxWait << " second(s)." << std::endl;
140 
141   std::vector<std::thread> threads(NUM_CONCURRENT_THREADS);
142   for (size_t i = 0; i < threads.size(); i++) {
143     threads.at(i) = std::thread(testWithTimes, threadWaitTimes.at(i), delayBeforeGet);
144   }
145 
146   for (auto& thread : threads) {
147     thread.join();
148   }
149 }
150 
TEST_F(AidlLazyTest,GetConcurrentWithWaitBefore)151 TEST_F(AidlLazyTest, GetConcurrentWithWaitBefore) {
152   testConcurrentThreadsWithDelays(true);
153 }
154 
TEST_F(AidlLazyTest,GetConcurrentWithWaitAfter)155 TEST_F(AidlLazyTest, GetConcurrentWithWaitAfter) {
156   testConcurrentThreadsWithDelays(false);
157 }
158 
159 class AidlLazyRegistrarTest : public ::testing::Test {
160  protected:
161   const String16 serviceName = String16("aidl_lazy_test_1");
SetUp()162   void SetUp() override {
163     if (std::find(gServiceNames.begin(), gServiceNames.end(), serviceName) == gServiceNames.end()) {
164       GTEST_SKIP() << "Persistence test requires special instance: " << serviceName;
165     }
166   }
167 };
168 
waitForLazyTestService(String16 name)169 sp<ILazyTestService> waitForLazyTestService(String16 name) {
170   sp<ILazyTestService> service = android::waitForService<ILazyTestService>(name);
171   EXPECT_NE(service, nullptr);
172   return service;
173 }
174 
TEST_F(AidlLazyRegistrarTest,ForcedPersistenceTest)175 TEST_F(AidlLazyRegistrarTest, ForcedPersistenceTest) {
176   sp<ILazyTestService> service;
177   for (int i = 0; i < 2; i++) {
178     service = waitForLazyTestService(serviceName);
179     EXPECT_TRUE(service->forcePersist(i == 0).isOk());
180     service = nullptr;
181 
182     std::cout << "Waiting " << SHUTDOWN_WAIT_TIME << " seconds before checking whether the "
183               << "service is still running." << std::endl;
184     IPCThreadState::self()->flushCommands();
185     sleep(SHUTDOWN_WAIT_TIME);
186 
187     if (i == 0) {
188       ASSERT_TRUE(isServiceRunning(serviceName)) << "Service shut down when it shouldn't have.";
189     } else {
190       ASSERT_FALSE(isServiceRunning(serviceName)) << "Service failed to shut down.";
191     }
192   }
193 }
194 
TEST_F(AidlLazyRegistrarTest,ActiveServicesCountCallbackTest)195 TEST_F(AidlLazyRegistrarTest, ActiveServicesCountCallbackTest) {
196   sp<ILazyTestService> service;
197   service = waitForLazyTestService(serviceName);
198   ASSERT_TRUE(service->setCustomActiveServicesCallback().isOk());
199   service = nullptr;
200 
201   std::cout << "Waiting " << SHUTDOWN_WAIT_TIME << " seconds before checking whether the "
202             << "service is still running." << std::endl;
203   IPCThreadState::self()->flushCommands();
204   sleep(SHUTDOWN_WAIT_TIME);
205 
206   ASSERT_FALSE(isServiceRunning(serviceName)) << "Service failed to shut down.";
207 }
208 
main(int argc,char ** argv)209 int main(int argc, char** argv) {
210   ::testing::InitGoogleTest(&argc, argv);
211 
212   srand(time(nullptr));
213 
214   if (argc < 2) {
215     // If the user does not specify any service to test, default to these test interfaces
216     gServiceNames.push_back(String16("aidl_lazy_test_1"));
217     gServiceNames.push_back(String16("aidl_lazy_test_2"));
218   } else {
219     for (int i = 1; i < argc; i++) {
220       gServiceNames.push_back(String16(argv[i]));
221     }
222   }
223 
224   android::ProcessState::self()->startThreadPool();
225 
226   return RUN_ALL_TESTS();
227 }
228