1 /*
2  * Copyright (C) 2014 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 <errno.h>
18 #include <fcntl.h>
19 #include <poll.h>
20 #include <pthread.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 
24 #include <gtest/gtest.h>
25 
26 #include <binder/Binder.h>
27 #include <binder/IBinder.h>
28 #include <binder/IPCThreadState.h>
29 #include <binder/IServiceManager.h>
30 
31 #include <sys/epoll.h>
32 
33 #define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
34 
35 using namespace android;
36 
IsPageAligned(void * buf)37 static ::testing::AssertionResult IsPageAligned(void *buf) {
38     if (((unsigned long)buf & ((unsigned long)PAGE_SIZE - 1)) == 0)
39         return ::testing::AssertionSuccess();
40     else
41         return ::testing::AssertionFailure() << buf << " is not page aligned";
42 }
43 
44 static testing::Environment* binder_env;
45 static char *binderservername;
46 static char *binderserversuffix;
47 static char binderserverarg[] = "--binderserver";
48 
49 static String16 binderLibTestServiceName = String16("test.binderLib");
50 
51 enum BinderLibTestTranscationCode {
52     BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
53     BINDER_LIB_TEST_REGISTER_SERVER,
54     BINDER_LIB_TEST_ADD_SERVER,
55     BINDER_LIB_TEST_ADD_POLL_SERVER,
56     BINDER_LIB_TEST_CALL_BACK,
57     BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
58     BINDER_LIB_TEST_DELAYED_CALL_BACK,
59     BINDER_LIB_TEST_NOP_CALL_BACK,
60     BINDER_LIB_TEST_GET_SELF_TRANSACTION,
61     BINDER_LIB_TEST_GET_ID_TRANSACTION,
62     BINDER_LIB_TEST_INDIRECT_TRANSACTION,
63     BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
64     BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
65     BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
66     BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
67     BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
68     BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
69     BINDER_LIB_TEST_PROMOTE_WEAK_REF_TRANSACTION,
70     BINDER_LIB_TEST_EXIT_TRANSACTION,
71     BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
72     BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
73     BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
74     BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
75     BINDER_LIB_TEST_ECHO_VECTOR,
76 };
77 
start_server_process(int arg2,bool usePoll=false)78 pid_t start_server_process(int arg2, bool usePoll = false)
79 {
80     int ret;
81     pid_t pid;
82     status_t status;
83     int pipefd[2];
84     char stri[16];
85     char strpipefd1[16];
86     char usepoll[2];
87     char *childargv[] = {
88         binderservername,
89         binderserverarg,
90         stri,
91         strpipefd1,
92         usepoll,
93         binderserversuffix,
94         nullptr
95     };
96 
97     ret = pipe(pipefd);
98     if (ret < 0)
99         return ret;
100 
101     snprintf(stri, sizeof(stri), "%d", arg2);
102     snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
103     snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
104 
105     pid = fork();
106     if (pid == -1)
107         return pid;
108     if (pid == 0) {
109         close(pipefd[0]);
110         execv(binderservername, childargv);
111         status = -errno;
112         write(pipefd[1], &status, sizeof(status));
113         fprintf(stderr, "execv failed, %s\n", strerror(errno));
114         _exit(EXIT_FAILURE);
115     }
116     close(pipefd[1]);
117     ret = read(pipefd[0], &status, sizeof(status));
118     //printf("pipe read returned %d, status %d\n", ret, status);
119     close(pipefd[0]);
120     if (ret == sizeof(status)) {
121         ret = status;
122     } else {
123         kill(pid, SIGKILL);
124         if (ret >= 0) {
125             ret = NO_INIT;
126         }
127     }
128     if (ret < 0) {
129         wait(nullptr);
130         return ret;
131     }
132     return pid;
133 }
134 
135 class BinderLibTestEnv : public ::testing::Environment {
136     public:
BinderLibTestEnv()137         BinderLibTestEnv() {}
getServer(void)138         sp<IBinder> getServer(void) {
139             return m_server;
140         }
141 
142     private:
SetUp()143         virtual void SetUp() {
144             m_serverpid = start_server_process(0);
145             //printf("m_serverpid %d\n", m_serverpid);
146             ASSERT_GT(m_serverpid, 0);
147 
148             sp<IServiceManager> sm = defaultServiceManager();
149             //printf("%s: pid %d, get service\n", __func__, m_pid);
150             m_server = sm->getService(binderLibTestServiceName);
151             ASSERT_TRUE(m_server != nullptr);
152             //printf("%s: pid %d, get service done\n", __func__, m_pid);
153         }
TearDown()154         virtual void TearDown() {
155             status_t ret;
156             Parcel data, reply;
157             int exitStatus;
158             pid_t pid;
159 
160             //printf("%s: pid %d\n", __func__, m_pid);
161             if (m_server != nullptr) {
162                 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
163                 EXPECT_EQ(0, ret);
164                 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
165                 EXPECT_EQ(0, ret);
166             }
167             if (m_serverpid > 0) {
168                 //printf("wait for %d\n", m_pids[i]);
169                 pid = wait(&exitStatus);
170                 EXPECT_EQ(m_serverpid, pid);
171                 EXPECT_TRUE(WIFEXITED(exitStatus));
172                 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
173             }
174         }
175 
176         pid_t m_serverpid;
177         sp<IBinder> m_server;
178 };
179 
180 class BinderLibTest : public ::testing::Test {
181     public:
SetUp()182         virtual void SetUp() {
183             m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
184             IPCThreadState::self()->restoreCallingWorkSource(0);
185         }
TearDown()186         virtual void TearDown() {
187         }
188     protected:
addServerEtc(int32_t * idPtr,int code)189         sp<IBinder> addServerEtc(int32_t *idPtr, int code)
190         {
191             int ret;
192             int32_t id;
193             Parcel data, reply;
194             sp<IBinder> binder;
195 
196             ret = m_server->transact(code, data, &reply);
197             EXPECT_EQ(NO_ERROR, ret);
198 
199             EXPECT_FALSE(binder != nullptr);
200             binder = reply.readStrongBinder();
201             EXPECT_TRUE(binder != nullptr);
202             ret = reply.readInt32(&id);
203             EXPECT_EQ(NO_ERROR, ret);
204             if (idPtr)
205                 *idPtr = id;
206             return binder;
207         }
208 
addServer(int32_t * idPtr=nullptr)209         sp<IBinder> addServer(int32_t *idPtr = nullptr)
210         {
211             return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
212         }
213 
addPollServer(int32_t * idPtr=nullptr)214         sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
215         {
216             return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
217         }
218 
waitForReadData(int fd,int timeout_ms)219         void waitForReadData(int fd, int timeout_ms) {
220             int ret;
221             pollfd pfd = pollfd();
222 
223             pfd.fd = fd;
224             pfd.events = POLLIN;
225             ret = poll(&pfd, 1, timeout_ms);
226             EXPECT_EQ(1, ret);
227         }
228 
229         sp<IBinder> m_server;
230 };
231 
232 class BinderLibTestBundle : public Parcel
233 {
234     public:
BinderLibTestBundle(void)235         BinderLibTestBundle(void) {}
BinderLibTestBundle(const Parcel * source)236         explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
237             int32_t mark;
238             int32_t bundleLen;
239             size_t pos;
240 
241             if (source->readInt32(&mark))
242                 return;
243             if (mark != MARK_START)
244                 return;
245             if (source->readInt32(&bundleLen))
246                 return;
247             pos = source->dataPosition();
248             if (Parcel::appendFrom(source, pos, bundleLen))
249                 return;
250             source->setDataPosition(pos + bundleLen);
251             if (source->readInt32(&mark))
252                 return;
253             if (mark != MARK_END)
254                 return;
255             m_isValid = true;
256             setDataPosition(0);
257         }
appendTo(Parcel * dest)258         void appendTo(Parcel *dest) {
259             dest->writeInt32(MARK_START);
260             dest->writeInt32(dataSize());
261             dest->appendFrom(this, 0, dataSize());
262             dest->writeInt32(MARK_END);
263         };
isValid(void)264         bool isValid(void) {
265             return m_isValid;
266         }
267     private:
268         enum {
269             MARK_START  = B_PACK_CHARS('B','T','B','S'),
270             MARK_END    = B_PACK_CHARS('B','T','B','E'),
271         };
272         bool m_isValid;
273 };
274 
275 class BinderLibTestEvent
276 {
277     public:
BinderLibTestEvent(void)278         BinderLibTestEvent(void)
279             : m_eventTriggered(false)
280         {
281             pthread_mutex_init(&m_waitMutex, nullptr);
282             pthread_cond_init(&m_waitCond, nullptr);
283         }
waitEvent(int timeout_s)284         int waitEvent(int timeout_s)
285         {
286             int ret;
287             pthread_mutex_lock(&m_waitMutex);
288             if (!m_eventTriggered) {
289                 struct timespec ts;
290                 clock_gettime(CLOCK_REALTIME, &ts);
291                 ts.tv_sec += timeout_s;
292                 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
293             }
294             ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
295             pthread_mutex_unlock(&m_waitMutex);
296             return ret;
297         }
getTriggeringThread()298         pthread_t getTriggeringThread()
299         {
300             return m_triggeringThread;
301         }
302     protected:
triggerEvent(void)303         void triggerEvent(void) {
304             pthread_mutex_lock(&m_waitMutex);
305             pthread_cond_signal(&m_waitCond);
306             m_eventTriggered = true;
307             m_triggeringThread = pthread_self();
308             pthread_mutex_unlock(&m_waitMutex);
309         };
310     private:
311         pthread_mutex_t m_waitMutex;
312         pthread_cond_t m_waitCond;
313         bool m_eventTriggered;
314         pthread_t m_triggeringThread;
315 };
316 
317 class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
318 {
319     public:
BinderLibTestCallBack()320         BinderLibTestCallBack()
321             : m_result(NOT_ENOUGH_DATA)
322             , m_prev_end(nullptr)
323         {
324         }
getResult(void)325         status_t getResult(void)
326         {
327             return m_result;
328         }
329 
330     private:
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags=0)331         virtual status_t onTransact(uint32_t code,
332                                     const Parcel& data, Parcel* reply,
333                                     uint32_t flags = 0)
334         {
335             (void)reply;
336             (void)flags;
337             switch(code) {
338             case BINDER_LIB_TEST_CALL_BACK: {
339                 status_t status = data.readInt32(&m_result);
340                 if (status != NO_ERROR) {
341                     m_result = status;
342                 }
343                 triggerEvent();
344                 return NO_ERROR;
345             }
346             case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
347                 sp<IBinder> server;
348                 int ret;
349                 const uint8_t *buf = data.data();
350                 size_t size = data.dataSize();
351                 if (m_prev_end) {
352                     /* 64-bit kernel needs at most 8 bytes to align buffer end */
353                     EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
354                 } else {
355                     EXPECT_TRUE(IsPageAligned((void *)buf));
356                 }
357 
358                 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
359 
360                 if (size > 0) {
361                     server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
362                     ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
363                                            data, reply);
364                     EXPECT_EQ(NO_ERROR, ret);
365                 }
366                 return NO_ERROR;
367             }
368             default:
369                 return UNKNOWN_TRANSACTION;
370             }
371         }
372 
373         status_t m_result;
374         const uint8_t *m_prev_end;
375 };
376 
377 class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
378 {
379     private:
binderDied(const wp<IBinder> & who)380         virtual void binderDied(const wp<IBinder>& who) {
381             (void)who;
382             triggerEvent();
383         };
384 };
385 
TEST_F(BinderLibTest,NopTransaction)386 TEST_F(BinderLibTest, NopTransaction) {
387     status_t ret;
388     Parcel data, reply;
389     ret = m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply);
390     EXPECT_EQ(NO_ERROR, ret);
391 }
392 
TEST_F(BinderLibTest,SetError)393 TEST_F(BinderLibTest, SetError) {
394     int32_t testValue[] = { 0, -123, 123 };
395     for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
396         status_t ret;
397         Parcel data, reply;
398         data.writeInt32(testValue[i]);
399         ret = m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply);
400         EXPECT_EQ(testValue[i], ret);
401     }
402 }
403 
TEST_F(BinderLibTest,GetId)404 TEST_F(BinderLibTest, GetId) {
405     status_t ret;
406     int32_t id;
407     Parcel data, reply;
408     ret = m_server->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
409     EXPECT_EQ(NO_ERROR, ret);
410     ret = reply.readInt32(&id);
411     EXPECT_EQ(NO_ERROR, ret);
412     EXPECT_EQ(0, id);
413 }
414 
TEST_F(BinderLibTest,PtrSize)415 TEST_F(BinderLibTest, PtrSize) {
416     status_t ret;
417     int32_t ptrsize;
418     Parcel data, reply;
419     sp<IBinder> server = addServer();
420     ASSERT_TRUE(server != nullptr);
421     ret = server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply);
422     EXPECT_EQ(NO_ERROR, ret);
423     ret = reply.readInt32(&ptrsize);
424     EXPECT_EQ(NO_ERROR, ret);
425     RecordProperty("TestPtrSize", sizeof(void *));
426     RecordProperty("ServerPtrSize", sizeof(void *));
427 }
428 
TEST_F(BinderLibTest,IndirectGetId2)429 TEST_F(BinderLibTest, IndirectGetId2)
430 {
431     status_t ret;
432     int32_t id;
433     int32_t count;
434     Parcel data, reply;
435     int32_t serverId[3];
436 
437     data.writeInt32(ARRAY_SIZE(serverId));
438     for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
439         sp<IBinder> server;
440         BinderLibTestBundle datai;
441 
442         server = addServer(&serverId[i]);
443         ASSERT_TRUE(server != nullptr);
444         data.writeStrongBinder(server);
445         data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
446         datai.appendTo(&data);
447     }
448 
449     ret = m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply);
450     ASSERT_EQ(NO_ERROR, ret);
451 
452     ret = reply.readInt32(&id);
453     ASSERT_EQ(NO_ERROR, ret);
454     EXPECT_EQ(0, id);
455 
456     ret = reply.readInt32(&count);
457     ASSERT_EQ(NO_ERROR, ret);
458     EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
459 
460     for (size_t i = 0; i < (size_t)count; i++) {
461         BinderLibTestBundle replyi(&reply);
462         EXPECT_TRUE(replyi.isValid());
463         ret = replyi.readInt32(&id);
464         EXPECT_EQ(NO_ERROR, ret);
465         EXPECT_EQ(serverId[i], id);
466         EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
467     }
468 
469     EXPECT_EQ(reply.dataSize(), reply.dataPosition());
470 }
471 
TEST_F(BinderLibTest,IndirectGetId3)472 TEST_F(BinderLibTest, IndirectGetId3)
473 {
474     status_t ret;
475     int32_t id;
476     int32_t count;
477     Parcel data, reply;
478     int32_t serverId[3];
479 
480     data.writeInt32(ARRAY_SIZE(serverId));
481     for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
482         sp<IBinder> server;
483         BinderLibTestBundle datai;
484         BinderLibTestBundle datai2;
485 
486         server = addServer(&serverId[i]);
487         ASSERT_TRUE(server != nullptr);
488         data.writeStrongBinder(server);
489         data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
490 
491         datai.writeInt32(1);
492         datai.writeStrongBinder(m_server);
493         datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
494         datai2.appendTo(&datai);
495 
496         datai.appendTo(&data);
497     }
498 
499     ret = m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply);
500     ASSERT_EQ(NO_ERROR, ret);
501 
502     ret = reply.readInt32(&id);
503     ASSERT_EQ(NO_ERROR, ret);
504     EXPECT_EQ(0, id);
505 
506     ret = reply.readInt32(&count);
507     ASSERT_EQ(NO_ERROR, ret);
508     EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
509 
510     for (size_t i = 0; i < (size_t)count; i++) {
511         int32_t counti;
512 
513         BinderLibTestBundle replyi(&reply);
514         EXPECT_TRUE(replyi.isValid());
515         ret = replyi.readInt32(&id);
516         EXPECT_EQ(NO_ERROR, ret);
517         EXPECT_EQ(serverId[i], id);
518 
519         ret = replyi.readInt32(&counti);
520         ASSERT_EQ(NO_ERROR, ret);
521         EXPECT_EQ(1, counti);
522 
523         BinderLibTestBundle replyi2(&replyi);
524         EXPECT_TRUE(replyi2.isValid());
525         ret = replyi2.readInt32(&id);
526         EXPECT_EQ(NO_ERROR, ret);
527         EXPECT_EQ(0, id);
528         EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
529 
530         EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
531     }
532 
533     EXPECT_EQ(reply.dataSize(), reply.dataPosition());
534 }
535 
TEST_F(BinderLibTest,CallBack)536 TEST_F(BinderLibTest, CallBack)
537 {
538     status_t ret;
539     Parcel data, reply;
540     sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
541     data.writeStrongBinder(callBack);
542     ret = m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY);
543     EXPECT_EQ(NO_ERROR, ret);
544     ret = callBack->waitEvent(5);
545     EXPECT_EQ(NO_ERROR, ret);
546     ret = callBack->getResult();
547     EXPECT_EQ(NO_ERROR, ret);
548 }
549 
TEST_F(BinderLibTest,AddServer)550 TEST_F(BinderLibTest, AddServer)
551 {
552     sp<IBinder> server = addServer();
553     ASSERT_TRUE(server != nullptr);
554 }
555 
TEST_F(BinderLibTest,DeathNotificationNoRefs)556 TEST_F(BinderLibTest, DeathNotificationNoRefs)
557 {
558     status_t ret;
559 
560     sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
561 
562     {
563         sp<IBinder> binder = addServer();
564         ASSERT_TRUE(binder != nullptr);
565         ret = binder->linkToDeath(testDeathRecipient);
566         EXPECT_EQ(NO_ERROR, ret);
567     }
568     IPCThreadState::self()->flushCommands();
569     ret = testDeathRecipient->waitEvent(5);
570     EXPECT_EQ(NO_ERROR, ret);
571 #if 0 /* Is there an unlink api that does not require a strong reference? */
572     ret = binder->unlinkToDeath(testDeathRecipient);
573     EXPECT_EQ(NO_ERROR, ret);
574 #endif
575 }
576 
TEST_F(BinderLibTest,DeathNotificationWeakRef)577 TEST_F(BinderLibTest, DeathNotificationWeakRef)
578 {
579     status_t ret;
580     wp<IBinder> wbinder;
581 
582     sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
583 
584     {
585         sp<IBinder> binder = addServer();
586         ASSERT_TRUE(binder != nullptr);
587         ret = binder->linkToDeath(testDeathRecipient);
588         EXPECT_EQ(NO_ERROR, ret);
589         wbinder = binder;
590     }
591     IPCThreadState::self()->flushCommands();
592     ret = testDeathRecipient->waitEvent(5);
593     EXPECT_EQ(NO_ERROR, ret);
594 #if 0 /* Is there an unlink api that does not require a strong reference? */
595     ret = binder->unlinkToDeath(testDeathRecipient);
596     EXPECT_EQ(NO_ERROR, ret);
597 #endif
598 }
599 
TEST_F(BinderLibTest,DeathNotificationStrongRef)600 TEST_F(BinderLibTest, DeathNotificationStrongRef)
601 {
602     status_t ret;
603     sp<IBinder> sbinder;
604 
605     sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
606 
607     {
608         sp<IBinder> binder = addServer();
609         ASSERT_TRUE(binder != nullptr);
610         ret = binder->linkToDeath(testDeathRecipient);
611         EXPECT_EQ(NO_ERROR, ret);
612         sbinder = binder;
613     }
614     {
615         Parcel data, reply;
616         ret = sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
617         EXPECT_EQ(0, ret);
618     }
619     IPCThreadState::self()->flushCommands();
620     ret = testDeathRecipient->waitEvent(5);
621     EXPECT_EQ(NO_ERROR, ret);
622     ret = sbinder->unlinkToDeath(testDeathRecipient);
623     EXPECT_EQ(DEAD_OBJECT, ret);
624 }
625 
TEST_F(BinderLibTest,DeathNotificationMultiple)626 TEST_F(BinderLibTest, DeathNotificationMultiple)
627 {
628     status_t ret;
629     const int clientcount = 2;
630     sp<IBinder> target;
631     sp<IBinder> linkedclient[clientcount];
632     sp<BinderLibTestCallBack> callBack[clientcount];
633     sp<IBinder> passiveclient[clientcount];
634 
635     target = addServer();
636     ASSERT_TRUE(target != nullptr);
637     for (int i = 0; i < clientcount; i++) {
638         {
639             Parcel data, reply;
640 
641             linkedclient[i] = addServer();
642             ASSERT_TRUE(linkedclient[i] != nullptr);
643             callBack[i] = new BinderLibTestCallBack();
644             data.writeStrongBinder(target);
645             data.writeStrongBinder(callBack[i]);
646             ret = linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply, TF_ONE_WAY);
647             EXPECT_EQ(NO_ERROR, ret);
648         }
649         {
650             Parcel data, reply;
651 
652             passiveclient[i] = addServer();
653             ASSERT_TRUE(passiveclient[i] != nullptr);
654             data.writeStrongBinder(target);
655             ret = passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply, TF_ONE_WAY);
656             EXPECT_EQ(NO_ERROR, ret);
657         }
658     }
659     {
660         Parcel data, reply;
661         ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
662         EXPECT_EQ(0, ret);
663     }
664 
665     for (int i = 0; i < clientcount; i++) {
666         ret = callBack[i]->waitEvent(5);
667         EXPECT_EQ(NO_ERROR, ret);
668         ret = callBack[i]->getResult();
669         EXPECT_EQ(NO_ERROR, ret);
670     }
671 }
672 
TEST_F(BinderLibTest,DeathNotificationThread)673 TEST_F(BinderLibTest, DeathNotificationThread)
674 {
675     status_t ret;
676     sp<BinderLibTestCallBack> callback;
677     sp<IBinder> target = addServer();
678     ASSERT_TRUE(target != nullptr);
679     sp<IBinder> client = addServer();
680     ASSERT_TRUE(client != nullptr);
681 
682     sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
683 
684     ret = target->linkToDeath(testDeathRecipient);
685     EXPECT_EQ(NO_ERROR, ret);
686 
687     {
688         Parcel data, reply;
689         ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
690         EXPECT_EQ(0, ret);
691     }
692 
693     /* Make sure it's dead */
694     testDeathRecipient->waitEvent(5);
695 
696     /* Now, pass the ref to another process and ask that process to
697      * call linkToDeath() on it, and wait for a response. This tests
698      * two things:
699      * 1) You still get death notifications when calling linkToDeath()
700      *    on a ref that is already dead when it was passed to you.
701      * 2) That death notifications are not directly pushed to the thread
702      *    registering them, but to the threadpool (proc workqueue) instead.
703      *
704      * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
705      * is blocked on a condition variable waiting for the death notification to be
706      * called; therefore, that thread is not available for handling proc work.
707      * So, if the death notification was pushed to the thread workqueue, the callback
708      * would never be called, and the test would timeout and fail.
709      *
710      * Note that we can't do this part of the test from this thread itself, because
711      * the binder driver would only push death notifications to the thread if
712      * it is a looper thread, which this thread is not.
713      *
714      * See b/23525545 for details.
715      */
716     {
717         Parcel data, reply;
718 
719         callback = new BinderLibTestCallBack();
720         data.writeStrongBinder(target);
721         data.writeStrongBinder(callback);
722         ret = client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply, TF_ONE_WAY);
723         EXPECT_EQ(NO_ERROR, ret);
724     }
725 
726     ret = callback->waitEvent(5);
727     EXPECT_EQ(NO_ERROR, ret);
728     ret = callback->getResult();
729     EXPECT_EQ(NO_ERROR, ret);
730 }
731 
TEST_F(BinderLibTest,PassFile)732 TEST_F(BinderLibTest, PassFile) {
733     int ret;
734     int pipefd[2];
735     uint8_t buf[1] = { 0 };
736     uint8_t write_value = 123;
737 
738     ret = pipe2(pipefd, O_NONBLOCK);
739     ASSERT_EQ(0, ret);
740 
741     {
742         Parcel data, reply;
743         uint8_t writebuf[1] = { write_value };
744 
745         ret = data.writeFileDescriptor(pipefd[1], true);
746         EXPECT_EQ(NO_ERROR, ret);
747 
748         ret = data.writeInt32(sizeof(writebuf));
749         EXPECT_EQ(NO_ERROR, ret);
750 
751         ret = data.write(writebuf, sizeof(writebuf));
752         EXPECT_EQ(NO_ERROR, ret);
753 
754         ret = m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply);
755         EXPECT_EQ(NO_ERROR, ret);
756     }
757 
758     ret = read(pipefd[0], buf, sizeof(buf));
759     EXPECT_EQ(sizeof(buf), (size_t)ret);
760     EXPECT_EQ(write_value, buf[0]);
761 
762     waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
763 
764     ret = read(pipefd[0], buf, sizeof(buf));
765     EXPECT_EQ(0, ret);
766 
767     close(pipefd[0]);
768 }
769 
TEST_F(BinderLibTest,PassParcelFileDescriptor)770 TEST_F(BinderLibTest, PassParcelFileDescriptor) {
771     const int datasize = 123;
772     std::vector<uint8_t> writebuf(datasize);
773     for (size_t i = 0; i < writebuf.size(); ++i) {
774         writebuf[i] = i;
775     }
776 
777     android::base::unique_fd read_end, write_end;
778     {
779         int pipefd[2];
780         ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
781         read_end.reset(pipefd[0]);
782         write_end.reset(pipefd[1]);
783     }
784     {
785         Parcel data;
786         EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
787         write_end.reset();
788         EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
789         EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
790 
791         Parcel reply;
792         EXPECT_EQ(NO_ERROR,
793                   m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
794                                      &reply));
795     }
796     std::vector<uint8_t> readbuf(datasize);
797     EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
798     EXPECT_EQ(writebuf, readbuf);
799 
800     waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
801 
802     EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
803 }
804 
TEST_F(BinderLibTest,PromoteLocal)805 TEST_F(BinderLibTest, PromoteLocal) {
806     sp<IBinder> strong = new BBinder();
807     wp<IBinder> weak = strong;
808     sp<IBinder> strong_from_weak = weak.promote();
809     EXPECT_TRUE(strong != nullptr);
810     EXPECT_EQ(strong, strong_from_weak);
811     strong = nullptr;
812     strong_from_weak = nullptr;
813     strong_from_weak = weak.promote();
814     EXPECT_TRUE(strong_from_weak == nullptr);
815 }
816 
TEST_F(BinderLibTest,PromoteRemote)817 TEST_F(BinderLibTest, PromoteRemote) {
818     int ret;
819     Parcel data, reply;
820     sp<IBinder> strong = new BBinder();
821     sp<IBinder> server = addServer();
822 
823     ASSERT_TRUE(server != nullptr);
824     ASSERT_TRUE(strong != nullptr);
825 
826     ret = data.writeWeakBinder(strong);
827     EXPECT_EQ(NO_ERROR, ret);
828 
829     ret = server->transact(BINDER_LIB_TEST_PROMOTE_WEAK_REF_TRANSACTION, data, &reply);
830     EXPECT_GE(ret, 0);
831 }
832 
TEST_F(BinderLibTest,CheckHandleZeroBinderHighBitsZeroCookie)833 TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
834     status_t ret;
835     Parcel data, reply;
836 
837     ret = m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply);
838     EXPECT_EQ(NO_ERROR, ret);
839 
840     const flat_binder_object *fb = reply.readObject(false);
841     ASSERT_TRUE(fb != nullptr);
842     EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
843     EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
844     EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
845     EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
846 }
847 
TEST_F(BinderLibTest,FreedBinder)848 TEST_F(BinderLibTest, FreedBinder) {
849     status_t ret;
850 
851     sp<IBinder> server = addServer();
852     ASSERT_TRUE(server != nullptr);
853 
854     __u32 freedHandle;
855     wp<IBinder> keepFreedBinder;
856     {
857         Parcel data, reply;
858         data.writeBool(false); /* request weak reference */
859         ret = server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply);
860         ASSERT_EQ(NO_ERROR, ret);
861         struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
862         freedHandle = freed->handle;
863         /* Add a weak ref to the freed binder so the driver does not
864          * delete its reference to it - otherwise the transaction
865          * fails regardless of whether the driver is fixed.
866          */
867         keepFreedBinder = reply.readWeakBinder();
868     }
869     {
870         Parcel data, reply;
871         data.writeStrongBinder(server);
872         /* Replace original handle with handle to the freed binder */
873         struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
874         __u32 oldHandle = strong->handle;
875         strong->handle = freedHandle;
876         ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
877         /* Returns DEAD_OBJECT (-32) if target crashes and
878          * FAILED_TRANSACTION if the driver rejects the invalid
879          * object.
880          */
881         EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
882         /* Restore original handle so parcel destructor does not use
883          * the wrong handle.
884          */
885         strong->handle = oldHandle;
886     }
887 }
888 
TEST_F(BinderLibTest,CheckNoHeaderMappedInUser)889 TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
890     status_t ret;
891     Parcel data, reply;
892     sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
893     for (int i = 0; i < 2; i++) {
894         BinderLibTestBundle datai;
895         datai.appendFrom(&data, 0, data.dataSize());
896 
897         data.freeData();
898         data.writeInt32(1);
899         data.writeStrongBinder(callBack);
900         data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
901 
902         datai.appendTo(&data);
903     }
904     ret = m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply);
905     EXPECT_EQ(NO_ERROR, ret);
906 }
907 
TEST_F(BinderLibTest,OnewayQueueing)908 TEST_F(BinderLibTest, OnewayQueueing)
909 {
910     status_t ret;
911     Parcel data, data2;
912 
913     sp<IBinder> pollServer = addPollServer();
914 
915     sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
916     data.writeStrongBinder(callBack);
917     data.writeInt32(500000); // delay in us before calling back
918 
919     sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
920     data2.writeStrongBinder(callBack2);
921     data2.writeInt32(0); // delay in us
922 
923     ret = pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY);
924     EXPECT_EQ(NO_ERROR, ret);
925 
926     // The delay ensures that this second transaction will end up on the async_todo list
927     // (for a single-threaded server)
928     ret = pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY);
929     EXPECT_EQ(NO_ERROR, ret);
930 
931     // The server will ensure that the two transactions are handled in the expected order;
932     // If the ordering is not as expected, an error will be returned through the callbacks.
933     ret = callBack->waitEvent(2);
934     EXPECT_EQ(NO_ERROR, ret);
935     ret = callBack->getResult();
936     EXPECT_EQ(NO_ERROR, ret);
937 
938     ret = callBack2->waitEvent(2);
939     EXPECT_EQ(NO_ERROR, ret);
940     ret = callBack2->getResult();
941     EXPECT_EQ(NO_ERROR, ret);
942 }
943 
TEST_F(BinderLibTest,WorkSourceUnsetByDefault)944 TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
945 {
946     status_t ret;
947     Parcel data, reply;
948     data.writeInterfaceToken(binderLibTestServiceName);
949     ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
950     EXPECT_EQ(-1, reply.readInt32());
951     EXPECT_EQ(NO_ERROR, ret);
952 }
953 
TEST_F(BinderLibTest,WorkSourceSet)954 TEST_F(BinderLibTest, WorkSourceSet)
955 {
956     status_t ret;
957     Parcel data, reply;
958     IPCThreadState::self()->clearCallingWorkSource();
959     int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
960     data.writeInterfaceToken(binderLibTestServiceName);
961     ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
962     EXPECT_EQ(100, reply.readInt32());
963     EXPECT_EQ(-1, previousWorkSource);
964     EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
965     EXPECT_EQ(NO_ERROR, ret);
966 }
967 
TEST_F(BinderLibTest,WorkSourceSetWithoutPropagation)968 TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
969 {
970     status_t ret;
971     Parcel data, reply;
972 
973     IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
974     EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
975 
976     data.writeInterfaceToken(binderLibTestServiceName);
977     ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
978     EXPECT_EQ(-1, reply.readInt32());
979     EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
980     EXPECT_EQ(NO_ERROR, ret);
981 }
982 
TEST_F(BinderLibTest,WorkSourceCleared)983 TEST_F(BinderLibTest, WorkSourceCleared)
984 {
985     status_t ret;
986     Parcel data, reply;
987 
988     IPCThreadState::self()->setCallingWorkSourceUid(100);
989     int64_t token = IPCThreadState::self()->clearCallingWorkSource();
990     int32_t previousWorkSource = (int32_t)token;
991     data.writeInterfaceToken(binderLibTestServiceName);
992     ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
993 
994     EXPECT_EQ(-1, reply.readInt32());
995     EXPECT_EQ(100, previousWorkSource);
996     EXPECT_EQ(NO_ERROR, ret);
997 }
998 
TEST_F(BinderLibTest,WorkSourceRestored)999 TEST_F(BinderLibTest, WorkSourceRestored)
1000 {
1001     status_t ret;
1002     Parcel data, reply;
1003 
1004     IPCThreadState::self()->setCallingWorkSourceUid(100);
1005     int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1006     IPCThreadState::self()->restoreCallingWorkSource(token);
1007 
1008     data.writeInterfaceToken(binderLibTestServiceName);
1009     ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1010 
1011     EXPECT_EQ(100, reply.readInt32());
1012     EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1013     EXPECT_EQ(NO_ERROR, ret);
1014 }
1015 
TEST_F(BinderLibTest,PropagateFlagSet)1016 TEST_F(BinderLibTest, PropagateFlagSet)
1017 {
1018     status_t ret;
1019     Parcel data, reply;
1020 
1021     IPCThreadState::self()->clearPropagateWorkSource();
1022     IPCThreadState::self()->setCallingWorkSourceUid(100);
1023     EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1024 }
1025 
TEST_F(BinderLibTest,PropagateFlagCleared)1026 TEST_F(BinderLibTest, PropagateFlagCleared)
1027 {
1028     status_t ret;
1029     Parcel data, reply;
1030 
1031     IPCThreadState::self()->setCallingWorkSourceUid(100);
1032     IPCThreadState::self()->clearPropagateWorkSource();
1033     EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1034 }
1035 
TEST_F(BinderLibTest,PropagateFlagRestored)1036 TEST_F(BinderLibTest, PropagateFlagRestored)
1037 {
1038     status_t ret;
1039     Parcel data, reply;
1040 
1041     int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1042     IPCThreadState::self()->restoreCallingWorkSource(token);
1043 
1044     EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1045 }
1046 
TEST_F(BinderLibTest,WorkSourcePropagatedForAllFollowingBinderCalls)1047 TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1048 {
1049     IPCThreadState::self()->setCallingWorkSourceUid(100);
1050 
1051     Parcel data, reply;
1052     status_t ret;
1053     data.writeInterfaceToken(binderLibTestServiceName);
1054     ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1055 
1056     Parcel data2, reply2;
1057     status_t ret2;
1058     data2.writeInterfaceToken(binderLibTestServiceName);
1059     ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1060     EXPECT_EQ(100, reply2.readInt32());
1061     EXPECT_EQ(NO_ERROR, ret2);
1062 }
1063 
TEST_F(BinderLibTest,VectorSent)1064 TEST_F(BinderLibTest, VectorSent) {
1065     Parcel data, reply;
1066     sp<IBinder> server = addServer();
1067     ASSERT_TRUE(server != nullptr);
1068 
1069     std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1070     data.writeUint64Vector(testValue);
1071 
1072     status_t ret = server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply);
1073     EXPECT_EQ(NO_ERROR, ret);
1074     std::vector<uint64_t> readValue;
1075     ret = reply.readUint64Vector(&readValue);
1076     EXPECT_EQ(readValue, testValue);
1077 }
1078 
1079 class BinderLibTestService : public BBinder
1080 {
1081     public:
BinderLibTestService(int32_t id)1082         explicit BinderLibTestService(int32_t id)
1083             : m_id(id)
1084             , m_nextServerId(id + 1)
1085             , m_serverStartRequested(false)
1086             , m_callback(nullptr)
1087         {
1088             pthread_mutex_init(&m_serverWaitMutex, nullptr);
1089             pthread_cond_init(&m_serverWaitCond, nullptr);
1090         }
~BinderLibTestService()1091         ~BinderLibTestService()
1092         {
1093             exit(EXIT_SUCCESS);
1094         }
1095 
processPendingCall()1096         void processPendingCall() {
1097             if (m_callback != nullptr) {
1098                 Parcel data;
1099                 data.writeInt32(NO_ERROR);
1100                 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1101                 m_callback = nullptr;
1102             }
1103         }
1104 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags=0)1105         virtual status_t onTransact(uint32_t code,
1106                                     const Parcel& data, Parcel* reply,
1107                                     uint32_t flags = 0) {
1108             //printf("%s: code %d\n", __func__, code);
1109             (void)flags;
1110 
1111             if (getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
1112                 return PERMISSION_DENIED;
1113             }
1114             switch (code) {
1115             case BINDER_LIB_TEST_REGISTER_SERVER: {
1116                 int32_t id;
1117                 sp<IBinder> binder;
1118                 id = data.readInt32();
1119                 binder = data.readStrongBinder();
1120                 if (binder == nullptr) {
1121                     return BAD_VALUE;
1122                 }
1123 
1124                 if (m_id != 0)
1125                     return INVALID_OPERATION;
1126 
1127                 pthread_mutex_lock(&m_serverWaitMutex);
1128                 if (m_serverStartRequested) {
1129                     m_serverStartRequested = false;
1130                     m_serverStarted = binder;
1131                     pthread_cond_signal(&m_serverWaitCond);
1132                 }
1133                 pthread_mutex_unlock(&m_serverWaitMutex);
1134                 return NO_ERROR;
1135             }
1136             case BINDER_LIB_TEST_ADD_POLL_SERVER:
1137             case BINDER_LIB_TEST_ADD_SERVER: {
1138                 int ret;
1139                 uint8_t buf[1] = { 0 };
1140                 int serverid;
1141 
1142                 if (m_id != 0) {
1143                     return INVALID_OPERATION;
1144                 }
1145                 pthread_mutex_lock(&m_serverWaitMutex);
1146                 if (m_serverStartRequested) {
1147                     ret = -EBUSY;
1148                 } else {
1149                     serverid = m_nextServerId++;
1150                     m_serverStartRequested = true;
1151                     bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
1152 
1153                     pthread_mutex_unlock(&m_serverWaitMutex);
1154                     ret = start_server_process(serverid, usePoll);
1155                     pthread_mutex_lock(&m_serverWaitMutex);
1156                 }
1157                 if (ret > 0) {
1158                     if (m_serverStartRequested) {
1159                         struct timespec ts;
1160                         clock_gettime(CLOCK_REALTIME, &ts);
1161                         ts.tv_sec += 5;
1162                         ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
1163                     }
1164                     if (m_serverStartRequested) {
1165                         m_serverStartRequested = false;
1166                         ret = -ETIMEDOUT;
1167                     } else {
1168                         reply->writeStrongBinder(m_serverStarted);
1169                         reply->writeInt32(serverid);
1170                         m_serverStarted = nullptr;
1171                         ret = NO_ERROR;
1172                     }
1173                 } else if (ret >= 0) {
1174                     m_serverStartRequested = false;
1175                     ret = UNKNOWN_ERROR;
1176                 }
1177                 pthread_mutex_unlock(&m_serverWaitMutex);
1178                 return ret;
1179             }
1180             case BINDER_LIB_TEST_NOP_TRANSACTION:
1181                 return NO_ERROR;
1182             case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1183                 // Note: this transaction is only designed for use with a
1184                 // poll() server. See comments around epoll_wait().
1185                 if (m_callback != nullptr) {
1186                     // A callback was already pending; this means that
1187                     // we received a second call while still processing
1188                     // the first one. Fail the test.
1189                     sp<IBinder> callback = data.readStrongBinder();
1190                     Parcel data2;
1191                     data2.writeInt32(UNKNOWN_ERROR);
1192 
1193                     callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
1194                 } else {
1195                     m_callback = data.readStrongBinder();
1196                     int32_t delayUs = data.readInt32();
1197                     /*
1198                      * It's necessary that we sleep here, so the next
1199                      * transaction the caller makes will be queued to
1200                      * the async queue.
1201                      */
1202                     usleep(delayUs);
1203 
1204                     /*
1205                      * Now when we return, libbinder will tell the kernel
1206                      * we are done with this transaction, and the kernel
1207                      * can move the queued transaction to either the
1208                      * thread todo worklist (for kernels without the fix),
1209                      * or the proc todo worklist. In case of the former,
1210                      * the next outbound call will pick up the pending
1211                      * transaction, which leads to undesired reentrant
1212                      * behavior. This is caught in the if() branch above.
1213                      */
1214                 }
1215 
1216                 return NO_ERROR;
1217             }
1218             case BINDER_LIB_TEST_NOP_CALL_BACK: {
1219                 Parcel data2, reply2;
1220                 sp<IBinder> binder;
1221                 binder = data.readStrongBinder();
1222                 if (binder == nullptr) {
1223                     return BAD_VALUE;
1224                 }
1225                 data2.writeInt32(NO_ERROR);
1226                 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1227                 return NO_ERROR;
1228             }
1229             case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1230                 reply->writeStrongBinder(this);
1231                 return NO_ERROR;
1232             case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1233                 reply->writeInt32(m_id);
1234                 return NO_ERROR;
1235             case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1236                 int32_t count;
1237                 uint32_t indirect_code;
1238                 sp<IBinder> binder;
1239 
1240                 count = data.readInt32();
1241                 reply->writeInt32(m_id);
1242                 reply->writeInt32(count);
1243                 for (int i = 0; i < count; i++) {
1244                     binder = data.readStrongBinder();
1245                     if (binder == nullptr) {
1246                         return BAD_VALUE;
1247                     }
1248                     indirect_code = data.readInt32();
1249                     BinderLibTestBundle data2(&data);
1250                     if (!data2.isValid()) {
1251                         return BAD_VALUE;
1252                     }
1253                     BinderLibTestBundle reply2;
1254                     binder->transact(indirect_code, data2, &reply2);
1255                     reply2.appendTo(reply);
1256                 }
1257                 return NO_ERROR;
1258             }
1259             case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1260                 reply->setError(data.readInt32());
1261                 return NO_ERROR;
1262             case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1263                 reply->writeInt32(sizeof(void *));
1264                 return NO_ERROR;
1265             case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1266                 return NO_ERROR;
1267             case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1268                 m_strongRef = data.readStrongBinder();
1269                 return NO_ERROR;
1270             case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1271                 int ret;
1272                 Parcel data2, reply2;
1273                 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1274                 sp<IBinder> target;
1275                 sp<IBinder> callback;
1276 
1277                 target = data.readStrongBinder();
1278                 if (target == nullptr) {
1279                     return BAD_VALUE;
1280                 }
1281                 callback = data.readStrongBinder();
1282                 if (callback == nullptr) {
1283                     return BAD_VALUE;
1284                 }
1285                 ret = target->linkToDeath(testDeathRecipient);
1286                 if (ret == NO_ERROR)
1287                     ret = testDeathRecipient->waitEvent(5);
1288                 data2.writeInt32(ret);
1289                 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1290                 return NO_ERROR;
1291             }
1292             case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1293                 int ret;
1294                 int32_t size;
1295                 const void *buf;
1296                 int fd;
1297 
1298                 fd = data.readFileDescriptor();
1299                 if (fd < 0) {
1300                     return BAD_VALUE;
1301                 }
1302                 ret = data.readInt32(&size);
1303                 if (ret != NO_ERROR) {
1304                     return ret;
1305                 }
1306                 buf = data.readInplace(size);
1307                 if (buf == nullptr) {
1308                     return BAD_VALUE;
1309                 }
1310                 ret = write(fd, buf, size);
1311                 if (ret != size)
1312                     return UNKNOWN_ERROR;
1313                 return NO_ERROR;
1314             }
1315             case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1316                 int ret;
1317                 int32_t size;
1318                 const void *buf;
1319                 android::base::unique_fd fd;
1320 
1321                 ret = data.readUniqueParcelFileDescriptor(&fd);
1322                 if (ret != NO_ERROR) {
1323                     return ret;
1324                 }
1325                 ret = data.readInt32(&size);
1326                 if (ret != NO_ERROR) {
1327                     return ret;
1328                 }
1329                 buf = data.readInplace(size);
1330                 if (buf == nullptr) {
1331                     return BAD_VALUE;
1332                 }
1333                 ret = write(fd.get(), buf, size);
1334                 if (ret != size) return UNKNOWN_ERROR;
1335                 return NO_ERROR;
1336             }
1337             case BINDER_LIB_TEST_PROMOTE_WEAK_REF_TRANSACTION: {
1338                 int ret;
1339                 wp<IBinder> weak;
1340                 sp<IBinder> strong;
1341                 Parcel data2, reply2;
1342                 sp<IServiceManager> sm = defaultServiceManager();
1343                 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1344 
1345                 weak = data.readWeakBinder();
1346                 if (weak == nullptr) {
1347                     return BAD_VALUE;
1348                 }
1349                 strong = weak.promote();
1350 
1351                 ret = server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data2, &reply2);
1352                 if (ret != NO_ERROR)
1353                     exit(EXIT_FAILURE);
1354 
1355                 if (strong == nullptr) {
1356                     reply->setError(1);
1357                 }
1358                 return NO_ERROR;
1359             }
1360             case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1361                 alarm(10);
1362                 return NO_ERROR;
1363             case BINDER_LIB_TEST_EXIT_TRANSACTION:
1364                 while (wait(nullptr) != -1 || errno != ECHILD)
1365                     ;
1366                 exit(EXIT_SUCCESS);
1367             case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
1368                 bool strongRef = data.readBool();
1369                 sp<IBinder> binder = new BBinder();
1370                 if (strongRef) {
1371                     reply->writeStrongBinder(binder);
1372                 } else {
1373                     reply->writeWeakBinder(binder);
1374                 }
1375                 return NO_ERROR;
1376             }
1377             case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1378                 data.enforceInterface(binderLibTestServiceName);
1379                 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
1380                 return NO_ERROR;
1381             }
1382             case BINDER_LIB_TEST_ECHO_VECTOR: {
1383                 std::vector<uint64_t> vector;
1384                 auto err = data.readUint64Vector(&vector);
1385                 if (err != NO_ERROR)
1386                     return err;
1387                 reply->writeUint64Vector(vector);
1388                 return NO_ERROR;
1389             }
1390             default:
1391                 return UNKNOWN_TRANSACTION;
1392             };
1393         }
1394     private:
1395         int32_t m_id;
1396         int32_t m_nextServerId;
1397         pthread_mutex_t m_serverWaitMutex;
1398         pthread_cond_t m_serverWaitCond;
1399         bool m_serverStartRequested;
1400         sp<IBinder> m_serverStarted;
1401         sp<IBinder> m_strongRef;
1402         bool m_callbackPending;
1403         sp<IBinder> m_callback;
1404 };
1405 
run_server(int index,int readypipefd,bool usePoll)1406 int run_server(int index, int readypipefd, bool usePoll)
1407 {
1408     binderLibTestServiceName += String16(binderserversuffix);
1409 
1410     status_t ret;
1411     sp<IServiceManager> sm = defaultServiceManager();
1412     BinderLibTestService* testServicePtr;
1413     {
1414         sp<BinderLibTestService> testService = new BinderLibTestService(index);
1415         /*
1416          * We need this below, but can't hold a sp<> because it prevents the
1417          * node from being cleaned up automatically. It's safe in this case
1418          * because of how the tests are written.
1419          */
1420         testServicePtr = testService.get();
1421 
1422         if (index == 0) {
1423             ret = sm->addService(binderLibTestServiceName, testService);
1424         } else {
1425             sp<IBinder> server = sm->getService(binderLibTestServiceName);
1426             Parcel data, reply;
1427             data.writeInt32(index);
1428             data.writeStrongBinder(testService);
1429 
1430             ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1431         }
1432     }
1433     write(readypipefd, &ret, sizeof(ret));
1434     close(readypipefd);
1435     //printf("%s: ret %d\n", __func__, ret);
1436     if (ret)
1437         return 1;
1438     //printf("%s: joinThreadPool\n", __func__);
1439     if (usePoll) {
1440         int fd;
1441         struct epoll_event ev;
1442         int epoll_fd;
1443         IPCThreadState::self()->setupPolling(&fd);
1444         if (fd < 0) {
1445             return 1;
1446         }
1447         IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1448 
1449         epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1450         if (epoll_fd == -1) {
1451             return 1;
1452         }
1453 
1454         ev.events = EPOLLIN;
1455         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1456             return 1;
1457         }
1458 
1459         while (1) {
1460              /*
1461               * We simulate a single-threaded process using the binder poll
1462               * interface; besides handling binder commands, it can also
1463               * issue outgoing transactions, by storing a callback in
1464               * m_callback and setting m_callbackPending.
1465               *
1466               * processPendingCall() will then issue that transaction.
1467               */
1468              struct epoll_event events[1];
1469              int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1470              if (numEvents < 0) {
1471                  if (errno == EINTR) {
1472                      continue;
1473                  }
1474                  return 1;
1475              }
1476              if (numEvents > 0) {
1477                  IPCThreadState::self()->handlePolledCommands();
1478                  IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
1479                  testServicePtr->processPendingCall();
1480              }
1481         }
1482     } else {
1483         ProcessState::self()->startThreadPool();
1484         IPCThreadState::self()->joinThreadPool();
1485     }
1486     //printf("%s: joinThreadPool returned\n", __func__);
1487     return 1; /* joinThreadPool should not return */
1488 }
1489 
main(int argc,char ** argv)1490 int main(int argc, char **argv) {
1491     int ret;
1492 
1493     if (argc == 4 && !strcmp(argv[1], "--servername")) {
1494         binderservername = argv[2];
1495     } else {
1496         binderservername = argv[0];
1497     }
1498 
1499     if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
1500         binderserversuffix = argv[5];
1501         return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
1502     }
1503     binderserversuffix = new char[16];
1504     snprintf(binderserversuffix, 16, "%d", getpid());
1505     binderLibTestServiceName += String16(binderserversuffix);
1506 
1507     ::testing::InitGoogleTest(&argc, argv);
1508     binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
1509     ProcessState::self()->startThreadPool();
1510     return RUN_ALL_TESTS();
1511 }
1512