blob: cf3e6ca01f484986629587d9e81009fd5263fa4a [file] [log] [blame]
Riley Andrews06b01ad2014-12-18 12:10:08 -08001/*
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>
Riley Andrews06b01ad2014-12-18 12:10:08 -080018#include <poll.h>
19#include <pthread.h>
20#include <stdio.h>
21#include <stdlib.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070022
23#include <chrono>
Yifan Hong8b890852021-06-10 13:44:09 -070024#include <fstream>
Steven Morelandd7088702021-01-13 00:27:00 +000025#include <thread>
Riley Andrews06b01ad2014-12-18 12:10:08 -080026
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070027#include <gmock/gmock.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080028#include <gtest/gtest.h>
29
Yifan Hong84bedeb2021-04-21 21:37:17 -070030#include <android-base/properties.h>
Yifan Hong28d6c352021-06-04 17:27:35 -070031#include <android-base/result-gmock.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070032#include <android-base/result.h>
Yifan Hong8b890852021-06-10 13:44:09 -070033#include <android-base/strings.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070034#include <android-base/unique_fd.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080035#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070036#include <binder/BpBinder.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080037#include <binder/IBinder.h>
38#include <binder/IPCThreadState.h>
39#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070040#include <binder/RpcServer.h>
41#include <binder/RpcSession.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080042
Steven Morelandcf03cf12020-12-04 02:58:40 +000043#include <linux/sched.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020044#include <sys/epoll.h>
Steven Morelandda048352020-02-19 13:25:53 -080045#include <sys/prctl.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070046#include <sys/socket.h>
47#include <sys/un.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020048
Steven Moreland6ba5a252021-05-04 22:49:00 +000049#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070050#include "binderAbiHelper.h"
51
Riley Andrews06b01ad2014-12-18 12:10:08 -080052#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
53
54using namespace android;
Yifan Hong84bedeb2021-04-21 21:37:17 -070055using namespace std::string_literals;
56using namespace std::chrono_literals;
Yifan Hong28d6c352021-06-04 17:27:35 -070057using android::base::testing::HasValue;
Yifan Hong8b890852021-06-10 13:44:09 -070058using android::base::testing::Ok;
Yifan Hong84bedeb2021-04-21 21:37:17 -070059using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080060using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070061using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070062using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070063
64// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
65MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
66 *result_listener << statusToString(arg);
67 return expected == arg;
68}
Riley Andrews06b01ad2014-12-18 12:10:08 -080069
Sherry Yang336cdd32017-07-24 14:12:27 -070070static ::testing::AssertionResult IsPageAligned(void *buf) {
71 if (((unsigned long)buf & ((unsigned long)PAGE_SIZE - 1)) == 0)
72 return ::testing::AssertionSuccess();
73 else
74 return ::testing::AssertionFailure() << buf << " is not page aligned";
75}
76
Riley Andrews06b01ad2014-12-18 12:10:08 -080077static testing::Environment* binder_env;
78static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070079static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080080static char binderserverarg[] = "--binderserver";
81
Steven Morelandbf1915b2020-07-16 22:43:02 +000082static constexpr int kSchedPolicy = SCHED_RR;
83static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000084static constexpr int kSchedPriorityMore = 8;
Elie Kheirallah47431c12022-04-21 23:46:17 +000085static constexpr int kKernelThreads = 15;
Steven Morelandbf1915b2020-07-16 22:43:02 +000086
Riley Andrews06b01ad2014-12-18 12:10:08 -080087static String16 binderLibTestServiceName = String16("test.binderLib");
88
89enum BinderLibTestTranscationCode {
90 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
91 BINDER_LIB_TEST_REGISTER_SERVER,
92 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020093 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +000094 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -080095 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -070096 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +020097 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -080098 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -070099 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800100 BINDER_LIB_TEST_GET_ID_TRANSACTION,
101 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
102 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
103 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
104 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
105 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
106 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900107 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800108 BINDER_LIB_TEST_EXIT_TRANSACTION,
109 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
110 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700111 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100112 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000113 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700114 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
115 BINDER_LIB_TEST_GETPID,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800116 BINDER_LIB_TEST_ECHO_VECTOR,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700117 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000118 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000119 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
120 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
121 BINDER_LIB_TEST_LOCK_UNLOCK,
122 BINDER_LIB_TEST_PROCESS_LOCK,
123 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
124 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800125};
126
Martijn Coenen45b07b42017-08-09 12:07:45 +0200127pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800128{
129 int ret;
130 pid_t pid;
131 status_t status;
132 int pipefd[2];
133 char stri[16];
134 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200135 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800136 char *childargv[] = {
137 binderservername,
138 binderserverarg,
139 stri,
140 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200141 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700142 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700143 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800144 };
145
146 ret = pipe(pipefd);
147 if (ret < 0)
148 return ret;
149
150 snprintf(stri, sizeof(stri), "%d", arg2);
151 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200152 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800153
154 pid = fork();
155 if (pid == -1)
156 return pid;
157 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800158 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800159 close(pipefd[0]);
160 execv(binderservername, childargv);
161 status = -errno;
162 write(pipefd[1], &status, sizeof(status));
163 fprintf(stderr, "execv failed, %s\n", strerror(errno));
164 _exit(EXIT_FAILURE);
165 }
166 close(pipefd[1]);
167 ret = read(pipefd[0], &status, sizeof(status));
168 //printf("pipe read returned %d, status %d\n", ret, status);
169 close(pipefd[0]);
170 if (ret == sizeof(status)) {
171 ret = status;
172 } else {
173 kill(pid, SIGKILL);
174 if (ret >= 0) {
175 ret = NO_INIT;
176 }
177 }
178 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700179 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800180 return ret;
181 }
182 return pid;
183}
184
Yifan Hong84bedeb2021-04-21 21:37:17 -0700185android::base::Result<int32_t> GetId(sp<IBinder> service) {
186 using android::base::Error;
187 Parcel data, reply;
188 data.markForBinder(service);
189 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
190 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
191 if (status != OK)
192 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
193 int32_t result = 0;
194 status = reply.readInt32(&result);
195 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
196 return result;
197}
198
Riley Andrews06b01ad2014-12-18 12:10:08 -0800199class BinderLibTestEnv : public ::testing::Environment {
200 public:
201 BinderLibTestEnv() {}
202 sp<IBinder> getServer(void) {
203 return m_server;
204 }
205
206 private:
207 virtual void SetUp() {
208 m_serverpid = start_server_process(0);
209 //printf("m_serverpid %d\n", m_serverpid);
210 ASSERT_GT(m_serverpid, 0);
211
212 sp<IServiceManager> sm = defaultServiceManager();
213 //printf("%s: pid %d, get service\n", __func__, m_pid);
214 m_server = sm->getService(binderLibTestServiceName);
Yi Kong91635562018-06-07 14:38:36 -0700215 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800216 //printf("%s: pid %d, get service done\n", __func__, m_pid);
217 }
218 virtual void TearDown() {
219 status_t ret;
220 Parcel data, reply;
221 int exitStatus;
222 pid_t pid;
223
224 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700225 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800226 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
227 EXPECT_EQ(0, ret);
228 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
229 EXPECT_EQ(0, ret);
230 }
231 if (m_serverpid > 0) {
232 //printf("wait for %d\n", m_pids[i]);
233 pid = wait(&exitStatus);
234 EXPECT_EQ(m_serverpid, pid);
235 EXPECT_TRUE(WIFEXITED(exitStatus));
236 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
237 }
238 }
239
240 pid_t m_serverpid;
241 sp<IBinder> m_server;
242};
243
244class BinderLibTest : public ::testing::Test {
245 public:
246 virtual void SetUp() {
247 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Olivier Gaillard91a04802018-11-14 17:32:41 +0000248 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800249 }
250 virtual void TearDown() {
251 }
252 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200253 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800254 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800255 int32_t id;
256 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800257
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700258 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800259
Elie Kheirallahb7246642022-05-03 18:01:43 +0000260 sp<IBinder> binder = reply.readStrongBinder();
261 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700262 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800263 if (idPtr)
264 *idPtr = id;
265 return binder;
266 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200267
Yi Kong91635562018-06-07 14:38:36 -0700268 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200269 {
270 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
271 }
272
Yi Kong91635562018-06-07 14:38:36 -0700273 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200274 {
275 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
276 }
277
Riley Andrews06b01ad2014-12-18 12:10:08 -0800278 void waitForReadData(int fd, int timeout_ms) {
279 int ret;
280 pollfd pfd = pollfd();
281
282 pfd.fd = fd;
283 pfd.events = POLLIN;
284 ret = poll(&pfd, 1, timeout_ms);
285 EXPECT_EQ(1, ret);
286 }
287
288 sp<IBinder> m_server;
289};
290
291class BinderLibTestBundle : public Parcel
292{
293 public:
294 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800295 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800296 int32_t mark;
297 int32_t bundleLen;
298 size_t pos;
299
300 if (source->readInt32(&mark))
301 return;
302 if (mark != MARK_START)
303 return;
304 if (source->readInt32(&bundleLen))
305 return;
306 pos = source->dataPosition();
307 if (Parcel::appendFrom(source, pos, bundleLen))
308 return;
309 source->setDataPosition(pos + bundleLen);
310 if (source->readInt32(&mark))
311 return;
312 if (mark != MARK_END)
313 return;
314 m_isValid = true;
315 setDataPosition(0);
316 }
317 void appendTo(Parcel *dest) {
318 dest->writeInt32(MARK_START);
319 dest->writeInt32(dataSize());
320 dest->appendFrom(this, 0, dataSize());
321 dest->writeInt32(MARK_END);
322 };
323 bool isValid(void) {
324 return m_isValid;
325 }
326 private:
327 enum {
328 MARK_START = B_PACK_CHARS('B','T','B','S'),
329 MARK_END = B_PACK_CHARS('B','T','B','E'),
330 };
331 bool m_isValid;
332};
333
334class BinderLibTestEvent
335{
336 public:
337 BinderLibTestEvent(void)
338 : m_eventTriggered(false)
339 {
Yi Kong91635562018-06-07 14:38:36 -0700340 pthread_mutex_init(&m_waitMutex, nullptr);
341 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800342 }
343 int waitEvent(int timeout_s)
344 {
345 int ret;
346 pthread_mutex_lock(&m_waitMutex);
347 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800348 struct timespec ts;
349 clock_gettime(CLOCK_REALTIME, &ts);
350 ts.tv_sec += timeout_s;
351 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800352 }
353 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
354 pthread_mutex_unlock(&m_waitMutex);
355 return ret;
356 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200357 pthread_t getTriggeringThread()
358 {
359 return m_triggeringThread;
360 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800361 protected:
362 void triggerEvent(void) {
363 pthread_mutex_lock(&m_waitMutex);
364 pthread_cond_signal(&m_waitCond);
365 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200366 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800367 pthread_mutex_unlock(&m_waitMutex);
368 };
369 private:
370 pthread_mutex_t m_waitMutex;
371 pthread_cond_t m_waitCond;
372 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200373 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800374};
375
376class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
377{
378 public:
379 BinderLibTestCallBack()
380 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700381 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800382 {
383 }
384 status_t getResult(void)
385 {
386 return m_result;
387 }
388
389 private:
390 virtual status_t onTransact(uint32_t code,
391 const Parcel& data, Parcel* reply,
392 uint32_t flags = 0)
393 {
394 (void)reply;
395 (void)flags;
396 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200397 case BINDER_LIB_TEST_CALL_BACK: {
398 status_t status = data.readInt32(&m_result);
399 if (status != NO_ERROR) {
400 m_result = status;
401 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800402 triggerEvent();
403 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200404 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700405 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
406 sp<IBinder> server;
407 int ret;
408 const uint8_t *buf = data.data();
409 size_t size = data.dataSize();
410 if (m_prev_end) {
411 /* 64-bit kernel needs at most 8 bytes to align buffer end */
412 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
413 } else {
414 EXPECT_TRUE(IsPageAligned((void *)buf));
415 }
416
417 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
418
419 if (size > 0) {
420 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
421 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
422 data, reply);
423 EXPECT_EQ(NO_ERROR, ret);
424 }
425 return NO_ERROR;
426 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800427 default:
428 return UNKNOWN_TRANSACTION;
429 }
430 }
431
432 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700433 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800434};
435
436class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
437{
438 private:
439 virtual void binderDied(const wp<IBinder>& who) {
440 (void)who;
441 triggerEvent();
442 };
443};
444
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700445TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
446 // EXPECT_DEATH works by forking the process
447 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
448}
449
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000450TEST_F(BinderLibTest, AddManagerToManager) {
451 sp<IServiceManager> sm = defaultServiceManager();
452 sp<IBinder> binder = IInterface::asBinder(sm);
453 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
454}
455
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500456TEST_F(BinderLibTest, WasParceled) {
457 auto binder = sp<BBinder>::make();
458 EXPECT_FALSE(binder->wasParceled());
459 Parcel data;
460 data.writeStrongBinder(binder);
461 EXPECT_TRUE(binder->wasParceled());
462}
463
Riley Andrews06b01ad2014-12-18 12:10:08 -0800464TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800465 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700466 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
467 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800468}
469
Steven Moreland80844f72020-12-12 02:06:08 +0000470TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000471 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700472 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
473 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000474}
475
Steven Morelandf183fdd2020-10-27 00:12:12 +0000476TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000477 Parcel data, reply;
478 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700479 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
480 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000481}
482
Marco Ballesio7ee17572020-09-08 10:30:03 -0700483TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700484 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700485 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700486
Li Li6f059292021-09-10 09:59:30 -0700487 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700488 if (freezer_file.fail()) {
489 GTEST_SKIP();
490 return;
491 }
492
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700493 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700494 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700495 for (int i = 0; i < 10; i++) {
496 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
497 }
Li Li6f059292021-09-10 09:59:30 -0700498
499 // Pass test on devices where BINDER_FREEZE ioctl is not supported
500 int ret = IPCThreadState::self()->freeze(pid, false, 0);
501 if (ret != 0) {
502 GTEST_SKIP();
503 return;
504 }
505
506 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
507 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
508 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700509 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700510
Li Li4e678b92021-09-14 12:14:42 -0700511 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700512
513 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
514 &async_received));
515
516 EXPECT_EQ(sync_received, 1);
517 EXPECT_EQ(async_received, 0);
518
Li Li4e678b92021-09-14 12:14:42 -0700519 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700520 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
521}
522
Riley Andrews06b01ad2014-12-18 12:10:08 -0800523TEST_F(BinderLibTest, SetError) {
524 int32_t testValue[] = { 0, -123, 123 };
525 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800526 Parcel data, reply;
527 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700528 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
529 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800530 }
531}
532
533TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700534 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800535}
536
537TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800538 int32_t ptrsize;
539 Parcel data, reply;
540 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700541 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700542 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
543 StatusEq(NO_ERROR));
544 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800545 RecordProperty("TestPtrSize", sizeof(void *));
546 RecordProperty("ServerPtrSize", sizeof(void *));
547}
548
549TEST_F(BinderLibTest, IndirectGetId2)
550{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800551 int32_t id;
552 int32_t count;
553 Parcel data, reply;
554 int32_t serverId[3];
555
556 data.writeInt32(ARRAY_SIZE(serverId));
557 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
558 sp<IBinder> server;
559 BinderLibTestBundle datai;
560
561 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700562 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800563 data.writeStrongBinder(server);
564 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
565 datai.appendTo(&data);
566 }
567
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700568 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
569 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800570
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700571 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800572 EXPECT_EQ(0, id);
573
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700574 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700575 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800576
577 for (size_t i = 0; i < (size_t)count; i++) {
578 BinderLibTestBundle replyi(&reply);
579 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700580 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800581 EXPECT_EQ(serverId[i], id);
582 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
583 }
584
585 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
586}
587
588TEST_F(BinderLibTest, IndirectGetId3)
589{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800590 int32_t id;
591 int32_t count;
592 Parcel data, reply;
593 int32_t serverId[3];
594
595 data.writeInt32(ARRAY_SIZE(serverId));
596 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
597 sp<IBinder> server;
598 BinderLibTestBundle datai;
599 BinderLibTestBundle datai2;
600
601 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700602 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800603 data.writeStrongBinder(server);
604 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
605
606 datai.writeInt32(1);
607 datai.writeStrongBinder(m_server);
608 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
609 datai2.appendTo(&datai);
610
611 datai.appendTo(&data);
612 }
613
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700614 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
615 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800616
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700617 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800618 EXPECT_EQ(0, id);
619
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700620 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700621 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800622
623 for (size_t i = 0; i < (size_t)count; i++) {
624 int32_t counti;
625
626 BinderLibTestBundle replyi(&reply);
627 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700628 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800629 EXPECT_EQ(serverId[i], id);
630
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700631 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800632 EXPECT_EQ(1, counti);
633
634 BinderLibTestBundle replyi2(&replyi);
635 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700636 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800637 EXPECT_EQ(0, id);
638 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
639
640 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
641 }
642
643 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
644}
645
646TEST_F(BinderLibTest, CallBack)
647{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800648 Parcel data, reply;
649 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
650 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700651 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
652 StatusEq(NO_ERROR));
653 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
654 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800655}
656
Steven Moreland35626652021-05-15 01:32:04 +0000657TEST_F(BinderLibTest, BinderCallContextGuard) {
658 sp<IBinder> binder = addServer();
659 Parcel data, reply;
660 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
661 StatusEq(DEAD_OBJECT));
662}
663
Riley Andrews06b01ad2014-12-18 12:10:08 -0800664TEST_F(BinderLibTest, AddServer)
665{
666 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700667 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800668}
669
Riley Andrews06b01ad2014-12-18 12:10:08 -0800670TEST_F(BinderLibTest, DeathNotificationStrongRef)
671{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800672 sp<IBinder> sbinder;
673
674 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
675
676 {
677 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700678 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700679 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800680 sbinder = binder;
681 }
682 {
683 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700684 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
685 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800686 }
687 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700688 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
689 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800690}
691
692TEST_F(BinderLibTest, DeathNotificationMultiple)
693{
694 status_t ret;
695 const int clientcount = 2;
696 sp<IBinder> target;
697 sp<IBinder> linkedclient[clientcount];
698 sp<BinderLibTestCallBack> callBack[clientcount];
699 sp<IBinder> passiveclient[clientcount];
700
701 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700702 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800703 for (int i = 0; i < clientcount; i++) {
704 {
705 Parcel data, reply;
706
707 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700708 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800709 callBack[i] = new BinderLibTestCallBack();
710 data.writeStrongBinder(target);
711 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700712 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
713 &reply, TF_ONE_WAY),
714 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800715 }
716 {
717 Parcel data, reply;
718
719 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700720 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800721 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700722 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
723 &reply, TF_ONE_WAY),
724 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800725 }
726 }
727 {
728 Parcel data, reply;
729 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
730 EXPECT_EQ(0, ret);
731 }
732
733 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700734 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
735 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800736 }
737}
738
Martijn Coenenf7100e42017-07-31 12:14:09 +0200739TEST_F(BinderLibTest, DeathNotificationThread)
740{
741 status_t ret;
742 sp<BinderLibTestCallBack> callback;
743 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700744 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200745 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700746 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200747
748 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
749
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700750 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200751
752 {
753 Parcel data, reply;
754 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
755 EXPECT_EQ(0, ret);
756 }
757
758 /* Make sure it's dead */
759 testDeathRecipient->waitEvent(5);
760
761 /* Now, pass the ref to another process and ask that process to
762 * call linkToDeath() on it, and wait for a response. This tests
763 * two things:
764 * 1) You still get death notifications when calling linkToDeath()
765 * on a ref that is already dead when it was passed to you.
766 * 2) That death notifications are not directly pushed to the thread
767 * registering them, but to the threadpool (proc workqueue) instead.
768 *
769 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
770 * is blocked on a condition variable waiting for the death notification to be
771 * called; therefore, that thread is not available for handling proc work.
772 * So, if the death notification was pushed to the thread workqueue, the callback
773 * would never be called, and the test would timeout and fail.
774 *
775 * Note that we can't do this part of the test from this thread itself, because
776 * the binder driver would only push death notifications to the thread if
777 * it is a looper thread, which this thread is not.
778 *
779 * See b/23525545 for details.
780 */
781 {
782 Parcel data, reply;
783
784 callback = new BinderLibTestCallBack();
785 data.writeStrongBinder(target);
786 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700787 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
788 TF_ONE_WAY),
789 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200790 }
791
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700792 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
793 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200794}
795
Riley Andrews06b01ad2014-12-18 12:10:08 -0800796TEST_F(BinderLibTest, PassFile) {
797 int ret;
798 int pipefd[2];
799 uint8_t buf[1] = { 0 };
800 uint8_t write_value = 123;
801
802 ret = pipe2(pipefd, O_NONBLOCK);
803 ASSERT_EQ(0, ret);
804
805 {
806 Parcel data, reply;
807 uint8_t writebuf[1] = { write_value };
808
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700809 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800810
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700811 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800812
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700813 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800814
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700815 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
816 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800817 }
818
819 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700820 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800821 EXPECT_EQ(write_value, buf[0]);
822
823 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
824
825 ret = read(pipefd[0], buf, sizeof(buf));
826 EXPECT_EQ(0, ret);
827
828 close(pipefd[0]);
829}
830
Ryo Hashimotobf551892018-05-31 16:58:35 +0900831TEST_F(BinderLibTest, PassParcelFileDescriptor) {
832 const int datasize = 123;
833 std::vector<uint8_t> writebuf(datasize);
834 for (size_t i = 0; i < writebuf.size(); ++i) {
835 writebuf[i] = i;
836 }
837
838 android::base::unique_fd read_end, write_end;
839 {
840 int pipefd[2];
841 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
842 read_end.reset(pipefd[0]);
843 write_end.reset(pipefd[1]);
844 }
845 {
846 Parcel data;
847 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
848 write_end.reset();
849 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
850 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
851
852 Parcel reply;
853 EXPECT_EQ(NO_ERROR,
854 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
855 &reply));
856 }
857 std::vector<uint8_t> readbuf(datasize);
858 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
859 EXPECT_EQ(writebuf, readbuf);
860
861 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
862
863 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
864}
865
Riley Andrews06b01ad2014-12-18 12:10:08 -0800866TEST_F(BinderLibTest, PromoteLocal) {
867 sp<IBinder> strong = new BBinder();
868 wp<IBinder> weak = strong;
869 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700870 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800871 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700872 strong = nullptr;
873 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800874 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700875 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800876}
877
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700878TEST_F(BinderLibTest, LocalGetExtension) {
879 sp<BBinder> binder = new BBinder();
880 sp<IBinder> ext = new BBinder();
881 binder->setExtension(ext);
882 EXPECT_EQ(ext, binder->getExtension());
883}
884
885TEST_F(BinderLibTest, RemoteGetExtension) {
886 sp<IBinder> server = addServer();
887 ASSERT_TRUE(server != nullptr);
888
889 sp<IBinder> extension;
890 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
891 ASSERT_NE(nullptr, extension.get());
892
893 EXPECT_EQ(NO_ERROR, extension->pingBinder());
894}
895
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700896TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700897 Parcel data, reply;
898
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700899 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
900 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700901
902 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700903 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800904 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
905 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
906 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
907 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700908}
909
Connor O'Brien52be2c92016-09-20 14:18:08 -0700910TEST_F(BinderLibTest, FreedBinder) {
911 status_t ret;
912
913 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700914 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700915
916 __u32 freedHandle;
917 wp<IBinder> keepFreedBinder;
918 {
919 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700920 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
921 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700922 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
923 freedHandle = freed->handle;
924 /* Add a weak ref to the freed binder so the driver does not
925 * delete its reference to it - otherwise the transaction
926 * fails regardless of whether the driver is fixed.
927 */
Steven Morelande171d622019-07-17 16:06:01 -0700928 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700929 }
Steven Morelande171d622019-07-17 16:06:01 -0700930 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700931 {
932 Parcel data, reply;
933 data.writeStrongBinder(server);
934 /* Replace original handle with handle to the freed binder */
935 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
936 __u32 oldHandle = strong->handle;
937 strong->handle = freedHandle;
938 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
939 /* Returns DEAD_OBJECT (-32) if target crashes and
940 * FAILED_TRANSACTION if the driver rejects the invalid
941 * object.
942 */
943 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
944 /* Restore original handle so parcel destructor does not use
945 * the wrong handle.
946 */
947 strong->handle = oldHandle;
948 }
949}
950
Sherry Yang336cdd32017-07-24 14:12:27 -0700951TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700952 Parcel data, reply;
953 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
954 for (int i = 0; i < 2; i++) {
955 BinderLibTestBundle datai;
956 datai.appendFrom(&data, 0, data.dataSize());
957
958 data.freeData();
959 data.writeInt32(1);
960 data.writeStrongBinder(callBack);
961 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
962
963 datai.appendTo(&data);
964 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700965 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
966 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700967}
968
Martijn Coenen45b07b42017-08-09 12:07:45 +0200969TEST_F(BinderLibTest, OnewayQueueing)
970{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200971 Parcel data, data2;
972
973 sp<IBinder> pollServer = addPollServer();
974
975 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
976 data.writeStrongBinder(callBack);
977 data.writeInt32(500000); // delay in us before calling back
978
979 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
980 data2.writeStrongBinder(callBack2);
981 data2.writeInt32(0); // delay in us
982
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700983 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
984 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200985
986 // The delay ensures that this second transaction will end up on the async_todo list
987 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700988 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
989 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200990
991 // The server will ensure that the two transactions are handled in the expected order;
992 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700993 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
994 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200995
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700996 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
997 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200998}
999
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001000TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1001{
1002 status_t ret;
1003 Parcel data, reply;
1004 data.writeInterfaceToken(binderLibTestServiceName);
1005 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1006 EXPECT_EQ(-1, reply.readInt32());
1007 EXPECT_EQ(NO_ERROR, ret);
1008}
1009
1010TEST_F(BinderLibTest, WorkSourceSet)
1011{
1012 status_t ret;
1013 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001014 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001015 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001016 data.writeInterfaceToken(binderLibTestServiceName);
1017 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1018 EXPECT_EQ(100, reply.readInt32());
1019 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001020 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1021 EXPECT_EQ(NO_ERROR, ret);
1022}
1023
1024TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1025{
1026 status_t ret;
1027 Parcel data, reply;
1028
1029 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1030 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1031
1032 data.writeInterfaceToken(binderLibTestServiceName);
1033 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1034 EXPECT_EQ(-1, reply.readInt32());
1035 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001036 EXPECT_EQ(NO_ERROR, ret);
1037}
1038
1039TEST_F(BinderLibTest, WorkSourceCleared)
1040{
1041 status_t ret;
1042 Parcel data, reply;
1043
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001044 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001045 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1046 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001047 data.writeInterfaceToken(binderLibTestServiceName);
1048 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1049
1050 EXPECT_EQ(-1, reply.readInt32());
1051 EXPECT_EQ(100, previousWorkSource);
1052 EXPECT_EQ(NO_ERROR, ret);
1053}
1054
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001055TEST_F(BinderLibTest, WorkSourceRestored)
1056{
1057 status_t ret;
1058 Parcel data, reply;
1059
1060 IPCThreadState::self()->setCallingWorkSourceUid(100);
1061 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1062 IPCThreadState::self()->restoreCallingWorkSource(token);
1063
1064 data.writeInterfaceToken(binderLibTestServiceName);
1065 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1066
1067 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001068 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001069 EXPECT_EQ(NO_ERROR, ret);
1070}
1071
Olivier Gaillard91a04802018-11-14 17:32:41 +00001072TEST_F(BinderLibTest, PropagateFlagSet)
1073{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001074 IPCThreadState::self()->clearPropagateWorkSource();
1075 IPCThreadState::self()->setCallingWorkSourceUid(100);
1076 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1077}
1078
1079TEST_F(BinderLibTest, PropagateFlagCleared)
1080{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001081 IPCThreadState::self()->setCallingWorkSourceUid(100);
1082 IPCThreadState::self()->clearPropagateWorkSource();
1083 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1084}
1085
1086TEST_F(BinderLibTest, PropagateFlagRestored)
1087{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001088 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1089 IPCThreadState::self()->restoreCallingWorkSource(token);
1090
1091 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1092}
1093
1094TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1095{
1096 IPCThreadState::self()->setCallingWorkSourceUid(100);
1097
1098 Parcel data, reply;
1099 status_t ret;
1100 data.writeInterfaceToken(binderLibTestServiceName);
1101 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1102
1103 Parcel data2, reply2;
1104 status_t ret2;
1105 data2.writeInterfaceToken(binderLibTestServiceName);
1106 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1107 EXPECT_EQ(100, reply2.readInt32());
1108 EXPECT_EQ(NO_ERROR, ret2);
1109}
1110
Steven Morelandbf1915b2020-07-16 22:43:02 +00001111TEST_F(BinderLibTest, SchedPolicySet) {
1112 sp<IBinder> server = addServer();
1113 ASSERT_TRUE(server != nullptr);
1114
1115 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001116 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1117 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001118
1119 int policy = reply.readInt32();
1120 int priority = reply.readInt32();
1121
1122 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1123 EXPECT_EQ(kSchedPriority, priority);
1124}
1125
Steven Morelandcf03cf12020-12-04 02:58:40 +00001126TEST_F(BinderLibTest, InheritRt) {
1127 sp<IBinder> server = addServer();
1128 ASSERT_TRUE(server != nullptr);
1129
1130 const struct sched_param param {
1131 .sched_priority = kSchedPriorityMore,
1132 };
1133 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1134
1135 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001136 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1137 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001138
1139 int policy = reply.readInt32();
1140 int priority = reply.readInt32();
1141
1142 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1143 EXPECT_EQ(kSchedPriorityMore, priority);
1144}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001145
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001146TEST_F(BinderLibTest, VectorSent) {
1147 Parcel data, reply;
1148 sp<IBinder> server = addServer();
1149 ASSERT_TRUE(server != nullptr);
1150
1151 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1152 data.writeUint64Vector(testValue);
1153
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001154 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001155 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001156 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001157 EXPECT_EQ(readValue, testValue);
1158}
1159
Martijn Coenen82c75312019-07-24 15:18:30 +02001160TEST_F(BinderLibTest, BufRejected) {
1161 Parcel data, reply;
1162 uint32_t buf;
1163 sp<IBinder> server = addServer();
1164 ASSERT_TRUE(server != nullptr);
1165
1166 binder_buffer_object obj {
1167 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001168 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001169 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1170 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001171 };
1172 data.setDataCapacity(1024);
1173 // Write a bogus object at offset 0 to get an entry in the offset table
1174 data.writeFileDescriptor(0);
1175 EXPECT_EQ(data.objectsCount(), 1);
1176 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1177 // And now, overwrite it with the buffer object
1178 memcpy(parcelData, &obj, sizeof(obj));
1179 data.setDataSize(sizeof(obj));
1180
Steven Morelandf2e0a952021-11-01 18:17:23 -07001181 EXPECT_EQ(data.objectsCount(), 1);
1182
Martijn Coenen82c75312019-07-24 15:18:30 +02001183 // Either the kernel should reject this transaction (if it's correct), but
1184 // if it's not, the server implementation should return an error if it
1185 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001186 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001187 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001188}
1189
Steven Morelandf2e0a952021-11-01 18:17:23 -07001190TEST_F(BinderLibTest, WeakRejected) {
1191 Parcel data, reply;
1192 sp<IBinder> server = addServer();
1193 ASSERT_TRUE(server != nullptr);
1194
1195 auto binder = sp<BBinder>::make();
1196 wp<BBinder> wpBinder(binder);
1197 flat_binder_object obj{
1198 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1199 .flags = 0,
1200 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1201 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1202 };
1203 data.setDataCapacity(1024);
1204 // Write a bogus object at offset 0 to get an entry in the offset table
1205 data.writeFileDescriptor(0);
1206 EXPECT_EQ(data.objectsCount(), 1);
1207 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1208 // And now, overwrite it with the weak binder
1209 memcpy(parcelData, &obj, sizeof(obj));
1210 data.setDataSize(sizeof(obj));
1211
1212 // a previous bug caused other objects to be released an extra time, so we
1213 // test with an object that libbinder will actually try to release
1214 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1215
1216 EXPECT_EQ(data.objectsCount(), 2);
1217
1218 // send it many times, since previous error was memory corruption, make it
1219 // more likely that the server crashes
1220 for (size_t i = 0; i < 100; i++) {
1221 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1222 StatusEq(BAD_VALUE));
1223 }
1224
1225 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1226}
1227
Steven Moreland254e8ef2021-04-19 22:28:50 +00001228TEST_F(BinderLibTest, GotSid) {
1229 sp<IBinder> server = addServer();
1230
1231 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001232 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001233}
1234
Jayant Chowdhary30700942022-01-31 14:12:40 -08001235TEST(ServiceNotifications, Unregister) {
1236 auto sm = defaultServiceManager();
1237 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1238 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1239 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1240 virtual ~LocalRegistrationCallbackImpl() {}
1241 };
1242 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1243
1244 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1245 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1246}
1247
Elie Kheirallah47431c12022-04-21 23:46:17 +00001248TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1249 Parcel data, reply;
1250 sp<IBinder> server = addServer();
1251 ASSERT_TRUE(server != nullptr);
1252 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1253 StatusEq(NO_ERROR));
1254 int32_t replyi = reply.readInt32();
1255 // Expect 16 threads: kKernelThreads = 15 + Pool thread == 16
1256 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
1257 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1258
1259 /*
1260 * This will use all threads in the pool expect the main pool thread.
1261 * The service should run fine without locking, and the thread count should
1262 * not exceed 16 (15 Max + pool thread).
1263 */
1264 std::vector<std::thread> ts;
1265 for (size_t i = 0; i < kKernelThreads - 1; i++) {
1266 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001267 Parcel local_reply;
1268 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1269 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001270 }));
1271 }
1272
1273 data.writeInt32(1);
1274 // Give a chance for all threads to be used
1275 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1276
1277 for (auto &t : ts) {
1278 t.join();
1279 }
1280
1281 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1282 StatusEq(NO_ERROR));
1283 replyi = reply.readInt32();
1284 // No more than 16 threads should exist.
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001285 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001286}
1287
1288size_t epochMillis() {
1289 using std::chrono::duration_cast;
1290 using std::chrono::milliseconds;
1291 using std::chrono::seconds;
1292 using std::chrono::system_clock;
1293 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1294}
1295
1296TEST_F(BinderLibTest, HangingServices) {
1297 Parcel data, reply;
1298 sp<IBinder> server = addServer();
1299 ASSERT_TRUE(server != nullptr);
1300 int32_t delay = 1000; // ms
1301 data.writeInt32(delay);
1302 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1303 std::vector<std::thread> ts;
1304 size_t epochMsBefore = epochMillis();
1305 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1306 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001307 Parcel local_reply;
1308 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1309 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001310 }));
1311 }
1312
1313 for (auto &t : ts) {
1314 t.join();
1315 }
1316 size_t epochMsAfter = epochMillis();
1317
1318 // deadlock occurred and threads only finished after 1s passed.
1319 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1320}
1321
Yifan Hong84bedeb2021-04-21 21:37:17 -07001322class BinderLibRpcTestBase : public BinderLibTest {
1323public:
1324 void SetUp() override {
1325 if (!base::GetBoolProperty("ro.debuggable", false)) {
1326 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1327 "non-debuggable builds.";
1328 }
1329 BinderLibTest::SetUp();
1330 }
1331
1332 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1333 auto rpcServer = RpcServer::make();
1334 EXPECT_NE(nullptr, rpcServer);
1335 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001336 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001337 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1338 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001339 return {};
1340 }
1341 return {rpcServer->releaseServer(), port};
1342 }
1343};
1344
Yifan Hong8b890852021-06-10 13:44:09 -07001345class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001346
Yifan Hongbd276552022-02-28 15:28:51 -08001347// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1348// If device is debuggable AND not on user builds, expects matcher.
1349// Otherwise expects INVALID_OPERATION.
1350// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1351static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1352 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1353 android::base::GetProperty("ro.build.type", "") != "user";
1354 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1355}
1356
Yifan Hong8b890852021-06-10 13:44:09 -07001357TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1358 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001359 ASSERT_TRUE(binder != nullptr);
1360 auto [socket, port] = CreateSocket();
1361 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001362 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1363 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001364}
1365
Yifan Hong8b890852021-06-10 13:44:09 -07001366// Tests for multiple RpcServer's on the same binder object.
1367TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1368 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001369 ASSERT_TRUE(binder != nullptr);
1370
1371 auto [socket1, port1] = CreateSocket();
1372 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001373 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001374 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1375 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001376
1377 auto [socket2, port2] = CreateSocket();
1378 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001379 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001380 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1381 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001382}
1383
Yifan Hong8b890852021-06-10 13:44:09 -07001384// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1385// local binders.
1386class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001387public:
1388 sp<IBinder> GetService() {
1389 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1390 }
1391 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1392 return info.param ? "remote" : "local";
1393 }
1394};
1395
Yifan Hong8b890852021-06-10 13:44:09 -07001396TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1397 auto binder = GetService();
1398 ASSERT_TRUE(binder != nullptr);
1399 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001400 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001401}
1402
1403TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001404 auto binder = GetService();
1405 ASSERT_TRUE(binder != nullptr);
1406 auto [socket, port] = CreateSocket();
1407 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001408 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1409 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001410}
Yifan Hong8b890852021-06-10 13:44:09 -07001411INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1412 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001413
Yifan Hong543edcd2021-05-18 19:47:30 -07001414class BinderLibTestService : public BBinder {
1415public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001416 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1417 : m_id(id),
1418 m_nextServerId(id + 1),
1419 m_serverStartRequested(false),
1420 m_callback(nullptr),
1421 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001422 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1423 pthread_cond_init(&m_serverWaitCond, nullptr);
1424 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001425 ~BinderLibTestService() {
1426 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1427 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001428
Yifan Hong543edcd2021-05-18 19:47:30 -07001429 void processPendingCall() {
1430 if (m_callback != nullptr) {
1431 Parcel data;
1432 data.writeInt32(NO_ERROR);
1433 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1434 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001435 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001436 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001437
Yifan Hong543edcd2021-05-18 19:47:30 -07001438 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1439 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001440 // TODO(b/182914638): also checks getCallingUid() for RPC
1441 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001442 return PERMISSION_DENIED;
1443 }
1444 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001445 case BINDER_LIB_TEST_REGISTER_SERVER: {
1446 int32_t id;
1447 sp<IBinder> binder;
1448 id = data.readInt32();
1449 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001450 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001451 return BAD_VALUE;
1452 }
1453
Yifan Hong543edcd2021-05-18 19:47:30 -07001454 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001455
1456 pthread_mutex_lock(&m_serverWaitMutex);
1457 if (m_serverStartRequested) {
1458 m_serverStartRequested = false;
1459 m_serverStarted = binder;
1460 pthread_cond_signal(&m_serverWaitCond);
1461 }
1462 pthread_mutex_unlock(&m_serverWaitMutex);
1463 return NO_ERROR;
1464 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001465 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001466 case BINDER_LIB_TEST_ADD_SERVER: {
1467 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001468 int serverid;
1469
1470 if (m_id != 0) {
1471 return INVALID_OPERATION;
1472 }
1473 pthread_mutex_lock(&m_serverWaitMutex);
1474 if (m_serverStartRequested) {
1475 ret = -EBUSY;
1476 } else {
1477 serverid = m_nextServerId++;
1478 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001479 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001480
1481 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001482 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001483 pthread_mutex_lock(&m_serverWaitMutex);
1484 }
1485 if (ret > 0) {
1486 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001487 struct timespec ts;
1488 clock_gettime(CLOCK_REALTIME, &ts);
1489 ts.tv_sec += 5;
1490 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001491 }
1492 if (m_serverStartRequested) {
1493 m_serverStartRequested = false;
1494 ret = -ETIMEDOUT;
1495 } else {
1496 reply->writeStrongBinder(m_serverStarted);
1497 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001498 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001499 ret = NO_ERROR;
1500 }
1501 } else if (ret >= 0) {
1502 m_serverStartRequested = false;
1503 ret = UNKNOWN_ERROR;
1504 }
1505 pthread_mutex_unlock(&m_serverWaitMutex);
1506 return ret;
1507 }
Steven Moreland35626652021-05-15 01:32:04 +00001508 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1509 IPCThreadState::SpGuard spGuard{
1510 .address = __builtin_frame_address(0),
1511 .context = "GuardInBinderTransaction",
1512 };
1513 const IPCThreadState::SpGuard *origGuard =
1514 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1515
1516 // if the guard works, this should abort
1517 (void)IPCThreadState::self()->getCallingPid();
1518
1519 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1520 return NO_ERROR;
1521 }
1522
Marco Ballesio7ee17572020-09-08 10:30:03 -07001523 case BINDER_LIB_TEST_GETPID:
1524 reply->writeInt32(getpid());
1525 return NO_ERROR;
1526 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1527 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001528 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001529 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001530 // oneway error codes should be ignored
1531 if (flags & TF_ONE_WAY) {
1532 return UNKNOWN_ERROR;
1533 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001534 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001535 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1536 // Note: this transaction is only designed for use with a
1537 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001538 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001539 // A callback was already pending; this means that
1540 // we received a second call while still processing
1541 // the first one. Fail the test.
1542 sp<IBinder> callback = data.readStrongBinder();
1543 Parcel data2;
1544 data2.writeInt32(UNKNOWN_ERROR);
1545
Yi Kong91635562018-06-07 14:38:36 -07001546 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001547 } else {
1548 m_callback = data.readStrongBinder();
1549 int32_t delayUs = data.readInt32();
1550 /*
1551 * It's necessary that we sleep here, so the next
1552 * transaction the caller makes will be queued to
1553 * the async queue.
1554 */
1555 usleep(delayUs);
1556
1557 /*
1558 * Now when we return, libbinder will tell the kernel
1559 * we are done with this transaction, and the kernel
1560 * can move the queued transaction to either the
1561 * thread todo worklist (for kernels without the fix),
1562 * or the proc todo worklist. In case of the former,
1563 * the next outbound call will pick up the pending
1564 * transaction, which leads to undesired reentrant
1565 * behavior. This is caught in the if() branch above.
1566 */
1567 }
1568
1569 return NO_ERROR;
1570 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001571 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1572 Parcel data2, reply2;
1573 sp<IBinder> binder;
1574 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001575 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001576 return BAD_VALUE;
1577 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001578 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001579 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1580 return NO_ERROR;
1581 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001582 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1583 reply->writeStrongBinder(this);
1584 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001585 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1586 reply->writeInt32(m_id);
1587 return NO_ERROR;
1588 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1589 int32_t count;
1590 uint32_t indirect_code;
1591 sp<IBinder> binder;
1592
1593 count = data.readInt32();
1594 reply->writeInt32(m_id);
1595 reply->writeInt32(count);
1596 for (int i = 0; i < count; i++) {
1597 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001598 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001599 return BAD_VALUE;
1600 }
1601 indirect_code = data.readInt32();
1602 BinderLibTestBundle data2(&data);
1603 if (!data2.isValid()) {
1604 return BAD_VALUE;
1605 }
1606 BinderLibTestBundle reply2;
1607 binder->transact(indirect_code, data2, &reply2);
1608 reply2.appendTo(reply);
1609 }
1610 return NO_ERROR;
1611 }
1612 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1613 reply->setError(data.readInt32());
1614 return NO_ERROR;
1615 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1616 reply->writeInt32(sizeof(void *));
1617 return NO_ERROR;
1618 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1619 return NO_ERROR;
1620 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1621 m_strongRef = data.readStrongBinder();
1622 return NO_ERROR;
1623 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1624 int ret;
1625 Parcel data2, reply2;
1626 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1627 sp<IBinder> target;
1628 sp<IBinder> callback;
1629
1630 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001631 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001632 return BAD_VALUE;
1633 }
1634 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001635 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001636 return BAD_VALUE;
1637 }
1638 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001639 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001640 data2.writeInt32(ret);
1641 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1642 return NO_ERROR;
1643 }
1644 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1645 int ret;
1646 int32_t size;
1647 const void *buf;
1648 int fd;
1649
1650 fd = data.readFileDescriptor();
1651 if (fd < 0) {
1652 return BAD_VALUE;
1653 }
1654 ret = data.readInt32(&size);
1655 if (ret != NO_ERROR) {
1656 return ret;
1657 }
1658 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001659 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001660 return BAD_VALUE;
1661 }
1662 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001663 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001664 return NO_ERROR;
1665 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001666 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1667 int ret;
1668 int32_t size;
1669 const void *buf;
1670 android::base::unique_fd fd;
1671
1672 ret = data.readUniqueParcelFileDescriptor(&fd);
1673 if (ret != NO_ERROR) {
1674 return ret;
1675 }
1676 ret = data.readInt32(&size);
1677 if (ret != NO_ERROR) {
1678 return ret;
1679 }
1680 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001681 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001682 return BAD_VALUE;
1683 }
1684 ret = write(fd.get(), buf, size);
1685 if (ret != size) return UNKNOWN_ERROR;
1686 return NO_ERROR;
1687 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001688 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1689 alarm(10);
1690 return NO_ERROR;
1691 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001692 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001693 ;
1694 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001695 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001696 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001697 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001698 return NO_ERROR;
1699 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001700 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1701 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001702 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001703 return NO_ERROR;
1704 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001705 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1706 int policy = 0;
1707 sched_param param;
1708 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1709 return UNKNOWN_ERROR;
1710 }
1711 reply->writeInt32(policy);
1712 reply->writeInt32(param.sched_priority);
1713 return NO_ERROR;
1714 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001715 case BINDER_LIB_TEST_ECHO_VECTOR: {
1716 std::vector<uint64_t> vector;
1717 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001718 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001719 reply->writeUint64Vector(vector);
1720 return NO_ERROR;
1721 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001722 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001723 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1724 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001725 case BINDER_LIB_TEST_CAN_GET_SID: {
1726 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1727 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001728 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1729 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1730 return NO_ERROR;
1731 }
1732 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001733 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001734 return NO_ERROR;
1735 }
1736 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001737 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001738 return NO_ERROR;
1739 }
1740 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1741 int32_t ms = data.readInt32();
1742 return unlockInMs(ms);
1743 }
1744 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001745 m_blockMutex.lock();
1746 sp<BinderLibTestService> thisService = this;
1747 int32_t value = data.readInt32();
1748 // start local thread to unlock in 1s
1749 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001750 t.detach();
1751 return NO_ERROR;
1752 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001753 default:
1754 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001755 };
1756 }
1757
Elie Kheirallah47431c12022-04-21 23:46:17 +00001758 status_t unlockInMs(int32_t ms) {
1759 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001760 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001761 return NO_ERROR;
1762 }
1763
Yifan Hong543edcd2021-05-18 19:47:30 -07001764private:
1765 int32_t m_id;
1766 int32_t m_nextServerId;
1767 pthread_mutex_t m_serverWaitMutex;
1768 pthread_cond_t m_serverWaitCond;
1769 bool m_serverStartRequested;
1770 sp<IBinder> m_serverStarted;
1771 sp<IBinder> m_strongRef;
1772 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001773 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001774 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001775};
1776
Martijn Coenen45b07b42017-08-09 12:07:45 +02001777int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001778{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001779 binderLibTestServiceName += String16(binderserversuffix);
1780
Steven Moreland35626652021-05-15 01:32:04 +00001781 // Testing to make sure that calls that we are serving can use getCallin*
1782 // even though we don't here.
1783 IPCThreadState::SpGuard spGuard{
1784 .address = __builtin_frame_address(0),
1785 .context = "main server thread",
1786 };
1787 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1788
Riley Andrews06b01ad2014-12-18 12:10:08 -08001789 status_t ret;
1790 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001791 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001792 {
1793 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001794
Steven Morelandbf1915b2020-07-16 22:43:02 +00001795 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1796
Steven Morelandcf03cf12020-12-04 02:58:40 +00001797 testService->setInheritRt(true);
1798
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001799 /*
1800 * Normally would also contain functionality as well, but we are only
1801 * testing the extension mechanism.
1802 */
1803 testService->setExtension(new BBinder());
1804
Martijn Coenen82c75312019-07-24 15:18:30 +02001805 // Required for test "BufRejected'
1806 testService->setRequestingSid(true);
1807
Martijn Coenen45b07b42017-08-09 12:07:45 +02001808 /*
1809 * We need this below, but can't hold a sp<> because it prevents the
1810 * node from being cleaned up automatically. It's safe in this case
1811 * because of how the tests are written.
1812 */
1813 testServicePtr = testService.get();
1814
Riley Andrews06b01ad2014-12-18 12:10:08 -08001815 if (index == 0) {
1816 ret = sm->addService(binderLibTestServiceName, testService);
1817 } else {
1818 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1819 Parcel data, reply;
1820 data.writeInt32(index);
1821 data.writeStrongBinder(testService);
1822
1823 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1824 }
1825 }
1826 write(readypipefd, &ret, sizeof(ret));
1827 close(readypipefd);
1828 //printf("%s: ret %d\n", __func__, ret);
1829 if (ret)
1830 return 1;
1831 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001832 if (usePoll) {
1833 int fd;
1834 struct epoll_event ev;
1835 int epoll_fd;
1836 IPCThreadState::self()->setupPolling(&fd);
1837 if (fd < 0) {
1838 return 1;
1839 }
1840 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1841
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001842 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001843 if (epoll_fd == -1) {
1844 return 1;
1845 }
1846
1847 ev.events = EPOLLIN;
1848 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1849 return 1;
1850 }
1851
1852 while (1) {
1853 /*
1854 * We simulate a single-threaded process using the binder poll
1855 * interface; besides handling binder commands, it can also
1856 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001857 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001858 *
1859 * processPendingCall() will then issue that transaction.
1860 */
1861 struct epoll_event events[1];
1862 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1863 if (numEvents < 0) {
1864 if (errno == EINTR) {
1865 continue;
1866 }
1867 return 1;
1868 }
1869 if (numEvents > 0) {
1870 IPCThreadState::self()->handlePolledCommands();
1871 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
1872 testServicePtr->processPendingCall();
1873 }
1874 }
1875 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001876 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001877 ProcessState::self()->startThreadPool();
1878 IPCThreadState::self()->joinThreadPool();
1879 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001880 //printf("%s: joinThreadPool returned\n", __func__);
1881 return 1; /* joinThreadPool should not return */
1882}
1883
1884int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07001885 ExitIfWrongAbi();
1886
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001887 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001888 binderservername = argv[2];
1889 } else {
1890 binderservername = argv[0];
1891 }
1892
Martijn Coenen45b07b42017-08-09 12:07:45 +02001893 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
1894 binderserversuffix = argv[5];
1895 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001896 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001897 binderserversuffix = new char[16];
1898 snprintf(binderserversuffix, 16, "%d", getpid());
1899 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001900
1901 ::testing::InitGoogleTest(&argc, argv);
1902 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
1903 ProcessState::self()->startThreadPool();
1904 return RUN_ALL_TESTS();
1905}