blob: 9788d9d1ddefec0c993955d654608425b144c940 [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 Hong8b890852021-06-10 13:44:09 -070032#include <android-base/strings.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080033#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070034#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000035#include <binder/Functional.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080036#include <binder/IBinder.h>
37#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070039#include <binder/RpcServer.h>
40#include <binder/RpcSession.h>
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070041#include <binder/unique_fd.h>
Tomasz Wasilczyk300aa132023-10-26 15:00:04 -070042#include <utils/Flattenable.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080043
Steven Morelandcf03cf12020-12-04 02:58:40 +000044#include <linux/sched.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020045#include <sys/epoll.h>
Steven Morelandda048352020-02-19 13:25:53 -080046#include <sys/prctl.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070047#include <sys/socket.h>
48#include <sys/un.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020049
Steven Moreland6ba5a252021-05-04 22:49:00 +000050#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070051
Riley Andrews06b01ad2014-12-18 12:10:08 -080052#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
53
54using namespace android;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000055using namespace android::binder::impl;
Yifan Hong84bedeb2021-04-21 21:37:17 -070056using namespace std::string_literals;
57using namespace std::chrono_literals;
Yifan Hong28d6c352021-06-04 17:27:35 -070058using android::base::testing::HasValue;
Yifan Hong8b890852021-06-10 13:44:09 -070059using android::base::testing::Ok;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070060using android::binder::unique_fd;
Yifan Hong84bedeb2021-04-21 21:37:17 -070061using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080062using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070063using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070064using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070065
66// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
67MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
68 *result_listener << statusToString(arg);
69 return expected == arg;
70}
Riley Andrews06b01ad2014-12-18 12:10:08 -080071
Sherry Yang336cdd32017-07-24 14:12:27 -070072static ::testing::AssertionResult IsPageAligned(void *buf) {
Vilas Bhat04e28c72024-02-12 21:47:15 +000073 if (((unsigned long)buf & ((unsigned long)getpagesize() - 1)) == 0)
Sherry Yang336cdd32017-07-24 14:12:27 -070074 return ::testing::AssertionSuccess();
75 else
76 return ::testing::AssertionFailure() << buf << " is not page aligned";
77}
78
Riley Andrews06b01ad2014-12-18 12:10:08 -080079static testing::Environment* binder_env;
80static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070081static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080082static char binderserverarg[] = "--binderserver";
83
Steven Morelandbf1915b2020-07-16 22:43:02 +000084static constexpr int kSchedPolicy = SCHED_RR;
85static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000086static constexpr int kSchedPriorityMore = 8;
Steven Moreland3e9debc2023-06-15 00:35:29 +000087static constexpr int kKernelThreads = 17; // anything different than the default
Steven Morelandbf1915b2020-07-16 22:43:02 +000088
Riley Andrews06b01ad2014-12-18 12:10:08 -080089static String16 binderLibTestServiceName = String16("test.binderLib");
90
91enum BinderLibTestTranscationCode {
92 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
93 BINDER_LIB_TEST_REGISTER_SERVER,
94 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020095 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +000096 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -080097 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -070098 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +020099 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800100 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700101 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800102 BINDER_LIB_TEST_GET_ID_TRANSACTION,
103 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
104 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
105 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
106 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
107 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
108 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900109 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800110 BINDER_LIB_TEST_EXIT_TRANSACTION,
111 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
112 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700113 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100114 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000115 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700116 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
117 BINDER_LIB_TEST_GETPID,
Jing Jibdbe29a2023-10-03 00:03:28 -0700118 BINDER_LIB_TEST_GETUID,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800119 BINDER_LIB_TEST_ECHO_VECTOR,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700120 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700121 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000122 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000123 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
124 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
Devin Moore4354f712022-12-08 01:44:46 +0000125 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000126 BINDER_LIB_TEST_LOCK_UNLOCK,
127 BINDER_LIB_TEST_PROCESS_LOCK,
128 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
129 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800130};
131
Martijn Coenen45b07b42017-08-09 12:07:45 +0200132pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800133{
134 int ret;
135 pid_t pid;
136 status_t status;
137 int pipefd[2];
138 char stri[16];
139 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200140 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800141 char *childargv[] = {
142 binderservername,
143 binderserverarg,
144 stri,
145 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200146 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700147 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700148 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800149 };
150
151 ret = pipe(pipefd);
152 if (ret < 0)
153 return ret;
154
155 snprintf(stri, sizeof(stri), "%d", arg2);
156 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200157 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800158
159 pid = fork();
160 if (pid == -1)
161 return pid;
162 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800163 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800164 close(pipefd[0]);
165 execv(binderservername, childargv);
166 status = -errno;
167 write(pipefd[1], &status, sizeof(status));
168 fprintf(stderr, "execv failed, %s\n", strerror(errno));
169 _exit(EXIT_FAILURE);
170 }
171 close(pipefd[1]);
172 ret = read(pipefd[0], &status, sizeof(status));
173 //printf("pipe read returned %d, status %d\n", ret, status);
174 close(pipefd[0]);
175 if (ret == sizeof(status)) {
176 ret = status;
177 } else {
178 kill(pid, SIGKILL);
179 if (ret >= 0) {
180 ret = NO_INIT;
181 }
182 }
183 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700184 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800185 return ret;
186 }
187 return pid;
188}
189
Yifan Hong84bedeb2021-04-21 21:37:17 -0700190android::base::Result<int32_t> GetId(sp<IBinder> service) {
191 using android::base::Error;
192 Parcel data, reply;
193 data.markForBinder(service);
194 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
195 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
196 if (status != OK)
197 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
198 int32_t result = 0;
199 status = reply.readInt32(&result);
200 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
201 return result;
202}
203
Riley Andrews06b01ad2014-12-18 12:10:08 -0800204class BinderLibTestEnv : public ::testing::Environment {
205 public:
206 BinderLibTestEnv() {}
207 sp<IBinder> getServer(void) {
208 return m_server;
209 }
210
211 private:
212 virtual void SetUp() {
213 m_serverpid = start_server_process(0);
214 //printf("m_serverpid %d\n", m_serverpid);
215 ASSERT_GT(m_serverpid, 0);
216
217 sp<IServiceManager> sm = defaultServiceManager();
218 //printf("%s: pid %d, get service\n", __func__, m_pid);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000219#pragma clang diagnostic push
220#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -0800221 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000222#pragma clang diagnostic pop
Yi Kong91635562018-06-07 14:38:36 -0700223 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800224 //printf("%s: pid %d, get service done\n", __func__, m_pid);
225 }
226 virtual void TearDown() {
227 status_t ret;
228 Parcel data, reply;
229 int exitStatus;
230 pid_t pid;
231
232 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700233 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800234 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
235 EXPECT_EQ(0, ret);
236 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
237 EXPECT_EQ(0, ret);
238 }
239 if (m_serverpid > 0) {
240 //printf("wait for %d\n", m_pids[i]);
241 pid = wait(&exitStatus);
242 EXPECT_EQ(m_serverpid, pid);
243 EXPECT_TRUE(WIFEXITED(exitStatus));
244 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
245 }
246 }
247
248 pid_t m_serverpid;
249 sp<IBinder> m_server;
250};
251
252class BinderLibTest : public ::testing::Test {
253 public:
254 virtual void SetUp() {
255 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Olivier Gaillard91a04802018-11-14 17:32:41 +0000256 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800257 }
258 virtual void TearDown() {
259 }
260 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200261 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800262 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800263 int32_t id;
264 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800265
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700266 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800267
Elie Kheirallahb7246642022-05-03 18:01:43 +0000268 sp<IBinder> binder = reply.readStrongBinder();
269 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700270 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800271 if (idPtr)
272 *idPtr = id;
273 return binder;
274 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200275
Yi Kong91635562018-06-07 14:38:36 -0700276 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200277 {
278 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
279 }
280
Yi Kong91635562018-06-07 14:38:36 -0700281 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200282 {
283 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
284 }
285
Riley Andrews06b01ad2014-12-18 12:10:08 -0800286 void waitForReadData(int fd, int timeout_ms) {
287 int ret;
288 pollfd pfd = pollfd();
289
290 pfd.fd = fd;
291 pfd.events = POLLIN;
292 ret = poll(&pfd, 1, timeout_ms);
293 EXPECT_EQ(1, ret);
294 }
295
296 sp<IBinder> m_server;
297};
298
299class BinderLibTestBundle : public Parcel
300{
301 public:
302 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800303 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800304 int32_t mark;
305 int32_t bundleLen;
306 size_t pos;
307
308 if (source->readInt32(&mark))
309 return;
310 if (mark != MARK_START)
311 return;
312 if (source->readInt32(&bundleLen))
313 return;
314 pos = source->dataPosition();
315 if (Parcel::appendFrom(source, pos, bundleLen))
316 return;
317 source->setDataPosition(pos + bundleLen);
318 if (source->readInt32(&mark))
319 return;
320 if (mark != MARK_END)
321 return;
322 m_isValid = true;
323 setDataPosition(0);
324 }
325 void appendTo(Parcel *dest) {
326 dest->writeInt32(MARK_START);
327 dest->writeInt32(dataSize());
328 dest->appendFrom(this, 0, dataSize());
329 dest->writeInt32(MARK_END);
330 };
331 bool isValid(void) {
332 return m_isValid;
333 }
334 private:
335 enum {
336 MARK_START = B_PACK_CHARS('B','T','B','S'),
337 MARK_END = B_PACK_CHARS('B','T','B','E'),
338 };
339 bool m_isValid;
340};
341
342class BinderLibTestEvent
343{
344 public:
345 BinderLibTestEvent(void)
346 : m_eventTriggered(false)
347 {
Yi Kong91635562018-06-07 14:38:36 -0700348 pthread_mutex_init(&m_waitMutex, nullptr);
349 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800350 }
351 int waitEvent(int timeout_s)
352 {
353 int ret;
354 pthread_mutex_lock(&m_waitMutex);
355 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800356 struct timespec ts;
357 clock_gettime(CLOCK_REALTIME, &ts);
358 ts.tv_sec += timeout_s;
359 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800360 }
361 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
362 pthread_mutex_unlock(&m_waitMutex);
363 return ret;
364 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200365 pthread_t getTriggeringThread()
366 {
367 return m_triggeringThread;
368 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800369 protected:
370 void triggerEvent(void) {
371 pthread_mutex_lock(&m_waitMutex);
372 pthread_cond_signal(&m_waitCond);
373 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200374 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800375 pthread_mutex_unlock(&m_waitMutex);
376 };
377 private:
378 pthread_mutex_t m_waitMutex;
379 pthread_cond_t m_waitCond;
380 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200381 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800382};
383
384class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
385{
386 public:
387 BinderLibTestCallBack()
388 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700389 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800390 {
391 }
392 status_t getResult(void)
393 {
394 return m_result;
395 }
396
397 private:
398 virtual status_t onTransact(uint32_t code,
399 const Parcel& data, Parcel* reply,
400 uint32_t flags = 0)
401 {
402 (void)reply;
403 (void)flags;
404 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200405 case BINDER_LIB_TEST_CALL_BACK: {
406 status_t status = data.readInt32(&m_result);
407 if (status != NO_ERROR) {
408 m_result = status;
409 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800410 triggerEvent();
411 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200412 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700413 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
414 sp<IBinder> server;
415 int ret;
416 const uint8_t *buf = data.data();
417 size_t size = data.dataSize();
418 if (m_prev_end) {
419 /* 64-bit kernel needs at most 8 bytes to align buffer end */
420 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
421 } else {
422 EXPECT_TRUE(IsPageAligned((void *)buf));
423 }
424
425 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
426
427 if (size > 0) {
428 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
429 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
430 data, reply);
431 EXPECT_EQ(NO_ERROR, ret);
432 }
433 return NO_ERROR;
434 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800435 default:
436 return UNKNOWN_TRANSACTION;
437 }
438 }
439
440 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700441 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800442};
443
444class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
445{
446 private:
447 virtual void binderDied(const wp<IBinder>& who) {
448 (void)who;
449 triggerEvent();
450 };
451};
452
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700453TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
454 // EXPECT_DEATH works by forking the process
455 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
456}
457
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000458TEST_F(BinderLibTest, AddManagerToManager) {
459 sp<IServiceManager> sm = defaultServiceManager();
460 sp<IBinder> binder = IInterface::asBinder(sm);
461 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
462}
463
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500464TEST_F(BinderLibTest, WasParceled) {
465 auto binder = sp<BBinder>::make();
466 EXPECT_FALSE(binder->wasParceled());
467 Parcel data;
468 data.writeStrongBinder(binder);
469 EXPECT_TRUE(binder->wasParceled());
470}
471
Riley Andrews06b01ad2014-12-18 12:10:08 -0800472TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800473 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700474 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
475 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800476}
477
Steven Moreland80844f72020-12-12 02:06:08 +0000478TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000479 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700480 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
481 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000482}
483
Steven Morelandf183fdd2020-10-27 00:12:12 +0000484TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000485 Parcel data, reply;
486 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700487 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
488 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000489}
490
Marco Ballesio7ee17572020-09-08 10:30:03 -0700491TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700492 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700493 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700494
Li Li6f059292021-09-10 09:59:30 -0700495 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700496 if (freezer_file.fail()) {
497 GTEST_SKIP();
498 return;
499 }
500
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700501 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700502 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700503 for (int i = 0; i < 10; i++) {
504 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
505 }
Li Li6f059292021-09-10 09:59:30 -0700506
507 // Pass test on devices where BINDER_FREEZE ioctl is not supported
508 int ret = IPCThreadState::self()->freeze(pid, false, 0);
Alice Ryhl4634c902024-04-11 12:52:11 +0000509 if (ret == -EINVAL) {
Li Li6f059292021-09-10 09:59:30 -0700510 GTEST_SKIP();
511 return;
512 }
Alice Ryhl4634c902024-04-11 12:52:11 +0000513 EXPECT_EQ(NO_ERROR, ret);
Li Li6f059292021-09-10 09:59:30 -0700514
515 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000516
517 // b/268232063 - succeeds ~0.08% of the time
518 {
519 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
520 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
521 }
522
Li Li6f059292021-09-10 09:59:30 -0700523 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700524 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700525
Li Li4e678b92021-09-14 12:14:42 -0700526 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700527
528 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
529 &async_received));
530
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700531 EXPECT_EQ(sync_received, 1u);
532 EXPECT_EQ(async_received, 0u);
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700533
Li Li4e678b92021-09-14 12:14:42 -0700534 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700535 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
536}
537
Riley Andrews06b01ad2014-12-18 12:10:08 -0800538TEST_F(BinderLibTest, SetError) {
539 int32_t testValue[] = { 0, -123, 123 };
540 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800541 Parcel data, reply;
542 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700543 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
544 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800545 }
546}
547
548TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700549 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800550}
551
552TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800553 int32_t ptrsize;
554 Parcel data, reply;
555 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700556 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700557 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
558 StatusEq(NO_ERROR));
559 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800560 RecordProperty("TestPtrSize", sizeof(void *));
561 RecordProperty("ServerPtrSize", sizeof(void *));
562}
563
564TEST_F(BinderLibTest, IndirectGetId2)
565{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800566 int32_t id;
567 int32_t count;
568 Parcel data, reply;
569 int32_t serverId[3];
570
571 data.writeInt32(ARRAY_SIZE(serverId));
572 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
573 sp<IBinder> server;
574 BinderLibTestBundle datai;
575
576 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700577 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800578 data.writeStrongBinder(server);
579 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
580 datai.appendTo(&data);
581 }
582
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700583 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
584 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800585
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700586 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800587 EXPECT_EQ(0, id);
588
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700589 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700590 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800591
592 for (size_t i = 0; i < (size_t)count; i++) {
593 BinderLibTestBundle replyi(&reply);
594 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700595 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800596 EXPECT_EQ(serverId[i], id);
597 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
598 }
599
600 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
601}
602
603TEST_F(BinderLibTest, IndirectGetId3)
604{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800605 int32_t id;
606 int32_t count;
607 Parcel data, reply;
608 int32_t serverId[3];
609
610 data.writeInt32(ARRAY_SIZE(serverId));
611 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
612 sp<IBinder> server;
613 BinderLibTestBundle datai;
614 BinderLibTestBundle datai2;
615
616 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700617 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800618 data.writeStrongBinder(server);
619 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
620
621 datai.writeInt32(1);
622 datai.writeStrongBinder(m_server);
623 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
624 datai2.appendTo(&datai);
625
626 datai.appendTo(&data);
627 }
628
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700629 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
630 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800631
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700632 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800633 EXPECT_EQ(0, id);
634
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700635 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700636 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800637
638 for (size_t i = 0; i < (size_t)count; i++) {
639 int32_t counti;
640
641 BinderLibTestBundle replyi(&reply);
642 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700643 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800644 EXPECT_EQ(serverId[i], id);
645
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700646 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800647 EXPECT_EQ(1, counti);
648
649 BinderLibTestBundle replyi2(&replyi);
650 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700651 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800652 EXPECT_EQ(0, id);
653 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
654
655 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
656 }
657
658 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
659}
660
661TEST_F(BinderLibTest, CallBack)
662{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800663 Parcel data, reply;
664 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
665 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700666 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
667 StatusEq(NO_ERROR));
668 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
669 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800670}
671
Steven Moreland35626652021-05-15 01:32:04 +0000672TEST_F(BinderLibTest, BinderCallContextGuard) {
673 sp<IBinder> binder = addServer();
674 Parcel data, reply;
675 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
676 StatusEq(DEAD_OBJECT));
677}
678
Riley Andrews06b01ad2014-12-18 12:10:08 -0800679TEST_F(BinderLibTest, AddServer)
680{
681 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700682 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800683}
684
Riley Andrews06b01ad2014-12-18 12:10:08 -0800685TEST_F(BinderLibTest, DeathNotificationStrongRef)
686{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800687 sp<IBinder> sbinder;
688
689 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
690
691 {
692 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700693 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700694 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800695 sbinder = binder;
696 }
697 {
698 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700699 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
700 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800701 }
702 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700703 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
704 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800705}
706
707TEST_F(BinderLibTest, DeathNotificationMultiple)
708{
709 status_t ret;
710 const int clientcount = 2;
711 sp<IBinder> target;
712 sp<IBinder> linkedclient[clientcount];
713 sp<BinderLibTestCallBack> callBack[clientcount];
714 sp<IBinder> passiveclient[clientcount];
715
716 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700717 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800718 for (int i = 0; i < clientcount; i++) {
719 {
720 Parcel data, reply;
721
722 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700723 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800724 callBack[i] = new BinderLibTestCallBack();
725 data.writeStrongBinder(target);
726 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700727 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
728 &reply, TF_ONE_WAY),
729 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800730 }
731 {
732 Parcel data, reply;
733
734 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700735 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800736 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700737 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
738 &reply, TF_ONE_WAY),
739 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800740 }
741 }
742 {
743 Parcel data, reply;
744 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
745 EXPECT_EQ(0, ret);
746 }
747
748 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700749 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
750 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800751 }
752}
753
Martijn Coenenf7100e42017-07-31 12:14:09 +0200754TEST_F(BinderLibTest, DeathNotificationThread)
755{
756 status_t ret;
757 sp<BinderLibTestCallBack> callback;
758 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700759 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200760 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700761 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200762
763 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
764
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700765 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200766
767 {
768 Parcel data, reply;
769 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
770 EXPECT_EQ(0, ret);
771 }
772
773 /* Make sure it's dead */
774 testDeathRecipient->waitEvent(5);
775
776 /* Now, pass the ref to another process and ask that process to
777 * call linkToDeath() on it, and wait for a response. This tests
778 * two things:
779 * 1) You still get death notifications when calling linkToDeath()
780 * on a ref that is already dead when it was passed to you.
781 * 2) That death notifications are not directly pushed to the thread
782 * registering them, but to the threadpool (proc workqueue) instead.
783 *
784 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
785 * is blocked on a condition variable waiting for the death notification to be
786 * called; therefore, that thread is not available for handling proc work.
787 * So, if the death notification was pushed to the thread workqueue, the callback
788 * would never be called, and the test would timeout and fail.
789 *
790 * Note that we can't do this part of the test from this thread itself, because
791 * the binder driver would only push death notifications to the thread if
792 * it is a looper thread, which this thread is not.
793 *
794 * See b/23525545 for details.
795 */
796 {
797 Parcel data, reply;
798
799 callback = new BinderLibTestCallBack();
800 data.writeStrongBinder(target);
801 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700802 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
803 TF_ONE_WAY),
804 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200805 }
806
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700807 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
808 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200809}
810
Riley Andrews06b01ad2014-12-18 12:10:08 -0800811TEST_F(BinderLibTest, PassFile) {
812 int ret;
813 int pipefd[2];
814 uint8_t buf[1] = { 0 };
815 uint8_t write_value = 123;
816
817 ret = pipe2(pipefd, O_NONBLOCK);
818 ASSERT_EQ(0, ret);
819
820 {
821 Parcel data, reply;
822 uint8_t writebuf[1] = { write_value };
823
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700824 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800825
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700826 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800827
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700828 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800829
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700830 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
831 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800832 }
833
834 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700835 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800836 EXPECT_EQ(write_value, buf[0]);
837
838 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
839
840 ret = read(pipefd[0], buf, sizeof(buf));
841 EXPECT_EQ(0, ret);
842
843 close(pipefd[0]);
844}
845
Ryo Hashimotobf551892018-05-31 16:58:35 +0900846TEST_F(BinderLibTest, PassParcelFileDescriptor) {
847 const int datasize = 123;
848 std::vector<uint8_t> writebuf(datasize);
849 for (size_t i = 0; i < writebuf.size(); ++i) {
850 writebuf[i] = i;
851 }
852
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700853 unique_fd read_end, write_end;
Ryo Hashimotobf551892018-05-31 16:58:35 +0900854 {
855 int pipefd[2];
856 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
857 read_end.reset(pipefd[0]);
858 write_end.reset(pipefd[1]);
859 }
860 {
861 Parcel data;
862 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
863 write_end.reset();
864 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
865 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
866
867 Parcel reply;
868 EXPECT_EQ(NO_ERROR,
869 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
870 &reply));
871 }
872 std::vector<uint8_t> readbuf(datasize);
873 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
874 EXPECT_EQ(writebuf, readbuf);
875
876 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
877
878 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
879}
880
Riley Andrews06b01ad2014-12-18 12:10:08 -0800881TEST_F(BinderLibTest, PromoteLocal) {
882 sp<IBinder> strong = new BBinder();
883 wp<IBinder> weak = strong;
884 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700885 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800886 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700887 strong = nullptr;
888 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800889 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700890 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800891}
892
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700893TEST_F(BinderLibTest, LocalGetExtension) {
894 sp<BBinder> binder = new BBinder();
895 sp<IBinder> ext = new BBinder();
896 binder->setExtension(ext);
897 EXPECT_EQ(ext, binder->getExtension());
898}
899
900TEST_F(BinderLibTest, RemoteGetExtension) {
901 sp<IBinder> server = addServer();
902 ASSERT_TRUE(server != nullptr);
903
904 sp<IBinder> extension;
905 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
906 ASSERT_NE(nullptr, extension.get());
907
908 EXPECT_EQ(NO_ERROR, extension->pingBinder());
909}
910
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700911TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700912 Parcel data, reply;
913
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700914 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
915 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700916
917 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700918 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800919 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
920 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
921 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
922 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700923}
924
Connor O'Brien52be2c92016-09-20 14:18:08 -0700925TEST_F(BinderLibTest, FreedBinder) {
926 status_t ret;
927
928 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700929 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700930
931 __u32 freedHandle;
932 wp<IBinder> keepFreedBinder;
933 {
934 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700935 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
936 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700937 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
938 freedHandle = freed->handle;
939 /* Add a weak ref to the freed binder so the driver does not
940 * delete its reference to it - otherwise the transaction
941 * fails regardless of whether the driver is fixed.
942 */
Steven Morelande171d622019-07-17 16:06:01 -0700943 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700944 }
Steven Morelande171d622019-07-17 16:06:01 -0700945 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700946 {
947 Parcel data, reply;
948 data.writeStrongBinder(server);
949 /* Replace original handle with handle to the freed binder */
950 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
951 __u32 oldHandle = strong->handle;
952 strong->handle = freedHandle;
953 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
954 /* Returns DEAD_OBJECT (-32) if target crashes and
955 * FAILED_TRANSACTION if the driver rejects the invalid
956 * object.
957 */
958 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
959 /* Restore original handle so parcel destructor does not use
960 * the wrong handle.
961 */
962 strong->handle = oldHandle;
963 }
964}
965
Sherry Yang336cdd32017-07-24 14:12:27 -0700966TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700967 Parcel data, reply;
968 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
969 for (int i = 0; i < 2; i++) {
970 BinderLibTestBundle datai;
971 datai.appendFrom(&data, 0, data.dataSize());
972
973 data.freeData();
974 data.writeInt32(1);
975 data.writeStrongBinder(callBack);
976 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
977
978 datai.appendTo(&data);
979 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700980 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
981 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700982}
983
Martijn Coenen45b07b42017-08-09 12:07:45 +0200984TEST_F(BinderLibTest, OnewayQueueing)
985{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200986 Parcel data, data2;
987
988 sp<IBinder> pollServer = addPollServer();
989
990 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
991 data.writeStrongBinder(callBack);
992 data.writeInt32(500000); // delay in us before calling back
993
994 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
995 data2.writeStrongBinder(callBack2);
996 data2.writeInt32(0); // delay in us
997
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700998 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
999 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001000
1001 // The delay ensures that this second transaction will end up on the async_todo list
1002 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001003 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1004 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001005
1006 // The server will ensure that the two transactions are handled in the expected order;
1007 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001008 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1009 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001010
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001011 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1012 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001013}
1014
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001015TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1016{
1017 status_t ret;
1018 Parcel data, reply;
1019 data.writeInterfaceToken(binderLibTestServiceName);
1020 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1021 EXPECT_EQ(-1, reply.readInt32());
1022 EXPECT_EQ(NO_ERROR, ret);
1023}
1024
1025TEST_F(BinderLibTest, WorkSourceSet)
1026{
1027 status_t ret;
1028 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001029 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001030 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001031 data.writeInterfaceToken(binderLibTestServiceName);
1032 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1033 EXPECT_EQ(100, reply.readInt32());
1034 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001035 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1036 EXPECT_EQ(NO_ERROR, ret);
1037}
1038
1039TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1040{
1041 status_t ret;
1042 Parcel data, reply;
1043
1044 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1045 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1046
1047 data.writeInterfaceToken(binderLibTestServiceName);
1048 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1049 EXPECT_EQ(-1, reply.readInt32());
1050 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001051 EXPECT_EQ(NO_ERROR, ret);
1052}
1053
1054TEST_F(BinderLibTest, WorkSourceCleared)
1055{
1056 status_t ret;
1057 Parcel data, reply;
1058
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001059 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001060 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1061 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001062 data.writeInterfaceToken(binderLibTestServiceName);
1063 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1064
1065 EXPECT_EQ(-1, reply.readInt32());
1066 EXPECT_EQ(100, previousWorkSource);
1067 EXPECT_EQ(NO_ERROR, ret);
1068}
1069
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001070TEST_F(BinderLibTest, WorkSourceRestored)
1071{
1072 status_t ret;
1073 Parcel data, reply;
1074
1075 IPCThreadState::self()->setCallingWorkSourceUid(100);
1076 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1077 IPCThreadState::self()->restoreCallingWorkSource(token);
1078
1079 data.writeInterfaceToken(binderLibTestServiceName);
1080 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1081
1082 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001083 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001084 EXPECT_EQ(NO_ERROR, ret);
1085}
1086
Olivier Gaillard91a04802018-11-14 17:32:41 +00001087TEST_F(BinderLibTest, PropagateFlagSet)
1088{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001089 IPCThreadState::self()->clearPropagateWorkSource();
1090 IPCThreadState::self()->setCallingWorkSourceUid(100);
1091 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1092}
1093
1094TEST_F(BinderLibTest, PropagateFlagCleared)
1095{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001096 IPCThreadState::self()->setCallingWorkSourceUid(100);
1097 IPCThreadState::self()->clearPropagateWorkSource();
1098 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1099}
1100
1101TEST_F(BinderLibTest, PropagateFlagRestored)
1102{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001103 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1104 IPCThreadState::self()->restoreCallingWorkSource(token);
1105
1106 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1107}
1108
1109TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1110{
1111 IPCThreadState::self()->setCallingWorkSourceUid(100);
1112
1113 Parcel data, reply;
1114 status_t ret;
1115 data.writeInterfaceToken(binderLibTestServiceName);
1116 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001117 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001118
1119 Parcel data2, reply2;
1120 status_t ret2;
1121 data2.writeInterfaceToken(binderLibTestServiceName);
1122 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1123 EXPECT_EQ(100, reply2.readInt32());
1124 EXPECT_EQ(NO_ERROR, ret2);
1125}
1126
Steven Morelandbf1915b2020-07-16 22:43:02 +00001127TEST_F(BinderLibTest, SchedPolicySet) {
1128 sp<IBinder> server = addServer();
1129 ASSERT_TRUE(server != nullptr);
1130
1131 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001132 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1133 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001134
1135 int policy = reply.readInt32();
1136 int priority = reply.readInt32();
1137
1138 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1139 EXPECT_EQ(kSchedPriority, priority);
1140}
1141
Steven Morelandcf03cf12020-12-04 02:58:40 +00001142TEST_F(BinderLibTest, InheritRt) {
1143 sp<IBinder> server = addServer();
1144 ASSERT_TRUE(server != nullptr);
1145
1146 const struct sched_param param {
1147 .sched_priority = kSchedPriorityMore,
1148 };
1149 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1150
1151 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001152 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1153 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001154
1155 int policy = reply.readInt32();
1156 int priority = reply.readInt32();
1157
1158 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1159 EXPECT_EQ(kSchedPriorityMore, priority);
1160}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001161
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001162TEST_F(BinderLibTest, VectorSent) {
1163 Parcel data, reply;
1164 sp<IBinder> server = addServer();
1165 ASSERT_TRUE(server != nullptr);
1166
1167 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1168 data.writeUint64Vector(testValue);
1169
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001170 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001171 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001172 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001173 EXPECT_EQ(readValue, testValue);
1174}
1175
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001176TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1177 sp<IBinder> server = addServer();
1178 ASSERT_TRUE(server != nullptr);
1179
1180 Parcel reply;
1181 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1182 StatusEq(NO_ERROR));
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001183 unique_fd fd;
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001184 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1185
1186 const int result = fcntl(fd.get(), F_GETFL);
1187 ASSERT_NE(result, -1);
1188 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1189}
1190
Steven Moreland59b84442022-07-12 18:32:44 +00001191// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1192// This value is not exposed, but some code in the framework relies on being able to use
1193// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001194constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001195constexpr size_t kSizeBytesOverFull = 1'050'000;
1196
1197TEST_F(BinderLibTest, GargantuanVectorSent) {
1198 sp<IBinder> server = addServer();
1199 ASSERT_TRUE(server != nullptr);
1200
1201 for (size_t i = 0; i < 10; i++) {
1202 // a slight variation in size is used to consider certain possible caching implementations
1203 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1204
1205 Parcel data, reply;
1206 data.writeUint64Vector(testValue);
1207 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1208 << i;
1209 std::vector<uint64_t> readValue;
1210 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1211 EXPECT_EQ(readValue, testValue);
1212 }
1213}
1214
1215TEST_F(BinderLibTest, LimitExceededVectorSent) {
1216 sp<IBinder> server = addServer();
1217 ASSERT_TRUE(server != nullptr);
1218 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1219
1220 Parcel data, reply;
1221 data.writeUint64Vector(testValue);
1222 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1223 StatusEq(FAILED_TRANSACTION));
1224}
1225
Martijn Coenen82c75312019-07-24 15:18:30 +02001226TEST_F(BinderLibTest, BufRejected) {
1227 Parcel data, reply;
1228 uint32_t buf;
1229 sp<IBinder> server = addServer();
1230 ASSERT_TRUE(server != nullptr);
1231
1232 binder_buffer_object obj {
1233 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001234 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001235 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1236 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001237 };
1238 data.setDataCapacity(1024);
1239 // Write a bogus object at offset 0 to get an entry in the offset table
1240 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001241 EXPECT_EQ(data.objectsCount(), 1u);
Martijn Coenen82c75312019-07-24 15:18:30 +02001242 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1243 // And now, overwrite it with the buffer object
1244 memcpy(parcelData, &obj, sizeof(obj));
1245 data.setDataSize(sizeof(obj));
1246
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001247 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001248
Martijn Coenen82c75312019-07-24 15:18:30 +02001249 // Either the kernel should reject this transaction (if it's correct), but
1250 // if it's not, the server implementation should return an error if it
1251 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001252 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001253 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001254}
1255
Steven Morelandf2e0a952021-11-01 18:17:23 -07001256TEST_F(BinderLibTest, WeakRejected) {
1257 Parcel data, reply;
1258 sp<IBinder> server = addServer();
1259 ASSERT_TRUE(server != nullptr);
1260
1261 auto binder = sp<BBinder>::make();
1262 wp<BBinder> wpBinder(binder);
1263 flat_binder_object obj{
1264 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1265 .flags = 0,
1266 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1267 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1268 };
1269 data.setDataCapacity(1024);
1270 // Write a bogus object at offset 0 to get an entry in the offset table
1271 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001272 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001273 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1274 // And now, overwrite it with the weak binder
1275 memcpy(parcelData, &obj, sizeof(obj));
1276 data.setDataSize(sizeof(obj));
1277
1278 // a previous bug caused other objects to be released an extra time, so we
1279 // test with an object that libbinder will actually try to release
1280 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1281
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001282 EXPECT_EQ(data.objectsCount(), 2u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001283
1284 // send it many times, since previous error was memory corruption, make it
1285 // more likely that the server crashes
1286 for (size_t i = 0; i < 100; i++) {
1287 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1288 StatusEq(BAD_VALUE));
1289 }
1290
1291 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1292}
1293
Steven Moreland254e8ef2021-04-19 22:28:50 +00001294TEST_F(BinderLibTest, GotSid) {
1295 sp<IBinder> server = addServer();
1296
1297 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001298 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001299}
1300
Andrei Homescu1519b982022-06-09 02:04:44 +00001301struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1302 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1303
1304 // Flattenable protocol
1305 size_t getFlattenedSize() const {
1306 // Return a valid non-zero size here so we don't get an unintended
1307 // BAD_VALUE from Parcel::write
1308 return 16;
1309 }
1310 size_t getFdCount() const { return mFdCount; }
1311 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1312 for (size_t i = 0; i < count; i++) {
1313 fds[i] = STDIN_FILENO;
1314 }
1315 return NO_ERROR;
1316 }
1317 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1318 size_t & /*count*/) {
1319 /* This doesn't get called */
1320 return NO_ERROR;
1321 }
1322
1323 size_t mFdCount;
1324};
1325
1326TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1327 rlimit origNofile;
1328 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1329 ASSERT_EQ(0, ret);
1330
1331 // Restore the original file limits when the test finishes
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +00001332 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001333
1334 rlimit testNofile = {1024, 1024};
1335 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1336 ASSERT_EQ(0, ret);
1337
1338 Parcel parcel;
1339 // Try to write more file descriptors than supported by the OS
1340 TooManyFdsFlattenable tooManyFds1(1024);
1341 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1342
1343 // Try to write more file descriptors than the internal limit
1344 TooManyFdsFlattenable tooManyFds2(1025);
1345 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1346}
1347
Jayant Chowdhary30700942022-01-31 14:12:40 -08001348TEST(ServiceNotifications, Unregister) {
1349 auto sm = defaultServiceManager();
1350 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1351 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1352 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1353 virtual ~LocalRegistrationCallbackImpl() {}
1354 };
1355 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1356
1357 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1358 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1359}
1360
Elie Kheirallah47431c12022-04-21 23:46:17 +00001361TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1362 Parcel data, reply;
1363 sp<IBinder> server = addServer();
1364 ASSERT_TRUE(server != nullptr);
1365 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1366 StatusEq(NO_ERROR));
1367 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001368 // see getThreadPoolMaxTotalThreadCount for why there is a race
1369 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1370
Elie Kheirallah47431c12022-04-21 23:46:17 +00001371 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1372
1373 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001374 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1375 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1376 * started threads from setThreadPoolMaxThreadCount
1377 *
1378 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001379 */
1380 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001381 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001382 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001383 Parcel local_reply;
1384 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1385 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001386 }));
1387 }
1388
Steven Moreland3e9debc2023-06-15 00:35:29 +00001389 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1390 // the time, the below call will pre-empt them (presumably because we have the
1391 // scheduler timeslice already + scheduler hint).
1392 sleep(1);
1393
1394 data.writeInt32(1000);
1395 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001396 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1397
1398 for (auto &t : ts) {
1399 t.join();
1400 }
1401
1402 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1403 StatusEq(NO_ERROR));
1404 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001405 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001406}
1407
Devin Moore4354f712022-12-08 01:44:46 +00001408TEST_F(BinderLibTest, ThreadPoolStarted) {
1409 Parcel data, reply;
1410 sp<IBinder> server = addServer();
1411 ASSERT_TRUE(server != nullptr);
1412 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1413 EXPECT_TRUE(reply.readBool());
1414}
1415
Elie Kheirallah47431c12022-04-21 23:46:17 +00001416size_t epochMillis() {
1417 using std::chrono::duration_cast;
1418 using std::chrono::milliseconds;
1419 using std::chrono::seconds;
1420 using std::chrono::system_clock;
1421 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1422}
1423
1424TEST_F(BinderLibTest, HangingServices) {
1425 Parcel data, reply;
1426 sp<IBinder> server = addServer();
1427 ASSERT_TRUE(server != nullptr);
1428 int32_t delay = 1000; // ms
1429 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001430 // b/266537959 - must take before taking lock, since countdown is started in the remote
1431 // process there.
1432 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001433 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1434 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001435 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1436 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001437 Parcel local_reply;
1438 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1439 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001440 }));
1441 }
1442
1443 for (auto &t : ts) {
1444 t.join();
1445 }
1446 size_t epochMsAfter = epochMillis();
1447
1448 // deadlock occurred and threads only finished after 1s passed.
1449 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1450}
1451
Jing Jibbe9ae62023-10-07 15:26:02 -07001452TEST_F(BinderLibTest, BinderProxyCount) {
1453 Parcel data, reply;
1454 sp<IBinder> server = addServer();
1455 ASSERT_NE(server, nullptr);
1456
1457 uint32_t initialCount = BpBinder::getBinderProxyCount();
1458 size_t iterations = 100;
1459 {
1460 uint32_t count = initialCount;
1461 std::vector<sp<IBinder> > proxies;
1462 sp<IBinder> proxy;
1463 // Create binder proxies and verify the count.
1464 for (size_t i = 0; i < iterations; i++) {
1465 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1466 StatusEq(NO_ERROR));
1467 proxies.push_back(reply.readStrongBinder());
1468 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1469 }
1470 // Remove every other one and verify the count.
1471 auto it = proxies.begin();
1472 for (size_t i = 0; it != proxies.end(); i++) {
1473 if (i % 2 == 0) {
1474 it = proxies.erase(it);
1475 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1476 }
1477 }
1478 }
1479 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1480}
1481
Jing Jibdbe29a2023-10-03 00:03:28 -07001482static constexpr int kBpCountHighWatermark = 20;
1483static constexpr int kBpCountLowWatermark = 10;
1484static constexpr int kBpCountWarningWatermark = 15;
1485static constexpr int kInvalidUid = -1;
1486
1487TEST_F(BinderLibTest, BinderProxyCountCallback) {
1488 Parcel data, reply;
1489 sp<IBinder> server = addServer();
1490 ASSERT_NE(server, nullptr);
1491
1492 BpBinder::enableCountByUid();
1493 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1494 int32_t uid = reply.readInt32();
1495 ASSERT_NE(uid, kInvalidUid);
1496
1497 uint32_t initialCount = BpBinder::getBinderProxyCount();
1498 {
1499 uint32_t count = initialCount;
1500 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1501 kBpCountLowWatermark,
1502 kBpCountWarningWatermark);
1503 int limitCallbackUid = kInvalidUid;
1504 int warningCallbackUid = kInvalidUid;
1505 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1506 [&](int uid) { warningCallbackUid = uid; });
1507
1508 std::vector<sp<IBinder> > proxies;
1509 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1510 warningCallbackUid = limitCallbackUid = kInvalidUid;
1511 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1512 StatusEq(NO_ERROR));
1513 proxies.push_back(reply.readStrongBinder());
1514 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1515 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1516 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1517 };
1518 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1519 warningCallbackUid = limitCallbackUid = kInvalidUid;
1520 proxies.pop_back();
1521 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1522 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1523 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1524 };
1525
1526 // Test the increment/decrement of the binder proxies.
1527 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1528 createProxyOnce(kInvalidUid, kInvalidUid);
1529 }
1530 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1531 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1532 createProxyOnce(kInvalidUid, kInvalidUid);
1533 }
1534 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1535 createProxyOnce(kInvalidUid, kInvalidUid);
1536 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1537 removeProxyOnce(kInvalidUid, kInvalidUid);
1538 }
1539 createProxyOnce(kInvalidUid, kInvalidUid);
1540
1541 // Go down below the low watermark.
1542 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1543 removeProxyOnce(kInvalidUid, kInvalidUid);
1544 }
1545 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1546 createProxyOnce(kInvalidUid, kInvalidUid);
1547 }
1548 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1549 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1550 createProxyOnce(kInvalidUid, kInvalidUid);
1551 }
1552 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1553 createProxyOnce(kInvalidUid, kInvalidUid);
1554 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1555 removeProxyOnce(kInvalidUid, kInvalidUid);
1556 }
1557 createProxyOnce(kInvalidUid, kInvalidUid);
1558 }
1559 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1560}
1561
Yifan Hong84bedeb2021-04-21 21:37:17 -07001562class BinderLibRpcTestBase : public BinderLibTest {
1563public:
1564 void SetUp() override {
1565 if (!base::GetBoolProperty("ro.debuggable", false)) {
1566 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1567 "non-debuggable builds.";
1568 }
1569 BinderLibTest::SetUp();
1570 }
1571
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001572 std::tuple<unique_fd, unsigned int> CreateSocket() {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001573 auto rpcServer = RpcServer::make();
1574 EXPECT_NE(nullptr, rpcServer);
1575 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001576 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001577 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1578 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001579 return {};
1580 }
1581 return {rpcServer->releaseServer(), port};
1582 }
1583};
1584
Yifan Hong8b890852021-06-10 13:44:09 -07001585class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001586
Yifan Hongbd276552022-02-28 15:28:51 -08001587// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1588// If device is debuggable AND not on user builds, expects matcher.
1589// Otherwise expects INVALID_OPERATION.
1590// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1591static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1592 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1593 android::base::GetProperty("ro.build.type", "") != "user";
1594 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1595}
1596
Yifan Hong8b890852021-06-10 13:44:09 -07001597TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1598 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001599 ASSERT_TRUE(binder != nullptr);
1600 auto [socket, port] = CreateSocket();
1601 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001602 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1603 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001604}
1605
Yifan Hong8b890852021-06-10 13:44:09 -07001606// Tests for multiple RpcServer's on the same binder object.
1607TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1608 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001609 ASSERT_TRUE(binder != nullptr);
1610
1611 auto [socket1, port1] = CreateSocket();
1612 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001613 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001614 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1615 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001616
1617 auto [socket2, port2] = CreateSocket();
1618 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001619 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001620 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1621 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001622}
1623
Yifan Hong8b890852021-06-10 13:44:09 -07001624// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1625// local binders.
1626class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001627public:
1628 sp<IBinder> GetService() {
1629 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1630 }
1631 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1632 return info.param ? "remote" : "local";
1633 }
1634};
1635
Yifan Hong8b890852021-06-10 13:44:09 -07001636TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1637 auto binder = GetService();
1638 ASSERT_TRUE(binder != nullptr);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001639 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001640 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001641}
1642
1643TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001644 auto binder = GetService();
1645 ASSERT_TRUE(binder != nullptr);
1646 auto [socket, port] = CreateSocket();
1647 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001648 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1649 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001650}
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001651INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1652 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001653
Yifan Hong543edcd2021-05-18 19:47:30 -07001654class BinderLibTestService : public BBinder {
1655public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001656 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1657 : m_id(id),
1658 m_nextServerId(id + 1),
1659 m_serverStartRequested(false),
1660 m_callback(nullptr),
1661 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001662 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1663 pthread_cond_init(&m_serverWaitCond, nullptr);
1664 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001665 ~BinderLibTestService() {
1666 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1667 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001668
Yifan Hong543edcd2021-05-18 19:47:30 -07001669 void processPendingCall() {
1670 if (m_callback != nullptr) {
1671 Parcel data;
1672 data.writeInt32(NO_ERROR);
1673 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1674 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001675 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001676 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001677
Yifan Hong543edcd2021-05-18 19:47:30 -07001678 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1679 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001680 // TODO(b/182914638): also checks getCallingUid() for RPC
1681 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001682 return PERMISSION_DENIED;
1683 }
1684 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001685 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001686 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001687 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08001688 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001689 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001690 return BAD_VALUE;
1691 }
1692
Yifan Hong543edcd2021-05-18 19:47:30 -07001693 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001694
1695 pthread_mutex_lock(&m_serverWaitMutex);
1696 if (m_serverStartRequested) {
1697 m_serverStartRequested = false;
1698 m_serverStarted = binder;
1699 pthread_cond_signal(&m_serverWaitCond);
1700 }
1701 pthread_mutex_unlock(&m_serverWaitMutex);
1702 return NO_ERROR;
1703 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001704 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001705 case BINDER_LIB_TEST_ADD_SERVER: {
1706 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001707 int serverid;
1708
1709 if (m_id != 0) {
1710 return INVALID_OPERATION;
1711 }
1712 pthread_mutex_lock(&m_serverWaitMutex);
1713 if (m_serverStartRequested) {
1714 ret = -EBUSY;
1715 } else {
1716 serverid = m_nextServerId++;
1717 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001718 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001719
1720 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001721 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001722 pthread_mutex_lock(&m_serverWaitMutex);
1723 }
1724 if (ret > 0) {
1725 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001726 struct timespec ts;
1727 clock_gettime(CLOCK_REALTIME, &ts);
1728 ts.tv_sec += 5;
1729 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001730 }
1731 if (m_serverStartRequested) {
1732 m_serverStartRequested = false;
1733 ret = -ETIMEDOUT;
1734 } else {
1735 reply->writeStrongBinder(m_serverStarted);
1736 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001737 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001738 ret = NO_ERROR;
1739 }
1740 } else if (ret >= 0) {
1741 m_serverStartRequested = false;
1742 ret = UNKNOWN_ERROR;
1743 }
1744 pthread_mutex_unlock(&m_serverWaitMutex);
1745 return ret;
1746 }
Steven Moreland35626652021-05-15 01:32:04 +00001747 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1748 IPCThreadState::SpGuard spGuard{
1749 .address = __builtin_frame_address(0),
1750 .context = "GuardInBinderTransaction",
1751 };
1752 const IPCThreadState::SpGuard *origGuard =
1753 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1754
1755 // if the guard works, this should abort
1756 (void)IPCThreadState::self()->getCallingPid();
1757
1758 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1759 return NO_ERROR;
1760 }
1761
Marco Ballesio7ee17572020-09-08 10:30:03 -07001762 case BINDER_LIB_TEST_GETPID:
1763 reply->writeInt32(getpid());
1764 return NO_ERROR;
Jing Jibdbe29a2023-10-03 00:03:28 -07001765 case BINDER_LIB_TEST_GETUID:
1766 reply->writeInt32(getuid());
1767 return NO_ERROR;
Marco Ballesio7ee17572020-09-08 10:30:03 -07001768 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1769 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001770 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001771 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001772 // oneway error codes should be ignored
1773 if (flags & TF_ONE_WAY) {
1774 return UNKNOWN_ERROR;
1775 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001776 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001777 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1778 // Note: this transaction is only designed for use with a
1779 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001780 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001781 // A callback was already pending; this means that
1782 // we received a second call while still processing
1783 // the first one. Fail the test.
1784 sp<IBinder> callback = data.readStrongBinder();
1785 Parcel data2;
1786 data2.writeInt32(UNKNOWN_ERROR);
1787
Yi Kong91635562018-06-07 14:38:36 -07001788 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001789 } else {
1790 m_callback = data.readStrongBinder();
1791 int32_t delayUs = data.readInt32();
1792 /*
1793 * It's necessary that we sleep here, so the next
1794 * transaction the caller makes will be queued to
1795 * the async queue.
1796 */
1797 usleep(delayUs);
1798
1799 /*
1800 * Now when we return, libbinder will tell the kernel
1801 * we are done with this transaction, and the kernel
1802 * can move the queued transaction to either the
1803 * thread todo worklist (for kernels without the fix),
1804 * or the proc todo worklist. In case of the former,
1805 * the next outbound call will pick up the pending
1806 * transaction, which leads to undesired reentrant
1807 * behavior. This is caught in the if() branch above.
1808 */
1809 }
1810
1811 return NO_ERROR;
1812 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001813 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1814 Parcel data2, reply2;
1815 sp<IBinder> binder;
1816 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001817 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001818 return BAD_VALUE;
1819 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001820 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001821 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1822 return NO_ERROR;
1823 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001824 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1825 reply->writeStrongBinder(this);
1826 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001827 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1828 reply->writeInt32(m_id);
1829 return NO_ERROR;
1830 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1831 int32_t count;
1832 uint32_t indirect_code;
1833 sp<IBinder> binder;
1834
1835 count = data.readInt32();
1836 reply->writeInt32(m_id);
1837 reply->writeInt32(count);
1838 for (int i = 0; i < count; i++) {
1839 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001840 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001841 return BAD_VALUE;
1842 }
1843 indirect_code = data.readInt32();
1844 BinderLibTestBundle data2(&data);
1845 if (!data2.isValid()) {
1846 return BAD_VALUE;
1847 }
1848 BinderLibTestBundle reply2;
1849 binder->transact(indirect_code, data2, &reply2);
1850 reply2.appendTo(reply);
1851 }
1852 return NO_ERROR;
1853 }
1854 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1855 reply->setError(data.readInt32());
1856 return NO_ERROR;
1857 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1858 reply->writeInt32(sizeof(void *));
1859 return NO_ERROR;
1860 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1861 return NO_ERROR;
1862 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1863 m_strongRef = data.readStrongBinder();
1864 return NO_ERROR;
1865 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1866 int ret;
1867 Parcel data2, reply2;
1868 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1869 sp<IBinder> target;
1870 sp<IBinder> callback;
1871
1872 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001873 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001874 return BAD_VALUE;
1875 }
1876 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001877 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001878 return BAD_VALUE;
1879 }
1880 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001881 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001882 data2.writeInt32(ret);
1883 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1884 return NO_ERROR;
1885 }
1886 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1887 int ret;
1888 int32_t size;
1889 const void *buf;
1890 int fd;
1891
1892 fd = data.readFileDescriptor();
1893 if (fd < 0) {
1894 return BAD_VALUE;
1895 }
1896 ret = data.readInt32(&size);
1897 if (ret != NO_ERROR) {
1898 return ret;
1899 }
1900 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001901 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001902 return BAD_VALUE;
1903 }
1904 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001905 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001906 return NO_ERROR;
1907 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001908 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1909 int ret;
1910 int32_t size;
1911 const void *buf;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001912 unique_fd fd;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001913
1914 ret = data.readUniqueParcelFileDescriptor(&fd);
1915 if (ret != NO_ERROR) {
1916 return ret;
1917 }
1918 ret = data.readInt32(&size);
1919 if (ret != NO_ERROR) {
1920 return ret;
1921 }
1922 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001923 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001924 return BAD_VALUE;
1925 }
1926 ret = write(fd.get(), buf, size);
1927 if (ret != size) return UNKNOWN_ERROR;
1928 return NO_ERROR;
1929 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001930 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1931 alarm(10);
1932 return NO_ERROR;
1933 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001934 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001935 ;
1936 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001937 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001938 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001939 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001940 return NO_ERROR;
1941 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001942 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1943 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001944 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001945 return NO_ERROR;
1946 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001947 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1948 int policy = 0;
1949 sched_param param;
1950 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1951 return UNKNOWN_ERROR;
1952 }
1953 reply->writeInt32(policy);
1954 reply->writeInt32(param.sched_priority);
1955 return NO_ERROR;
1956 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001957 case BINDER_LIB_TEST_ECHO_VECTOR: {
1958 std::vector<uint64_t> vector;
1959 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001960 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001961 reply->writeUint64Vector(vector);
1962 return NO_ERROR;
1963 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001964 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1965 std::array<int, 2> sockets;
1966 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1967 if (!created) {
1968 ALOGE("Could not create socket pair");
1969 return UNKNOWN_ERROR;
1970 }
1971
1972 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
1973 if (result != 0) {
1974 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
1975 return UNKNOWN_ERROR;
1976 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001977 unique_fd out(sockets[0]);
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001978 status_t writeResult = reply->writeUniqueFileDescriptor(out);
1979 if (writeResult != NO_ERROR) {
1980 ALOGE("Could not write unique_fd");
1981 return writeResult;
1982 }
1983 close(sockets[1]); // we don't need the other side of the fd
1984 return NO_ERROR;
1985 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001986 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001987 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1988 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001989 case BINDER_LIB_TEST_CAN_GET_SID: {
1990 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1991 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001992 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1993 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1994 return NO_ERROR;
1995 }
Devin Moore4354f712022-12-08 01:44:46 +00001996 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
1997 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
1998 return NO_ERROR;
1999 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002000 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002001 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002002 return NO_ERROR;
2003 }
2004 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002005 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00002006 return NO_ERROR;
2007 }
2008 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2009 int32_t ms = data.readInt32();
2010 return unlockInMs(ms);
2011 }
2012 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002013 m_blockMutex.lock();
2014 sp<BinderLibTestService> thisService = this;
2015 int32_t value = data.readInt32();
2016 // start local thread to unlock in 1s
2017 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00002018 t.detach();
2019 return NO_ERROR;
2020 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002021 default:
2022 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07002023 };
2024 }
2025
Elie Kheirallah47431c12022-04-21 23:46:17 +00002026 status_t unlockInMs(int32_t ms) {
2027 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002028 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002029 return NO_ERROR;
2030 }
2031
Yifan Hong543edcd2021-05-18 19:47:30 -07002032private:
2033 int32_t m_id;
2034 int32_t m_nextServerId;
2035 pthread_mutex_t m_serverWaitMutex;
2036 pthread_cond_t m_serverWaitCond;
2037 bool m_serverStartRequested;
2038 sp<IBinder> m_serverStarted;
2039 sp<IBinder> m_strongRef;
2040 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07002041 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002042 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002043};
2044
Martijn Coenen45b07b42017-08-09 12:07:45 +02002045int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002046{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002047 binderLibTestServiceName += String16(binderserversuffix);
2048
Steven Moreland35626652021-05-15 01:32:04 +00002049 // Testing to make sure that calls that we are serving can use getCallin*
2050 // even though we don't here.
2051 IPCThreadState::SpGuard spGuard{
2052 .address = __builtin_frame_address(0),
2053 .context = "main server thread",
2054 };
2055 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2056
Riley Andrews06b01ad2014-12-18 12:10:08 -08002057 status_t ret;
2058 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02002059 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002060 {
2061 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002062
Steven Morelandbf1915b2020-07-16 22:43:02 +00002063 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2064
Steven Morelandcf03cf12020-12-04 02:58:40 +00002065 testService->setInheritRt(true);
2066
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002067 /*
2068 * Normally would also contain functionality as well, but we are only
2069 * testing the extension mechanism.
2070 */
2071 testService->setExtension(new BBinder());
2072
Martijn Coenen82c75312019-07-24 15:18:30 +02002073 // Required for test "BufRejected'
2074 testService->setRequestingSid(true);
2075
Martijn Coenen45b07b42017-08-09 12:07:45 +02002076 /*
2077 * We need this below, but can't hold a sp<> because it prevents the
2078 * node from being cleaned up automatically. It's safe in this case
2079 * because of how the tests are written.
2080 */
2081 testServicePtr = testService.get();
2082
Riley Andrews06b01ad2014-12-18 12:10:08 -08002083 if (index == 0) {
2084 ret = sm->addService(binderLibTestServiceName, testService);
2085 } else {
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002086#pragma clang diagnostic push
2087#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -08002088 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002089#pragma clang diagnostic pop
Riley Andrews06b01ad2014-12-18 12:10:08 -08002090 Parcel data, reply;
2091 data.writeInt32(index);
2092 data.writeStrongBinder(testService);
2093
2094 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2095 }
2096 }
2097 write(readypipefd, &ret, sizeof(ret));
2098 close(readypipefd);
2099 //printf("%s: ret %d\n", __func__, ret);
2100 if (ret)
2101 return 1;
2102 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002103 if (usePoll) {
2104 int fd;
2105 struct epoll_event ev;
2106 int epoll_fd;
2107 IPCThreadState::self()->setupPolling(&fd);
2108 if (fd < 0) {
2109 return 1;
2110 }
2111 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2112
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002113 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002114 if (epoll_fd == -1) {
2115 return 1;
2116 }
2117
2118 ev.events = EPOLLIN;
2119 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2120 return 1;
2121 }
2122
2123 while (1) {
2124 /*
2125 * We simulate a single-threaded process using the binder poll
2126 * interface; besides handling binder commands, it can also
2127 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002128 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002129 *
2130 * processPendingCall() will then issue that transaction.
2131 */
2132 struct epoll_event events[1];
2133 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2134 if (numEvents < 0) {
2135 if (errno == EINTR) {
2136 continue;
2137 }
2138 return 1;
2139 }
2140 if (numEvents > 0) {
2141 IPCThreadState::self()->handlePolledCommands();
2142 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2143 testServicePtr->processPendingCall();
2144 }
2145 }
2146 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002147 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002148 ProcessState::self()->startThreadPool();
2149 IPCThreadState::self()->joinThreadPool();
2150 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002151 //printf("%s: joinThreadPool returned\n", __func__);
2152 return 1; /* joinThreadPool should not return */
2153}
2154
Steven Moreland68275d72023-04-21 22:12:45 +00002155int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002156 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002157 binderservername = argv[2];
2158 } else {
2159 binderservername = argv[0];
2160 }
2161
Martijn Coenen45b07b42017-08-09 12:07:45 +02002162 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2163 binderserversuffix = argv[5];
2164 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002165 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002166 binderserversuffix = new char[16];
2167 snprintf(binderserversuffix, 16, "%d", getpid());
2168 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002169
2170 ::testing::InitGoogleTest(&argc, argv);
2171 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2172 ProcessState::self()->startThreadPool();
2173 return RUN_ALL_TESTS();
2174}