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