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 <android/binder_libbinder.h>
18 #include <android/binder_manager.h>
19 #include <android/binder_stability.h>
20 #include <binder/Binder.h>
21 #include <binder/IBinder.h>
22 #include <binder/IPCThreadState.h>
23 #include <binder/IServiceManager.h>
24 #include <binder/Parcel.h>
25 #include <binder/Stability.h>
26 #include <gtest/gtest.h>
27 
28 #include <sys/prctl.h>
29 
30 #include "aidl/BnBinderStabilityTest.h"
31 #include "BnBinderStabilityTest.h"
32 
33 using namespace android;
34 using namespace ndk;
35 using android::binder::Status;
36 using android::internal::Stability; // for testing only!
37 
38 const String16 kSystemStabilityServer = String16("binder_stability_test_service_system");
39 
40 // This is handwritten so that we can test different stability levels w/o having the AIDL
41 // compiler assign them. Hand-writing binder interfaces is considered a bad practice
42 // sanity reasons. YOU SHOULD DEFINE AN AIDL INTERFACE INSTEAD!
43 class BadStableBinder : public BBinder {
44 public:
45     static constexpr uint32_t USER_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION;
46     static String16 kDescriptor;
47 
48     bool gotUserTransaction = false;
49 
doUserTransaction(const sp<IBinder> & binder)50     static status_t doUserTransaction(const sp<IBinder>& binder) {
51         Parcel data, reply;
52         data.writeInterfaceToken(kDescriptor);
53         return binder->transact(USER_TRANSACTION, data, &reply, 0/*flags*/);
54     }
55 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)56     status_t onTransact(uint32_t code,
57             const Parcel& data, Parcel* reply, uint32_t flags) override {
58         if (code == USER_TRANSACTION) {
59             // not interested in this kind of stability. Make sure
60             // we have a test failure
61             LOG_ALWAYS_FATAL_IF(!data.enforceInterface(kDescriptor));
62 
63             gotUserTransaction = true;
64 
65             ALOGE("binder stability: Got user transaction");
66             return OK;
67         }
68         return BBinder::onTransact(code, data, reply, flags);
69     }
70 
undef()71     static sp<BadStableBinder> undef() {
72         sp<BadStableBinder> iface = new BadStableBinder();
73         return iface;
74     }
75 
system()76     static sp<BadStableBinder> system() {
77         sp<BadStableBinder> iface = new BadStableBinder();
78         Stability::markCompilationUnit(iface.get()); // <- for test only
79         return iface;
80     }
81 
vintf()82     static sp<BadStableBinder> vintf() {
83         sp<BadStableBinder> iface = new BadStableBinder();
84         Stability::markVintf(iface.get()); // <- for test only
85         return iface;
86     }
87 
vendor()88     static sp<BadStableBinder> vendor() {
89         sp<BadStableBinder> iface = new BadStableBinder();
90         Stability::markVndk(iface.get()); // <- for test only
91         return iface;
92     }
93 };
94 String16 BadStableBinder::kDescriptor = String16("BadStableBinder.test");
95 
96 // NO! NO! NO! Do not even think of doing something like this!
97 // This is for testing! If a class like this was actually used in production,
98 // it would ruin everything!
99 class MyBinderStabilityTest : public BnBinderStabilityTest {
100 public:
sendBinder(const sp<IBinder> &)101     Status sendBinder(const sp<IBinder>& /*binder*/) override {
102         return Status::ok();
103     }
sendAndCallBinder(const sp<IBinder> & binder)104     Status sendAndCallBinder(const sp<IBinder>& binder) override {
105         ALOGI("Debug log stability: %s", Stability::debugToString(binder).c_str());
106         return Status::fromExceptionCode(BadStableBinder::doUserTransaction(binder));
107     }
returnNoStabilityBinder(sp<IBinder> * _aidl_return)108     Status returnNoStabilityBinder(sp<IBinder>* _aidl_return) override {
109         *_aidl_return = BadStableBinder::undef();
110         return Status::ok();
111     }
returnLocalStabilityBinder(sp<IBinder> * _aidl_return)112     Status returnLocalStabilityBinder(sp<IBinder>* _aidl_return) override {
113         *_aidl_return = BadStableBinder::system();
114         return Status::ok();
115     }
returnVintfStabilityBinder(sp<IBinder> * _aidl_return)116     Status returnVintfStabilityBinder(sp<IBinder>* _aidl_return) override {
117         *_aidl_return = BadStableBinder::vintf();
118         return Status::ok();
119     }
returnVendorStabilityBinder(sp<IBinder> * _aidl_return)120     Status returnVendorStabilityBinder(sp<IBinder>* _aidl_return) override {
121         *_aidl_return = BadStableBinder::vendor();
122         return Status::ok();
123     }
124 };
125 
TEST(BinderStability,OnlyVintfStabilityBinderNeedsVintfDeclaration)126 TEST(BinderStability, OnlyVintfStabilityBinderNeedsVintfDeclaration) {
127     EXPECT_FALSE(Stability::requiresVintfDeclaration(nullptr));
128     EXPECT_FALSE(Stability::requiresVintfDeclaration(BadStableBinder::undef()));
129     EXPECT_FALSE(Stability::requiresVintfDeclaration(BadStableBinder::system()));
130     EXPECT_FALSE(Stability::requiresVintfDeclaration(BadStableBinder::vendor()));
131 
132     EXPECT_TRUE(Stability::requiresVintfDeclaration(BadStableBinder::vintf()));
133 }
134 
TEST(BinderStability,ForceDowngradeToLocalStability)135 TEST(BinderStability, ForceDowngradeToLocalStability) {
136     sp<IBinder> someBinder = BadStableBinder::vintf();
137 
138     EXPECT_TRUE(Stability::requiresVintfDeclaration(someBinder));
139 
140     // silly to do this after already using the binder, but it's for the test
141     Stability::forceDowngradeToLocalStability(someBinder);
142 
143     EXPECT_FALSE(Stability::requiresVintfDeclaration(someBinder));
144 }
145 
TEST(BinderStability,NdkForceDowngradeToLocalStability)146 TEST(BinderStability, NdkForceDowngradeToLocalStability) {
147     sp<IBinder> someBinder = BadStableBinder::vintf();
148 
149     EXPECT_TRUE(Stability::requiresVintfDeclaration(someBinder));
150 
151     // silly to do this after already using the binder, but it's for the test
152     AIBinder_forceDowngradeToLocalStability(AIBinder_fromPlatformBinder(someBinder));
153 
154     EXPECT_FALSE(Stability::requiresVintfDeclaration(someBinder));
155 }
156 
TEST(BinderStability,ForceDowngradeToVendorStability)157 TEST(BinderStability, ForceDowngradeToVendorStability) {
158 #pragma clang diagnostic push
159 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
160     sp<IBinder> serverBinder = android::defaultServiceManager()->getService(kSystemStabilityServer);
161 #pragma clang diagnostic pop
162     auto server = interface_cast<IBinderStabilityTest>(serverBinder);
163 
164     ASSERT_NE(nullptr, server.get());
165     ASSERT_NE(nullptr, IInterface::asBinder(server)->remoteBinder());
166 
167     {
168         sp<BadStableBinder> binder = BadStableBinder::vintf();
169 
170         EXPECT_TRUE(Stability::requiresVintfDeclaration(binder));
171         EXPECT_TRUE(server->sendAndCallBinder(binder).isOk());
172         EXPECT_TRUE(binder->gotUserTransaction);
173     }
174     {
175         sp<BadStableBinder> binder = BadStableBinder::vintf();
176 
177         // This method should never be called directly. This is done only for the test.
178         Stability::forceDowngradeToVendorStability(binder);
179 
180         // Binder downgraded to vendor stability, cannot be called from system context
181         EXPECT_FALSE(Stability::requiresVintfDeclaration(binder));
182         EXPECT_EQ(BAD_TYPE, server->sendAndCallBinder(binder).exceptionCode());
183         EXPECT_FALSE(binder->gotUserTransaction);
184     }
185 }
186 
TEST(BinderStability,VintfStabilityServerMustBeDeclaredInManifest)187 TEST(BinderStability, VintfStabilityServerMustBeDeclaredInManifest) {
188     sp<IBinder> vintfServer = BadStableBinder::vintf();
189 
190     for (const char* instance8 : {
191         ".", "/", "/.", "a.d.IFoo", "foo", "a.d.IFoo/foo"
192     }) {
193         String16 instance (instance8);
194 
195         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT,
196             android::defaultServiceManager()->addService(String16("."), vintfServer)) << instance8;
197         EXPECT_FALSE(android::defaultServiceManager()->isDeclared(instance)) << instance8;
198         EXPECT_EQ(std::nullopt, android::defaultServiceManager()->updatableViaApex(instance))
199                 << instance8;
200     }
201 }
202 
TEST(BinderStability,ConnectionInfoRequiresManifestEntries)203 TEST(BinderStability, ConnectionInfoRequiresManifestEntries) {
204     sp<IServiceManager> sm = android::defaultServiceManager();
205     sp<IBinder> systemBinder = BadStableBinder::system();
206     EXPECT_EQ(OK, sm->addService(String16("no.connection.foo"), systemBinder));
207     std::optional<android::IServiceManager::ConnectionInfo> connectionInfo;
208     connectionInfo = sm->getConnectionInfo(String16("no.connection.foo"));
209     EXPECT_EQ(connectionInfo, std::nullopt);
210 }
TEST(BinderStability,CantCallVendorBinderInSystemContext)211 TEST(BinderStability, CantCallVendorBinderInSystemContext) {
212 #pragma clang diagnostic push
213 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
214     sp<IBinder> serverBinder = android::defaultServiceManager()->getService(kSystemStabilityServer);
215 #pragma clang diagnostic pop
216     auto server = interface_cast<IBinderStabilityTest>(serverBinder);
217 
218     ASSERT_NE(nullptr, server.get());
219     ASSERT_NE(nullptr, IInterface::asBinder(server)->remoteBinder());
220 
221     EXPECT_TRUE(server->sendBinder(BadStableBinder::undef()).isOk());
222     EXPECT_TRUE(server->sendBinder(BadStableBinder::system()).isOk());
223     EXPECT_TRUE(server->sendBinder(BadStableBinder::vintf()).isOk());
224     EXPECT_TRUE(server->sendBinder(BadStableBinder::vendor()).isOk());
225 
226     {
227         sp<BadStableBinder> binder = BadStableBinder::undef();
228         EXPECT_TRUE(server->sendAndCallBinder(binder).isOk());
229         EXPECT_TRUE(binder->gotUserTransaction);
230     }
231     {
232         sp<BadStableBinder> binder = BadStableBinder::system();
233         EXPECT_TRUE(server->sendAndCallBinder(binder).isOk());
234         EXPECT_TRUE(binder->gotUserTransaction);
235     }
236     {
237         sp<BadStableBinder> binder = BadStableBinder::vintf();
238         EXPECT_TRUE(server->sendAndCallBinder(binder).isOk());
239         EXPECT_TRUE(binder->gotUserTransaction);
240     }
241     {
242         // !!! user-defined transaction may not be stable for remote server !!!
243         // !!! so, it does not work !!!
244         sp<BadStableBinder> binder = BadStableBinder::vendor();
245         EXPECT_EQ(BAD_TYPE, server->sendAndCallBinder(binder).exceptionCode());
246         EXPECT_FALSE(binder->gotUserTransaction);
247     }
248 
249     sp<IBinder> out;
250     EXPECT_TRUE(server->returnNoStabilityBinder(&out).isOk());
251     ASSERT_NE(nullptr, out.get());
252     EXPECT_EQ(OK, out->pingBinder());
253     EXPECT_EQ(OK, BadStableBinder::doUserTransaction(out));
254 
255     EXPECT_TRUE(server->returnLocalStabilityBinder(&out).isOk());
256     ASSERT_NE(nullptr, out.get());
257     EXPECT_EQ(OK, out->pingBinder());
258     EXPECT_EQ(OK, BadStableBinder::doUserTransaction(out));
259 
260     EXPECT_TRUE(server->returnVintfStabilityBinder(&out).isOk());
261     ASSERT_NE(nullptr, out.get());
262     EXPECT_EQ(OK, out->pingBinder());
263     EXPECT_EQ(OK, BadStableBinder::doUserTransaction(out));
264 
265     EXPECT_TRUE(server->returnVendorStabilityBinder(&out).isOk());
266     ASSERT_NE(nullptr, out.get());
267 
268     // !!! libbinder-defined transaction works !!!
269     EXPECT_EQ(OK, out->pingBinder());
270 
271     // !!! user-defined transaction may not be stable !!!
272     // !!! so, it does not work !!!
273     EXPECT_EQ(BAD_TYPE, BadStableBinder::doUserTransaction(out));
274 }
275 
276 // This is handwritten so that we can test different stability levels w/o having the AIDL
277 // compiler assign them. Hand-writing binder interfaces is considered a bad practice
278 // sanity reasons. YOU SHOULD DEFINE AN AIDL INTERFACE INSTEAD!
279 
280 struct NdkBinderStable_DataClass {
281     bool gotUserTransaction = false;
282 };
NdkBadStableBinder_Class_onCreate(void * args)283 void* NdkBadStableBinder_Class_onCreate(void* args) {
284     LOG_ALWAYS_FATAL_IF(args != nullptr, "Takes no args");
285     return static_cast<void*>(new NdkBinderStable_DataClass);
286 }
NdkBadStableBinder_Class_onDestroy(void * userData)287 void NdkBadStableBinder_Class_onDestroy(void* userData) {
288     delete static_cast<NdkBinderStable_DataClass*>(userData);
289 }
NdkBadStableBinder_getUserData(AIBinder * binder)290 NdkBinderStable_DataClass* NdkBadStableBinder_getUserData(AIBinder* binder) {
291     LOG_ALWAYS_FATAL_IF(binder == nullptr);
292     void* userData = AIBinder_getUserData(binder);
293     LOG_ALWAYS_FATAL_IF(userData == nullptr, "null data - binder is remote?");
294 
295     return static_cast<NdkBinderStable_DataClass*>(userData);
296 }
NdkBadStableBinder_Class_onTransact(AIBinder * binder,transaction_code_t code,const AParcel *,AParcel *)297 binder_status_t NdkBadStableBinder_Class_onTransact(
298     AIBinder* binder, transaction_code_t code, const AParcel* /*in*/, AParcel* /*out*/) {
299 
300     if (code == BadStableBinder::USER_TRANSACTION) {
301         ALOGE("ndk binder stability: Got user transaction");
302         NdkBadStableBinder_getUserData(binder)->gotUserTransaction = true;
303         return STATUS_OK;
304     }
305 
306     return STATUS_UNKNOWN_TRANSACTION;
307 }
308 
309 static AIBinder_Class* kNdkBadStableBinder =
310     AIBinder_Class_define(String8(BadStableBinder::kDescriptor).c_str(),
311                           NdkBadStableBinder_Class_onCreate,
312                           NdkBadStableBinder_Class_onDestroy,
313                           NdkBadStableBinder_Class_onTransact);
314 
315 // for testing only to get around __ANDROID_VNDK__ guard.
316 extern "C" void AIBinder_markVendorStability(AIBinder* binder); // <- BAD DO NOT COPY
317 
TEST(BinderStability,NdkCantCallVendorBinderInSystemContext)318 TEST(BinderStability, NdkCantCallVendorBinderInSystemContext) {
319 #pragma clang diagnostic push
320 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
321     SpAIBinder binder = SpAIBinder(AServiceManager_getService(
322         String8(kSystemStabilityServer).c_str()));
323 #pragma clang diagnostic pop
324 
325     std::shared_ptr<aidl::IBinderStabilityTest> remoteServer =
326         aidl::IBinderStabilityTest::fromBinder(binder);
327 
328     ASSERT_NE(nullptr, remoteServer.get());
329 
330     SpAIBinder comp = SpAIBinder(AIBinder_new(kNdkBadStableBinder, nullptr /*args*/));
331     EXPECT_TRUE(remoteServer->sendBinder(comp).isOk());
332     EXPECT_TRUE(remoteServer->sendAndCallBinder(comp).isOk());
333     EXPECT_TRUE(NdkBadStableBinder_getUserData(comp.get())->gotUserTransaction);
334 
335     SpAIBinder vendor = SpAIBinder(AIBinder_new(kNdkBadStableBinder, nullptr /*args*/));
336     AIBinder_markVendorStability(vendor.get());
337     EXPECT_TRUE(remoteServer->sendBinder(vendor).isOk());
338     EXPECT_FALSE(remoteServer->sendAndCallBinder(vendor).isOk());
339     EXPECT_FALSE(NdkBadStableBinder_getUserData(vendor.get())->gotUserTransaction);
340 }
341 
342 class MarksStabilityInConstructor : public BBinder {
343 public:
344     static bool gDestructed;
345 
MarksStabilityInConstructor()346     MarksStabilityInConstructor() {
347         Stability::markCompilationUnit(this);
348     }
~MarksStabilityInConstructor()349     ~MarksStabilityInConstructor() {
350         gDestructed = true;
351     }
352 };
353 bool MarksStabilityInConstructor::gDestructed = false;
354 
TEST(BinderStability,MarkingObjectNoDestructTest)355 TEST(BinderStability, MarkingObjectNoDestructTest) {
356     ASSERT_FALSE(MarksStabilityInConstructor::gDestructed);
357 
358     // best practice is to put this directly in an sp, but for this test, we
359     // want to explicitly check what happens before that happens
360     MarksStabilityInConstructor* binder = new MarksStabilityInConstructor();
361     ASSERT_FALSE(MarksStabilityInConstructor::gDestructed);
362 
363     sp<MarksStabilityInConstructor> binderSp = binder;
364     ASSERT_FALSE(MarksStabilityInConstructor::gDestructed);
365 
366     binderSp = nullptr;
367     ASSERT_TRUE(MarksStabilityInConstructor::gDestructed);
368 }
369 
TEST(BinderStability,RemarkDies)370 TEST(BinderStability, RemarkDies) {
371     ASSERT_DEATH({
372         sp<IBinder> binder = new BBinder();
373         Stability::markCompilationUnit(binder.get()); // <-- only called for tests
374         Stability::markVndk(binder.get()); // <-- only called for tests
375     }, "Should only mark known object.");
376 }
377 
main(int argc,char ** argv)378 int main(int argc, char** argv) {
379     ::testing::InitGoogleTest(&argc, argv);
380 
381     if (fork() == 0) {
382         // child process
383         prctl(PR_SET_PDEATHSIG, SIGHUP);
384 
385         sp<IBinder> server = new MyBinderStabilityTest;
386         android::defaultServiceManager()->addService(kSystemStabilityServer, server);
387 
388         IPCThreadState::self()->joinThreadPool(true);
389         exit(1);  // should not reach
390     }
391 
392     // This is not racey. Just giving these services some time to register before we call
393     // getService which sleeps for much longer...
394     usleep(10000);
395 
396     return RUN_ALL_TESTS();
397 }
398