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 <poll.h>
19 #include <pthread.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22
23 #include <chrono>
24 #include <fstream>
25 #include <thread>
26
27 #include <gmock/gmock.h>
28 #include <gtest/gtest.h>
29
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32 #include <android-base/result-gmock.h>
33 #include <binder/Binder.h>
34 #include <binder/BpBinder.h>
35 #include <binder/Functional.h>
36 #include <binder/IBinder.h>
37 #include <binder/IPCThreadState.h>
38 #include <binder/IServiceManager.h>
39 #include <binder/RpcServer.h>
40 #include <binder/RpcSession.h>
41 #include <binder/Status.h>
42 #include <binder/unique_fd.h>
43 #include <input/BlockingQueue.h>
44 #include <processgroup/processgroup.h>
45 #include <utils/Flattenable.h>
46 #include <utils/SystemClock.h>
47
48 #include <linux/sched.h>
49 #include <sys/epoll.h>
50 #include <sys/mman.h>
51 #include <sys/prctl.h>
52 #include <sys/socket.h>
53 #include <sys/un.h>
54
55 #include "../Utils.h"
56 #include "../binder_module.h"
57
58 using namespace android;
59 using namespace android::binder::impl;
60 using namespace std::string_literals;
61 using namespace std::chrono_literals;
62 using android::base::testing::HasValue;
63 using android::binder::Status;
64 using android::binder::unique_fd;
65 using std::chrono_literals::operator""ms;
66 using testing::ExplainMatchResult;
67 using testing::Matcher;
68 using testing::Not;
69 using testing::WithParamInterface;
70
71 // e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
72 MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
73 *result_listener << statusToString(arg);
74 return expected == arg;
75 }
76
IsPageAligned(void * buf)77 static ::testing::AssertionResult IsPageAligned(void *buf) {
78 if (((unsigned long)buf & ((unsigned long)getpagesize() - 1)) == 0)
79 return ::testing::AssertionSuccess();
80 else
81 return ::testing::AssertionFailure() << buf << " is not page aligned";
82 }
83
84 static testing::Environment* binder_env;
85 static char *binderservername;
86 static char *binderserversuffix;
87 static char binderserverarg[] = "--binderserver";
88
89 static constexpr int kSchedPolicy = SCHED_RR;
90 static constexpr int kSchedPriority = 7;
91 static constexpr int kSchedPriorityMore = 8;
92 static constexpr int kKernelThreads = 17; // anything different than the default
93
94 static String16 binderLibTestServiceName = String16("test.binderLib");
95
96 enum BinderLibTestTranscationCode {
97 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
98 BINDER_LIB_TEST_REGISTER_SERVER,
99 BINDER_LIB_TEST_ADD_SERVER,
100 BINDER_LIB_TEST_ADD_POLL_SERVER,
101 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
102 BINDER_LIB_TEST_CALL_BACK,
103 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
104 BINDER_LIB_TEST_DELAYED_CALL_BACK,
105 BINDER_LIB_TEST_NOP_CALL_BACK,
106 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
107 BINDER_LIB_TEST_GET_ID_TRANSACTION,
108 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
109 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
110 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
111 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
112 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
113 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
114 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
115 BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION,
116 BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION,
117 BINDER_LIB_TEST_EXIT_TRANSACTION,
118 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
119 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
120 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
121 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
122 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
123 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
124 BINDER_LIB_TEST_GETPID,
125 BINDER_LIB_TEST_GETUID,
126 BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE,
127 BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS,
128 BINDER_LIB_TEST_ECHO_VECTOR,
129 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
130 BINDER_LIB_TEST_REJECT_OBJECTS,
131 BINDER_LIB_TEST_CAN_GET_SID,
132 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
133 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
134 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
135 BINDER_LIB_TEST_LOCK_UNLOCK,
136 BINDER_LIB_TEST_PROCESS_LOCK,
137 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
138 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
139 };
140
start_server_process(int arg2,bool usePoll=false)141 pid_t start_server_process(int arg2, bool usePoll = false)
142 {
143 int ret;
144 pid_t pid;
145 status_t status;
146 int pipefd[2];
147 char stri[16];
148 char strpipefd1[16];
149 char usepoll[2];
150 char *childargv[] = {
151 binderservername,
152 binderserverarg,
153 stri,
154 strpipefd1,
155 usepoll,
156 binderserversuffix,
157 nullptr
158 };
159
160 ret = pipe(pipefd);
161 if (ret < 0)
162 return ret;
163
164 snprintf(stri, sizeof(stri), "%d", arg2);
165 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
166 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
167
168 pid = fork();
169 if (pid == -1)
170 return pid;
171 if (pid == 0) {
172 prctl(PR_SET_PDEATHSIG, SIGHUP);
173 close(pipefd[0]);
174 execv(binderservername, childargv);
175 status = -errno;
176 write(pipefd[1], &status, sizeof(status));
177 fprintf(stderr, "execv failed, %s\n", strerror(errno));
178 _exit(EXIT_FAILURE);
179 }
180 close(pipefd[1]);
181 ret = read(pipefd[0], &status, sizeof(status));
182 //printf("pipe read returned %d, status %d\n", ret, status);
183 close(pipefd[0]);
184 if (ret == sizeof(status)) {
185 ret = status;
186 } else {
187 kill(pid, SIGKILL);
188 if (ret >= 0) {
189 ret = NO_INIT;
190 }
191 }
192 if (ret < 0) {
193 wait(nullptr);
194 return ret;
195 }
196 return pid;
197 }
198
GetId(sp<IBinder> service)199 android::base::Result<int32_t> GetId(sp<IBinder> service) {
200 using android::base::Error;
201 Parcel data, reply;
202 data.markForBinder(service);
203 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
204 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
205 if (status != OK)
206 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
207 int32_t result = 0;
208 status = reply.readInt32(&result);
209 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
210 return result;
211 }
212
213 class BinderLibTestEnv : public ::testing::Environment {
214 public:
BinderLibTestEnv()215 BinderLibTestEnv() {}
getServer(void)216 sp<IBinder> getServer(void) {
217 return m_server;
218 }
219
220 private:
SetUp()221 virtual void SetUp() {
222 m_serverpid = start_server_process(0);
223 //printf("m_serverpid %d\n", m_serverpid);
224 ASSERT_GT(m_serverpid, 0);
225
226 sp<IServiceManager> sm = defaultServiceManager();
227 // disable caching during addService.
228 sm->enableAddServiceCache(false);
229 //printf("%s: pid %d, get service\n", __func__, m_pid);
230 LIBBINDER_IGNORE("-Wdeprecated-declarations")
231 m_server = sm->getService(binderLibTestServiceName);
232 LIBBINDER_IGNORE_END()
233 ASSERT_TRUE(m_server != nullptr);
234 //printf("%s: pid %d, get service done\n", __func__, m_pid);
235 }
TearDown()236 virtual void TearDown() {
237 status_t ret;
238 Parcel data, reply;
239 int exitStatus;
240 pid_t pid;
241
242 //printf("%s: pid %d\n", __func__, m_pid);
243 if (m_server != nullptr) {
244 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
245 EXPECT_EQ(0, ret);
246 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
247 EXPECT_EQ(0, ret);
248 }
249 if (m_serverpid > 0) {
250 //printf("wait for %d\n", m_pids[i]);
251 pid = wait(&exitStatus);
252 EXPECT_EQ(m_serverpid, pid);
253 EXPECT_TRUE(WIFEXITED(exitStatus));
254 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
255 }
256 }
257
258 pid_t m_serverpid;
259 sp<IBinder> m_server;
260 };
261
262 class TestFrozenStateChangeCallback : public IBinder::FrozenStateChangeCallback {
263 public:
264 BlockingQueue<std::pair<const wp<IBinder>, State>> events;
265
onStateChanged(const wp<IBinder> & who,State state)266 virtual void onStateChanged(const wp<IBinder>& who, State state) {
267 events.push(std::make_pair(who, state));
268 }
269
ensureFrozenEventReceived()270 void ensureFrozenEventReceived() {
271 auto event = events.popWithTimeout(500ms);
272 ASSERT_TRUE(event.has_value());
273 EXPECT_EQ(State::FROZEN, event->second); // isFrozen should be true
274 EXPECT_EQ(0u, events.size());
275 }
276
ensureUnfrozenEventReceived()277 void ensureUnfrozenEventReceived() {
278 auto event = events.popWithTimeout(500ms);
279 ASSERT_TRUE(event.has_value());
280 EXPECT_EQ(State::UNFROZEN, event->second); // isFrozen should be false
281 EXPECT_EQ(0u, events.size());
282 }
283
getAllAndClear()284 std::vector<bool> getAllAndClear() {
285 std::vector<bool> results;
286 while (true) {
287 auto event = events.popWithTimeout(0ms);
288 if (!event.has_value()) {
289 break;
290 }
291 results.push_back(event->second == State::FROZEN);
292 }
293 return results;
294 }
295
296 sp<IBinder> binder;
297 };
298
299 class BinderLibTest : public ::testing::Test {
300 public:
SetUp()301 virtual void SetUp() {
302 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
303 IPCThreadState::self()->restoreCallingWorkSource(0);
304 sp<IServiceManager> sm = defaultServiceManager();
305 // disable caching during addService.
306 sm->enableAddServiceCache(false);
307 }
TearDown()308 virtual void TearDown() {
309 }
310 protected:
addServerEtc(int32_t * idPtr,int code)311 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
312 {
313 int32_t id;
314 Parcel data, reply;
315
316 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
317
318 sp<IBinder> binder = reply.readStrongBinder();
319 EXPECT_NE(nullptr, binder);
320 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
321 if (idPtr)
322 *idPtr = id;
323 return binder;
324 }
325
addServer(int32_t * idPtr=nullptr)326 sp<IBinder> addServer(int32_t *idPtr = nullptr)
327 {
328 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
329 }
330
addPollServer(int32_t * idPtr=nullptr)331 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
332 {
333 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
334 }
335
waitForReadData(int fd,int timeout_ms)336 void waitForReadData(int fd, int timeout_ms) {
337 int ret;
338 pollfd pfd = pollfd();
339
340 pfd.fd = fd;
341 pfd.events = POLLIN;
342 ret = poll(&pfd, 1, timeout_ms);
343 EXPECT_EQ(1, ret);
344 }
345
checkFreezeSupport()346 bool checkFreezeSupport() {
347 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
348 // Pass test on devices where the cgroup v2 freezer is not supported
349 if (freezer_file.fail()) {
350 return false;
351 }
352 return IPCThreadState::self()->freeze(getpid(), false, 0) == NO_ERROR;
353 }
354
checkFreezeAndNotificationSupport()355 bool checkFreezeAndNotificationSupport() {
356 if (!checkFreezeSupport()) {
357 return false;
358 }
359 return ProcessState::isDriverFeatureEnabled(
360 ProcessState::DriverFeature::FREEZE_NOTIFICATION);
361 }
362
getBinderPid(int32_t * pid,sp<IBinder> server)363 bool getBinderPid(int32_t* pid, sp<IBinder> server) {
364 Parcel data, replypid;
365 if (server->transact(BINDER_LIB_TEST_GETPID, data, &replypid) != NO_ERROR) {
366 ALOGE("BINDER_LIB_TEST_GETPID failed");
367 return false;
368 }
369 *pid = replypid.readInt32();
370 if (*pid <= 0) {
371 ALOGE("pid should be greater than zero");
372 return false;
373 }
374 return true;
375 }
376
freezeProcess(int32_t pid)377 void freezeProcess(int32_t pid) {
378 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
379 }
380
unfreezeProcess(int32_t pid)381 void unfreezeProcess(int32_t pid) {
382 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
383 }
384
removeCallbackAndValidateNoEvent(sp<IBinder> binder,sp<TestFrozenStateChangeCallback> callback)385 void removeCallbackAndValidateNoEvent(sp<IBinder> binder,
386 sp<TestFrozenStateChangeCallback> callback) {
387 EXPECT_THAT(binder->removeFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
388 EXPECT_EQ(0u, callback->events.size());
389 }
390
391 sp<IBinder> m_server;
392 };
393
394 class BinderLibTestBundle : public Parcel
395 {
396 public:
BinderLibTestBundle(void)397 BinderLibTestBundle(void) {}
BinderLibTestBundle(const Parcel * source)398 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
399 int32_t mark;
400 int32_t bundleLen;
401 size_t pos;
402
403 if (source->readInt32(&mark))
404 return;
405 if (mark != MARK_START)
406 return;
407 if (source->readInt32(&bundleLen))
408 return;
409 pos = source->dataPosition();
410 if (Parcel::appendFrom(source, pos, bundleLen))
411 return;
412 source->setDataPosition(pos + bundleLen);
413 if (source->readInt32(&mark))
414 return;
415 if (mark != MARK_END)
416 return;
417 m_isValid = true;
418 setDataPosition(0);
419 }
appendTo(Parcel * dest)420 void appendTo(Parcel *dest) {
421 dest->writeInt32(MARK_START);
422 dest->writeInt32(dataSize());
423 dest->appendFrom(this, 0, dataSize());
424 dest->writeInt32(MARK_END);
425 };
isValid(void)426 bool isValid(void) {
427 return m_isValid;
428 }
429 private:
430 enum {
431 MARK_START = B_PACK_CHARS('B','T','B','S'),
432 MARK_END = B_PACK_CHARS('B','T','B','E'),
433 };
434 bool m_isValid;
435 };
436
437 class BinderLibTestEvent
438 {
439 public:
BinderLibTestEvent(void)440 BinderLibTestEvent(void)
441 : m_eventTriggered(false)
442 {
443 pthread_mutex_init(&m_waitMutex, nullptr);
444 pthread_cond_init(&m_waitCond, nullptr);
445 }
waitEvent(int timeout_s)446 int waitEvent(int timeout_s)
447 {
448 int ret;
449 pthread_mutex_lock(&m_waitMutex);
450 if (!m_eventTriggered) {
451 struct timespec ts;
452 clock_gettime(CLOCK_REALTIME, &ts);
453 ts.tv_sec += timeout_s;
454 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
455 }
456 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
457 pthread_mutex_unlock(&m_waitMutex);
458 return ret;
459 }
getTriggeringThread()460 pthread_t getTriggeringThread()
461 {
462 return m_triggeringThread;
463 }
464 protected:
triggerEvent(void)465 void triggerEvent(void) {
466 pthread_mutex_lock(&m_waitMutex);
467 pthread_cond_signal(&m_waitCond);
468 m_eventTriggered = true;
469 m_triggeringThread = pthread_self();
470 pthread_mutex_unlock(&m_waitMutex);
471 };
472 private:
473 pthread_mutex_t m_waitMutex;
474 pthread_cond_t m_waitCond;
475 bool m_eventTriggered;
476 pthread_t m_triggeringThread;
477 };
478
479 class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
480 {
481 public:
BinderLibTestCallBack()482 BinderLibTestCallBack()
483 : m_result(NOT_ENOUGH_DATA)
484 , m_prev_end(nullptr)
485 {
486 }
getResult(void)487 status_t getResult(void)
488 {
489 return m_result;
490 }
491
492 private:
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags=0)493 virtual status_t onTransact(uint32_t code,
494 const Parcel& data, Parcel* reply,
495 uint32_t flags = 0)
496 {
497 (void)reply;
498 (void)flags;
499 switch(code) {
500 case BINDER_LIB_TEST_CALL_BACK: {
501 status_t status = data.readInt32(&m_result);
502 if (status != NO_ERROR) {
503 m_result = status;
504 }
505 triggerEvent();
506 return NO_ERROR;
507 }
508 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
509 sp<IBinder> server;
510 int ret;
511 const uint8_t *buf = data.data();
512 size_t size = data.dataSize();
513 if (m_prev_end) {
514 /* 64-bit kernel needs at most 8 bytes to align buffer end */
515 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
516 } else {
517 EXPECT_TRUE(IsPageAligned((void *)buf));
518 }
519
520 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
521
522 if (size > 0) {
523 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
524 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
525 data, reply);
526 EXPECT_EQ(NO_ERROR, ret);
527 }
528 return NO_ERROR;
529 }
530 default:
531 return UNKNOWN_TRANSACTION;
532 }
533 }
534
535 status_t m_result;
536 const uint8_t *m_prev_end;
537 };
538
539 class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
540 {
541 private:
binderDied(const wp<IBinder> & who)542 virtual void binderDied(const wp<IBinder>& who) {
543 (void)who;
544 triggerEvent();
545 };
546 };
547
countFds()548 ssize_t countFds() {
549 return std::distance(std::filesystem::directory_iterator("/proc/self/fd"),
550 std::filesystem::directory_iterator{});
551 }
552
553 struct FdLeakDetector {
554 int startCount;
555
FdLeakDetectorFdLeakDetector556 FdLeakDetector() {
557 // This log statement is load bearing. We have to log something before
558 // counting FDs to make sure the logging system is initialized, otherwise
559 // the sockets it opens will look like a leak.
560 ALOGW("FdLeakDetector counting FDs.");
561 startCount = countFds();
562 }
~FdLeakDetectorFdLeakDetector563 ~FdLeakDetector() {
564 int endCount = countFds();
565 if (startCount != endCount) {
566 ADD_FAILURE() << "fd count changed (" << startCount << " -> " << endCount
567 << ") fd leak?";
568 }
569 }
570 };
571
TEST_F(BinderLibTest,CannotUseBinderAfterFork)572 TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
573 // EXPECT_DEATH works by forking the process
574 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
575 }
576
TEST_F(BinderLibTest,AddManagerToManager)577 TEST_F(BinderLibTest, AddManagerToManager) {
578 sp<IServiceManager> sm = defaultServiceManager();
579 sp<IBinder> binder = IInterface::asBinder(sm);
580 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
581 }
582
TEST_F(BinderLibTest,RegisterForNotificationsFailure)583 TEST_F(BinderLibTest, RegisterForNotificationsFailure) {
584 auto sm = defaultServiceManager();
585 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
586 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
587 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
588 virtual ~LocalRegistrationCallbackImpl() {}
589 };
590 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
591
592 EXPECT_EQ(BAD_VALUE, sm->registerForNotifications(String16("ValidName"), nullptr));
593 EXPECT_EQ(UNKNOWN_ERROR, sm->registerForNotifications(String16("InvalidName!$"), cb));
594 }
595
TEST_F(BinderLibTest,UnregisterForNotificationsFailure)596 TEST_F(BinderLibTest, UnregisterForNotificationsFailure) {
597 auto sm = defaultServiceManager();
598 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
599 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
600 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
601 virtual ~LocalRegistrationCallbackImpl() {}
602 };
603 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
604
605 EXPECT_EQ(OK, sm->registerForNotifications(String16("ValidName"), cb));
606
607 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("ValidName"), nullptr));
608 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("AnotherValidName"), cb));
609 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("InvalidName!!!"), cb));
610 }
611
TEST_F(BinderLibTest,WasParceled)612 TEST_F(BinderLibTest, WasParceled) {
613 auto binder = sp<BBinder>::make();
614 EXPECT_FALSE(binder->wasParceled());
615 Parcel data;
616 data.writeStrongBinder(binder);
617 EXPECT_TRUE(binder->wasParceled());
618 }
619
TEST_F(BinderLibTest,NopTransaction)620 TEST_F(BinderLibTest, NopTransaction) {
621 Parcel data, reply;
622 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
623 StatusEq(NO_ERROR));
624 }
625
TEST_F(BinderLibTest,NopTransactionOneway)626 TEST_F(BinderLibTest, NopTransactionOneway) {
627 Parcel data, reply;
628 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
629 StatusEq(NO_ERROR));
630 }
631
TEST_F(BinderLibTest,NopTransactionClear)632 TEST_F(BinderLibTest, NopTransactionClear) {
633 Parcel data, reply;
634 // make sure it accepts the transaction flag
635 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
636 StatusEq(NO_ERROR));
637 }
638
TEST_F(BinderLibTest,Freeze)639 TEST_F(BinderLibTest, Freeze) {
640 if (!checkFreezeSupport()) {
641 GTEST_SKIP() << "Skipping test for kernels that do not support proceess freezing";
642 return;
643 }
644 Parcel data, reply, replypid;
645 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
646 int32_t pid = replypid.readInt32();
647 for (int i = 0; i < 10; i++) {
648 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
649 }
650
651 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
652 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
653
654 // b/268232063 - succeeds ~0.08% of the time
655 {
656 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
657 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
658 }
659
660 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
661 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
662
663 uint32_t sync_received, async_received;
664
665 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
666 &async_received));
667
668 EXPECT_EQ(sync_received, 1u);
669 EXPECT_EQ(async_received, 0u);
670
671 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
672 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
673 }
674
TEST_F(BinderLibTest,SetError)675 TEST_F(BinderLibTest, SetError) {
676 int32_t testValue[] = { 0, -123, 123 };
677 for (size_t i = 0; i < countof(testValue); i++) {
678 Parcel data, reply;
679 data.writeInt32(testValue[i]);
680 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
681 StatusEq(testValue[i]));
682 }
683 }
684
TEST_F(BinderLibTest,GetId)685 TEST_F(BinderLibTest, GetId) {
686 EXPECT_THAT(GetId(m_server), HasValue(0));
687 }
688
TEST_F(BinderLibTest,PtrSize)689 TEST_F(BinderLibTest, PtrSize) {
690 int32_t ptrsize;
691 Parcel data, reply;
692 sp<IBinder> server = addServer();
693 ASSERT_TRUE(server != nullptr);
694 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
695 StatusEq(NO_ERROR));
696 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
697 RecordProperty("TestPtrSize", sizeof(void *));
698 RecordProperty("ServerPtrSize", sizeof(void *));
699 }
700
TEST_F(BinderLibTest,IndirectGetId2)701 TEST_F(BinderLibTest, IndirectGetId2)
702 {
703 int32_t id;
704 int32_t count;
705 Parcel data, reply;
706 int32_t serverId[3];
707
708 data.writeInt32(countof(serverId));
709 for (size_t i = 0; i < countof(serverId); i++) {
710 sp<IBinder> server;
711 BinderLibTestBundle datai;
712
713 server = addServer(&serverId[i]);
714 ASSERT_TRUE(server != nullptr);
715 data.writeStrongBinder(server);
716 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
717 datai.appendTo(&data);
718 }
719
720 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
721 StatusEq(NO_ERROR));
722
723 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
724 EXPECT_EQ(0, id);
725
726 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
727 EXPECT_EQ(countof(serverId), (size_t)count);
728
729 for (size_t i = 0; i < (size_t)count; i++) {
730 BinderLibTestBundle replyi(&reply);
731 EXPECT_TRUE(replyi.isValid());
732 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
733 EXPECT_EQ(serverId[i], id);
734 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
735 }
736
737 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
738 }
739
TEST_F(BinderLibTest,IndirectGetId3)740 TEST_F(BinderLibTest, IndirectGetId3)
741 {
742 int32_t id;
743 int32_t count;
744 Parcel data, reply;
745 int32_t serverId[3];
746
747 data.writeInt32(countof(serverId));
748 for (size_t i = 0; i < countof(serverId); i++) {
749 sp<IBinder> server;
750 BinderLibTestBundle datai;
751 BinderLibTestBundle datai2;
752
753 server = addServer(&serverId[i]);
754 ASSERT_TRUE(server != nullptr);
755 data.writeStrongBinder(server);
756 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
757
758 datai.writeInt32(1);
759 datai.writeStrongBinder(m_server);
760 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
761 datai2.appendTo(&datai);
762
763 datai.appendTo(&data);
764 }
765
766 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
767 StatusEq(NO_ERROR));
768
769 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
770 EXPECT_EQ(0, id);
771
772 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
773 EXPECT_EQ(countof(serverId), (size_t)count);
774
775 for (size_t i = 0; i < (size_t)count; i++) {
776 int32_t counti;
777
778 BinderLibTestBundle replyi(&reply);
779 EXPECT_TRUE(replyi.isValid());
780 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
781 EXPECT_EQ(serverId[i], id);
782
783 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
784 EXPECT_EQ(1, counti);
785
786 BinderLibTestBundle replyi2(&replyi);
787 EXPECT_TRUE(replyi2.isValid());
788 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
789 EXPECT_EQ(0, id);
790 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
791
792 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
793 }
794
795 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
796 }
797
TEST_F(BinderLibTest,CallBack)798 TEST_F(BinderLibTest, CallBack)
799 {
800 Parcel data, reply;
801 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
802 data.writeStrongBinder(callBack);
803 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
804 StatusEq(NO_ERROR));
805 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
806 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
807 }
808
TEST_F(BinderLibTest,BinderCallContextGuard)809 TEST_F(BinderLibTest, BinderCallContextGuard) {
810 sp<IBinder> binder = addServer();
811 Parcel data, reply;
812 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
813 StatusEq(DEAD_OBJECT));
814 }
815
TEST_F(BinderLibTest,AddServer)816 TEST_F(BinderLibTest, AddServer)
817 {
818 sp<IBinder> server = addServer();
819 ASSERT_TRUE(server != nullptr);
820 }
821
TEST_F(BinderLibTest,DeathNotificationStrongRef)822 TEST_F(BinderLibTest, DeathNotificationStrongRef)
823 {
824 sp<IBinder> sbinder;
825
826 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
827
828 {
829 sp<IBinder> binder = addServer();
830 ASSERT_TRUE(binder != nullptr);
831 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
832 sbinder = binder;
833 }
834 {
835 Parcel data, reply;
836 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
837 StatusEq(OK));
838 }
839 IPCThreadState::self()->flushCommands();
840 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
841 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
842 }
843
TEST_F(BinderLibTest,DeathNotificationMultiple)844 TEST_F(BinderLibTest, DeathNotificationMultiple)
845 {
846 status_t ret;
847 const int clientcount = 2;
848 sp<IBinder> target;
849 sp<IBinder> linkedclient[clientcount];
850 sp<BinderLibTestCallBack> callBack[clientcount];
851 sp<IBinder> passiveclient[clientcount];
852
853 target = addServer();
854 ASSERT_TRUE(target != nullptr);
855 for (int i = 0; i < clientcount; i++) {
856 {
857 Parcel data, reply;
858
859 linkedclient[i] = addServer();
860 ASSERT_TRUE(linkedclient[i] != nullptr);
861 callBack[i] = new BinderLibTestCallBack();
862 data.writeStrongBinder(target);
863 data.writeStrongBinder(callBack[i]);
864 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
865 &reply, TF_ONE_WAY),
866 StatusEq(NO_ERROR));
867 }
868 {
869 Parcel data, reply;
870
871 passiveclient[i] = addServer();
872 ASSERT_TRUE(passiveclient[i] != nullptr);
873 data.writeStrongBinder(target);
874 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
875 &reply, TF_ONE_WAY),
876 StatusEq(NO_ERROR));
877 }
878 }
879 {
880 Parcel data, reply;
881 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
882 EXPECT_EQ(0, ret);
883 }
884
885 for (int i = 0; i < clientcount; i++) {
886 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
887 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
888 }
889 }
890
TEST_F(BinderLibTest,DeathNotificationThread)891 TEST_F(BinderLibTest, DeathNotificationThread)
892 {
893 status_t ret;
894 sp<BinderLibTestCallBack> callback;
895 sp<IBinder> target = addServer();
896 ASSERT_TRUE(target != nullptr);
897 sp<IBinder> client = addServer();
898 ASSERT_TRUE(client != nullptr);
899
900 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
901
902 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
903
904 {
905 Parcel data, reply;
906 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
907 EXPECT_EQ(0, ret);
908 }
909
910 /* Make sure it's dead */
911 testDeathRecipient->waitEvent(5);
912
913 /* Now, pass the ref to another process and ask that process to
914 * call linkToDeath() on it, and wait for a response. This tests
915 * two things:
916 * 1) You still get death notifications when calling linkToDeath()
917 * on a ref that is already dead when it was passed to you.
918 * 2) That death notifications are not directly pushed to the thread
919 * registering them, but to the threadpool (proc workqueue) instead.
920 *
921 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
922 * is blocked on a condition variable waiting for the death notification to be
923 * called; therefore, that thread is not available for handling proc work.
924 * So, if the death notification was pushed to the thread workqueue, the callback
925 * would never be called, and the test would timeout and fail.
926 *
927 * Note that we can't do this part of the test from this thread itself, because
928 * the binder driver would only push death notifications to the thread if
929 * it is a looper thread, which this thread is not.
930 *
931 * See b/23525545 for details.
932 */
933 {
934 Parcel data, reply;
935
936 callback = new BinderLibTestCallBack();
937 data.writeStrongBinder(target);
938 data.writeStrongBinder(callback);
939 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
940 TF_ONE_WAY),
941 StatusEq(NO_ERROR));
942 }
943
944 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
945 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
946 }
947
TEST_F(BinderLibTest,ReturnErrorIfKernelDoesNotSupportFreezeNotification)948 TEST_F(BinderLibTest, ReturnErrorIfKernelDoesNotSupportFreezeNotification) {
949 if (ProcessState::isDriverFeatureEnabled(ProcessState::DriverFeature::FREEZE_NOTIFICATION)) {
950 GTEST_SKIP() << "Skipping test for kernels that support FREEZE_NOTIFICATION";
951 return;
952 }
953 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
954 sp<IBinder> binder = addServer();
955 ASSERT_NE(nullptr, binder);
956 ASSERT_EQ(nullptr, binder->localBinder());
957 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(INVALID_OPERATION));
958 }
959
TEST_F(BinderLibTest,FrozenStateChangeNotificatiion)960 TEST_F(BinderLibTest, FrozenStateChangeNotificatiion) {
961 if (!checkFreezeAndNotificationSupport()) {
962 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
963 return;
964 }
965 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
966 sp<IBinder> binder = addServer();
967 ASSERT_NE(nullptr, binder);
968 int32_t pid;
969 ASSERT_TRUE(getBinderPid(&pid, binder));
970
971 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
972 // Expect current state (unfrozen) to be delivered immediately.
973 callback->ensureUnfrozenEventReceived();
974 // Check that the process hasn't died otherwise there's a risk of freezing
975 // the wrong process.
976 EXPECT_EQ(OK, binder->pingBinder());
977 freezeProcess(pid);
978 callback->ensureFrozenEventReceived();
979 unfreezeProcess(pid);
980 callback->ensureUnfrozenEventReceived();
981 removeCallbackAndValidateNoEvent(binder, callback);
982 }
983
TEST_F(BinderLibTest,AddFrozenCallbackWhenFrozen)984 TEST_F(BinderLibTest, AddFrozenCallbackWhenFrozen) {
985 if (!checkFreezeAndNotificationSupport()) {
986 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
987 return;
988 }
989 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
990 sp<IBinder> binder = addServer();
991 ASSERT_NE(nullptr, binder);
992 int32_t pid;
993 ASSERT_TRUE(getBinderPid(&pid, binder));
994
995 // Check that the process hasn't died otherwise there's a risk of freezing
996 // the wrong process.
997 EXPECT_EQ(OK, binder->pingBinder());
998 freezeProcess(pid);
999 // Add the callback while the target process is frozen.
1000 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1001 callback->ensureFrozenEventReceived();
1002 unfreezeProcess(pid);
1003 callback->ensureUnfrozenEventReceived();
1004 removeCallbackAndValidateNoEvent(binder, callback);
1005
1006 // Check that the process hasn't died otherwise there's a risk of freezing
1007 // the wrong process.
1008 EXPECT_EQ(OK, binder->pingBinder());
1009 freezeProcess(pid);
1010 unfreezeProcess(pid);
1011 // Make sure no callback happens since the listener has been removed.
1012 EXPECT_EQ(0u, callback->events.size());
1013 }
1014
TEST_F(BinderLibTest,NoFrozenNotificationAfterCallbackRemoval)1015 TEST_F(BinderLibTest, NoFrozenNotificationAfterCallbackRemoval) {
1016 if (!checkFreezeAndNotificationSupport()) {
1017 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1018 return;
1019 }
1020 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
1021 sp<IBinder> binder = addServer();
1022 ASSERT_NE(nullptr, binder);
1023 int32_t pid;
1024 ASSERT_TRUE(getBinderPid(&pid, binder));
1025
1026 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1027 callback->ensureUnfrozenEventReceived();
1028 removeCallbackAndValidateNoEvent(binder, callback);
1029
1030 // Make sure no callback happens after the listener is removed.
1031 freezeProcess(pid);
1032 unfreezeProcess(pid);
1033 EXPECT_EQ(0u, callback->events.size());
1034 }
1035
TEST_F(BinderLibTest,MultipleFrozenStateChangeCallbacks)1036 TEST_F(BinderLibTest, MultipleFrozenStateChangeCallbacks) {
1037 if (!checkFreezeAndNotificationSupport()) {
1038 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1039 return;
1040 }
1041 sp<TestFrozenStateChangeCallback> callback1 = sp<TestFrozenStateChangeCallback>::make();
1042 sp<TestFrozenStateChangeCallback> callback2 = sp<TestFrozenStateChangeCallback>::make();
1043 sp<IBinder> binder = addServer();
1044 ASSERT_NE(nullptr, binder);
1045 int32_t pid;
1046 ASSERT_TRUE(getBinderPid(&pid, binder));
1047
1048 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback1), StatusEq(NO_ERROR));
1049 // Expect current state (unfrozen) to be delivered immediately.
1050 callback1->ensureUnfrozenEventReceived();
1051
1052 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback2), StatusEq(NO_ERROR));
1053 // Expect current state (unfrozen) to be delivered immediately.
1054 callback2->ensureUnfrozenEventReceived();
1055
1056 freezeProcess(pid);
1057 callback1->ensureFrozenEventReceived();
1058 callback2->ensureFrozenEventReceived();
1059
1060 removeCallbackAndValidateNoEvent(binder, callback1);
1061 unfreezeProcess(pid);
1062 EXPECT_EQ(0u, callback1->events.size());
1063 callback2->ensureUnfrozenEventReceived();
1064 removeCallbackAndValidateNoEvent(binder, callback2);
1065
1066 freezeProcess(pid);
1067 EXPECT_EQ(0u, callback2->events.size());
1068 }
1069
TEST_F(BinderLibTest,RemoveThenAddFrozenStateChangeCallbacks)1070 TEST_F(BinderLibTest, RemoveThenAddFrozenStateChangeCallbacks) {
1071 if (!checkFreezeAndNotificationSupport()) {
1072 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1073 return;
1074 }
1075 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
1076 sp<IBinder> binder = addServer();
1077 ASSERT_NE(nullptr, binder);
1078 int32_t pid;
1079 ASSERT_TRUE(getBinderPid(&pid, binder));
1080
1081 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1082 // Expect current state (unfrozen) to be delivered immediately.
1083 callback->ensureUnfrozenEventReceived();
1084 removeCallbackAndValidateNoEvent(binder, callback);
1085
1086 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1087 callback->ensureUnfrozenEventReceived();
1088 }
1089
TEST_F(BinderLibTest,CoalesceFreezeCallbacksWhenListenerIsFrozen)1090 TEST_F(BinderLibTest, CoalesceFreezeCallbacksWhenListenerIsFrozen) {
1091 if (!checkFreezeAndNotificationSupport()) {
1092 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1093 return;
1094 }
1095 sp<IBinder> binder = addServer();
1096 sp<IBinder> listener = addServer();
1097 ASSERT_NE(nullptr, binder);
1098 ASSERT_NE(nullptr, listener);
1099 int32_t pid, listenerPid;
1100 ASSERT_TRUE(getBinderPid(&pid, binder));
1101 ASSERT_TRUE(getBinderPid(&listenerPid, listener));
1102
1103 // Ask the listener process to register for state change callbacks.
1104 {
1105 Parcel data, reply;
1106 data.writeStrongBinder(binder);
1107 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE, data,
1108 &reply),
1109 StatusEq(NO_ERROR));
1110 }
1111 // Freeze the listener process.
1112 freezeProcess(listenerPid);
1113 createProcessGroup(getuid(), listenerPid);
1114 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Frozen"}));
1115 // Repeatedly flip the target process between frozen and unfrozen states.
1116 for (int i = 0; i < 1000; i++) {
1117 usleep(50);
1118 unfreezeProcess(pid);
1119 usleep(50);
1120 freezeProcess(pid);
1121 }
1122 // Unfreeze the listener process. Now it should receive the frozen state
1123 // change notifications.
1124 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Unfrozen"}));
1125 unfreezeProcess(listenerPid);
1126 // Wait for 500ms to give the process enough time to wake up and handle
1127 // notifications.
1128 usleep(500 * 1000);
1129 {
1130 std::vector<bool> events;
1131 Parcel data, reply;
1132 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS, data, &reply),
1133 StatusEq(NO_ERROR));
1134 reply.readBoolVector(&events);
1135 // There should only be one single state change notifications delievered.
1136 ASSERT_EQ(1u, events.size());
1137 EXPECT_TRUE(events[0]);
1138 }
1139 }
1140
TEST_F(BinderLibTest,PassFile)1141 TEST_F(BinderLibTest, PassFile) {
1142 int ret;
1143 int pipefd[2];
1144 uint8_t buf[1] = { 0 };
1145 uint8_t write_value = 123;
1146
1147 ret = pipe2(pipefd, O_NONBLOCK);
1148 ASSERT_EQ(0, ret);
1149
1150 {
1151 Parcel data, reply;
1152 uint8_t writebuf[1] = { write_value };
1153
1154 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
1155
1156 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
1157
1158 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
1159
1160 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
1161 StatusEq(NO_ERROR));
1162 }
1163
1164 ret = read(pipefd[0], buf, sizeof(buf));
1165 EXPECT_EQ(sizeof(buf), (size_t)ret);
1166 EXPECT_EQ(write_value, buf[0]);
1167
1168 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
1169
1170 ret = read(pipefd[0], buf, sizeof(buf));
1171 EXPECT_EQ(0, ret);
1172
1173 close(pipefd[0]);
1174 }
1175
TEST_F(BinderLibTest,PassParcelFileDescriptor)1176 TEST_F(BinderLibTest, PassParcelFileDescriptor) {
1177 const int datasize = 123;
1178 std::vector<uint8_t> writebuf(datasize);
1179 for (size_t i = 0; i < writebuf.size(); ++i) {
1180 writebuf[i] = i;
1181 }
1182
1183 unique_fd read_end, write_end;
1184 {
1185 int pipefd[2];
1186 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
1187 read_end.reset(pipefd[0]);
1188 write_end.reset(pipefd[1]);
1189 }
1190 {
1191 Parcel data;
1192 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
1193 write_end.reset();
1194 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
1195 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
1196
1197 Parcel reply;
1198 EXPECT_EQ(NO_ERROR,
1199 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
1200 &reply));
1201 }
1202 std::vector<uint8_t> readbuf(datasize);
1203 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
1204 EXPECT_EQ(writebuf, readbuf);
1205
1206 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
1207
1208 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
1209 }
1210
TEST_F(BinderLibTest,RecvOwnedFileDescriptors)1211 TEST_F(BinderLibTest, RecvOwnedFileDescriptors) {
1212 FdLeakDetector fd_leak_detector;
1213
1214 Parcel data;
1215 Parcel reply;
1216 EXPECT_EQ(NO_ERROR,
1217 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION, data,
1218 &reply));
1219 unique_fd a, b;
1220 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1221 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1222 }
1223
1224 // Used to trigger fdsan error (b/239222407).
TEST_F(BinderLibTest,RecvOwnedFileDescriptorsAndWriteInt)1225 TEST_F(BinderLibTest, RecvOwnedFileDescriptorsAndWriteInt) {
1226 GTEST_SKIP() << "triggers fdsan false positive: b/370824489";
1227
1228 FdLeakDetector fd_leak_detector;
1229
1230 Parcel data;
1231 Parcel reply;
1232 EXPECT_EQ(NO_ERROR,
1233 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION, data,
1234 &reply));
1235 reply.setDataPosition(reply.dataSize());
1236 reply.writeInt32(0);
1237 reply.setDataPosition(0);
1238 unique_fd a, b;
1239 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1240 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1241 }
1242
1243 // Used to trigger fdsan error (b/239222407).
TEST_F(BinderLibTest,RecvOwnedFileDescriptorsAndTruncate)1244 TEST_F(BinderLibTest, RecvOwnedFileDescriptorsAndTruncate) {
1245 GTEST_SKIP() << "triggers fdsan false positive: b/370824489";
1246
1247 FdLeakDetector fd_leak_detector;
1248
1249 Parcel data;
1250 Parcel reply;
1251 EXPECT_EQ(NO_ERROR,
1252 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION, data,
1253 &reply));
1254 reply.setDataSize(reply.dataSize() - sizeof(flat_binder_object));
1255 unique_fd a, b;
1256 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1257 EXPECT_EQ(BAD_TYPE, reply.readUniqueFileDescriptor(&b));
1258 }
1259
TEST_F(BinderLibTest,RecvUnownedFileDescriptors)1260 TEST_F(BinderLibTest, RecvUnownedFileDescriptors) {
1261 FdLeakDetector fd_leak_detector;
1262
1263 Parcel data;
1264 Parcel reply;
1265 EXPECT_EQ(NO_ERROR,
1266 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION, data,
1267 &reply));
1268 unique_fd a, b;
1269 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1270 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1271 }
1272
1273 // Used to trigger fdsan error (b/239222407).
TEST_F(BinderLibTest,RecvUnownedFileDescriptorsAndWriteInt)1274 TEST_F(BinderLibTest, RecvUnownedFileDescriptorsAndWriteInt) {
1275 FdLeakDetector fd_leak_detector;
1276
1277 Parcel data;
1278 Parcel reply;
1279 EXPECT_EQ(NO_ERROR,
1280 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION, data,
1281 &reply));
1282 reply.setDataPosition(reply.dataSize());
1283 reply.writeInt32(0);
1284 reply.setDataPosition(0);
1285 unique_fd a, b;
1286 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1287 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1288 }
1289
1290 // Used to trigger fdsan error (b/239222407).
TEST_F(BinderLibTest,RecvUnownedFileDescriptorsAndTruncate)1291 TEST_F(BinderLibTest, RecvUnownedFileDescriptorsAndTruncate) {
1292 FdLeakDetector fd_leak_detector;
1293
1294 Parcel data;
1295 Parcel reply;
1296 EXPECT_EQ(NO_ERROR,
1297 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION, data,
1298 &reply));
1299 reply.setDataSize(reply.dataSize() - sizeof(flat_binder_object));
1300 unique_fd a, b;
1301 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1302 EXPECT_EQ(BAD_TYPE, reply.readUniqueFileDescriptor(&b));
1303 }
1304
TEST_F(BinderLibTest,PromoteLocal)1305 TEST_F(BinderLibTest, PromoteLocal) {
1306 sp<IBinder> strong = new BBinder();
1307 wp<IBinder> weak = strong;
1308 sp<IBinder> strong_from_weak = weak.promote();
1309 EXPECT_TRUE(strong != nullptr);
1310 EXPECT_EQ(strong, strong_from_weak);
1311 strong = nullptr;
1312 strong_from_weak = nullptr;
1313 strong_from_weak = weak.promote();
1314 EXPECT_TRUE(strong_from_weak == nullptr);
1315 }
1316
TEST_F(BinderLibTest,LocalGetExtension)1317 TEST_F(BinderLibTest, LocalGetExtension) {
1318 sp<BBinder> binder = new BBinder();
1319 sp<IBinder> ext = new BBinder();
1320 binder->setExtension(ext);
1321 EXPECT_EQ(ext, binder->getExtension());
1322 }
1323
TEST_F(BinderLibTest,RemoteGetExtension)1324 TEST_F(BinderLibTest, RemoteGetExtension) {
1325 sp<IBinder> server = addServer();
1326 ASSERT_TRUE(server != nullptr);
1327
1328 sp<IBinder> extension;
1329 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
1330 ASSERT_NE(nullptr, extension.get());
1331
1332 EXPECT_EQ(NO_ERROR, extension->pingBinder());
1333 }
1334
TEST_F(BinderLibTest,CheckHandleZeroBinderHighBitsZeroCookie)1335 TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
1336 Parcel data, reply;
1337
1338 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
1339 StatusEq(NO_ERROR));
1340
1341 const flat_binder_object *fb = reply.readObject(false);
1342 ASSERT_TRUE(fb != nullptr);
1343 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
1344 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
1345 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
1346 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
1347 }
1348
TEST_F(BinderLibTest,FreedBinder)1349 TEST_F(BinderLibTest, FreedBinder) {
1350 status_t ret;
1351
1352 sp<IBinder> server = addServer();
1353 ASSERT_TRUE(server != nullptr);
1354
1355 __u32 freedHandle;
1356 wp<IBinder> keepFreedBinder;
1357 {
1358 Parcel data, reply;
1359 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1360 StatusEq(NO_ERROR));
1361 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
1362 freedHandle = freed->handle;
1363 /* Add a weak ref to the freed binder so the driver does not
1364 * delete its reference to it - otherwise the transaction
1365 * fails regardless of whether the driver is fixed.
1366 */
1367 keepFreedBinder = reply.readStrongBinder();
1368 }
1369 IPCThreadState::self()->flushCommands();
1370 {
1371 Parcel data, reply;
1372 data.writeStrongBinder(server);
1373 /* Replace original handle with handle to the freed binder */
1374 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
1375 __u32 oldHandle = strong->handle;
1376 strong->handle = freedHandle;
1377 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
1378 /* Returns DEAD_OBJECT (-32) if target crashes and
1379 * FAILED_TRANSACTION if the driver rejects the invalid
1380 * object.
1381 */
1382 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
1383 /* Restore original handle so parcel destructor does not use
1384 * the wrong handle.
1385 */
1386 strong->handle = oldHandle;
1387 }
1388 }
1389
TEST_F(BinderLibTest,CheckNoHeaderMappedInUser)1390 TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
1391 Parcel data, reply;
1392 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1393 for (int i = 0; i < 2; i++) {
1394 BinderLibTestBundle datai;
1395 datai.appendFrom(&data, 0, data.dataSize());
1396
1397 data.freeData();
1398 data.writeInt32(1);
1399 data.writeStrongBinder(callBack);
1400 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
1401
1402 datai.appendTo(&data);
1403 }
1404 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
1405 StatusEq(NO_ERROR));
1406 }
1407
TEST_F(BinderLibTest,OnewayQueueing)1408 TEST_F(BinderLibTest, OnewayQueueing)
1409 {
1410 Parcel data, data2;
1411
1412 sp<IBinder> pollServer = addPollServer();
1413
1414 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1415 data.writeStrongBinder(callBack);
1416 data.writeInt32(500000); // delay in us before calling back
1417
1418 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
1419 data2.writeStrongBinder(callBack2);
1420 data2.writeInt32(0); // delay in us
1421
1422 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
1423 StatusEq(NO_ERROR));
1424
1425 // The delay ensures that this second transaction will end up on the async_todo list
1426 // (for a single-threaded server)
1427 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1428 StatusEq(NO_ERROR));
1429
1430 // The server will ensure that the two transactions are handled in the expected order;
1431 // If the ordering is not as expected, an error will be returned through the callbacks.
1432 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1433 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
1434
1435 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1436 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
1437 }
1438
TEST_F(BinderLibTest,WorkSourceUnsetByDefault)1439 TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1440 {
1441 status_t ret;
1442 Parcel data, reply;
1443 data.writeInterfaceToken(binderLibTestServiceName);
1444 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1445 EXPECT_EQ(-1, reply.readInt32());
1446 EXPECT_EQ(NO_ERROR, ret);
1447 }
1448
TEST_F(BinderLibTest,WorkSourceSet)1449 TEST_F(BinderLibTest, WorkSourceSet)
1450 {
1451 status_t ret;
1452 Parcel data, reply;
1453 IPCThreadState::self()->clearCallingWorkSource();
1454 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
1455 data.writeInterfaceToken(binderLibTestServiceName);
1456 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1457 EXPECT_EQ(100, reply.readInt32());
1458 EXPECT_EQ(-1, previousWorkSource);
1459 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1460 EXPECT_EQ(NO_ERROR, ret);
1461 }
1462
TEST_F(BinderLibTest,WorkSourceSetWithoutPropagation)1463 TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1464 {
1465 status_t ret;
1466 Parcel data, reply;
1467
1468 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1469 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1470
1471 data.writeInterfaceToken(binderLibTestServiceName);
1472 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1473 EXPECT_EQ(-1, reply.readInt32());
1474 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1475 EXPECT_EQ(NO_ERROR, ret);
1476 }
1477
TEST_F(BinderLibTest,WorkSourceCleared)1478 TEST_F(BinderLibTest, WorkSourceCleared)
1479 {
1480 status_t ret;
1481 Parcel data, reply;
1482
1483 IPCThreadState::self()->setCallingWorkSourceUid(100);
1484 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1485 int32_t previousWorkSource = (int32_t)token;
1486 data.writeInterfaceToken(binderLibTestServiceName);
1487 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1488
1489 EXPECT_EQ(-1, reply.readInt32());
1490 EXPECT_EQ(100, previousWorkSource);
1491 EXPECT_EQ(NO_ERROR, ret);
1492 }
1493
TEST_F(BinderLibTest,WorkSourceRestored)1494 TEST_F(BinderLibTest, WorkSourceRestored)
1495 {
1496 status_t ret;
1497 Parcel data, reply;
1498
1499 IPCThreadState::self()->setCallingWorkSourceUid(100);
1500 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1501 IPCThreadState::self()->restoreCallingWorkSource(token);
1502
1503 data.writeInterfaceToken(binderLibTestServiceName);
1504 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1505
1506 EXPECT_EQ(100, reply.readInt32());
1507 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1508 EXPECT_EQ(NO_ERROR, ret);
1509 }
1510
TEST_F(BinderLibTest,PropagateFlagSet)1511 TEST_F(BinderLibTest, PropagateFlagSet)
1512 {
1513 IPCThreadState::self()->clearPropagateWorkSource();
1514 IPCThreadState::self()->setCallingWorkSourceUid(100);
1515 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1516 }
1517
TEST_F(BinderLibTest,PropagateFlagCleared)1518 TEST_F(BinderLibTest, PropagateFlagCleared)
1519 {
1520 IPCThreadState::self()->setCallingWorkSourceUid(100);
1521 IPCThreadState::self()->clearPropagateWorkSource();
1522 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1523 }
1524
TEST_F(BinderLibTest,PropagateFlagRestored)1525 TEST_F(BinderLibTest, PropagateFlagRestored)
1526 {
1527 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1528 IPCThreadState::self()->restoreCallingWorkSource(token);
1529
1530 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1531 }
1532
TEST_F(BinderLibTest,WorkSourcePropagatedForAllFollowingBinderCalls)1533 TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1534 {
1535 IPCThreadState::self()->setCallingWorkSourceUid(100);
1536
1537 Parcel data, reply;
1538 status_t ret;
1539 data.writeInterfaceToken(binderLibTestServiceName);
1540 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1541 EXPECT_EQ(NO_ERROR, ret);
1542
1543 Parcel data2, reply2;
1544 status_t ret2;
1545 data2.writeInterfaceToken(binderLibTestServiceName);
1546 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1547 EXPECT_EQ(100, reply2.readInt32());
1548 EXPECT_EQ(NO_ERROR, ret2);
1549 }
1550
TEST_F(BinderLibTest,SchedPolicySet)1551 TEST_F(BinderLibTest, SchedPolicySet) {
1552 sp<IBinder> server = addServer();
1553 ASSERT_TRUE(server != nullptr);
1554
1555 Parcel data, reply;
1556 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1557 StatusEq(NO_ERROR));
1558
1559 int policy = reply.readInt32();
1560 int priority = reply.readInt32();
1561
1562 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1563 EXPECT_EQ(kSchedPriority, priority);
1564 }
1565
TEST_F(BinderLibTest,InheritRt)1566 TEST_F(BinderLibTest, InheritRt) {
1567 sp<IBinder> server = addServer();
1568 ASSERT_TRUE(server != nullptr);
1569
1570 const struct sched_param param {
1571 .sched_priority = kSchedPriorityMore,
1572 };
1573 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, ¶m));
1574
1575 Parcel data, reply;
1576 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1577 StatusEq(NO_ERROR));
1578
1579 int policy = reply.readInt32();
1580 int priority = reply.readInt32();
1581
1582 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1583 EXPECT_EQ(kSchedPriorityMore, priority);
1584 }
1585
TEST_F(BinderLibTest,VectorSent)1586 TEST_F(BinderLibTest, VectorSent) {
1587 Parcel data, reply;
1588 sp<IBinder> server = addServer();
1589 ASSERT_TRUE(server != nullptr);
1590
1591 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1592 data.writeUint64Vector(testValue);
1593
1594 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
1595 std::vector<uint64_t> readValue;
1596 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1597 EXPECT_EQ(readValue, testValue);
1598 }
1599
TEST_F(BinderLibTest,FileDescriptorRemainsNonBlocking)1600 TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1601 sp<IBinder> server = addServer();
1602 ASSERT_TRUE(server != nullptr);
1603
1604 Parcel reply;
1605 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1606 StatusEq(NO_ERROR));
1607 unique_fd fd;
1608 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1609
1610 const int result = fcntl(fd.get(), F_GETFL);
1611 ASSERT_NE(result, -1);
1612 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1613 }
1614
1615 // see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1616 // This value is not exposed, but some code in the framework relies on being able to use
1617 // buffers near the cap size.
1618 constexpr size_t kSizeBytesAlmostFull = 950'000;
1619 constexpr size_t kSizeBytesOverFull = 1'050'000;
1620
TEST_F(BinderLibTest,GargantuanVectorSent)1621 TEST_F(BinderLibTest, GargantuanVectorSent) {
1622 sp<IBinder> server = addServer();
1623 ASSERT_TRUE(server != nullptr);
1624
1625 for (size_t i = 0; i < 10; i++) {
1626 // a slight variation in size is used to consider certain possible caching implementations
1627 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1628
1629 Parcel data, reply;
1630 data.writeUint64Vector(testValue);
1631 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1632 << i;
1633 std::vector<uint64_t> readValue;
1634 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1635 EXPECT_EQ(readValue, testValue);
1636 }
1637 }
1638
TEST_F(BinderLibTest,LimitExceededVectorSent)1639 TEST_F(BinderLibTest, LimitExceededVectorSent) {
1640 sp<IBinder> server = addServer();
1641 ASSERT_TRUE(server != nullptr);
1642 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1643
1644 Parcel data, reply;
1645 data.writeUint64Vector(testValue);
1646 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1647 StatusEq(FAILED_TRANSACTION));
1648 }
1649
TEST_F(BinderLibTest,BufRejected)1650 TEST_F(BinderLibTest, BufRejected) {
1651 Parcel data, reply;
1652 uint32_t buf;
1653 sp<IBinder> server = addServer();
1654 ASSERT_TRUE(server != nullptr);
1655
1656 binder_buffer_object obj {
1657 .hdr = { .type = BINDER_TYPE_PTR },
1658 .flags = 0,
1659 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1660 .length = 4,
1661 };
1662 data.setDataCapacity(1024);
1663 // Write a bogus object at offset 0 to get an entry in the offset table
1664 data.writeFileDescriptor(0);
1665 EXPECT_EQ(data.objectsCount(), 1u);
1666 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1667 // And now, overwrite it with the buffer object
1668 memcpy(parcelData, &obj, sizeof(obj));
1669 data.setDataSize(sizeof(obj));
1670
1671 EXPECT_EQ(data.objectsCount(), 1u);
1672
1673 // Either the kernel should reject this transaction (if it's correct), but
1674 // if it's not, the server implementation should return an error if it
1675 // finds an object in the received Parcel.
1676 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1677 Not(StatusEq(NO_ERROR)));
1678 }
1679
TEST_F(BinderLibTest,WeakRejected)1680 TEST_F(BinderLibTest, WeakRejected) {
1681 Parcel data, reply;
1682 sp<IBinder> server = addServer();
1683 ASSERT_TRUE(server != nullptr);
1684
1685 auto binder = sp<BBinder>::make();
1686 wp<BBinder> wpBinder(binder);
1687 flat_binder_object obj{
1688 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1689 .flags = 0,
1690 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1691 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1692 };
1693 data.setDataCapacity(1024);
1694 // Write a bogus object at offset 0 to get an entry in the offset table
1695 data.writeFileDescriptor(0);
1696 EXPECT_EQ(data.objectsCount(), 1u);
1697 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1698 // And now, overwrite it with the weak binder
1699 memcpy(parcelData, &obj, sizeof(obj));
1700 data.setDataSize(sizeof(obj));
1701
1702 // a previous bug caused other objects to be released an extra time, so we
1703 // test with an object that libbinder will actually try to release
1704 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1705
1706 EXPECT_EQ(data.objectsCount(), 2u);
1707
1708 // send it many times, since previous error was memory corruption, make it
1709 // more likely that the server crashes
1710 for (size_t i = 0; i < 100; i++) {
1711 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1712 StatusEq(BAD_VALUE));
1713 }
1714
1715 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1716 }
1717
TEST_F(BinderLibTest,GotSid)1718 TEST_F(BinderLibTest, GotSid) {
1719 sp<IBinder> server = addServer();
1720
1721 Parcel data;
1722 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
1723 }
1724
1725 struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
TooManyFdsFlattenableTooManyFdsFlattenable1726 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1727
1728 // Flattenable protocol
getFlattenedSizeTooManyFdsFlattenable1729 size_t getFlattenedSize() const {
1730 // Return a valid non-zero size here so we don't get an unintended
1731 // BAD_VALUE from Parcel::write
1732 return 16;
1733 }
getFdCountTooManyFdsFlattenable1734 size_t getFdCount() const { return mFdCount; }
flattenTooManyFdsFlattenable1735 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1736 for (size_t i = 0; i < count; i++) {
1737 fds[i] = STDIN_FILENO;
1738 }
1739 return NO_ERROR;
1740 }
unflattenTooManyFdsFlattenable1741 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1742 size_t & /*count*/) {
1743 /* This doesn't get called */
1744 return NO_ERROR;
1745 }
1746
1747 size_t mFdCount;
1748 };
1749
TEST_F(BinderLibTest,TooManyFdsFlattenable)1750 TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1751 rlimit origNofile;
1752 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1753 ASSERT_EQ(0, ret);
1754
1755 // Restore the original file limits when the test finishes
1756 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
1757
1758 rlimit testNofile = {1024, 1024};
1759 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1760 ASSERT_EQ(0, ret);
1761
1762 Parcel parcel;
1763 // Try to write more file descriptors than supported by the OS
1764 TooManyFdsFlattenable tooManyFds1(1024);
1765 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1766
1767 // Try to write more file descriptors than the internal limit
1768 TooManyFdsFlattenable tooManyFds2(1025);
1769 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1770 }
1771
TEST(ServiceNotifications,Unregister)1772 TEST(ServiceNotifications, Unregister) {
1773 auto sm = defaultServiceManager();
1774 sm->enableAddServiceCache(false);
1775 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1776 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1777 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1778 virtual ~LocalRegistrationCallbackImpl() {}
1779 };
1780 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1781
1782 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1783 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1784 }
1785
TEST_F(BinderLibTest,ThreadPoolAvailableThreads)1786 TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1787 Parcel data, reply;
1788 sp<IBinder> server = addServer();
1789 ASSERT_TRUE(server != nullptr);
1790 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1791 StatusEq(NO_ERROR));
1792 int32_t replyi = reply.readInt32();
1793 // see getThreadPoolMaxTotalThreadCount for why there is a race
1794 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1795
1796 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1797
1798 /*
1799 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1800 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1801 * started threads from setThreadPoolMaxThreadCount
1802 *
1803 * Adding one more will cause it to deadlock.
1804 */
1805 std::vector<std::thread> ts;
1806 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1807 ts.push_back(std::thread([&] {
1808 Parcel local_reply;
1809 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1810 NO_ERROR);
1811 }));
1812 }
1813
1814 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1815 // the time, the below call will pre-empt them (presumably because we have the
1816 // scheduler timeslice already + scheduler hint).
1817 sleep(1);
1818
1819 data.writeInt32(1000);
1820 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
1821 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1822
1823 for (auto &t : ts) {
1824 t.join();
1825 }
1826
1827 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1828 StatusEq(NO_ERROR));
1829 replyi = reply.readInt32();
1830 EXPECT_EQ(replyi, kKernelThreads + 2);
1831 }
1832
TEST_F(BinderLibTest,ThreadPoolStarted)1833 TEST_F(BinderLibTest, ThreadPoolStarted) {
1834 Parcel data, reply;
1835 sp<IBinder> server = addServer();
1836 ASSERT_TRUE(server != nullptr);
1837 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1838 EXPECT_TRUE(reply.readBool());
1839 }
1840
TEST_F(BinderLibTest,HangingServices)1841 TEST_F(BinderLibTest, HangingServices) {
1842 Parcel data, reply;
1843 sp<IBinder> server = addServer();
1844 ASSERT_TRUE(server != nullptr);
1845 int32_t delay = 1000; // ms
1846 data.writeInt32(delay);
1847 // b/266537959 - must take before taking lock, since countdown is started in the remote
1848 // process there.
1849 int64_t timeBefore = uptimeMillis();
1850 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1851 std::vector<std::thread> ts;
1852 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1853 ts.push_back(std::thread([&] {
1854 Parcel local_reply;
1855 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1856 NO_ERROR);
1857 }));
1858 }
1859
1860 for (auto &t : ts) {
1861 t.join();
1862 }
1863 int64_t timeAfter = uptimeMillis();
1864
1865 // deadlock occurred and threads only finished after 1s passed.
1866 EXPECT_GE(timeAfter, timeBefore + delay);
1867 }
1868
TEST_F(BinderLibTest,BinderProxyCount)1869 TEST_F(BinderLibTest, BinderProxyCount) {
1870 Parcel data, reply;
1871 sp<IBinder> server = addServer();
1872 ASSERT_NE(server, nullptr);
1873
1874 uint32_t initialCount = BpBinder::getBinderProxyCount();
1875 size_t iterations = 100;
1876 {
1877 uint32_t count = initialCount;
1878 std::vector<sp<IBinder> > proxies;
1879 sp<IBinder> proxy;
1880 // Create binder proxies and verify the count.
1881 for (size_t i = 0; i < iterations; i++) {
1882 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1883 StatusEq(NO_ERROR));
1884 proxies.push_back(reply.readStrongBinder());
1885 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1886 }
1887 // Remove every other one and verify the count.
1888 auto it = proxies.begin();
1889 for (size_t i = 0; it != proxies.end(); i++) {
1890 if (i % 2 == 0) {
1891 it = proxies.erase(it);
1892 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1893 }
1894 }
1895 }
1896 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1897 }
1898
1899 static constexpr int kBpCountHighWatermark = 20;
1900 static constexpr int kBpCountLowWatermark = 10;
1901 static constexpr int kBpCountWarningWatermark = 15;
1902 static constexpr int kInvalidUid = -1;
1903
TEST_F(BinderLibTest,BinderProxyCountCallback)1904 TEST_F(BinderLibTest, BinderProxyCountCallback) {
1905 Parcel data, reply;
1906 sp<IBinder> server = addServer();
1907 ASSERT_NE(server, nullptr);
1908
1909 BpBinder::enableCountByUid();
1910 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1911 int32_t uid = reply.readInt32();
1912 ASSERT_NE(uid, kInvalidUid);
1913
1914 uint32_t initialCount = BpBinder::getBinderProxyCount();
1915 {
1916 uint32_t count = initialCount;
1917 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1918 kBpCountLowWatermark,
1919 kBpCountWarningWatermark);
1920 int limitCallbackUid = kInvalidUid;
1921 int warningCallbackUid = kInvalidUid;
1922 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1923 [&](int uid) { warningCallbackUid = uid; });
1924
1925 std::vector<sp<IBinder> > proxies;
1926 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1927 warningCallbackUid = limitCallbackUid = kInvalidUid;
1928 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1929 StatusEq(NO_ERROR));
1930 proxies.push_back(reply.readStrongBinder());
1931 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1932 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1933 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1934 };
1935 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1936 warningCallbackUid = limitCallbackUid = kInvalidUid;
1937 proxies.pop_back();
1938 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1939 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1940 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1941 };
1942
1943 // Test the increment/decrement of the binder proxies.
1944 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1945 createProxyOnce(kInvalidUid, kInvalidUid);
1946 }
1947 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1948 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1949 createProxyOnce(kInvalidUid, kInvalidUid);
1950 }
1951 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1952 createProxyOnce(kInvalidUid, kInvalidUid);
1953 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1954 removeProxyOnce(kInvalidUid, kInvalidUid);
1955 }
1956 createProxyOnce(kInvalidUid, kInvalidUid);
1957
1958 // Go down below the low watermark.
1959 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1960 removeProxyOnce(kInvalidUid, kInvalidUid);
1961 }
1962 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1963 createProxyOnce(kInvalidUid, kInvalidUid);
1964 }
1965 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1966 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1967 createProxyOnce(kInvalidUid, kInvalidUid);
1968 }
1969 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1970 createProxyOnce(kInvalidUid, kInvalidUid);
1971 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1972 removeProxyOnce(kInvalidUid, kInvalidUid);
1973 }
1974 createProxyOnce(kInvalidUid, kInvalidUid);
1975 }
1976 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1977 }
1978
1979 class BinderLibRpcTestBase : public BinderLibTest {
1980 public:
SetUp()1981 void SetUp() override {
1982 if (!base::GetBoolProperty("ro.debuggable", false)) {
1983 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1984 "non-debuggable builds.";
1985 }
1986 BinderLibTest::SetUp();
1987 }
1988
CreateSocket()1989 std::tuple<unique_fd, unsigned int> CreateSocket() {
1990 auto rpcServer = RpcServer::make();
1991 EXPECT_NE(nullptr, rpcServer);
1992 if (rpcServer == nullptr) return {};
1993 unsigned int port;
1994 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1995 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
1996 return {};
1997 }
1998 return {rpcServer->releaseServer(), port};
1999 }
2000 };
2001
2002 class BinderLibRpcTest : public BinderLibRpcTestBase {};
2003
2004 // e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
2005 // If device is debuggable AND not on user builds, expects matcher.
2006 // Otherwise expects INVALID_OPERATION.
2007 // Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
Debuggable(const Matcher<status_t> & matcher)2008 static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
2009 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
2010 android::base::GetProperty("ro.build.type", "") != "user";
2011 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
2012 }
2013
TEST_F(BinderLibRpcTest,SetRpcClientDebug)2014 TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
2015 auto binder = addServer();
2016 ASSERT_TRUE(binder != nullptr);
2017 auto [socket, port] = CreateSocket();
2018 ASSERT_TRUE(socket.ok());
2019 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
2020 Debuggable(StatusEq(OK)));
2021 }
2022
2023 // Tests for multiple RpcServer's on the same binder object.
TEST_F(BinderLibRpcTest,SetRpcClientDebugTwice)2024 TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
2025 auto binder = addServer();
2026 ASSERT_TRUE(binder != nullptr);
2027
2028 auto [socket1, port1] = CreateSocket();
2029 ASSERT_TRUE(socket1.ok());
2030 auto keepAliveBinder1 = sp<BBinder>::make();
2031 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
2032 Debuggable(StatusEq(OK)));
2033
2034 auto [socket2, port2] = CreateSocket();
2035 ASSERT_TRUE(socket2.ok());
2036 auto keepAliveBinder2 = sp<BBinder>::make();
2037 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
2038 Debuggable(StatusEq(OK)));
2039 }
2040
2041 // Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
2042 // local binders.
2043 class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
2044 public:
GetService()2045 sp<IBinder> GetService() {
2046 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
2047 }
ParamToString(const testing::TestParamInfo<ParamType> & info)2048 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
2049 return info.param ? "remote" : "local";
2050 }
2051 };
2052
TEST_P(BinderLibRpcTestP,SetRpcClientDebugNoFd)2053 TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
2054 auto binder = GetService();
2055 ASSERT_TRUE(binder != nullptr);
2056 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
2057 Debuggable(StatusEq(BAD_VALUE)));
2058 }
2059
TEST_P(BinderLibRpcTestP,SetRpcClientDebugNoKeepAliveBinder)2060 TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
2061 auto binder = GetService();
2062 ASSERT_TRUE(binder != nullptr);
2063 auto [socket, port] = CreateSocket();
2064 ASSERT_TRUE(socket.ok());
2065 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
2066 Debuggable(StatusEq(UNEXPECTED_NULL)));
2067 }
2068 INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
2069 BinderLibRpcTestP::ParamToString);
2070
2071 class BinderLibTestService : public BBinder {
2072 public:
BinderLibTestService(int32_t id,bool exitOnDestroy=true)2073 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
2074 : m_id(id),
2075 m_nextServerId(id + 1),
2076 m_serverStartRequested(false),
2077 m_callback(nullptr),
2078 m_exitOnDestroy(exitOnDestroy) {
2079 pthread_mutex_init(&m_serverWaitMutex, nullptr);
2080 pthread_cond_init(&m_serverWaitCond, nullptr);
2081 }
~BinderLibTestService()2082 ~BinderLibTestService() {
2083 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
2084 }
2085
processPendingCall()2086 void processPendingCall() {
2087 if (m_callback != nullptr) {
2088 Parcel data;
2089 data.writeInt32(NO_ERROR);
2090 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
2091 m_callback = nullptr;
2092 }
2093 }
2094
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags=0)2095 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
2096 uint32_t flags = 0) {
2097 // TODO(b/182914638): also checks getCallingUid() for RPC
2098 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
2099 return PERMISSION_DENIED;
2100 }
2101 switch (code) {
2102 case BINDER_LIB_TEST_REGISTER_SERVER: {
2103 sp<IBinder> binder;
2104 /*id =*/data.readInt32();
2105 binder = data.readStrongBinder();
2106 if (binder == nullptr) {
2107 return BAD_VALUE;
2108 }
2109
2110 if (m_id != 0) return INVALID_OPERATION;
2111
2112 pthread_mutex_lock(&m_serverWaitMutex);
2113 if (m_serverStartRequested) {
2114 m_serverStartRequested = false;
2115 m_serverStarted = binder;
2116 pthread_cond_signal(&m_serverWaitCond);
2117 }
2118 pthread_mutex_unlock(&m_serverWaitMutex);
2119 return NO_ERROR;
2120 }
2121 case BINDER_LIB_TEST_ADD_POLL_SERVER:
2122 case BINDER_LIB_TEST_ADD_SERVER: {
2123 int ret;
2124 int serverid;
2125
2126 if (m_id != 0) {
2127 return INVALID_OPERATION;
2128 }
2129 pthread_mutex_lock(&m_serverWaitMutex);
2130 if (m_serverStartRequested) {
2131 ret = -EBUSY;
2132 } else {
2133 serverid = m_nextServerId++;
2134 m_serverStartRequested = true;
2135 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
2136
2137 pthread_mutex_unlock(&m_serverWaitMutex);
2138 ret = start_server_process(serverid, usePoll);
2139 pthread_mutex_lock(&m_serverWaitMutex);
2140 }
2141 if (ret > 0) {
2142 if (m_serverStartRequested) {
2143 struct timespec ts;
2144 clock_gettime(CLOCK_REALTIME, &ts);
2145 ts.tv_sec += 5;
2146 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
2147 }
2148 if (m_serverStartRequested) {
2149 m_serverStartRequested = false;
2150 ret = -ETIMEDOUT;
2151 } else {
2152 reply->writeStrongBinder(m_serverStarted);
2153 reply->writeInt32(serverid);
2154 m_serverStarted = nullptr;
2155 ret = NO_ERROR;
2156 }
2157 } else if (ret >= 0) {
2158 m_serverStartRequested = false;
2159 ret = UNKNOWN_ERROR;
2160 }
2161 pthread_mutex_unlock(&m_serverWaitMutex);
2162 return ret;
2163 }
2164 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
2165 IPCThreadState::SpGuard spGuard{
2166 .address = __builtin_frame_address(0),
2167 .context = "GuardInBinderTransaction",
2168 };
2169 const IPCThreadState::SpGuard *origGuard =
2170 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2171
2172 // if the guard works, this should abort
2173 (void)IPCThreadState::self()->getCallingPid();
2174
2175 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
2176 return NO_ERROR;
2177 }
2178
2179 case BINDER_LIB_TEST_GETPID:
2180 reply->writeInt32(getpid());
2181 return NO_ERROR;
2182 case BINDER_LIB_TEST_GETUID:
2183 reply->writeInt32(getuid());
2184 return NO_ERROR;
2185 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
2186 usleep(5000);
2187 [[fallthrough]];
2188 case BINDER_LIB_TEST_NOP_TRANSACTION:
2189 // oneway error codes should be ignored
2190 if (flags & TF_ONE_WAY) {
2191 return UNKNOWN_ERROR;
2192 }
2193 return NO_ERROR;
2194 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
2195 // Note: this transaction is only designed for use with a
2196 // poll() server. See comments around epoll_wait().
2197 if (m_callback != nullptr) {
2198 // A callback was already pending; this means that
2199 // we received a second call while still processing
2200 // the first one. Fail the test.
2201 sp<IBinder> callback = data.readStrongBinder();
2202 Parcel data2;
2203 data2.writeInt32(UNKNOWN_ERROR);
2204
2205 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
2206 } else {
2207 m_callback = data.readStrongBinder();
2208 int32_t delayUs = data.readInt32();
2209 /*
2210 * It's necessary that we sleep here, so the next
2211 * transaction the caller makes will be queued to
2212 * the async queue.
2213 */
2214 usleep(delayUs);
2215
2216 /*
2217 * Now when we return, libbinder will tell the kernel
2218 * we are done with this transaction, and the kernel
2219 * can move the queued transaction to either the
2220 * thread todo worklist (for kernels without the fix),
2221 * or the proc todo worklist. In case of the former,
2222 * the next outbound call will pick up the pending
2223 * transaction, which leads to undesired reentrant
2224 * behavior. This is caught in the if() branch above.
2225 */
2226 }
2227
2228 return NO_ERROR;
2229 }
2230 case BINDER_LIB_TEST_NOP_CALL_BACK: {
2231 Parcel data2, reply2;
2232 sp<IBinder> binder;
2233 binder = data.readStrongBinder();
2234 if (binder == nullptr) {
2235 return BAD_VALUE;
2236 }
2237 data2.writeInt32(NO_ERROR);
2238 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2239 return NO_ERROR;
2240 }
2241 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
2242 reply->writeStrongBinder(this);
2243 return NO_ERROR;
2244 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
2245 reply->writeInt32(m_id);
2246 return NO_ERROR;
2247 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
2248 int32_t count;
2249 uint32_t indirect_code;
2250 sp<IBinder> binder;
2251
2252 count = data.readInt32();
2253 reply->writeInt32(m_id);
2254 reply->writeInt32(count);
2255 for (int i = 0; i < count; i++) {
2256 binder = data.readStrongBinder();
2257 if (binder == nullptr) {
2258 return BAD_VALUE;
2259 }
2260 indirect_code = data.readInt32();
2261 BinderLibTestBundle data2(&data);
2262 if (!data2.isValid()) {
2263 return BAD_VALUE;
2264 }
2265 BinderLibTestBundle reply2;
2266 binder->transact(indirect_code, data2, &reply2);
2267 reply2.appendTo(reply);
2268 }
2269 return NO_ERROR;
2270 }
2271 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
2272 reply->setError(data.readInt32());
2273 return NO_ERROR;
2274 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
2275 reply->writeInt32(sizeof(void *));
2276 return NO_ERROR;
2277 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
2278 return NO_ERROR;
2279 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
2280 m_strongRef = data.readStrongBinder();
2281 return NO_ERROR;
2282 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
2283 int ret;
2284 Parcel data2, reply2;
2285 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
2286 sp<IBinder> target;
2287 sp<IBinder> callback;
2288
2289 target = data.readStrongBinder();
2290 if (target == nullptr) {
2291 return BAD_VALUE;
2292 }
2293 callback = data.readStrongBinder();
2294 if (callback == nullptr) {
2295 return BAD_VALUE;
2296 }
2297 ret = target->linkToDeath(testDeathRecipient);
2298 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
2299 data2.writeInt32(ret);
2300 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2301 return NO_ERROR;
2302 }
2303 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
2304 int ret;
2305 int32_t size;
2306 const void *buf;
2307 int fd;
2308
2309 fd = data.readFileDescriptor();
2310 if (fd < 0) {
2311 return BAD_VALUE;
2312 }
2313 ret = data.readInt32(&size);
2314 if (ret != NO_ERROR) {
2315 return ret;
2316 }
2317 buf = data.readInplace(size);
2318 if (buf == nullptr) {
2319 return BAD_VALUE;
2320 }
2321 ret = write(fd, buf, size);
2322 if (ret != size) return UNKNOWN_ERROR;
2323 return NO_ERROR;
2324 }
2325 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
2326 int ret;
2327 int32_t size;
2328 const void *buf;
2329 unique_fd fd;
2330
2331 ret = data.readUniqueParcelFileDescriptor(&fd);
2332 if (ret != NO_ERROR) {
2333 return ret;
2334 }
2335 ret = data.readInt32(&size);
2336 if (ret != NO_ERROR) {
2337 return ret;
2338 }
2339 buf = data.readInplace(size);
2340 if (buf == nullptr) {
2341 return BAD_VALUE;
2342 }
2343 ret = write(fd.get(), buf, size);
2344 if (ret != size) return UNKNOWN_ERROR;
2345 return NO_ERROR;
2346 }
2347 case BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION: {
2348 unique_fd fd1(memfd_create("memfd1", MFD_CLOEXEC));
2349 if (!fd1.ok()) {
2350 PLOGE("memfd_create failed");
2351 return UNKNOWN_ERROR;
2352 }
2353 unique_fd fd2(memfd_create("memfd2", MFD_CLOEXEC));
2354 if (!fd2.ok()) {
2355 PLOGE("memfd_create failed");
2356 return UNKNOWN_ERROR;
2357 }
2358 status_t ret;
2359 ret = reply->writeFileDescriptor(fd1.release(), true);
2360 if (ret != NO_ERROR) {
2361 return ret;
2362 }
2363 ret = reply->writeFileDescriptor(fd2.release(), true);
2364 if (ret != NO_ERROR) {
2365 return ret;
2366 }
2367 return NO_ERROR;
2368 }
2369 case BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION: {
2370 status_t ret;
2371 ret = reply->writeFileDescriptor(STDOUT_FILENO, false);
2372 if (ret != NO_ERROR) {
2373 return ret;
2374 }
2375 ret = reply->writeFileDescriptor(STDERR_FILENO, false);
2376 if (ret != NO_ERROR) {
2377 return ret;
2378 }
2379 return NO_ERROR;
2380 }
2381 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
2382 alarm(10);
2383 return NO_ERROR;
2384 case BINDER_LIB_TEST_EXIT_TRANSACTION:
2385 while (wait(nullptr) != -1 || errno != ECHILD)
2386 ;
2387 exit(EXIT_SUCCESS);
2388 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
2389 sp<IBinder> binder = new BBinder();
2390 reply->writeStrongBinder(binder);
2391 return NO_ERROR;
2392 }
2393 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
2394 data.enforceInterface(binderLibTestServiceName);
2395 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
2396 return NO_ERROR;
2397 }
2398 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
2399 int policy = 0;
2400 sched_param param;
2401 if (0 != pthread_getschedparam(pthread_self(), &policy, ¶m)) {
2402 return UNKNOWN_ERROR;
2403 }
2404 reply->writeInt32(policy);
2405 reply->writeInt32(param.sched_priority);
2406 return NO_ERROR;
2407 }
2408 case BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE: {
2409 sp<IBinder> binder = data.readStrongBinder();
2410 frozenStateChangeCallback = sp<TestFrozenStateChangeCallback>::make();
2411 // Hold an strong pointer to the binder object so it doesn't go
2412 // away.
2413 frozenStateChangeCallback->binder = binder;
2414 int ret = binder->addFrozenStateChangeCallback(frozenStateChangeCallback);
2415 if (ret != NO_ERROR) {
2416 return ret;
2417 }
2418 auto event = frozenStateChangeCallback->events.popWithTimeout(1000ms);
2419 if (!event.has_value()) {
2420 return NOT_ENOUGH_DATA;
2421 }
2422 return NO_ERROR;
2423 }
2424 case BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS: {
2425 reply->writeBoolVector(frozenStateChangeCallback->getAllAndClear());
2426 return NO_ERROR;
2427 }
2428 case BINDER_LIB_TEST_ECHO_VECTOR: {
2429 std::vector<uint64_t> vector;
2430 auto err = data.readUint64Vector(&vector);
2431 if (err != NO_ERROR) return err;
2432 reply->writeUint64Vector(vector);
2433 return NO_ERROR;
2434 }
2435 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
2436 std::array<int, 2> sockets;
2437 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
2438 if (!created) {
2439 ALOGE("Could not create socket pair");
2440 return UNKNOWN_ERROR;
2441 }
2442
2443 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
2444 if (result != 0) {
2445 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
2446 return UNKNOWN_ERROR;
2447 }
2448 unique_fd out(sockets[0]);
2449 status_t writeResult = reply->writeUniqueFileDescriptor(out);
2450 if (writeResult != NO_ERROR) {
2451 ALOGE("Could not write unique_fd");
2452 return writeResult;
2453 }
2454 close(sockets[1]); // we don't need the other side of the fd
2455 return NO_ERROR;
2456 }
2457 case BINDER_LIB_TEST_REJECT_OBJECTS: {
2458 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
2459 }
2460 case BINDER_LIB_TEST_CAN_GET_SID: {
2461 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
2462 }
2463 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
2464 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
2465 return NO_ERROR;
2466 }
2467 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
2468 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
2469 return NO_ERROR;
2470 }
2471 case BINDER_LIB_TEST_PROCESS_LOCK: {
2472 m_blockMutex.lock();
2473 return NO_ERROR;
2474 }
2475 case BINDER_LIB_TEST_LOCK_UNLOCK: {
2476 std::lock_guard<std::mutex> _l(m_blockMutex);
2477 return NO_ERROR;
2478 }
2479 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2480 int32_t ms = data.readInt32();
2481 return unlockInMs(ms);
2482 }
2483 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
2484 m_blockMutex.lock();
2485 sp<BinderLibTestService> thisService = this;
2486 int32_t value = data.readInt32();
2487 // start local thread to unlock in 1s
2488 std::thread t([=] { thisService->unlockInMs(value); });
2489 t.detach();
2490 return NO_ERROR;
2491 }
2492 default:
2493 return UNKNOWN_TRANSACTION;
2494 };
2495 }
2496
unlockInMs(int32_t ms)2497 status_t unlockInMs(int32_t ms) {
2498 usleep(ms * 1000);
2499 m_blockMutex.unlock();
2500 return NO_ERROR;
2501 }
2502
2503 private:
2504 int32_t m_id;
2505 int32_t m_nextServerId;
2506 pthread_mutex_t m_serverWaitMutex;
2507 pthread_cond_t m_serverWaitCond;
2508 bool m_serverStartRequested;
2509 sp<IBinder> m_serverStarted;
2510 sp<IBinder> m_strongRef;
2511 sp<IBinder> m_callback;
2512 bool m_exitOnDestroy;
2513 std::mutex m_blockMutex;
2514 sp<TestFrozenStateChangeCallback> frozenStateChangeCallback;
2515 };
2516
run_server(int index,int readypipefd,bool usePoll)2517 int run_server(int index, int readypipefd, bool usePoll)
2518 {
2519 binderLibTestServiceName += String16(binderserversuffix);
2520
2521 // Testing to make sure that calls that we are serving can use getCallin*
2522 // even though we don't here.
2523 IPCThreadState::SpGuard spGuard{
2524 .address = __builtin_frame_address(0),
2525 .context = "main server thread",
2526 };
2527 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2528
2529 status_t ret;
2530 sp<IServiceManager> sm = defaultServiceManager();
2531 sm->enableAddServiceCache(false);
2532
2533 BinderLibTestService* testServicePtr;
2534 {
2535 sp<BinderLibTestService> testService = new BinderLibTestService(index);
2536
2537 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2538
2539 testService->setInheritRt(true);
2540
2541 /*
2542 * Normally would also contain functionality as well, but we are only
2543 * testing the extension mechanism.
2544 */
2545 testService->setExtension(new BBinder());
2546
2547 // Required for test "BufRejected'
2548 testService->setRequestingSid(true);
2549
2550 /*
2551 * We need this below, but can't hold a sp<> because it prevents the
2552 * node from being cleaned up automatically. It's safe in this case
2553 * because of how the tests are written.
2554 */
2555 testServicePtr = testService.get();
2556
2557 if (index == 0) {
2558 ret = sm->addService(binderLibTestServiceName, testService);
2559 } else {
2560 LIBBINDER_IGNORE("-Wdeprecated-declarations")
2561 sp<IBinder> server = sm->getService(binderLibTestServiceName);
2562 LIBBINDER_IGNORE_END()
2563 Parcel data, reply;
2564 data.writeInt32(index);
2565 data.writeStrongBinder(testService);
2566
2567 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2568 }
2569 }
2570 write(readypipefd, &ret, sizeof(ret));
2571 close(readypipefd);
2572 //printf("%s: ret %d\n", __func__, ret);
2573 if (ret)
2574 return 1;
2575 //printf("%s: joinThreadPool\n", __func__);
2576 if (usePoll) {
2577 int fd;
2578 struct epoll_event ev;
2579 int epoll_fd;
2580 IPCThreadState::self()->setupPolling(&fd);
2581 if (fd < 0) {
2582 return 1;
2583 }
2584 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2585
2586 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
2587 if (epoll_fd == -1) {
2588 return 1;
2589 }
2590
2591 ev.events = EPOLLIN;
2592 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2593 return 1;
2594 }
2595
2596 while (1) {
2597 /*
2598 * We simulate a single-threaded process using the binder poll
2599 * interface; besides handling binder commands, it can also
2600 * issue outgoing transactions, by storing a callback in
2601 * m_callback.
2602 *
2603 * processPendingCall() will then issue that transaction.
2604 */
2605 struct epoll_event events[1];
2606 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2607 if (numEvents < 0) {
2608 if (errno == EINTR) {
2609 continue;
2610 }
2611 return 1;
2612 }
2613 if (numEvents > 0) {
2614 IPCThreadState::self()->handlePolledCommands();
2615 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2616 testServicePtr->processPendingCall();
2617 }
2618 }
2619 } else {
2620 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
2621 ProcessState::self()->startThreadPool();
2622 IPCThreadState::self()->joinThreadPool();
2623 }
2624 //printf("%s: joinThreadPool returned\n", __func__);
2625 return 1; /* joinThreadPool should not return */
2626 }
2627
main(int argc,char ** argv)2628 int main(int argc, char** argv) {
2629 if (argc == 4 && !strcmp(argv[1], "--servername")) {
2630 binderservername = argv[2];
2631 } else {
2632 binderservername = argv[0];
2633 }
2634
2635 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2636 binderserversuffix = argv[5];
2637 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
2638 }
2639 binderserversuffix = new char[16];
2640 snprintf(binderserversuffix, 16, "%d", getpid());
2641 binderLibTestServiceName += String16(binderserversuffix);
2642
2643 ::testing::InitGoogleTest(&argc, argv);
2644 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2645 ProcessState::self()->startThreadPool();
2646 return RUN_ALL_TESTS();
2647 }
2648