blob: 18a9f86f8ef6c3f6968e8d87b0ac1d0879eb15da [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([&] {
1267 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &reply), NO_ERROR);
1268 }));
1269 }
1270
1271 data.writeInt32(1);
1272 // Give a chance for all threads to be used
1273 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1274
1275 for (auto &t : ts) {
1276 t.join();
1277 }
1278
1279 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1280 StatusEq(NO_ERROR));
1281 replyi = reply.readInt32();
1282 // No more than 16 threads should exist.
1283 EXPECT_EQ(replyi, kKernelThreads + 1);
1284}
1285
1286size_t epochMillis() {
1287 using std::chrono::duration_cast;
1288 using std::chrono::milliseconds;
1289 using std::chrono::seconds;
1290 using std::chrono::system_clock;
1291 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1292}
1293
1294TEST_F(BinderLibTest, HangingServices) {
1295 Parcel data, reply;
1296 sp<IBinder> server = addServer();
1297 ASSERT_TRUE(server != nullptr);
1298 int32_t delay = 1000; // ms
1299 data.writeInt32(delay);
1300 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1301 std::vector<std::thread> ts;
1302 size_t epochMsBefore = epochMillis();
1303 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1304 ts.push_back(std::thread([&] {
1305 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &reply), NO_ERROR);
1306 }));
1307 }
1308
1309 for (auto &t : ts) {
1310 t.join();
1311 }
1312 size_t epochMsAfter = epochMillis();
1313
1314 // deadlock occurred and threads only finished after 1s passed.
1315 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1316}
1317
Yifan Hong84bedeb2021-04-21 21:37:17 -07001318class BinderLibRpcTestBase : public BinderLibTest {
1319public:
1320 void SetUp() override {
1321 if (!base::GetBoolProperty("ro.debuggable", false)) {
1322 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1323 "non-debuggable builds.";
1324 }
1325 BinderLibTest::SetUp();
1326 }
1327
1328 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1329 auto rpcServer = RpcServer::make();
1330 EXPECT_NE(nullptr, rpcServer);
1331 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001332 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001333 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1334 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001335 return {};
1336 }
1337 return {rpcServer->releaseServer(), port};
1338 }
1339};
1340
Yifan Hong8b890852021-06-10 13:44:09 -07001341class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001342
Yifan Hongbd276552022-02-28 15:28:51 -08001343// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1344// If device is debuggable AND not on user builds, expects matcher.
1345// Otherwise expects INVALID_OPERATION.
1346// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1347static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1348 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1349 android::base::GetProperty("ro.build.type", "") != "user";
1350 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1351}
1352
Yifan Hong8b890852021-06-10 13:44:09 -07001353TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1354 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001355 ASSERT_TRUE(binder != nullptr);
1356 auto [socket, port] = CreateSocket();
1357 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001358 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1359 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001360}
1361
Yifan Hong8b890852021-06-10 13:44:09 -07001362// Tests for multiple RpcServer's on the same binder object.
1363TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1364 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001365 ASSERT_TRUE(binder != nullptr);
1366
1367 auto [socket1, port1] = CreateSocket();
1368 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001369 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001370 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1371 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001372
1373 auto [socket2, port2] = CreateSocket();
1374 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001375 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001376 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1377 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001378}
1379
Yifan Hong8b890852021-06-10 13:44:09 -07001380// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1381// local binders.
1382class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001383public:
1384 sp<IBinder> GetService() {
1385 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1386 }
1387 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1388 return info.param ? "remote" : "local";
1389 }
1390};
1391
Yifan Hong8b890852021-06-10 13:44:09 -07001392TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1393 auto binder = GetService();
1394 ASSERT_TRUE(binder != nullptr);
1395 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001396 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001397}
1398
1399TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001400 auto binder = GetService();
1401 ASSERT_TRUE(binder != nullptr);
1402 auto [socket, port] = CreateSocket();
1403 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001404 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1405 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001406}
Yifan Hong8b890852021-06-10 13:44:09 -07001407INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1408 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001409
Yifan Hong543edcd2021-05-18 19:47:30 -07001410class BinderLibTestService : public BBinder {
1411public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001412 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1413 : m_id(id),
1414 m_nextServerId(id + 1),
1415 m_serverStartRequested(false),
1416 m_callback(nullptr),
1417 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001418 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1419 pthread_cond_init(&m_serverWaitCond, nullptr);
1420 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001421 ~BinderLibTestService() {
1422 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1423 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001424
Yifan Hong543edcd2021-05-18 19:47:30 -07001425 void processPendingCall() {
1426 if (m_callback != nullptr) {
1427 Parcel data;
1428 data.writeInt32(NO_ERROR);
1429 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1430 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001431 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001432 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001433
Yifan Hong543edcd2021-05-18 19:47:30 -07001434 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1435 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001436 // TODO(b/182914638): also checks getCallingUid() for RPC
1437 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001438 return PERMISSION_DENIED;
1439 }
1440 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001441 case BINDER_LIB_TEST_REGISTER_SERVER: {
1442 int32_t id;
1443 sp<IBinder> binder;
1444 id = data.readInt32();
1445 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001446 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001447 return BAD_VALUE;
1448 }
1449
Yifan Hong543edcd2021-05-18 19:47:30 -07001450 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001451
1452 pthread_mutex_lock(&m_serverWaitMutex);
1453 if (m_serverStartRequested) {
1454 m_serverStartRequested = false;
1455 m_serverStarted = binder;
1456 pthread_cond_signal(&m_serverWaitCond);
1457 }
1458 pthread_mutex_unlock(&m_serverWaitMutex);
1459 return NO_ERROR;
1460 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001461 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001462 case BINDER_LIB_TEST_ADD_SERVER: {
1463 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001464 int serverid;
1465
1466 if (m_id != 0) {
1467 return INVALID_OPERATION;
1468 }
1469 pthread_mutex_lock(&m_serverWaitMutex);
1470 if (m_serverStartRequested) {
1471 ret = -EBUSY;
1472 } else {
1473 serverid = m_nextServerId++;
1474 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001475 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001476
1477 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001478 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001479 pthread_mutex_lock(&m_serverWaitMutex);
1480 }
1481 if (ret > 0) {
1482 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001483 struct timespec ts;
1484 clock_gettime(CLOCK_REALTIME, &ts);
1485 ts.tv_sec += 5;
1486 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001487 }
1488 if (m_serverStartRequested) {
1489 m_serverStartRequested = false;
1490 ret = -ETIMEDOUT;
1491 } else {
1492 reply->writeStrongBinder(m_serverStarted);
1493 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001494 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001495 ret = NO_ERROR;
1496 }
1497 } else if (ret >= 0) {
1498 m_serverStartRequested = false;
1499 ret = UNKNOWN_ERROR;
1500 }
1501 pthread_mutex_unlock(&m_serverWaitMutex);
1502 return ret;
1503 }
Steven Moreland35626652021-05-15 01:32:04 +00001504 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1505 IPCThreadState::SpGuard spGuard{
1506 .address = __builtin_frame_address(0),
1507 .context = "GuardInBinderTransaction",
1508 };
1509 const IPCThreadState::SpGuard *origGuard =
1510 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1511
1512 // if the guard works, this should abort
1513 (void)IPCThreadState::self()->getCallingPid();
1514
1515 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1516 return NO_ERROR;
1517 }
1518
Marco Ballesio7ee17572020-09-08 10:30:03 -07001519 case BINDER_LIB_TEST_GETPID:
1520 reply->writeInt32(getpid());
1521 return NO_ERROR;
1522 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1523 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001524 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001525 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001526 // oneway error codes should be ignored
1527 if (flags & TF_ONE_WAY) {
1528 return UNKNOWN_ERROR;
1529 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001530 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001531 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1532 // Note: this transaction is only designed for use with a
1533 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001534 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001535 // A callback was already pending; this means that
1536 // we received a second call while still processing
1537 // the first one. Fail the test.
1538 sp<IBinder> callback = data.readStrongBinder();
1539 Parcel data2;
1540 data2.writeInt32(UNKNOWN_ERROR);
1541
Yi Kong91635562018-06-07 14:38:36 -07001542 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001543 } else {
1544 m_callback = data.readStrongBinder();
1545 int32_t delayUs = data.readInt32();
1546 /*
1547 * It's necessary that we sleep here, so the next
1548 * transaction the caller makes will be queued to
1549 * the async queue.
1550 */
1551 usleep(delayUs);
1552
1553 /*
1554 * Now when we return, libbinder will tell the kernel
1555 * we are done with this transaction, and the kernel
1556 * can move the queued transaction to either the
1557 * thread todo worklist (for kernels without the fix),
1558 * or the proc todo worklist. In case of the former,
1559 * the next outbound call will pick up the pending
1560 * transaction, which leads to undesired reentrant
1561 * behavior. This is caught in the if() branch above.
1562 */
1563 }
1564
1565 return NO_ERROR;
1566 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001567 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1568 Parcel data2, reply2;
1569 sp<IBinder> binder;
1570 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001571 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001572 return BAD_VALUE;
1573 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001574 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001575 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1576 return NO_ERROR;
1577 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001578 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1579 reply->writeStrongBinder(this);
1580 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001581 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1582 reply->writeInt32(m_id);
1583 return NO_ERROR;
1584 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1585 int32_t count;
1586 uint32_t indirect_code;
1587 sp<IBinder> binder;
1588
1589 count = data.readInt32();
1590 reply->writeInt32(m_id);
1591 reply->writeInt32(count);
1592 for (int i = 0; i < count; i++) {
1593 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001594 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001595 return BAD_VALUE;
1596 }
1597 indirect_code = data.readInt32();
1598 BinderLibTestBundle data2(&data);
1599 if (!data2.isValid()) {
1600 return BAD_VALUE;
1601 }
1602 BinderLibTestBundle reply2;
1603 binder->transact(indirect_code, data2, &reply2);
1604 reply2.appendTo(reply);
1605 }
1606 return NO_ERROR;
1607 }
1608 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1609 reply->setError(data.readInt32());
1610 return NO_ERROR;
1611 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1612 reply->writeInt32(sizeof(void *));
1613 return NO_ERROR;
1614 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1615 return NO_ERROR;
1616 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1617 m_strongRef = data.readStrongBinder();
1618 return NO_ERROR;
1619 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1620 int ret;
1621 Parcel data2, reply2;
1622 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1623 sp<IBinder> target;
1624 sp<IBinder> callback;
1625
1626 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001627 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001628 return BAD_VALUE;
1629 }
1630 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001631 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001632 return BAD_VALUE;
1633 }
1634 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001635 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001636 data2.writeInt32(ret);
1637 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1638 return NO_ERROR;
1639 }
1640 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1641 int ret;
1642 int32_t size;
1643 const void *buf;
1644 int fd;
1645
1646 fd = data.readFileDescriptor();
1647 if (fd < 0) {
1648 return BAD_VALUE;
1649 }
1650 ret = data.readInt32(&size);
1651 if (ret != NO_ERROR) {
1652 return ret;
1653 }
1654 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001655 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001656 return BAD_VALUE;
1657 }
1658 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001659 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001660 return NO_ERROR;
1661 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001662 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1663 int ret;
1664 int32_t size;
1665 const void *buf;
1666 android::base::unique_fd fd;
1667
1668 ret = data.readUniqueParcelFileDescriptor(&fd);
1669 if (ret != NO_ERROR) {
1670 return ret;
1671 }
1672 ret = data.readInt32(&size);
1673 if (ret != NO_ERROR) {
1674 return ret;
1675 }
1676 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001677 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001678 return BAD_VALUE;
1679 }
1680 ret = write(fd.get(), buf, size);
1681 if (ret != size) return UNKNOWN_ERROR;
1682 return NO_ERROR;
1683 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001684 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1685 alarm(10);
1686 return NO_ERROR;
1687 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001688 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001689 ;
1690 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001691 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001692 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001693 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001694 return NO_ERROR;
1695 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001696 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1697 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001698 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001699 return NO_ERROR;
1700 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001701 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1702 int policy = 0;
1703 sched_param param;
1704 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1705 return UNKNOWN_ERROR;
1706 }
1707 reply->writeInt32(policy);
1708 reply->writeInt32(param.sched_priority);
1709 return NO_ERROR;
1710 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001711 case BINDER_LIB_TEST_ECHO_VECTOR: {
1712 std::vector<uint64_t> vector;
1713 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001714 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001715 reply->writeUint64Vector(vector);
1716 return NO_ERROR;
1717 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001718 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001719 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1720 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001721 case BINDER_LIB_TEST_CAN_GET_SID: {
1722 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1723 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001724 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1725 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1726 return NO_ERROR;
1727 }
1728 case BINDER_LIB_TEST_PROCESS_LOCK: {
1729 blockMutex.lock();
1730 return NO_ERROR;
1731 }
1732 case BINDER_LIB_TEST_LOCK_UNLOCK: {
1733 std::lock_guard<std::mutex> _l(blockMutex);
1734 return NO_ERROR;
1735 }
1736 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1737 int32_t ms = data.readInt32();
1738 return unlockInMs(ms);
1739 }
1740 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
1741 blockMutex.lock();
1742 std::thread t([&] {
1743 unlockInMs(data.readInt32());
1744 }); // start local thread to unlock in 1s
1745 t.detach();
1746 return NO_ERROR;
1747 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001748 default:
1749 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001750 };
1751 }
1752
Elie Kheirallah47431c12022-04-21 23:46:17 +00001753 status_t unlockInMs(int32_t ms) {
1754 usleep(ms * 1000);
1755 blockMutex.unlock();
1756 return NO_ERROR;
1757 }
1758
Yifan Hong543edcd2021-05-18 19:47:30 -07001759private:
1760 int32_t m_id;
1761 int32_t m_nextServerId;
1762 pthread_mutex_t m_serverWaitMutex;
1763 pthread_cond_t m_serverWaitCond;
1764 bool m_serverStartRequested;
1765 sp<IBinder> m_serverStarted;
1766 sp<IBinder> m_strongRef;
1767 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001768 bool m_exitOnDestroy;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001769 std::mutex blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001770};
1771
Martijn Coenen45b07b42017-08-09 12:07:45 +02001772int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001773{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001774 binderLibTestServiceName += String16(binderserversuffix);
1775
Steven Moreland35626652021-05-15 01:32:04 +00001776 // Testing to make sure that calls that we are serving can use getCallin*
1777 // even though we don't here.
1778 IPCThreadState::SpGuard spGuard{
1779 .address = __builtin_frame_address(0),
1780 .context = "main server thread",
1781 };
1782 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1783
Riley Andrews06b01ad2014-12-18 12:10:08 -08001784 status_t ret;
1785 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001786 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001787 {
1788 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001789
Steven Morelandbf1915b2020-07-16 22:43:02 +00001790 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1791
Steven Morelandcf03cf12020-12-04 02:58:40 +00001792 testService->setInheritRt(true);
1793
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001794 /*
1795 * Normally would also contain functionality as well, but we are only
1796 * testing the extension mechanism.
1797 */
1798 testService->setExtension(new BBinder());
1799
Martijn Coenen82c75312019-07-24 15:18:30 +02001800 // Required for test "BufRejected'
1801 testService->setRequestingSid(true);
1802
Martijn Coenen45b07b42017-08-09 12:07:45 +02001803 /*
1804 * We need this below, but can't hold a sp<> because it prevents the
1805 * node from being cleaned up automatically. It's safe in this case
1806 * because of how the tests are written.
1807 */
1808 testServicePtr = testService.get();
1809
Riley Andrews06b01ad2014-12-18 12:10:08 -08001810 if (index == 0) {
1811 ret = sm->addService(binderLibTestServiceName, testService);
1812 } else {
1813 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1814 Parcel data, reply;
1815 data.writeInt32(index);
1816 data.writeStrongBinder(testService);
1817
1818 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1819 }
1820 }
1821 write(readypipefd, &ret, sizeof(ret));
1822 close(readypipefd);
1823 //printf("%s: ret %d\n", __func__, ret);
1824 if (ret)
1825 return 1;
1826 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001827 if (usePoll) {
1828 int fd;
1829 struct epoll_event ev;
1830 int epoll_fd;
1831 IPCThreadState::self()->setupPolling(&fd);
1832 if (fd < 0) {
1833 return 1;
1834 }
1835 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1836
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001837 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001838 if (epoll_fd == -1) {
1839 return 1;
1840 }
1841
1842 ev.events = EPOLLIN;
1843 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1844 return 1;
1845 }
1846
1847 while (1) {
1848 /*
1849 * We simulate a single-threaded process using the binder poll
1850 * interface; besides handling binder commands, it can also
1851 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001852 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001853 *
1854 * processPendingCall() will then issue that transaction.
1855 */
1856 struct epoll_event events[1];
1857 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1858 if (numEvents < 0) {
1859 if (errno == EINTR) {
1860 continue;
1861 }
1862 return 1;
1863 }
1864 if (numEvents > 0) {
1865 IPCThreadState::self()->handlePolledCommands();
1866 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
1867 testServicePtr->processPendingCall();
1868 }
1869 }
1870 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001871 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001872 ProcessState::self()->startThreadPool();
1873 IPCThreadState::self()->joinThreadPool();
1874 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001875 //printf("%s: joinThreadPool returned\n", __func__);
1876 return 1; /* joinThreadPool should not return */
1877}
1878
1879int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07001880 ExitIfWrongAbi();
1881
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001882 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001883 binderservername = argv[2];
1884 } else {
1885 binderservername = argv[0];
1886 }
1887
Martijn Coenen45b07b42017-08-09 12:07:45 +02001888 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
1889 binderserversuffix = argv[5];
1890 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001891 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001892 binderserversuffix = new char[16];
1893 snprintf(binderserversuffix, 16, "%d", getpid());
1894 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001895
1896 ::testing::InitGoogleTest(&argc, argv);
1897 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
1898 ProcessState::self()->startThreadPool();
1899 return RUN_ALL_TESTS();
1900}